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.CacheConstants;
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.enums.*;
import com.hzs.common.core.service.RedisService;
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.BdTradeWhiteConfig;
import com.hzs.common.domain.system.config.ext.BdTradeWhiteConfigExt;
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.IBdTradeWhiteConfigService;
import com.hzs.system.config.vo.BdTradeWhiteConfigVO;
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 javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 交易白名单配置表 前端控制器
 * </p>
 *
 * @author hzs
 * @since 2023-08-18
 */
@Slf4j
@RestController
@RequestMapping("/manage/trade-white")
public class BdTradeWhiteConfigController extends BaseController {

    @Autowired
    IBdTradeWhiteConfigService bdTradeWhiteConfigService;

    @DubboReference
    IMemberServiceApi iMemberServiceApi;

    @Autowired
    private RedisService redisService;

    @Autowired
    ITransactionCommonService iTransactionCommonService;

    /**
     * 保存交易配置白名单
     *
     * @param tradeWhiteConfigVO 入参
     * @return AjaxResult
     */
    @Log(module = EOperationModule.TRADE_CONFIG, business = EOperationBusiness.TRADE_WHITE_CONFIG, method = EOperationMethod.INSERT)
    @PostMapping("/add")
    public AjaxResult addTradeWhiteConfig(@RequestBody BdTradeWhiteConfigVO tradeWhiteConfigVO) {
        String memberCode = tradeWhiteConfigVO.getMemberCode();
        CuMember cumember = iMemberServiceApi.getMember(memberCode).getData();

        AjaxResult ajaxResult = parametersVerify(tradeWhiteConfigVO, cumember);
        if ((Integer) ajaxResult.get(AjaxResult.CODE_TAG) == HttpStatus.ERROR) {
            return ajaxResult;
        }
        BdTradeWhiteConfig tradeWhiteConfig = bdTradeWhiteConfigService.selectTradeWhiteConfigByPkMember(cumember.getPkId());
        if (null != tradeWhiteConfig) {
            return AjaxResult.error(ConfigMsgConstants.MEMBER_EXIST);
        }

        tradeWhiteConfigVO.setPkCreator(SecurityUtils.getUserId());
        tradeWhiteConfigVO.setPkMember(cumember.getPkId());
        tradeWhiteConfigVO.setPkCountry(SecurityUtils.getPkCountry());
        return toAjax(bdTradeWhiteConfigService.addTradeWhiteConfig(tradeWhiteConfigVO));
    }


    /**
     * 交易配置白名单列表显示
     *
     * @param tradeWhiteConfigVO 入参
     * @return AjaxResult
     */
    @Log(module = EOperationModule.TRADE_CONFIG, business = EOperationBusiness.TRADE_WHITE_CONFIG, method = EOperationMethod.SELECT)
    @PostMapping("/list")
    public TableDataInfo showTradeConfigList(@RequestBody BdTradeWhiteConfigVO tradeWhiteConfigVO) {
        tradeWhiteConfigVO.setPkCountry(SecurityUtils.getPkCountry());
        String memberCode = tradeWhiteConfigVO.getMemberCode();
        //转化会员编号为会员ID
        if (StringUtils.isNotEmpty(memberCode)) {
            CuMember cumember = iMemberServiceApi.getMember(memberCode).getData();
            Long pkMember = null != cumember ? cumember.getPkId() : null;
            tradeWhiteConfigVO.setPkMember(pkMember);
        }
        startPage();
        Object[] objects = bdTradeWhiteConfigService.showTradeWhiteConfigList(tradeWhiteConfigVO);
        TableDataInfo tableDataInfo = getDataTable((List<BdTradeWhiteConfigExt>) objects[0]);
        tableDataInfo.setRows((List<BdTradeWhiteConfigVO>) objects[1]);
        return tableDataInfo;
    }


    /**
     * 白名单导出
     *
     * @param response           响应
     * @param tradeWhiteConfigVO 查询入参
     */
    @Log(module = EOperationModule.TRADE_CONFIG, business = EOperationBusiness.TRADE_WHITE_CONFIG, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BdTradeWhiteConfigVO tradeWhiteConfigVO) {
        tradeWhiteConfigVO.setPkCountry(SecurityUtils.getPkCountry());
        String memberCode = tradeWhiteConfigVO.getMemberCode();
        //转化会员编号为会员ID
        if (StringUtils.isNotEmpty(memberCode)) {
            CuMember cumember = iMemberServiceApi.getMember(memberCode).getData();
            Long pkMember = null != cumember ? cumember.getPkId() : null;
            tradeWhiteConfigVO.setPkMember(pkMember);
        }
        List<BdTradeWhiteConfigVO> bdTradeWhiteConfigVOList = (List<BdTradeWhiteConfigVO>) bdTradeWhiteConfigService.showTradeWhiteConfigList(tradeWhiteConfigVO)[1];
        //多语言翻译
        if (CollUtil.isNotEmpty(bdTradeWhiteConfigVOList)) {
            //枚举翻译
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EYesNo.values());
            Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_AWARD);
            for (BdTradeWhiteConfigVO configVO : bdTradeWhiteConfigVOList) {
                configVO.setPkAwardsVal(transactionMap1.get(configVO.getPkAwards()));
                configVO.setWithdrawalStateVal(transactionMap.get(EnumsPrefixConstants.YES_NO + configVO.getWithdrawalState()));
                configVO.setTransferStateVal(transactionMap.get(EnumsPrefixConstants.YES_NO + configVO.getTransferState()));
            }
        }
        ExcelUtil<BdTradeWhiteConfigVO> util = new ExcelUtil<>(BdTradeWhiteConfigVO.class);
        util.exportExcel(response, bdTradeWhiteConfigVOList, "白名单导出");
    }


    /**
     * 更新交易配置白名单信息
     *
     * @param tradeWhiteConfigVO 入参
     * @return AjaxResult
     */
    @Log(module = EOperationModule.TRADE_CONFIG, business = EOperationBusiness.TRADE_WHITE_CONFIG, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult updateTradeConfig(@RequestBody BdTradeWhiteConfigVO tradeWhiteConfigVO) {
        CuMember cumember = iMemberServiceApi.getMember(tradeWhiteConfigVO.getMemberCode()).getData();
        AjaxResult ajaxResult = parametersVerify(tradeWhiteConfigVO, cumember);
        if ((Integer) ajaxResult.get(AjaxResult.CODE_TAG) == HttpStatus.ERROR) {
            return ajaxResult;
        }
        tradeWhiteConfigVO.setPkCreator(SecurityUtils.getUserId());
        tradeWhiteConfigVO.setPkCountry(SecurityUtils.getPkCountry());
        deleteKet(tradeWhiteConfigVO.getPkId());
        return toAjax(bdTradeWhiteConfigService.updateTradeWhiteConfig(tradeWhiteConfigVO));
    }

    /**
     * 删除交易白名单配置
     *
     * @param pkId 主键ID
     * @return AjaxResult
     */
    @Log(module = EOperationModule.TRADE_CONFIG, business = EOperationBusiness.TRADE_WHITE_CONFIG, method = EOperationMethod.DELETE)
    @GetMapping("/delete")
    public AjaxResult deleteTradeConfig(String pkId) {
        if (StringUtils.isEmpty(pkId)) {
            return AjaxResult.success();
        } else {
            //删除缓存
            String[] pkIds = pkId.split(",");
            for (String id : pkIds) {
                deleteKet(Integer.parseInt(id));
            }
            return toAjax(bdTradeWhiteConfigService.deleteTradeWhiteConfig(pkId, SecurityUtils.getUserId()));
        }
    }


    /**
     * 查看详情
     *
     * @param pkId 主键ID
     * @return AjaxResult
     */
    @Log(module = EOperationModule.TRADE_CONFIG, business = EOperationBusiness.WITHDRAWAL_CONFIG, method = EOperationMethod.DELETE)
    @GetMapping("/detail")
    public AjaxResult selectTradeWhiteConfigDetail(Integer pkId) {
        BdTradeWhiteConfigVO bdTradeWhiteConfigVO = BeanUtil.copyProperties(bdTradeWhiteConfigService.getById(pkId), BdTradeWhiteConfigVO.class);
        CuMember cumember = iMemberServiceApi.getMember(bdTradeWhiteConfigVO.getPkMember()).getData();
        bdTradeWhiteConfigVO.setMemberCode(cumember.getMemberCode());
        return AjaxResult.success(bdTradeWhiteConfigVO);
    }

    /**
     * 获取缓存健值
     *
     * @param pkId 主键ID
     * @return String
     */
    private String deleteKet(Integer pkId) {
        BdTradeWhiteConfig tradeWhiteConfig = bdTradeWhiteConfigService.getById(pkId);
        Long pkMember = tradeWhiteConfig.getPkMember();
        Integer pkCountry = tradeWhiteConfig.getPkCountry();
        Integer withdrawalState = tradeWhiteConfig.getWithdrawalState();
        Integer transferState = tradeWhiteConfig.getTransferState();
        if (null != pkMember && null != withdrawalState) {
            String key = CacheConstants.TRADE_CONFIG_WHITE + ":" + pkCountry + EBusinessModule.WITHDRAWAL.getValue() + ":" + pkMember + withdrawalState;
            if (null != key) {
                redisService.deleteObjectByKey(key);
            }
        }
        if (null != pkMember && null != transferState) {
            String key = CacheConstants.TRADE_CONFIG_WHITE + ":" + pkCountry + EBusinessModule.TRANSFER_ACCOUNTS.getValue() + ":" + pkMember + transferState;
            if (null != key) {
                redisService.deleteObjectByKey(key);
            }
        }
        return null;
    }

    /**
     * 公共参数校验
     *
     * @param tradeWhiteConfigVO 入参
     * @return AjaxResult
     */
    private AjaxResult parametersVerify(BdTradeWhiteConfigVO tradeWhiteConfigVO, CuMember cumember) {

        if (StringUtils.isEmpty(tradeWhiteConfigVO.getMemberCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_EMPTY));
        }

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

        if (null == tradeWhiteConfigVO.getTransferState() && null == tradeWhiteConfigVO.getWithdrawalState()) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.WITHDRAWAL_NOT_EMPTY));
        }

        return AjaxResult.success();
    }

}
