package com.hzs.member.account.controller.manage;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.hzs.common.core.annotation.ColumnAuthority;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
import com.hzs.common.core.constant.msg.FinanceMsgConstants;
import com.hzs.common.core.constant.msg.NoticeMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.TransactionUtils;
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.account.CuMemberRechargeMatch;
import com.hzs.common.domain.member.account.CuMemberRechargeMatchExt;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.member.account.service.ICuMemberRechargeMatchService;
import com.hzs.member.account.vo.CuMemberRechargeMatchVO;

import com.hzs.member.account.vo.RechargeBatchTemplateVO;

import com.hzs.member.base.service.ICuMemberService;
import org.apache.commons.validator.GenericValidator;
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.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**
 * <p>
 * 充值匹配 前端控制器
 * </p>
 *
 * @author hzs
 * @since 2024-04-17
 */
@RestController
@RequestMapping("/manager/recharge/match")
public class CuMemberRechargeMatchController extends BaseController {

    @Autowired
    private ICuMemberRechargeMatchService memberRechargeMatchService;

    @Autowired
    ICuMemberService cuMemberService;


    @Autowired
    ITransactionCommonService iTransactionCommonService;


    /**
     * 下载模板
     *
     * @return
     */
    @PostMapping("/download-match-template")
    @Log(module = EOperationModule.RECHARGE_MATCH, business = EOperationBusiness.RECHARGE_MATCH, method = EOperationMethod.EXPORT, remark = "下载模板")
    public void downloadMatchTemplate(HttpServletResponse response) {
        ExcelUtil<RechargeBatchTemplateVO> util = new ExcelUtil<>(RechargeBatchTemplateVO.class);
        util.exportExcel(response, null, TransactionUtils.getContent(FinanceMsgConstants.RECHARGE_MATCH_TEMPLATE));
    }


    /**
     * 批量导入汇款信息
     *
     * @param file 文件
     * @return AjaxResult
     * @throws Exception
     */
    @PostMapping("/import-remittance")
    @Log(module = EOperationModule.RECHARGE_MATCH, business = EOperationBusiness.RECHARGE_MATCH, method = EOperationMethod.IMPORT)
    public AjaxResult importRemittance(MultipartFile file) throws Exception {
        Integer pkCountry = SecurityUtils.getPkCountry();
        CuMemberRechargeMatch cuMemberRechargeMatch;
        ExcelUtil<RechargeBatchTemplateVO> util = new ExcelUtil<>(RechargeBatchTemplateVO.class);
        List<RechargeBatchTemplateVO> rechargeBatchTemplateVOList = util.importExcel(file.getInputStream(), 0);
        if (CollUtil.isEmpty(rechargeBatchTemplateVOList)) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.RECHAGER_IMPORT_DATA_ERROR));
        }
        for (RechargeBatchTemplateVO templateVO : rechargeBatchTemplateVOList) {
            String remittanceDate = templateVO.getRemittanceDate();
            if (StringUtils.isEmpty(templateVO.getRemitter()) || null == templateVO.getRemittanceAmount() || StringUtils.isEmpty(remittanceDate) || null == templateVO.getVoucherNumber()) {
                return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
            }
            //校验日期格式
            if (!GenericValidator.isDate(remittanceDate, "dd/MM/yyyy", true)) {
                return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.RECHARGE_MATCH_DATE_ERROR));
            }
        }


        //导入数据去重
        List<RechargeBatchTemplateVO> dedupMatchVoList = rechargeBatchTemplateVOList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(Comparator.comparing(RechargeBatchTemplateVO::getRemitter)
                                .thenComparing(RechargeBatchTemplateVO::getRemittanceAmount)
                                .thenComparing(RechargeBatchTemplateVO::getRemittanceDate)
                                .thenComparing(RechargeBatchTemplateVO::getVoucherNumber)
                        )), ArrayList::new)
        );

        if (rechargeBatchTemplateVOList.size() != dedupMatchVoList.size()) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.IMPORT_REPEAT_INFO));
        }

        //查询重复的汇款信息
        List<CuMemberRechargeMatch> rePeatRechargeMatches = memberRechargeMatchService.selectRepeatRecord(rechargeBatchTemplateVOList, pkCountry);
        if (CollUtil.isNotEmpty(rePeatRechargeMatches)) {
            return AjaxResult.error(rePeatInfo(rePeatRechargeMatches) + TransactionUtils.getContent(FinanceMsgConstants.SUBMITTED_REPEAT_INFO));
        }
        List<CuMemberRechargeMatch> cuMemberRechargeMatches = new ArrayList<>();
        for (RechargeBatchTemplateVO batchTemplateVO : rechargeBatchTemplateVOList) {
            cuMemberRechargeMatch = BeanUtil.copyProperties(batchTemplateVO, CuMemberRechargeMatch.class, "remittanceDate");
            String memberCode = batchTemplateVO.getMemberCode();
            if (StringUtils.isNotEmpty(memberCode)) {
                CuMemberExt cuMember = cuMemberService.getMemberByCode(memberCode);
                if (null != cuMember) {
                    cuMemberRechargeMatch.setPkMember(cuMember.getPkId());
                }
            }
            cuMemberRechargeMatch.setRemittanceDate(DateUtils.parseDateOne(batchTemplateVO.getRemittanceDate(), "dd/MM/yyyy"));
            cuMemberRechargeMatch.setPkCreator(SecurityUtils.getUserId());
            cuMemberRechargeMatch.setPkCountry(pkCountry);
            cuMemberRechargeMatches.add(cuMemberRechargeMatch);
        }
        return toAjax(memberRechargeMatchService.saveBatch(cuMemberRechargeMatches));
    }


    /**
     * 查询列表
     *
     * @param rechargeMatchVO 入参
     * @return TableDataInfo
     */

    @Log(module = EOperationModule.RECHARGE_MATCH, business = EOperationBusiness.RECHARGE_MATCH, method = EOperationMethod.SELECT)
    @PostMapping("/list")
    public TableDataInfo findRechargeMatchList(@RequestBody CuMemberRechargeMatchVO rechargeMatchVO) {
        rechargeMatchVO.setPkCountry(SecurityUtils.getPkCountry());
        startPage();
        Object[] objects = memberRechargeMatchService.findRechargeMatchList(rechargeMatchVO);
        TableDataInfo tableDataInfo = getDataTable((List<CuMemberRechargeMatchExt>) objects[0]);
        tableDataInfo.setRows((List<CuMemberRechargeMatchVO>) objects[1]);
        return tableDataInfo;
    }


    /**
     * 列表导出
     *
     * @param response        响应
     * @param rechargeMatchVO 查询入参
     */
    @Log(module = EOperationModule.RECHARGE_MATCH, business = EOperationBusiness.RECHARGE_MATCH, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CuMemberRechargeMatchVO rechargeMatchVO) {
        rechargeMatchVO.setPkCountry(SecurityUtils.getPkCountry());
        List<CuMemberRechargeMatchVO> memberRechargeMatchVOList = (List<CuMemberRechargeMatchVO>) memberRechargeMatchService.findRechargeMatchList(rechargeMatchVO)[1];
        //多语言翻译
        if (CollUtil.isNotEmpty(memberRechargeMatchVOList)) {
            //枚举翻译
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(ERechargeStatus.values());
            for (CuMemberRechargeMatchVO memberRechargeMatchVO : memberRechargeMatchVOList) {
                memberRechargeMatchVO.setStatusVal(transactionMap.get(EnumsPrefixConstants.RECHARGE_STATUS + memberRechargeMatchVO.getStatus()));
            }
        }
        ExcelUtil<CuMemberRechargeMatchVO> util = new ExcelUtil<>(CuMemberRechargeMatchVO.class);
        util.exportExcel(response, memberRechargeMatchVOList, TransactionUtils.getContent(FinanceMsgConstants.RECHARGE_MATCH_EXPORT));
    }


    /**
     * 删除
     *
     * @return
     */
    @Log(module = EOperationModule.RECHARGE_MATCH, business = EOperationBusiness.RECHARGE_MATCH, method = EOperationMethod.DELETE)
    @GetMapping("/delete")
    public AjaxResult deleteRechargeMatchById(Long pkId) {
        return toAjax(memberRechargeMatchService.deleteRechargeMatchById(pkId, SecurityUtils.getUserId()));
    }

    /**
     * 拼接重复提醒信息
     *
     * @param rePeatRechargeMatches 查询重复信息
     * @return String
     */
    private String rePeatInfo(List<CuMemberRechargeMatch> rePeatRechargeMatches) {
        StringBuilder sb = new StringBuilder();
        for (CuMemberRechargeMatch cuMemberRechargeMatch : rePeatRechargeMatches) {
            sb.append(cuMemberRechargeMatch.getRemitter());
            sb.append(",");
            sb.append(cuMemberRechargeMatch.getRemittanceAmount());
            sb.append(",");
            sb.append(DateUtils.parseDateToStr("dd/MM/yyyy", cuMemberRechargeMatch.getRemittanceDate()));
            sb.append(",");
            if (0 != cuMemberRechargeMatch.getVoucherNumber()) {
                sb.append(cuMemberRechargeMatch.getVoucherNumber());
            }
            sb.append("   ");
        }
        return sb.toString();
    }

}
