package com.hzs.member.self.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.member.account.CuMemberAccount;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.member.self.CuSelfServiceLog;
import com.hzs.common.domain.member.self.CuSelfServiceLogExt;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.account.dto.MemberAmountDTO;
import com.hzs.member.account.service.*;
import com.hzs.member.base.service.ICuMemberBusinessService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.handlebusiness.vo.BusinessMemberVO;
import com.hzs.member.self.mapper.CuSelfServiceLogMapper;
import com.hzs.member.self.service.ICuSelfServiceLogService;
import com.hzs.member.self.vo.DomicileChangeVO;
import com.hzs.member.self.vo.MyOrderItemsVO;
import com.hzs.member.self.vo.SelfModifyAddressVO;
import com.hzs.sale.order.ISaOrderServiceApi;
import com.hzs.system.sys.IApprovalServiceApi;
import com.hzs.system.sys.dto.ApprovalBusinessResultDTO;
import com.hzs.system.sys.dto.ApprovalSubmitDTO;
import com.hzs.system.sys.dto.BusinessLogDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 自助服务日志表 服务实现类
 */
@Service
public class CuSelfServiceLogServiceImpl extends ServiceImpl<CuSelfServiceLogMapper, CuSelfServiceLog> implements ICuSelfServiceLogService {

    @DubboReference
    IApprovalServiceApi iApprovalServiceApi;
    @DubboReference
    ISaOrderServiceApi iSaOrderServiceApi;

    @Autowired
    private ICuMemberBusinessService iCuMemberBusinessService;
    @Autowired
    private ICuMemberAccountService iCuMemberAccountService;
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @Autowired
    private ICuMemberAuthenticationService cuMemberAuthenticationService;
    @Autowired
    private ICuMemberBusinessLicenseService cuMemberBusinessLicenseService;
    @Autowired
    private ICuMemberService cuMemberService;
    @Autowired
    private ICuMemberBankService cuMemberBankService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public List<SelfModifyAddressVO> querySelfModifyAddressList(SelfModifyAddressVO selfModifyAddressVO) {
        return baseMapper.querySelfModifyAddressList(selfModifyAddressVO);
    }

    @Override
    public List<SelfModifyAddressVO> querySelfModifyAddressManageList(SelfModifyAddressVO selfModifyAddressVO) {
        return baseMapper.querySelfModifyAddressManageList(selfModifyAddressVO);
    }

    @Override
    public Integer checkSelfService(CuSelfServiceLog cuSelfServiceLog) {
        return baseMapper.checkSelfService(cuSelfServiceLog);
    }

    @Override
    public Integer selectByMaxApproveNumber(CuSelfServiceLog cuSelfServiceLog) {
        return baseMapper.selectByMaxApproveNumber(cuSelfServiceLog);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean putin(SelfModifyAddressVO selfModifyAddressVO) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SELF_SERVICE.getValue());
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        SelfModifyAddressVO oldsma = new SelfModifyAddressVO();
        oldsma.setRecAddress(selfModifyAddressVO.getRecAddress());
        oldsma.setRecName(selfModifyAddressVO.getRecName());
        oldsma.setRecPhone(selfModifyAddressVO.getRecPhone());
        oldsma.setRecProvince(selfModifyAddressVO.getRecProvince());
        oldsma.setRecCity(selfModifyAddressVO.getRecCity());
        oldsma.setPostage(selfModifyAddressVO.getPostage());
        if (StringUtils.isNotNull(selfModifyAddressVO.getRecCounty())) {
            oldsma.setRecCounty(selfModifyAddressVO.getRecCounty());
        }
        SelfModifyAddressVO newsma = new SelfModifyAddressVO();
        newsma.setNewRecAddress(selfModifyAddressVO.getNewRecAddress());
        newsma.setNewRecName(selfModifyAddressVO.getNewRecName());
        newsma.setNewRecPhone(selfModifyAddressVO.getNewRecPhone());
        newsma.setNewRecProvince(selfModifyAddressVO.getNewRecProvince());
        newsma.setNewRecCity(selfModifyAddressVO.getNewRecCity());
        newsma.setNewPostage(selfModifyAddressVO.getNewPostage());
        if (StringUtils.isNotNull(selfModifyAddressVO.getNewRecCounty())) {
            newsma.setNewRecCounty(selfModifyAddressVO.getNewRecCounty());
        }
        //新增修改订单地址日志记录
        CuSelfServiceLog css = new CuSelfServiceLog();
        css.setPkCountry(selfModifyAddressVO.getPkCountry());
        css.setEditType(selfModifyAddressVO.getEditType());
        css.setApproveStatus(EApproveRechargeStatus.AGREE.getValue());
        css.setBusinessNo(code);
        css.setPkMember(selfModifyAddressVO.getPkMember());
        css.setOldValue(JSONObject.toJSONString(oldsma));
        css.setNewValue(JSONObject.toJSONString(newsma));
        css.setApproveNumber(selfModifyAddressVO.getApproveNumber());
        css.setEditType(EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue());
        css.setEditTypePay(EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue());
        css.setSingleAmount(selfModifyAddressVO.getSingleAmount());
        css.setOrderCode(selfModifyAddressVO.getOrderCode());
        css.setCreationTime(date);
        css.setPkCreator(userID);
        css.setSelfRemark(selfModifyAddressVO.getSelfRemark());
        baseMapper.insert(css);
        //修改订单相关信息
        SaOrder so = new SaOrder();
        so.setPkId(selfModifyAddressVO.getPkId());
        so.setPostage(selfModifyAddressVO.getNewPostage());
        so.setRecName(selfModifyAddressVO.getNewRecName());
        so.setRecPhone(selfModifyAddressVO.getNewRecPhone());
        so.setRecProvince(selfModifyAddressVO.getNewRecProvince());
        so.setRecCity(selfModifyAddressVO.getNewRecCity());
        so.setRecCounty(selfModifyAddressVO.getNewRecCounty());
        so.setRecAddress(selfModifyAddressVO.getNewRecAddress());
        if (null != selfModifyAddressVO.getPkStorehouse()) {
            so.setPkStorehouse(selfModifyAddressVO.getPkStorehouse());
        }
        //修改订单的收货地址
        iSaOrderServiceApi.updateOrder(so);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveChangeDomicile(DomicileChangeVO domicileChangeVO) {
        Long pkMember = domicileChangeVO.getPkMember();
        int editType = EApprovalBusiness.DOMICILE_CHANGE.getValue();
        Integer pkCountry = domicileChangeVO.getPkCountry();
        CuSelfServiceLogExt cuSelfServiceLogExt = baseMapper.selectDomicileChangeByPkMember(editType, pkMember, pkCountry);
        //逻辑删除已有的信息
        if (null != cuSelfServiceLogExt) {
            UpdateWrapper<CuSelfServiceLog> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.DELETE.getValue());
            updateWrapper.set(SystemFieldConstants.PK_MODIFIED, pkMember);
            updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, new Date());
            updateWrapper.eq("PK_ID", cuSelfServiceLogExt.getPkId());
            update(updateWrapper);
        }
        //变更前值
        DomicileChangeVO oldValue = DomicileChangeVO.builder().memberName(domicileChangeVO.getMemberName())
                .phone(domicileChangeVO.getPhone()).idFront(domicileChangeVO.getIdFront()).idBack(domicileChangeVO.getIdBack()).build();
        //变更后的值
        DomicileChangeVO newValue = DomicileChangeVO.builder().changeMemberName(domicileChangeVO.getChangeMemberName())
                .changePhone(domicileChangeVO.getChangePhone()).changeIdFront(domicileChangeVO.getChangeIdFront()).changeIdBack(domicileChangeVO.getChangeIdBack()).build();

        String businessNo = CommonUtil.createSerialNumber(EOrderPrefix.SELF_SERVICE.getValue());
        CuSelfServiceLog oldServiceLog = CuSelfServiceLog.builder().pkMember(pkMember)
                .editType(editType).oldValue(JSONUtil.toJsonStr(oldValue)).selfRemark(domicileChangeVO.getRemark()).description(domicileChangeVO.getDescription())
                .newValue(JSONUtil.toJsonStr(newValue)).businessNo(businessNo).approveStatus(EApproveRechargeStatus.SUBMIT.getValue()).pkAccount(domicileChangeVO.getPkAccount())
                .approveNumber(MagicNumberConstants.CHANGE_NUM).singleAmount(domicileChangeVO.getAmount()).editTypePay(ETradeType.getValueByApprovalValue(editType)).build();
        oldServiceLog.setPkCreator(pkMember);
        oldServiceLog.setPkCountry(pkCountry);
        //保存
        this.save(oldServiceLog);
        //扣费
        return Charging(domicileChangeVO, businessNo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer domicileChangeAgree(DomicileChangeVO domicileChangeVO) {
        String businessNo = domicileChangeVO.getBusinessNo();
        Long pkMember = domicileChangeVO.getPkMember();
        Long pkModified = domicileChangeVO.getPkModified();
        //更新审核状态
        DomicileChangeVO domicileChange = DomicileChangeVO.builder().businessNo(businessNo)
                .approveStatus(EApproveRechargeStatus.WAIT.getValue()).approveTime(new Date())
                .pkModified(pkModified).build();
        Integer result = baseMapper.updateSelfServiceByBusinessNo(domicileChange);
        //调用审批接口，修改审批状态
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.DOMICILE_CHANGE)
                .businessCode(businessNo).signSource(ESignSource.MANAGE)
                .signType(ESignType.GENERAL).userIdList(domicileChangeVO.getUserIdList())
                .remark(domicileChangeVO.getRemark()).pkMemberList(Collections.singleton(pkMember))
                .sendIdList(domicileChangeVO.getSendIdList()).fileList(domicileChangeVO.getFileList())
                .build();
        R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, domicileChangeVO.getLoginUser());
        if (!submit.isSuccess()) {
            throw new RuntimeException(submit.getMsg());
        }
        //MQ户籍变更操作日志
        CuSelfServiceLog cuSelfServiceLog = baseMapper.selectSelfServiceByBusinessNo(EApprovalBusiness.DOMICILE_CHANGE.getValue(), businessNo);
        packageDomicileOperationLog(cuSelfServiceLog, businessNo, "同意", pkModified, false);
        return result;
    }

    /**
     * 户籍变更操作日志
     *
     * @param cuSelfServiceLog 入参
     * @param businessNo       业务编号
     * @param operationType    操作类型
     */
    private void packageDomicileOperationLog(CuSelfServiceLog cuSelfServiceLog, String businessNo, String operationType, Long pkMember, Boolean freeSignFlag) {
        DomicileChangeVO oldValue = JSONUtil.toBean(cuSelfServiceLog.getOldValue(), DomicileChangeVO.class);
        DomicileChangeVO newValue = JSONUtil.toBean(cuSelfServiceLog.getNewValue(), DomicileChangeVO.class);
        CuMemberExt cumember = cuMemberService.getMemberById(cuSelfServiceLog.getPkMember());
        String sb = "会员编号：" + cumember.getMemberCode() +
                " 变更前的会员姓名：" + oldValue.getMemberName() +
                " 变更后的会员姓名：" + newValue.getChangeMemberName() +
                " 变更前的联系方式：" + oldValue.getPhone() +
                " 变更后的联系方式：" + newValue.getChangePhone() +
                " 操作类型：" + operationType;
        BusinessLogDTO businessLog = BusinessLogDTO.builder()
                .businessType(EApprovalBusiness.DOMICILE_CHANGE.getValue())
                .businessCode(businessNo).pkMember(cuSelfServiceLog.getPkMember())
                .content(sb).pkCreator(pkMember)
                .pkCountry(cuSelfServiceLog.getPkCountry())
                .freeSignFlag(freeSignFlag).build();
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, Collections.singleton(businessLog));
    }


    /**
     * 扣费
     *
     * @param domicileChangeVO 户籍变更信息
     * @param businessNo       业务编号
     */
    public Boolean Charging(DomicileChangeVO domicileChangeVO, String businessNo) {
        MemberAmountDTO memberAmountDTO = MemberAmountDTO.builder().pkMember(domicileChangeVO.getPkMember()).tradeAmount(domicileChangeVO.getAmount()).build();
        List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
        memberAmountDTOList.add(memberAmountDTO);

        BusinessCommissionDTO businessCommissionDTO = BusinessCommissionDTO.builder().pkAccount(domicileChangeVO.getPkAccount())
                .tradeType(EApprovalBusiness.DOMICILE_CHANGE.getValue())
                .tradeCode(businessNo)
                .pkCountry(domicileChangeVO.getPkCountry())
                .pkCreator(domicileChangeVO.getPkModified()).build();
        businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
        return cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
    }


    @Override
    public Object[] selectSelfServiceByPkMember(DomicileChangeVO domicileChangeVO) {
        DomicileChangeVO domicileChange;
        List<DomicileChangeVO> domicileChangeVOList = new ArrayList<>();
        List<CuSelfServiceLogExt> cuSelfServiceLogs = baseMapper.selectSelfServiceByPkMember(domicileChangeVO);
        if (CollUtil.isNotEmpty(cuSelfServiceLogs)) {
            for (CuSelfServiceLogExt selfServiceLog : cuSelfServiceLogs) {
                domicileChange = chargeDomicileChangeVO(selfServiceLog);
                domicileChangeVOList.add(domicileChange);
            }
        }
        return new Object[]{cuSelfServiceLogs, domicileChangeVOList};
    }

    @Override
    public Integer showIndexDomicile(Integer pkCountry, Long pkMember) {
        QueryWrapper<CuSelfServiceLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_MEMBER", pkMember);
        queryWrapper.eq("PK_COUNTRY", pkCountry);
        queryWrapper.eq("EDIT_TYPE", EApprovalBusiness.DOMICILE_CHANGE.getValue());
        queryWrapper.eq("APPROVE_STATUS", EApproveRechargeStatus.AGREE.getValue());
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0 ? EYesNo.NO.getIntValue() : EYesNo.YES.getIntValue();
    }

    @Override
    public DomicileChangeVO selectDomicileChangeDetail(Long pkId) {
        CuSelfServiceLogExt cuSelfServiceLogExt = baseMapper.selectDomicileChangeDetail(pkId);
        return chargeDomicileChangeVO(cuSelfServiceLogExt);

    }


    @Override
    public DomicileChangeVO selectDomicileChangeByPkMember(Long pkMember, Integer editType, Integer pkCountry) {
        CuSelfServiceLogExt cuSelfServiceLogExt = baseMapper.selectDomicileChangeByPkMember(editType, pkMember, pkCountry);
        return chargeDomicileChangeVO(cuSelfServiceLogExt);

    }


    /**
     * 转化户籍VO
     *
     * @param selfServiceLog 自助信息
     * @return DomicileChangeVO
     */
    private DomicileChangeVO chargeDomicileChangeVO(CuSelfServiceLogExt selfServiceLog) {
        DomicileChangeVO oldValue = JSONUtil.toBean(selfServiceLog.getOldValue(), DomicileChangeVO.class);
        DomicileChangeVO newValue = JSONUtil.toBean(selfServiceLog.getNewValue(), DomicileChangeVO.class);
        return DomicileChangeVO.builder()
                .memberCode(selfServiceLog.getMemberCode()).pkId(selfServiceLog.getPkId()).businessNo(selfServiceLog.getBusinessNo())
                .memberName(oldValue.getMemberName()).phone(oldValue.getPhone()).idFront(oldValue.getIdFront()).pkMember(selfServiceLog.getPkMember())
                .idBack(oldValue.getIdBack()).changeMemberName(newValue.getChangeMemberName()).description(selfServiceLog.getDescription())
                .changePhone(newValue.getChangePhone()).changeIdBack(newValue.getChangeIdBack()).pkAccount(selfServiceLog.getPkAccount())
                .changeIdFront(newValue.getChangeIdFront()).amount(selfServiceLog.getSingleAmount())
                .creationTime(selfServiceLog.getCreationTime()).approveStatus(selfServiceLog.getApproveStatus())
                .rejectMsg(selfServiceLog.getRejectMsg())
                .approveTime(selfServiceLog.getApproveTime())
                .remark(selfServiceLog.getSelfRemark()).build();

    }

    @Override
    public CuSelfServiceLog selectSelfServiceByBusinessNo(Integer editType, String businessNo) {
        return baseMapper.selectSelfServiceByBusinessNo(editType, businessNo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer domicileChangeApproved(ApprovalBusinessResultDTO approvalBusinessResultDTO, CuSelfServiceLog selfServiceLog) {
        Long pkMember = selfServiceLog.getPkMember();
        Long pkModified = approvalBusinessResultDTO.getLoginUser().getUserId();
        DomicileChangeVO domicileChangeVO = JSONUtil.toBean(selfServiceLog.getNewValue(), DomicileChangeVO.class);
        //更新业务
        cuMemberService.updateMemberNameAndPhone(pkMember, domicileChangeVO.getChangeMemberName(), domicileChangeVO.getChangePhone(), pkModified);
        //注销实名认证、营业执照
        changeBusinessByChangeName(pkMember, pkModified);
        //重置银行卡
        BusinessMemberVO businessMemberVO = BusinessMemberVO.builder().pkMember(pkMember).build();
        cuMemberBankService.batchUpdateBankBypkMembers(Collections.singletonList(businessMemberVO), pkModified);
        //修改会员的变更次数
        List<Long> pkMembers = Collections.singletonList(businessMemberVO.getPkMember());
        cuMemberService.updateMemberEditNumber(pkMembers, pkModified);
        //更新状态
        return updateApprovalStatus(approvalBusinessResultDTO, pkModified);
    }

    /**
     * 更新姓名删除相关实名操作
     *
     * @param pkMember   会员ID
     * @param pkModified 更新人信息
     * @return Boolean
     */
    private void changeBusinessByChangeName(Long pkMember, Long pkModified) {
        List<Long> pkMembers = Collections.singletonList(pkMember);
        //更新实名认证
        Boolean auth = cuMemberAuthenticationService.deleteByPkMembers(pkMembers, pkModified);
        //更新会员是否实名
        if (auth) {
            cuMemberService.updateMemberStatusByPkIds(pkMembers, pkModified, EAuthType.REAL_NAME.getValue());
        }
        //更新营业执照
        Boolean license = cuMemberBusinessLicenseService.updateMemberLicenseByPkMembers(pkMembers, pkModified);
        //更新会员是否营业执照
        if (license) {
            cuMemberService.updateMemberStatusByPkIds(pkMembers, pkModified, EAuthType.BUS_LICENSE.getValue());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer domicileChangeReject(ApprovalBusinessResultDTO approvalBusinessResultDTO, CuSelfServiceLog selfServiceLog) {
        Long userId = approvalBusinessResultDTO.getLoginUser().getUserId();
        //扣费横冲
        EApprovalBusiness eApprovalBusiness = approvalBusinessResultDTO.getEApprovalBusiness();
        String businessCode = approvalBusinessResultDTO.getBusinessCode();
        BusinessCommissionDTO businessCommissionDTO = BusinessCommissionDTO.builder().tradeType(eApprovalBusiness.getValue())
                .tradeCode(businessCode).pkCountry(selfServiceLog.getPkCountry())
                .pkCreator(userId).build();
        cuMemberTradeService.businessCommissionReject(businessCommissionDTO);
        //更新状态
        return updateApprovalStatus(approvalBusinessResultDTO, userId);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean domicileChangeRejectById(DomicileChangeVO domicileChangeVO, Long pkMember) {
        UpdateWrapper<CuSelfServiceLog> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, pkMember);
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, new Date());
        updateWrapper.set("approve_status", EApproveRechargeStatus.REJECT.getValue());
        updateWrapper.set("approve_time", new Date());
        updateWrapper.set("REJECT_MSG", domicileChangeVO.getRejectMsg());
        updateWrapper.eq("PK_ID", domicileChangeVO.getPkId());
        //更新状态
        update(updateWrapper);
        CuSelfServiceLog selfServiceLog = baseMapper.selectById(domicileChangeVO.getPkId());
        //扣费横冲
        BusinessCommissionDTO businessCommissionDTO = BusinessCommissionDTO.builder().tradeType(selfServiceLog.getEditType())
                .tradeCode(selfServiceLog.getBusinessNo()).pkCountry(selfServiceLog.getPkCountry())
                .pkCreator(pkMember).build();
        Boolean result = cuMemberTradeService.businessCommissionReject(businessCommissionDTO);
        // MQ户籍变更操作日志
        packageDomicileOperationLog(selfServiceLog, selfServiceLog.getBusinessNo(), "驳回", pkMember, true);
        return result;
    }

    /**
     * 更新审核状态
     *
     * @param approvalBusinessResultDTO 审核参数
     * @param pkModified                修改人ID
     * @return Integer
     */
    public Integer updateApprovalStatus(ApprovalBusinessResultDTO approvalBusinessResultDTO, Long pkModified) {
        DomicileChangeVO domicileChange = DomicileChangeVO.builder().businessNo(approvalBusinessResultDTO.getBusinessCode())
                .approveStatus(approvalBusinessResultDTO.getApproveOperation() + 1).approveTime(new Date())
                .pkModified(pkModified).build();
        return baseMapper.updateSelfServiceByBusinessNo(domicileChange);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean selfExamine(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        Integer pkCountry = approvalBusinessResultDTO.getLoginUser().getDataCountry();
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();
        SelfModifyAddressVO csv = SelfModifyAddressVO.builder()
                .businessNo(approvalBusinessResultDTO.getBusinessCode())
                .approveStatus(EApproveRechargeStatus.WAIT.getValue())
                .pkCountry(pkCountry)
                .build();
        List<SelfModifyAddressVO> slList = querySelfModifyAddressList(csv);
        SelfModifyAddressVO csso = JSONObject.parseObject(slList.get(0).getNewValue(), SelfModifyAddressVO.class);
        UpdateWrapper<CuSelfServiceLog> updateWrapper = new UpdateWrapper<>();
        //审核通过
        if (approvalBusinessResultDTO.getApproveOperation() == EApproveOperation.AGREE.getValue()) {
            List<Long> orderIdList = new ArrayList<>();
            orderIdList.add(slList.get(0).getPkId());
            SaOrder so = new SaOrder();
            R<List<SaOrderExt>> saOrder = iSaOrderServiceApi.queryOrderListByIdList(orderIdList, pkCountry);
            if (CollectionUtil.isNotEmpty(saOrder.getData())) {
                so = BeanUtil.copyProperties(saOrder.getData().get(0), SaOrder.class);
            }
            CuMemberAccount cma = iCuMemberAccountService.queryCuMemberAccountByPkMember(slList.get(0).getPkMember());
//            if (StringUtils.isNotNull(so) && StringUtils.isNotNull(cma)) {
//                //撤销订单，回退给创建人金额
//                iCuMemberBusinessService.selfCancelAnOrder(approvalBusinessResultDTO.getSysUser().getUserId(), so, cma);
//            }
            //修改订单相关信息
            so.setPostage(csso.getNewPostage());
            so.setRecName(csso.getNewRecName());
            so.setRecPhone(csso.getNewRecPhone());
            so.setRecProvince(csso.getNewRecProvince());
            so.setRecCity(csso.getNewRecCity());
            so.setRecCounty(csso.getNewRecCounty());
            so.setRecAddress(csso.getNewRecAddress());
            //订单扣费
            iCuMemberBusinessService.selfInsertMemberTrade(so, cma);
            //修改订单的收货地址
            iSaOrderServiceApi.updateOrder(so);
            updateWrapper.set("APPROVE_STATUS", EApproveRechargeStatus.AGREE.getValue());
        }
        //审核驳回
        if (approvalBusinessResultDTO.getApproveOperation() == EApproveOperation.REJECT.getValue()) {
            //退款
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(pkCountry);
            businessCommissionDTO.setTradeCode(approvalBusinessResultDTO.getBusinessCode());
            businessCommissionDTO.setPkAccount(csso.getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(csso.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue());
            Boolean b = cuMemberTradeService.businessCommissionReject(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY);
            }
            updateWrapper.set("APPROVE_STATUS", EApproveRechargeStatus.REJECT.getValue());
        }
        //修改日志状态
        updateWrapper.set("MODIFIED_TIME", date);
        updateWrapper.set("PK_MODIFIED", userID);
        updateWrapper.eq("BUSINESS_NO", slList.get(0).getBusinessNo());
        baseMapper.update(null, updateWrapper);
        return true;
    }

    @Override
    public List<MyOrderItemsVO> queryListByOrderId(List<Long> orderIdList) {
        return baseMapper.queryListByOrderId(orderIdList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean firstInstance(List<SelfModifyAddressVO> selList) {
        for (SelfModifyAddressVO selVO : selList) {
            CuSelfServiceLog serviceLog = BeanUtil.copyProperties(selVO, CuSelfServiceLog.class);
            if (selVO.getApproveOperation() == EApproveOperation.AGREE.getValue()) {
                serviceLog.setApproveStatus(EApproveRechargeStatus.WAIT.getValue());
                //生成签呈
                ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.SELF_MODIFY_ADDRESS)
                        .businessCode(serviceLog.getBusinessNo())
                        .remark(selVO.getRemark())
                        .signType(ESignType.getEnumByValue(selVO.getSignType()))
                        .userIdList(selVO.getUserIdList())
                        .signSource(ESignSource.MEMBER)
                        .sendIdList(selVO.getSendIdList())
                        .build();
                R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, selVO.getLoginUser());
                if (!submit.isSuccess()) {
                    log.error("====" + submit.getData());
                    throw new RuntimeException(ConfigMsgConstants.SELF_MODIFY_ADDRESS);
                }
                //扣钱
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setPkCountry(selVO.getPkCountry());
                businessCommissionDTO.setTradeCode(selVO.getBusinessNo());
                businessCommissionDTO.setPkAccount(selVO.getPkAccount());
                businessCommissionDTO.setMemberAmountDTOList(selVO.getMemberAmountDTOList());
                businessCommissionDTO.setTradeType(EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue());
                Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
                if (!b) {
                    throw new ServiceException(ConfigMsgConstants.SELF_MODIFY_ADDRESS);
                }

            } else if (selVO.getApproveOperation() == EApproveOperation.REJECT.getValue()) {
                serviceLog.setApproveStatus(EApproveRechargeStatus.REJECT.getValue());
                serviceLog.setRejectMsg(selVO.getRejectMsg());
            }
            baseMapper.updateById(serviceLog);
        }
        return true;
    }

    @Override
    public Integer showHiddenAddress(Long pkMember, Integer pkCountry) {
        Integer count = baseMapper.showHiddenAddressList(pkMember, pkCountry);
        if (count > 0) {
            return EYesNo.YES.getIntValue();
        } else {
            return EYesNo.NO.getIntValue();
        }
    }


}
