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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.DistinctByKeyUtil;
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.system.config.BdAccount;
import com.hzs.common.domain.system.config.BdAreaCurrency;
import com.hzs.common.domain.system.config.ext.BdAreaCurrencyDetailExt;
import com.hzs.common.domain.system.config.ext.BdAreaCurrencyExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.system.base.ITransactionServiceApi;
import com.hzs.system.config.service.IBdAccountService;
import com.hzs.system.config.service.IBdAreaCurrencyDetailService;
import com.hzs.system.config.service.IBdAreaCurrencyService;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 消费配置表 前端控制器
 *
 * @author zhangjing
 * @since 2022-08-26
 */
@Slf4j
@RestController
@RequestMapping("/manage/area-currency")
public class BdAreaCurrencyController extends BaseController {

    @Autowired
    private IBdAreaCurrencyService areaCurrencyParamService;
    @Autowired
    private IBdAreaCurrencyDetailService areaCurrencyDetailService;
    @Autowired
    private IBdAccountService iBdAccountService;

    @DubboReference
    private ITransactionServiceApi iTransactionServiceApi;


    /**
     * @description: 查询消费配置列表
     * @author: zhang jing
     * @date: 2022/8/29 9:59
     * @param: [areaCurrencyParam]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CONSUME_CONFIG, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BdAreaCurrencyExt areaCurrencyExt) {
        startPage();
        QueryWrapper<BdAreaCurrency> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(areaCurrencyExt.getSpecialArea())) {
            queryWrapper.eq("SPECIAL_AREA", areaCurrencyExt.getSpecialArea());
        }
        queryWrapper.orderByAsc("SPECIAL_AREA");
        List<BdAreaCurrency> list = areaCurrencyParamService.list(queryWrapper);
        List<BdAreaCurrencyExt> listExt = new ArrayList<>();
        for (BdAreaCurrency bac : list) {
            BdAreaCurrencyExt bacExt = BeanUtil.copyProperties(bac, BdAreaCurrencyExt.class);
            BdAreaCurrencyDetailExt areaCurrencyDetailExt = new BdAreaCurrencyDetailExt();
            areaCurrencyDetailExt.setPkAreaCurrency(bac.getPkId().intValue());
            List<BdAreaCurrencyDetailExt> detailsList = areaCurrencyDetailService.getAreaCurrencyDetailList(areaCurrencyDetailExt);
            bacExt.setDetailsList(detailsList);
            listExt.add(bacExt);
        }
        return getDataTable(listExt);
    }

    /**
     * @description: 导出
     * @author: zhang jing
     * @date: 2023/3/3 15:47
     * @param: [response, areaCurrencyExt]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CONSUME_CONFIG, method = EOperationMethod.SELECT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BdAreaCurrencyExt areaCurrencyExt) {
        QueryWrapper<BdAreaCurrency> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(areaCurrencyExt.getSpecialArea())) {
            queryWrapper.eq("SPECIAL_AREA", areaCurrencyExt.getSpecialArea());
        }
        queryWrapper.orderByAsc("EFFECTIVE_DATE");
        List<BdAreaCurrency> list = areaCurrencyParamService.list(queryWrapper);
        List<BdAreaCurrencyExt> listExt = new ArrayList<>();
        String deductSortName = "";
        for (BdAreaCurrency bac : list) {
            BdAreaCurrencyExt bacExt = BeanUtil.copyProperties(bac, BdAreaCurrencyExt.class);
            BdAreaCurrencyDetailExt areaCurrencyDetailExt = new BdAreaCurrencyDetailExt();
            areaCurrencyDetailExt.setPkAreaCurrency(bac.getPkId().intValue());
            List<BdAreaCurrencyDetailExt> detailsList = areaCurrencyDetailService.getAreaCurrencyDetailList(areaCurrencyDetailExt);
            if (CollectionUtil.isNotEmpty(detailsList)) {
                for (BdAreaCurrencyDetailExt acd : detailsList) {
                    deductSortName = acd.getAccountName() + "/" + acd.getDeductRatio() + " " + deductSortName;
                }
                bacExt.setDeductSortName(deductSortName);
            }
            bacExt.setDetailsList(detailsList);
            listExt.add(bacExt);
        }
        ExcelUtil<BdAreaCurrencyExt> util = new ExcelUtil<>(BdAreaCurrencyExt.class);
        util.exportExcel(response, listExt, "消费配置");
    }

    /**
     * @description: 新增消费配置
     * @author: zhang jing
     * @date: 2022/8/29 9:59
     * @param: [areaCurrencyParam]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CONSUME_CONFIG, method = EOperationMethod.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody BdAreaCurrencyExt areaCurrencyExt) {
        if (StringUtils.isNull(areaCurrencyExt.getSpecialArea())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SPECIAL_AREA_NOT_NULL));
        }
        if (StringUtils.isNull(areaCurrencyExt.getEffectiveDate())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EFFECTIVE_DATE_NOT_NULL));
        }
        BigDecimal maxDeductRatio = new BigDecimal(100);
        BigDecimal deductRatio = BigDecimal.ZERO;
        List<BdAreaCurrencyDetailExt> detailsList = areaCurrencyExt.getDetailsList();
        if (CollectionUtil.isEmpty(detailsList)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_NOT_NULL));
        }
        List<BdAreaCurrencyDetailExt> detailsList1 = detailsList.stream().filter(DistinctByKeyUtil.distinctByKey(BdAreaCurrencyDetailExt::getDeductSort)).collect(Collectors.toList());
        if (detailsList.size() != detailsList1.size()) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_SORT_NOT_REPEAT));
        }
        for (BdAreaCurrencyDetailExt bcd : detailsList) {
            if (StringUtils.isNull(bcd.getPkAccount())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PK_ACCOUNT_NOT_NULL));
            }
            if (StringUtils.isNull(bcd.getDeductRatio())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_RATIO_NOT_NULL));
            }
            if (StringUtils.isNull(bcd.getDeductSort())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_SORT_NOT_NULL));
            }
            deductRatio = deductRatio.add(bcd.getDeductRatio());

            // 添加校验，如果是政策币，不能为0%
            BdAccount bdAccount = iBdAccountService.getBdAccount(bcd.getPkAccount());
            if(bdAccount==null){
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.CURRENCY_NOT_EFFECTIVE));
            }
            if (EAccount.POLICY.getValue() == bdAccount.getFieldValue() && bcd.getDeductRatio().compareTo(BigDecimal.ZERO) <= 0) {
                // 政策币账户，并且小于等于0，则不能进行保存
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.POLICY_GREATER_ZERO));
            }
        }
        int result = maxDeductRatio.compareTo(deductRatio);
        if (result < 0) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_EXCEED_MAX));
        }
        areaCurrencyExt.setPkCountry(SecurityUtils.getPkCountry());
        areaCurrencyExt.setPkCreator(SecurityUtils.getUserId());
        areaCurrencyExt.setCreationTime(new Date());
        return toAjax(areaCurrencyParamService.saveAreaCurrency(areaCurrencyExt));
    }


    /**
     * @description: 修改消费配置
     * @author: zhang jing
     * @date: 2022/8/29 9:59
     * @param: [areaCurrencyParam]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CONSUME_CONFIG, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody BdAreaCurrencyExt areaCurrencyExt) {
        if (StringUtils.isNull(areaCurrencyExt.getSpecialArea())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SPECIAL_AREA_NOT_NULL));
        }
        if (StringUtils.isNull(areaCurrencyExt.getEffectiveDate())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EFFECTIVE_DATE_NOT_NULL));
        }
        List<BdAreaCurrencyDetailExt> detailsList = areaCurrencyExt.getDetailsList();
        if (CollectionUtil.isEmpty(detailsList)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_NOT_NULL));
        }
        List<BdAreaCurrencyDetailExt> detailsList1 = detailsList.stream().filter(DistinctByKeyUtil.distinctByKey(BdAreaCurrencyDetailExt::getDeductSort)).collect(Collectors.toList());
        if (detailsList.size() != detailsList1.size()) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_SORT_NOT_REPEAT));
        }
        BigDecimal maxDeductRatio = new BigDecimal(100);
        BigDecimal deductRatio = BigDecimal.ZERO;
        for (BdAreaCurrencyDetailExt bcd : detailsList) {
            if (StringUtils.isNull(bcd.getPkAccount())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PK_ACCOUNT_NOT_NULL));
            }
            if (StringUtils.isNull(bcd.getDeductRatio())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_RATIO_NOT_NULL));
            }
            if (StringUtils.isNull(bcd.getDeductSort())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_SORT_NOT_NULL));
            }
            deductRatio = deductRatio.add(bcd.getDeductRatio());

            // 添加校验，如果是政策币，不能为0%
            BdAccount bdAccount = iBdAccountService.getBdAccount(bcd.getPkAccount());
            if(bdAccount==null){
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.CURRENCY_NOT_EFFECTIVE));
            }
            if (EAccount.POLICY.getValue() == bdAccount.getFieldValue() && bcd.getDeductRatio().compareTo(BigDecimal.ZERO) <= 0) {
                // 政策币账户，并且小于等于0，则不能进行保存
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.POLICY_GREATER_ZERO));
            }
        }
        int result = maxDeductRatio.compareTo(deductRatio);
        if (result < 0) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_EXCEED_MAX));
        }
        areaCurrencyExt.setPkModified(SecurityUtils.getUserId());
        areaCurrencyExt.setModifiedTime(new Date());
        return toAjax(areaCurrencyParamService.updateAreaCurrency(areaCurrencyExt));
    }


    /**
     * @description: 获取单条消费配置
     * @author: zhang jing
     * @date: 2022/8/29 9:59
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CONSUME_CONFIG, method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Long pkId) {
        BdAreaCurrency areaCurrencyParam = areaCurrencyParamService.getById(pkId);
        BdAreaCurrencyExt areaCurrencyExt = BeanUtil.copyProperties(areaCurrencyParam, BdAreaCurrencyExt.class);
        BdAreaCurrencyDetailExt areaCurrencyDetailExt = new BdAreaCurrencyDetailExt();
        areaCurrencyDetailExt.setPkAreaCurrency(pkId.intValue());
        areaCurrencyExt.setDetailsList(areaCurrencyDetailService.getAreaCurrencyDetailList(areaCurrencyDetailExt));
        return AjaxResult.success(areaCurrencyExt);
    }

    /**
     * @description: 删除消费配置
     * @author: zhang jing
     * @date: 2022/8/29 9:59
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CONSUME_CONFIG, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Long pkId) {
        Long pkModified = SecurityUtils.getUserId();
        Date date = new Date();
        BdAreaCurrency areaCurrency = new BdAreaCurrency();
        areaCurrency.setPkModified(pkModified);
        areaCurrency.setModifiedTime(date);
        areaCurrency.setPkId(pkId);
        return toAjax(areaCurrencyParamService.delAreaCurrency(areaCurrency));
    }

}
