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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.member.account.CuMemberBusinessLicense;
import com.hzs.common.domain.member.account.CuMemberBusinessLicenseExt;
import com.hzs.member.account.mapper.CuMemberBusinessLicenseMapper;
import com.hzs.member.account.service.ICuMemberBusinessLicenseService;
import com.hzs.member.account.vo.CuMemberBusinessLicenseVO;
import com.hzs.system.sys.IApprovalServiceApi;
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 CuMemberBusinessLicenseServiceImpl extends ServiceImpl<CuMemberBusinessLicenseMapper, CuMemberBusinessLicense> implements ICuMemberBusinessLicenseService {

    @DubboReference
    IApprovalServiceApi iApprovalServiceApi;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public CuMemberBusinessLicenseVO selectBusinessLicenseById(Long pkMember, Integer pkCountry) {
        return BeanUtil.copyProperties(baseMapper.selectBusinessLicenseById(pkMember, pkCountry), CuMemberBusinessLicenseVO.class);
    }

    @Override
    public Integer isExistBusinessLicense(Long pkMember, Integer pkCountry) {
        return baseMapper.isExistBusinessLicense(pkMember, pkCountry);
    }

    @Override
    public Object[] selectLicenseList(CuMemberBusinessLicenseVO licenseVO) {
        List<CuMemberBusinessLicenseExt> cuMemberBusinessLicenseExts = baseMapper.selectLicenseList(licenseVO);
        List<CuMemberBusinessLicenseVO> memberBusinessLicenseVOList = BeanUtil.copyToList(cuMemberBusinessLicenseExts, CuMemberBusinessLicenseVO.class);
        if (CollectionUtil.isNotEmpty(memberBusinessLicenseVOList)) {
            for (CuMemberBusinessLicenseVO cuMemberBusinessLicenseVO : memberBusinessLicenseVOList) {
                if (StringUtils.isNotEmpty(cuMemberBusinessLicenseVO.getParentChief())) {
                    // 处理所属总监
                    String tmpChief = cuMemberBusinessLicenseVO.getParentChief().split(",")[0];
                    if (StringUtils.isNotEmpty(tmpChief)) {
                        cuMemberBusinessLicenseVO.setParentChief(tmpChief.split("-")[0]);
                        cuMemberBusinessLicenseVO.setParentChiefName(tmpChief.split("-")[1]);
                    }
                }
            }
        }
        return new Object[]{cuMemberBusinessLicenseExts, memberBusinessLicenseVOList};
    }

    @Override
    public Integer updateLicenseByBusinessNo(CuMemberBusinessLicenseVO licenseVO) {
        return baseMapper.updateLicenseByBusinessNo(licenseVO);
    }

    @Override
    public Integer deleteLicense(CuMemberBusinessLicenseVO licenseVO) {
        CuMemberBusinessLicense cbl = BeanUtil.copyProperties(licenseVO, CuMemberBusinessLicense.class);
        LambdaUpdateWrapper<CuMemberBusinessLicense> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CuMemberBusinessLicense::getBusinessNo, cbl.getBusinessNo());
        updateWrapper.set(CuMemberBusinessLicense::getDelFlag, EDelFlag.DELETE.getValue());
        updateWrapper.set(CuMemberBusinessLicense::getApproveStatus, EApproveStatus.FINISH.getValue());
        updateWrapper.set(CuMemberBusinessLicense::getModifiedTime, new Date());
        updateWrapper.set(CuMemberBusinessLicense::getPkModified, licenseVO.getPkModified());
        return baseMapper.update(null, updateWrapper);
    }

    @Override
    public Integer rejectResetLicense(CuMemberBusinessLicenseVO licenseVO) {
        CuMemberBusinessLicense cbl = BeanUtil.copyProperties(licenseVO, CuMemberBusinessLicense.class);
        LambdaUpdateWrapper<CuMemberBusinessLicense> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CuMemberBusinessLicense::getBusinessNo, cbl.getBusinessNo());
        updateWrapper.set(CuMemberBusinessLicense::getApproveStatus, EApproveStatus.FINISH.getValue());
        updateWrapper.set(CuMemberBusinessLicense::getModifiedTime, new Date());
        updateWrapper.set(CuMemberBusinessLicense::getPkModified, licenseVO.getPkModified());
        return baseMapper.update(null, updateWrapper);
    }

    @Override
    public Boolean rejectById(CuMemberBusinessLicenseVO cmb, Long pkMember) {
        LambdaUpdateWrapper<CuMemberBusinessLicense> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CuMemberBusinessLicense::getPkModified, pkMember);
        updateWrapper.set(CuMemberBusinessLicense::getModifiedTime, new Date());
        updateWrapper.set(CuMemberBusinessLicense::getApproveStatus, EApproveStatus.REJECTED.getValue());
        updateWrapper.set(CuMemberBusinessLicense::getApproveTime, new Date());
        updateWrapper.set(CuMemberBusinessLicense::getRejectMsg, cmb.getRejectMsg());
        updateWrapper.eq(CuMemberBusinessLicense::getPkId, cmb.getPkId());
        return update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer licenseAgree(CuMemberBusinessLicenseVO licenseVO, CuMemberBusinessLicenseVO license) {
        String businessNo = CommonUtil.createSerialNumber(EOrderPrefix.BUSINESS_LICENSE.getValue());
        //更新审核状态
        CuMemberBusinessLicense memberBusinessLicense = CuMemberBusinessLicense.builder().businessNo(businessNo)
                .approveStatus(EApproveStatus.APPROVE.getValue())
                .approveTime(new Date()).pkId(licenseVO.getPkId()).build();
        memberBusinessLicense.setPkModified(licenseVO.getPkModified());
        memberBusinessLicense.setModifiedTime(new Date());
        Integer result = baseMapper.updateById(memberBusinessLicense);

        //调用审批接口，修改审批状态
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.BUSINESS_LICENSE)
                .businessCode(businessNo).signSource(ESignSource.MANAGE)
                .signType(ESignType.GENERAL).userIdList(licenseVO.getUserIdList()).businessData(JSONUtil.toJsonStr(license))
                .remark(licenseVO.getRemark()).pkMemberList(Collections.singleton(licenseVO.getPkMember()))
                .sendIdList(licenseVO.getSendIdList())
                .build();
        R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, licenseVO.getLoginUser());
        if (!submit.isSuccess()) {
            throw new RuntimeException(submit.getMsg());
        }
        // 封装修改结算国业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        CuMemberBusinessLicenseVO licenseDetail = this.selectLicenseDetail(licenseVO.getPkId());
        //组装日志数据
        BusinessLogDTO businessLog = BusinessLogDTO.builder()
                .businessType(EApprovalBusiness.BUSINESS_LICENSE.getValue())
                .businessCode(businessNo)
                .pkMember(licenseVO.getPkMember())
                .content(EApprovalBusiness.BUSINESS_LICENSE.getLabel() +
                        "审核通过：营业执照名称 " + licenseDetail.getLicenseName() + " 统一社会信用代码 : " + licenseDetail.getCreditCode() +
                        " 法人姓名 :" + licenseDetail.getLegalName())
                .pkCreator(licenseVO.getPkModified())
                .pkCountry(licenseVO.getPkCountry())
                .freeSignFlag(false).build();
        dtoList.add(businessLog);
        //发送MQ到操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                dtoList);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer resettingLicense(CuMemberBusinessLicenseVO licenseVO, CuMemberBusinessLicenseVO license) {
        String businessNo = CommonUtil.createSerialNumber(EOrderPrefix.BUSINESS_LICENSE.getValue());
        //更新审核状态
        CuMemberBusinessLicense memberBusinessLicense = CuMemberBusinessLicense.builder().businessNo(businessNo)
                .approveStatus(EApproveStatus.APPROVE.getValue())
                .approveTime(new Date()).pkId(licenseVO.getPkId()).build();
        memberBusinessLicense.setPkModified(licenseVO.getPkModified());
        memberBusinessLicense.setModifiedTime(new Date());
        Integer result = baseMapper.updateById(memberBusinessLicense);

        //调用审批接口，修改审批状态
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.BUSINESS_LICENSE_RESETTING)
                .businessCode(businessNo).signSource(ESignSource.MANAGE)
                .signType(ESignType.GENERAL).userIdList(licenseVO.getUserIdList()).businessData(JSONUtil.toJsonStr(license))
                .remark(licenseVO.getRemark()).pkMemberList(Collections.singleton(licenseVO.getPkMember()))
                .sendIdList(licenseVO.getSendIdList())
                .build();
        R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, licenseVO.getLoginUser());
        if (!submit.isSuccess()) {
            throw new RuntimeException(submit.getMsg());
        }

        // 封装修改结算国业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        CuMemberBusinessLicenseVO licenseDetail = this.selectLicenseDetail(licenseVO.getPkId());
        //组装日志数据
        BusinessLogDTO businessLog = BusinessLogDTO.builder()
                .businessType(EApprovalBusiness.BUSINESS_LICENSE_RESETTING.getValue())
                .businessCode(businessNo)
                .pkMember(licenseVO.getPkMember())
                .content(EApprovalBusiness.BUSINESS_LICENSE_RESETTING.getLabel() +
                        "：重置前营业执照名称 " + licenseDetail.getLicenseName() + " 重置前统一社会信用代码 : " + licenseDetail.getCreditCode() +
                        " 重置前法人姓名 :" + licenseDetail.getLegalName())
                .pkCreator(licenseVO.getPkModified())
                .pkCountry(licenseVO.getPkCountry())
                .freeSignFlag(false).build();
        dtoList.add(businessLog);
        //发送MQ到操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                dtoList);
        return result;
    }

    @Override
    public CuMemberBusinessLicense selectLicenseByBusinessNo(String businessNo) {
        LambdaQueryWrapper<CuMemberBusinessLicense> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberBusinessLicense::getBusinessNo, businessNo);
        return getOne(queryWrapper);
    }


    @Override
    public CuMemberBusinessLicenseVO selectLicenseDetail(Long pkId) {
        return BeanUtil.copyProperties(baseMapper.selectLicenseDetail(pkId), CuMemberBusinessLicenseVO.class);
    }


    @Override
    public Boolean updateMemberLicenseByPkMembers(List<Long> pkMembers, Long updatePkMember) {
        LambdaUpdateWrapper<CuMemberBusinessLicense> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(CuMemberBusinessLicense::getPkMember, pkMembers);
        updateWrapper.set(CuMemberBusinessLicense::getDelFlag, EDelFlag.DELETE.getValue());
        updateWrapper.set(CuMemberBusinessLicense::getPkModified, updatePkMember);
        updateWrapper.set(CuMemberBusinessLicense::getModifiedTime, new Date());
        return this.update(updateWrapper);
    }
}
