package com.liquidnet.service.adam.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.liquidnet.common.exception.constant.ErrorCode;
import com.liquidnet.commons.lang.constant.LnsRegex;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.SensitizeUtil;
import com.liquidnet.service.adam.dto.AdamEntersParam;
import com.liquidnet.service.adam.dto.vo.AdamEntersVo;
import com.liquidnet.service.adam.service.IAdamEntersService;
import com.liquidnet.service.adam.service.AdamRdmService;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * <p>
 * 入场人 前端控制器
 * </p>
 *
 * @author liquidnet
 * @since 2021-04-28
 */
@ApiSupport(order = 10040)
@Api(tags = "入场人")
@Slf4j
@Validated
@RestController
@RequestMapping("enters")
public class AdamEntersController {
    @Autowired
    AdamRdmService adamRdmService;
    @Autowired
    IAdamEntersService adamEntersService;


    @Value("${liquidnet.reviewer.limit.enters:10}")
    private int reviewLimitEnters;
//    @Value("${liquidnet.reviewer.limit.enters_opr:10}")
//    private int reviewLimitEntersOpr;

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "添加入场人")
    @PostMapping("add")
    public ResponseDto<String> add(@RequestBody @Valid AdamEntersParam parameter) {
        switch (parameter.getType()) {// 证件类型:1-大陆身份证,2-港澳通行证,3-台胞证,4-护照,5-军官证
            case 1:
                if (!Pattern.matches(LnsRegex.Valid.CN_HANZI, parameter.getName())) {
                    return ResponseDto.failure(ErrorMapping.get("10103"));
                }
                if (!Pattern.matches(LnsRegex.Valid.CN_ID_CARD_REF, parameter.getIdCard())) {
                    return ResponseDto.failure(ErrorMapping.get("10104"));
                }
                break;
            case 2:
                if (!Pattern.matches(LnsRegex.Valid.CN_ID_CARD_HM, parameter.getIdCard())) {
                    return ResponseDto.failure(ErrorMapping.get("10107"));
                }
                break;
            case 3:
                if (!Pattern.matches(LnsRegex.Valid.CN_ID_CARD_TW, parameter.getIdCard())) {
                    return ResponseDto.failure(ErrorMapping.get("10108"));
                }
                break;
            case 4:
                if (Pattern.matches(LnsRegex.Valid.CN_ID_CARD_PP, parameter.getIdCard())) {
                    return ResponseDto.failure(ErrorMapping.get("10109"));
                }
                if (!Pattern.matches(LnsRegex.Valid.CN_ID_CARD_PP_NON, parameter.getIdCard())) {
                    return ResponseDto.failure(ErrorMapping.get("10110"));
                }
                break;
            case 5:
                if (!Pattern.matches(LnsRegex.Valid.CN_ID_CARD_MO, parameter.getIdCard())) {
                    return ResponseDto.failure(ErrorMapping.get("10111"));
                }
                break;
        }
        String currentUid = CurrentUtil.getCurrentUid();

        List<AdamEntersVo> vos = adamRdmService.getEntersVoByUid(currentUid);

        if (!CollectionUtils.isEmpty(vos)) {
            Optional<AdamEntersVo> any = vos.stream().filter(r -> (r.getIdCard().equals(parameter.getIdCard())) && r.getType().equals(parameter.getType())).findAny();
            if (any.isPresent()) {
                return ResponseDto.failure(ErrorMapping.get("10019"));
            }

            if (reviewLimitEnters > 0 && vos.size() >= reviewLimitEnters) {
                return ResponseDto.failure(ErrorMapping.get("10025"));
            }
        }

//        int userEntersOprNo = adamRdmService.getUserEntersOprNo(currentUid);
//        if (reviewLimitEntersOpr > 0 && userEntersOprNo >= reviewLimitEntersOpr) {
//            return ResponseDto.failure(ErrorMapping.get("10026"));
//        }

        String entersId = adamEntersService.add(parameter, currentUid, vos);

//        if (userEntersOprNo == -1) {
//            adamRdmService.setUserEntersOprNo(currentUid);
//        } else {
//            adamRdmService.incrUserEntersOprNo(currentUid);
//        }
        return ResponseDto.success(entersId);
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "入场人列表")
    @GetMapping("list")
    public ResponseDto<List<AdamEntersVo>> list() {
        List<AdamEntersVo> vos = adamRdmService.getEntersVoByUid(CurrentUtil.getCurrentUid());
        if (!CollectionUtils.isEmpty(vos)) {
            for (AdamEntersVo vo : vos) {
                vo.setName(SensitizeUtil.chineseName(vo.getName()));
                vo.setIdCard(SensitizeUtil.custom(vo.getIdCard(), 3, 2));
                vo.setMobile(SensitizeUtil.custom(vo.getMobile(), 3, 4));
            }
        }
        return ResponseDto.success(vos);
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "设置默认入场人")
    @PostMapping("def/{entersId}")
    public ResponseDto<Object> def(@NotBlank(message = "入场人ID不能为空") @PathVariable String entersId) {
        String currentUid = CurrentUtil.getCurrentUid();

        AdamEntersVo vo = adamRdmService.getEntersVoByUidEntersId(currentUid, entersId);
        if (null == vo) return ResponseDto.failure(ErrorMapping.get("10105"));

        if (!vo.getIsDefault()) {
            adamEntersService.def(currentUid, entersId);
        }
        return ResponseDto.success();
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "编辑入场人")
    @PostMapping("edit")
    public ResponseDto<Object> edit(@RequestBody @Valid AdamEntersParam parameter) {
        if (1 == parameter.getType()) {
            if (!Pattern.matches(LnsRegex.Valid.CN_HANZI, parameter.getName())) {
                return ResponseDto.failure(ErrorMapping.get("10103"));
            }
            if (!Pattern.matches(LnsRegex.Valid.CN_ID_CARD_REF, parameter.getIdCard())) {
                return ResponseDto.failure(ErrorMapping.get("10104"));
            }
        }
        if (StringUtils.isBlank(parameter.getEntersId())) {
            return ResponseDto.failure(ErrorMapping.get("10015"));
        }
        String currentUid = CurrentUtil.getCurrentUid();
        if (null == adamRdmService.getEntersVoByUidEntersId(currentUid, parameter.getEntersId())) {
            return ResponseDto.failure(ErrorMapping.get("10105"));
        }

////        int userEntersOprNo = adamRdmService.getUserEntersOprNo(currentUid);
////        if (reviewLimitEntersOpr > 0 && userEntersOprNo >= reviewLimitEntersOpr) {
////            return ResponseDto.failure(ErrorMapping.get("10026"));
////        }
////
//        adamEntersService.edit(parameter);
////
////        if (userEntersOprNo == -1) {
////            adamRdmService.setUserEntersOprNo(currentUid);
////        } else {
////            adamRdmService.incrUserEntersOprNo(currentUid);
////        }
        return ResponseDto.success();
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "删除入场人")
    @PostMapping("del/{entersId}")
    public ResponseDto<Object> del(@NotBlank(message = "入场人ID不能为空") @PathVariable String entersId) {
        String currentUid = CurrentUtil.getCurrentUid();

        AdamEntersVo enters = adamRdmService.getEntersVoByUidEntersId(currentUid, entersId);
        if (null == enters) return ResponseDto.failure(ErrorMapping.get("10105"));

//        adamEntersService.remove(currentUid, entersId);

        return ResponseDto.success();
    }

    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "入场人详情")
    @PostMapping("query")
    public ResponseDto<List<AdamEntersVo>> query(@NotBlank(message = "入场人ID不能为空") @RequestParam String entersIds) {
        List<AdamEntersVo> vos = adamRdmService.getEntersVoByUidEntersIds(CurrentUtil.getCurrentUid(), Arrays.asList(entersIds.split(",")));
        if (!CollectionUtils.isEmpty(vos)) {
            for (AdamEntersVo vo : vos) {
                vo.setName(SensitizeUtil.chineseName(vo.getName()));
                vo.setIdCard(SensitizeUtil.custom(vo.getIdCard(), 3, 2));
                vo.setMobile(SensitizeUtil.custom(vo.getMobile(), 3, 4));
            }
        }
        return CollectionUtils.isEmpty(vos) ? ResponseDto.failure(ErrorMapping.get("10105")) : ResponseDto.success(vos);
    }

    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "获取默认入场人")
    @PostMapping("query/def")
    public ResponseDto<AdamEntersVo> queryDef() {
        AdamEntersVo vo = adamEntersService.queryDefault(null, CurrentUtil.getCurrentUid(), true);
        if (null != vo) {
            vo.setName(SensitizeUtil.chineseName(vo.getName()));
            vo.setIdCard(SensitizeUtil.custom(vo.getIdCard(), 3, 2));
            vo.setMobile(SensitizeUtil.custom(vo.getMobile(), 3, 4));
        }
        return ResponseDto.success(vo);
    }

    /* ------------------------------------------------------------｜@API:RSC */

    @ApiOperationSupport(order = 99)
    @ApiOperation(value = "不推荐使用@API:入场人详情", notes = "不推荐使用，建议使用`rsc/inquire/enters`")
    @GetMapping("query/depth")
    public ResponseDto<AdamEntersVo> queryForDepth(@NotBlank(message = "入场人ID不能为空") @RequestParam String entersId,
                                                   @NotBlank(message = "用户ID不能为空") @RequestParam String uid) {
        AdamEntersVo vo = adamRdmService.getEntersVoByUidEntersId(uid, entersId);
        return null == vo ? ResponseDto.failure(ErrorMapping.get("10105")) : ResponseDto.success(vo);
    }
}
