package com.hzs.system.config.controller.manage;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.HttpStatus;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.constant.msg.FinanceMsgConstants;
import com.hzs.common.core.enums.EAgreementWhiteType;
import com.hzs.common.core.enums.EOperationBusiness;
import com.hzs.common.core.enums.EOperationMethod;
import com.hzs.common.core.enums.EOperationModule;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.system.config.BdAgreementRenewalWhite;
import com.hzs.common.domain.system.config.ext.BdAgreementRenewalWhiteExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.system.config.service.IBdAgreementRenewalWhiteService;
import com.hzs.system.config.vo.BdAgreementRenewalWhiteVO;
import com.hzs.system.config.vo.TemplateAgreementVO;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 协议续约白名单 前端控制器
 * </p>
 *
 * @author hzs
 * @since 2024-01-12
 */
@Slf4j
@RestController
@RequestMapping("/manage/renewal-white")
public class BdAgreementRenewalWhiteController extends BaseController {

    @DubboReference
    private IMemberServiceApi iMemberServiceApi;

    @Autowired
    IBdAgreementRenewalWhiteService agreementRenewalWhiteService;

    @Autowired
    ITransactionCommonService iTransactionCommonService;


    /**
     * 保存协议续约白名单
     *
     * @param agreementRenewalWhiteVO 入参
     * @return AjaxResult
     */
    @Log(module = EOperationModule.TRADE_CONFIG, business = EOperationBusiness.AGREEMENT_RENEWAL_WHITE, method = EOperationMethod.INSERT)
    @PostMapping("/add")
    public AjaxResult addAgreementRenewalWhite(@RequestBody BdAgreementRenewalWhiteVO agreementRenewalWhiteVO) {
        String memberCode = agreementRenewalWhiteVO.getMemberCode();
        CuMember cumember = iMemberServiceApi.getMember(memberCode).getData();

        AjaxResult ajaxResult = parametersVerify(agreementRenewalWhiteVO, cumember);
        if ((Integer) ajaxResult.get(AjaxResult.CODE_TAG) == HttpStatus.ERROR) {
            return ajaxResult;
        }
        Integer type = agreementRenewalWhiteVO.getType();
        BdAgreementRenewalWhite agreementRenewalWhite;
        if(type.equals(EAgreementWhiteType.AUTO_RENEW.getValue())){
            agreementRenewalWhite = agreementRenewalWhiteService.selectByPkMember(cumember.getPkId()).get(0);
        }else {
            agreementRenewalWhite = agreementRenewalWhiteService.selectByPkMemberAndType(cumember.getPkId(), type);
        }

        if (null != agreementRenewalWhite) {
            return AjaxResult.error(ConfigMsgConstants.MEMBER_EXIST);
        }

        agreementRenewalWhiteVO.setPkCreator(SecurityUtils.getUserId());
        agreementRenewalWhiteVO.setPkMember(cumember.getPkId());
        agreementRenewalWhiteVO.setPkCountry(SecurityUtils.getPkCountry());
        agreementRenewalWhiteVO.setType(type);
        return toAjax(agreementRenewalWhiteService.save(BeanUtil.copyProperties(agreementRenewalWhiteVO, BdAgreementRenewalWhite.class)));
    }


    /**
     * 协议续约白名单列表显示
     *
     * @param agreementRenewalWhiteVO 入参
     * @return AjaxResult
     */
    @Log(module = EOperationModule.TRADE_CONFIG, business = EOperationBusiness.AGREEMENT_RENEWAL_WHITE, method = EOperationMethod.SELECT)
    @PostMapping("/list")
    public TableDataInfo showAgreementRenewalWhiteList(@RequestBody BdAgreementRenewalWhiteVO agreementRenewalWhiteVO) {
        getBdAgreementRenewalWhiteVO(agreementRenewalWhiteVO);
        startPage();
        Object[] objects = agreementRenewalWhiteService.selectWhiteList(agreementRenewalWhiteVO);
        TableDataInfo tableDataInfo = getDataTable((List<BdAgreementRenewalWhiteExt>) objects[0]);
        tableDataInfo.setRows((List<BdAgreementRenewalWhiteVO>) objects[1]);
        return tableDataInfo;
    }


    /**
     * 获取协议续约白名单
     *
     * @param agreementRenewalWhiteVO 入参
     * @return BdAgreementRenewalWhiteVO
     */
    private BdAgreementRenewalWhiteVO getBdAgreementRenewalWhiteVO(BdAgreementRenewalWhiteVO agreementRenewalWhiteVO) {
        agreementRenewalWhiteVO.setPkCountry(SecurityUtils.getPkCountry());
        String memberCode = agreementRenewalWhiteVO.getMemberCode();
        agreementRenewalWhiteVO.setMemberCode(memberCode);
        return agreementRenewalWhiteVO;
    }

    /**
     * 协议续约白名单导出
     *
     * @param response                响应
     * @param agreementRenewalWhiteVO 查询入参
     */
    @Log(module = EOperationModule.TRADE_CONFIG, business = EOperationBusiness.AGREEMENT_RENEWAL_WHITE, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void agreementRenewalWhiteExport(HttpServletResponse response, BdAgreementRenewalWhiteVO agreementRenewalWhiteVO) {
        getBdAgreementRenewalWhiteVO(agreementRenewalWhiteVO);
        List<BdAgreementRenewalWhiteVO> agreementRenewalWhiteVOList = (List<BdAgreementRenewalWhiteVO>) agreementRenewalWhiteService.selectWhiteList(agreementRenewalWhiteVO)[1];
        //多语言翻译
        if (CollUtil.isNotEmpty(agreementRenewalWhiteVOList)) {
            //枚举翻译
            Map<Integer, String> transactionMap = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_AWARD);
            for (BdAgreementRenewalWhiteVO configVO : agreementRenewalWhiteVOList) {
                configVO.setPkAwardsVal(transactionMap.get(configVO.getPkAwards()));
            }
        }
        ExcelUtil<BdAgreementRenewalWhiteVO> util = new ExcelUtil<>(BdAgreementRenewalWhiteVO.class);
        util.exportExcel(response, agreementRenewalWhiteVOList, "续约白名单");
    }

    /**
     * 删除交易白名单配置
     *
     * @param pkId 主键ID
     * @return AjaxResult
     */
    @Log(module = EOperationModule.TRADE_CONFIG, business = EOperationBusiness.AGREEMENT_RENEWAL_WHITE, method = EOperationMethod.DELETE)
    @GetMapping("/delete")
    public AjaxResult deleteWhite(String pkId) {
        if (StringUtils.isEmpty(pkId)) {
            return AjaxResult.error(ConfigMsgConstants.DELETE_INFO);
        }
        return toAjax(agreementRenewalWhiteService.deleteAgreementRenewalWhite(pkId, SecurityUtils.getUserId()));

    }


    /**
     * 下载模板
     *
     * @return
     */
    @PostMapping("/download-agreement-template")
    @Log(module = EOperationModule.TRADE_CONFIG, business = EOperationBusiness.AGREEMENT_RENEWAL_WHITE, method = EOperationMethod.EXPORT, remark = "下载模板")
    public void downloadAgreementTemplate(HttpServletResponse response) {
        ExcelUtil<TemplateAgreementVO> util = new ExcelUtil<>(TemplateAgreementVO.class);
        util.exportExcel(response, null, FinanceMsgConstants.MEMBER_AGREEMENT_TEMPLATE);
    }


    /**
     * 批量导入会员信息
     *
     * @param file 文件
     * @return AjaxResult
     * @throws Exception
     */
    @PostMapping("/import-agreement")
    @Log(module = EOperationModule.TRADE_CONFIG, business = EOperationBusiness.AGREEMENT_RENEWAL_WHITE, method = EOperationMethod.IMPORT)
    public AjaxResult importAgreementMemberCode(MultipartFile file) throws Exception {
        BdAgreementRenewalWhite white = null;
        List<BdAgreementRenewalWhite> whiteList = new ArrayList<>();
        Integer pkCountry = SecurityUtils.getPkCountry();
        ExcelUtil<TemplateAgreementVO> util = new ExcelUtil<>(TemplateAgreementVO.class);
        List<TemplateAgreementVO> templateAgreementVOList = util.importExcel(file.getInputStream(), 0);
        if (CollUtil.isEmpty(templateAgreementVOList)) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.RECHAGER_IMPORT_DATA_ERROR));
        }
        //导入数据去重
        List<String> memberCodeList = templateAgreementVOList.stream().map(TemplateAgreementVO::getMemberCode).distinct().collect(Collectors.toList());
        //导入数据有重复
        if (memberCodeList.size() != templateAgreementVOList.size()) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.IMPORT_TABLE_DATA_REPEAT));
        }
        //查询会员信息
        List<CuMember> cuMemberList = iMemberServiceApi.findMemberByMemberCodeList(memberCodeList, pkCountry).getData();
        if (templateAgreementVOList.size() != cuMemberList.size()) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.IMPORT_MEMBER_ERROR));
        }

        //会员续约表中是否存在导入的数据
        List<Long> memberPkIds = cuMemberList.stream().map(CuMember::getPkId).distinct().collect(Collectors.toList());
        Integer num = agreementRenewalWhiteService.isIncludeMemberId(memberPkIds, pkCountry);
        if (num > 0) {
            return AjaxResult.error(FinanceMsgConstants.IMPORT_TABLE_DATA_ERROR);
        }

        Map<String, Long> memberMap = cuMemberList.stream().collect(Collectors.toMap(CuMember::getMemberCode, CuMember::getPkId));
        for (TemplateAgreementVO templateVO : templateAgreementVOList) {
            if (StringUtils.isEmpty(templateVO.getMemberCode())) {
                return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.IMPORT_MEMBER_NOT_EMPTY));
            }
            white = new BdAgreementRenewalWhite();
            white.setPkMember(memberMap.get(templateVO.getMemberCode()));
            white.setPkCountry(pkCountry);
            white.setPkCreator(SecurityUtils.getUserId());
            whiteList.add(white);
        }
        return AjaxResult.success(agreementRenewalWhiteService.saveBatch(whiteList));
    }

    /**
     * 公共参数校验
     *
     * @param agreementRenewalWhiteVO 入参
     * @return AjaxResult
     */
    private AjaxResult parametersVerify(BdAgreementRenewalWhiteVO agreementRenewalWhiteVO, CuMember cumember) {
        if (StringUtils.isEmpty(agreementRenewalWhiteVO.getMemberCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_EMPTY));
        }

        if (null == cumember) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_EXIST));
        }

        return AjaxResult.success();
    }


}
