package com.hzs.member.self.controller.api;

import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.constant.msg.FinanceMsgConstants;
import com.hzs.common.core.enums.EApprovalBusiness;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.member.self.CuSelfServiceLog;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.account.service.ICuMemberAuthenticationService;
import com.hzs.member.account.vo.CuMemberAuthenticationVO;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.self.service.ICuSelfServiceLogService;
import com.hzs.member.self.vo.DomicileChangeVO;
import com.hzs.member.sms.service.IApiAliSmsService;
import com.hzs.system.config.IServiceChargeServiceApi;
import com.hzs.system.config.dto.ServiceChargeDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 变理户籍
 */
@Slf4j
@RequestMapping("/api/change-domicile")
@RestController
public class ApiDomicileChangeController extends BaseController {

    @Autowired
    private ICuMemberAuthenticationService iCuMemberAuthenticationService;
    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private IApiAliSmsService iApiAliSmsService;
    @Autowired
    private ICuSelfServiceLogService iCuSelfServiceLogService;

    @DubboReference
    IServiceChargeServiceApi iServiceChargeServiceApi;

    /**
     * 查询可申请信息
     *
     * @return AjaxResult
     */
    @GetMapping("/application-info-list")
    public AjaxResult applicationInformation() {
        Long pkMember = SecurityUtils.getUserId();
        CuMemberExt member = iCuMemberService.getMemberById(pkMember);
        DomicileChangeVO domicileChangeVO = DomicileChangeVO.builder().memberCode(member.getMemberCode())
                .memberName(member.getMemberName()).phone(member.getPhone())
                .changeNum(MagicNumberConstants.CHANGE_NUM).build();
        return AjaxResult.success(domicileChangeVO);
    }


    @GetMapping("/application-info-detail")
    public AjaxResult applicationInformationDetail() {
        return AjaxResult.success(iCuSelfServiceLogService.selectDomicileChangeByPkMember(SecurityUtils.getUserId(), EApprovalBusiness.DOMICILE_CHANGE.getValue(), SecurityUtils.getPkCountry()));
    }

    /**
     * 查询已申请信息
     *
     * @return AjaxResult
     */
    @GetMapping("/applied-info-list")
    public AjaxResult appliedInformation() {
        DomicileChangeVO domicileChangeVO = DomicileChangeVO.builder().pkMember(SecurityUtils.getUserId())
                .pkCountry(SecurityUtils.getPkCountry()).editType(EApprovalBusiness.DOMICILE_CHANGE.getValue()).build();
        List<DomicileChangeVO> domicileChangeVOList = (List<DomicileChangeVO>) iCuSelfServiceLogService.selectSelfServiceByPkMember(domicileChangeVO)[1];
        return AjaxResult.success(domicileChangeVOList);
    }


    /**
     * 自助服务是否显示户籍认证
     *
     * @return AjaxResult
     */
    @GetMapping("/show-index-domicile")
    public AjaxResult showIndexDomicile() {
        return AjaxResult.success(iCuSelfServiceLogService.showIndexDomicile(SecurityUtils.getPkCountry(), SecurityUtils.getUserId()));
    }


    /**
     * 申请户籍变更
     *
     * @param domicileChangeVO 变更信息
     * @return TableDataInfo
     */
    @PostMapping("/change-domicile")
    @RepeatSubmitSimple
    public AjaxResult changeDomicile(@RequestBody DomicileChangeVO domicileChangeVO) {
        Long pkMember = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (StringUtils.isEmpty(domicileChangeVO.getChangePhone())) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.MEMBER_PHONE_CANNOT_EMPTY));
        }
        if (StringUtils.isEmpty(domicileChangeVO.getChangeMemberName())) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.MEMBER_NAME_CANNOT_EMPTY));
        }
        if (StringUtils.isEmpty(domicileChangeVO.getIdFront())) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.ID_FRONT_CANNOT_EMPTY));
        }
        if (StringUtils.isEmpty(domicileChangeVO.getIdBack())) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.ID_BACK_CANNOT_EMPTY));
        }
        if (StringUtils.isEmpty(domicileChangeVO.getChangeIdFront())) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.ID_FRONT_CANNOT_EMPTY));
        }
        if (StringUtils.isEmpty(domicileChangeVO.getChangeIdBack())) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.ID_BACK_CANNOT_EMPTY));
        }
        domicileChangeVO.setPkCountry(pkCountry);
        domicileChangeVO.setPkMember(pkMember);
        //是否有正在审批业务
        AjaxResult existApprovalData = isExistApprovalData(domicileChangeVO);
        if (!existApprovalData.equals(AjaxResult.success())) {
            return existApprovalData;
        }
        // 校验短信验证码
        String message = iApiAliSmsService.checkCode(domicileChangeVO.getChangePhone(), domicileChangeVO.getVerificationCode(), null);
        if (null != message) {
            return AjaxResult.error(message);
        }
        return toAjax(iCuSelfServiceLogService.saveChangeDomicile(domicileChangeVO));
    }

    /**
     * 显示户籍变更信息
     *
     * @return AjaxResult
     */
    @GetMapping("/show-change-domicile")
    public AjaxResult showChangeDomicile() {
        String idBack = null;
        String idFront = null;
        Long pkMember = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        CuMemberExt member = iCuMemberService.getMemberById(pkMember);
        //查询实名认证信息原证件图
        CuMemberAuthenticationVO authenticationVO = CuMemberAuthenticationVO.builder().pkCountry(pkCountry).pkMember(pkMember).build();
        CuMemberAuthenticationVO cuMemberAuthenticationVO = iCuMemberAuthenticationService.selectCuMemberAuthenticationByPkMember(authenticationVO);
        if (null != cuMemberAuthenticationVO) {
            idBack = cuMemberAuthenticationVO.getIdBack();
            idFront = cuMemberAuthenticationVO.getIdFront();
        }
        ServiceChargeDTO serviceChargeInfo = getServiceChargeInfo(pkCountry);
        BigDecimal cost = null != serviceChargeInfo ? serviceChargeInfo.getCost() : BigDecimal.ZERO;
        DomicileChangeVO domicileChangeVO = DomicileChangeVO.builder().memberCode(member.getMemberCode())
                .memberName(member.getMemberName()).phone(member.getPhone()).amount(cost).pkAccount(serviceChargeInfo.getPkAccount())
                .idBack(idBack).idFront(idFront).build();
        return AjaxResult.success(domicileChangeVO);
    }

    /**
     * 是否存在审核的数据
     *
     * @param domicileChangeVO 户籍变更信息
     * @return AjaxResult
     */
    private AjaxResult isExistApprovalData(DomicileChangeVO domicileChangeVO) {
        CuSelfServiceLog cuSelfServiceLog = new CuSelfServiceLog();
        cuSelfServiceLog.setPkCountry(domicileChangeVO.getPkCountry());
        cuSelfServiceLog.setEditType(EApprovalBusiness.DOMICILE_CHANGE.getValue());
        cuSelfServiceLog.setPkMember(domicileChangeVO.getPkMember());
        Integer check = iCuSelfServiceLogService.checkSelfService(cuSelfServiceLog);
        if (check > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
        }
        return AjaxResult.success();
    }

    /**
     * 查询手续费
     *
     * @param pkCountry 国家pID
     * @return ServiceChargeDTO
     */
    private ServiceChargeDTO getServiceChargeInfo(Integer pkCountry) {
        //查询扣费金额，账户信息
        ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
        serviceChargeDTO.setType(EApprovalBusiness.DOMICILE_CHANGE.getValue());
        serviceChargeDTO.setPkCountry(pkCountry);
        serviceChargeDTO.setQuantity(MagicNumberConstants.CHANGE_NUM);
        return iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO).getData();
    }

}
