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.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.CacheConstants;
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.system.config.BdWithdrawal;
import com.hzs.common.domain.system.config.BdWithdrawalAuto;
import com.hzs.common.domain.system.config.ext.BdWithdrawalAutoExt;
import com.hzs.common.domain.system.config.ext.BdWithdrawalExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.system.base.ITransactionServiceApi;
import com.hzs.system.base.service.IBdCurrencyService;
import com.hzs.system.config.IWithdrawalServiceApi;
import com.hzs.system.config.service.IBdWithdrawalAutoService;
import com.hzs.system.config.service.IBdWithdrawalService;
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 javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 提现设置主表 前端控制器
 * </p>
 *
 * @author zhangjing
 * @since 2022-08-29
 */
@Slf4j
@RestController
@RequestMapping("/manage/withdrawal")
public class BdWithdrawalController extends BaseController {

    @Autowired
    private IBdWithdrawalService withdrawalService;
    @DubboReference
    private ITransactionServiceApi iTransactionServiceApi;
    private RedisService redisService;
    @DubboReference
    private IWithdrawalServiceApi withdrawalServiceApi;
    @Autowired
    private IBdWithdrawalAutoService withdrawalAutoService;
    @Autowired
    IBdCurrencyService currencyService;


    @Autowired
    public void setRedisService(RedisService redisService) {
        this.redisService = redisService;
    }


    /**
     * @description: 查询提现设置列表 理论每个国家只有一个提现配置
     * @author: zhang jing
     * @date: 2022/8/30 10:20
     * @param: [withdrawalParam]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.WALLET_CONFIG,business = EOperationBusiness.WITHDRAWAL_CONFIG,method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BdWithdrawalExt withdrawalExt) {
        startPage();
        withdrawalExt.setPkCountry(SecurityUtils.getPkCountry());
        List<BdWithdrawalExt> listExt = withdrawalService.listExt(withdrawalExt);
        for(BdWithdrawalExt bwd: listExt){
             //暂时使用中国
            if(StringUtils.isNotNull(bwd.getMinAmount())){
                bwd.setMinAmountUsa(currencyService.getDollar(bwd.getMinAmount(),SecurityUtils.getPkCountry()));
            }
            if(StringUtils.isNotNull(bwd.getMaxAmount())){
                bwd.setMaxAmountUsa(currencyService.getDollar(bwd.getMaxAmount(),SecurityUtils.getPkCountry()));
            }
            if(StringUtils.isNotNull(bwd.getLowerBound())){
                bwd.setLowerBoundUsa(currencyService.getDollar(bwd.getLowerBound(),SecurityUtils.getPkCountry()));
            }
            if(StringUtils.isNotNull(bwd.getUpperBound())){
                bwd.setUpperBoundUsa(currencyService.getDollar(bwd.getUpperBound(),SecurityUtils.getPkCountry()));
            }

            QueryWrapper<BdWithdrawalAuto> queryWrapperAuto = new QueryWrapper();
            queryWrapperAuto.eq("PK_COUNTRY",SecurityUtils.getPkCountry());
            if(StringUtils.isNotNull(bwd.getPkId())){
                queryWrapperAuto.eq("PK_WITHDRAWAL",bwd.getPkId());
            }
            List<BdWithdrawalAuto> listAuto = withdrawalAutoService.list(queryWrapperAuto);
            List<BdWithdrawalAutoExt> watExtList = new ArrayList<>();
            listAuto.forEach(item -> watExtList.add(BeanUtil.copyProperties(item, BdWithdrawalAutoExt.class)));
            bwd.setWithdrawalAutoList(watExtList);
        }
        return getDataTable(listExt);
    }

    /**
     * @description: 导出提现配置
     * @author: zhang jing
     * @date: 2023/3/3 16:19
     * @param: [response, withdrawalExt]
     * @return: void
     **/
    @Log(module = EOperationModule.WALLET_CONFIG,business = EOperationBusiness.WITHDRAWAL_CONFIG,method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BdWithdrawalExt withdrawalExt) {
        QueryWrapper<BdWithdrawal> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY",SecurityUtils.getPkCountry());
        queryWrapper.orderByDesc("CREATION_TIME");
        List<BdWithdrawal> list = withdrawalService.list(queryWrapper);
        List<BdWithdrawalExt> listExt=new ArrayList<>();
        for(BdWithdrawal bwd: list){
            BdWithdrawalExt withdrawalExtNew= BeanUtil.copyProperties(bwd, BdWithdrawalExt.class);
            //暂时使用中国
            if(StringUtils.isNotNull(bwd.getMinAmount())){
                withdrawalExtNew.setMinAmountUsa(currencyService.getDollar(bwd.getMinAmount(),SecurityUtils.getPkCountry()));
            }
            if(StringUtils.isNotNull(bwd.getMaxAmount())){
                withdrawalExtNew.setMaxAmountUsa(currencyService.getDollar(bwd.getMaxAmount(),SecurityUtils.getPkCountry()));
            }
            if(StringUtils.isNotNull(bwd.getLowerBound())){
                withdrawalExtNew.setLowerBoundUsa(currencyService.getDollar(bwd.getLowerBound(),SecurityUtils.getPkCountry()));
            }
            if(StringUtils.isNotNull(bwd.getUpperBound())){
                withdrawalExtNew.setUpperBoundUsa(currencyService.getDollar(bwd.getUpperBound(),SecurityUtils.getPkCountry()));
            }

            QueryWrapper<BdWithdrawalAuto> queryWrapperAuto = new QueryWrapper();
            queryWrapperAuto.eq("PK_COUNTRY",SecurityUtils.getPkCountry());
            if(StringUtils.isNotNull(bwd.getPkId())){
                queryWrapperAuto.eq("PK_WITHDRAWAL",bwd.getPkId());
            }
            List<BdWithdrawalAuto> listAuto = withdrawalAutoService.list(queryWrapperAuto);
            List<BdWithdrawalAutoExt> watExtList = new ArrayList<>();
            listAuto.forEach(item -> watExtList.add(BeanUtil.copyProperties(item, BdWithdrawalAutoExt.class)));
            withdrawalExtNew.setWithdrawalAutoList(watExtList);
            listExt.add(withdrawalExtNew);
        }
        ExcelUtil<BdWithdrawalExt> util = new ExcelUtil<>(BdWithdrawalExt.class);
        util.exportExcel(response, listExt, "提现设置");
    }

    /**
     * @description: 提现手续费配置，理论每个国家只有一个提现配置
     * @author: zhang jing
     * @date: 2022/11/2 11:38
     * @param: [withdrawalExt]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.WALLET_CONFIG,business = EOperationBusiness.WITHDRAWAL_CONFIG,method = EOperationMethod.SELECT)
    @GetMapping("/serviceChargelist")
    public TableDataInfo serviceChargelist(BdWithdrawalExt withdrawalExt) {
        startPage();
        QueryWrapper<BdWithdrawal> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY",SecurityUtils.getPkCountry());
        queryWrapper.orderByDesc("CREATION_TIME");
        List<BdWithdrawal> list = withdrawalService.list(queryWrapper);
        List<BdWithdrawalExt> listExt=new ArrayList<>();
        for(BdWithdrawal bwd: list){
            BdWithdrawalExt withdrawalExtNew= BeanUtil.copyProperties(bwd, BdWithdrawalExt.class);
            //暂时使用中国
            if(StringUtils.isNotNull(bwd.getMinAmount())){
                withdrawalExtNew.setMinAmountUsa(currencyService.getDollar(bwd.getMinAmount(),SecurityUtils.getPkCountry()));
            }
            if(StringUtils.isNotNull(bwd.getMaxAmount())){
                withdrawalExtNew.setMaxAmountUsa(currencyService.getDollar(bwd.getMaxAmount(),SecurityUtils.getPkCountry()));
            }
            if(StringUtils.isNotNull(bwd.getLowerBound())){
                withdrawalExtNew.setLowerBoundUsa(currencyService.getDollar(bwd.getLowerBound(),SecurityUtils.getPkCountry()));
            }
            if(StringUtils.isNotNull(bwd.getUpperBound())){
                withdrawalExtNew.setUpperBoundUsa(currencyService.getDollar(bwd.getUpperBound(),SecurityUtils.getPkCountry()));
            }

            QueryWrapper<BdWithdrawalAuto> queryWrapperAuto = new QueryWrapper();
            queryWrapperAuto.eq("PK_COUNTRY",SecurityUtils.getPkCountry());
            if(StringUtils.isNotNull(bwd.getPkId())){
                queryWrapperAuto.eq("PK_WITHDRAWAL",bwd.getPkId());
            }
            List<BdWithdrawalAuto> listAuto = withdrawalAutoService.list(queryWrapperAuto);
            List<BdWithdrawalAutoExt> watExtList = new ArrayList<>();
            listAuto.forEach(item -> watExtList.add(BeanUtil.copyProperties(item, BdWithdrawalAutoExt.class)));
            withdrawalExtNew.setWithdrawalAutoList(watExtList);
            listExt.add(withdrawalExtNew);
        }
        return getDataTable(listExt);
    }


    /**
     * @description: 新增提现设置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [withdrawalParam]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.WALLET_CONFIG,business = EOperationBusiness.WITHDRAWAL_CONFIG,method = EOperationMethod.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody @Valid BdWithdrawalExt withdrawalExt) {
        if(StringUtils.isNull(withdrawalExt.getMinAmount())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MIN_AMOUNT_NOT_NULL));
        }
        if(StringUtils.isNull(withdrawalExt.getMaxAmount())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MAX_AMOUNT_NOT_NULL));
        }
        if (withdrawalExt.getMaxAmount().compareTo(withdrawalExt.getMinAmount()) <0) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.COMPARISON_OF_SIZE));
        }
        if(StringUtils.isNull(withdrawalExt.getIsAuto())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.IS_AUTO_NOT_NULL));
        }
        if(StringUtils.isNull(withdrawalExt.getIsRounding())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.IS_ROUNDING_NOT_NULL));
        }
        if(StringUtils.isNull(withdrawalExt.getWithdrawalNumber())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.WITHDRAWAL_NUMBER_NOT_NULL));
        }
        if(EYesNo.YES.getIntValue()==withdrawalExt.getIsAuto()){
            if(StringUtils.isNull(withdrawalExt.getLowerBound())){
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LOWER_BOUND_NOT_NULL));
            }
            if(StringUtils.isNull(withdrawalExt.getUpperBound())){
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.UPPER_BOUND_NOT_NULL));
            }
            if(CollectionUtil.isEmpty(withdrawalExt.getWithdrawalAutoList())){
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.WITHDRAWAL_CYCLE_NOT_NULL));
            }
        }
        if(StringUtils.isNull(withdrawalExt.getEffectiveDate())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EFFECTIVE_DATE_NOT_NULL));
        }
        withdrawalExt.setPkCountry(SecurityUtils.getPkCountry());
        withdrawalExt.setPkCreator(SecurityUtils.getUserId());
        withdrawalExt.setCreationTime(new Date());
        return toAjax(withdrawalService.saveWithdrawal(withdrawalExt));
    }


    /**
     * @description: 修改提现设置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [withdrawalParam]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.WALLET_CONFIG,business = EOperationBusiness.WITHDRAWAL_CONFIG,method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody BdWithdrawalExt withdrawalExt) {
        if(StringUtils.isNull(withdrawalExt.getMinAmount())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MIN_AMOUNT_NOT_NULL));
        }
        if(StringUtils.isNull(withdrawalExt.getMaxAmount())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MAX_AMOUNT_NOT_NULL));
        }
        if (withdrawalExt.getMaxAmount().compareTo(withdrawalExt.getMinAmount()) <0) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.COMPARISON_OF_SIZE));
        }
        if(StringUtils.isNull(withdrawalExt.getIsAuto())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.IS_AUTO_NOT_NULL));
        }
        if(StringUtils.isNull(withdrawalExt.getIsRounding())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.IS_ROUNDING_NOT_NULL));
        }
        if(StringUtils.isNull(withdrawalExt.getWithdrawalNumber())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.WITHDRAWAL_NUMBER_NOT_NULL));
        }

        if(StringUtils.isNull(withdrawalExt.getEffectiveDate())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EFFECTIVE_DATE_NOT_NULL));
        }
        if(EYesNo.YES.getIntValue()==withdrawalExt.getIsAuto()){
            if(StringUtils.isNull(withdrawalExt.getLowerBound())){
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LOWER_BOUND_NOT_NULL));
            }
            if(StringUtils.isNull(withdrawalExt.getUpperBound())){
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.UPPER_BOUND_NOT_NULL));
            }
            if(CollectionUtil.isEmpty(withdrawalExt.getWithdrawalAutoList())){
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.WITHDRAWAL_CYCLE_NOT_NULL));
            }
        }
        if(StringUtils.isNull(withdrawalExt.getEffectiveDate())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EFFECTIVE_DATE_NOT_NULL));
        }
        withdrawalExt.setPkModified(SecurityUtils.getUserId());
        withdrawalExt.setModifiedTime(new Date());
        return toAjax(withdrawalService.updateWithdrawal(withdrawalExt));
    }


    /**
     * @description: 查询单条提现设置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.WALLET_CONFIG,business = EOperationBusiness.WITHDRAWAL_CONFIG,method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Integer pkId) {
        BdWithdrawal withdrawalParam = withdrawalService.getById(pkId);
        BdWithdrawalExt withdrawalExt = BeanUtil.copyProperties(withdrawalParam, BdWithdrawalExt.class);
        BdWithdrawalAutoExt withdrawalAutoExt=new BdWithdrawalAutoExt();
        withdrawalAutoExt.setPkWithdrawal(pkId);
        List<BdWithdrawalAutoExt> withdrawalAutoList =withdrawalService.getWithdrawalAutoList(withdrawalAutoExt);
        if(CollectionUtil.isNotEmpty(withdrawalAutoList)){
            withdrawalExt.setWithdrawalAutoList(withdrawalAutoList);
        }else{
            List<BdWithdrawalAutoExt> withdrawalAutoListNew=new ArrayList<>();
            withdrawalExt.setWithdrawalAutoList(withdrawalAutoListNew);
        }
        return AjaxResult.success(withdrawalExt);
    }


    /**
     * @description: 删除提现设置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.WALLET_CONFIG,business = EOperationBusiness.WITHDRAWAL_CONFIG,method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Long pkId) {
        BdWithdrawalAutoExt withdrawalAutoExt =new BdWithdrawalAutoExt();
        withdrawalAutoExt.setPkCountry(SecurityUtils.getPkCountry());
        Integer count= withdrawalService.checkWithdraw(withdrawalAutoExt);
        if(count>0){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ENABLE_STATE_NOT_DELETE));
        }
        UpdateWrapper<BdWithdrawal> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PK_ID", pkId);
        updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        updateWrapper.set("PK_MODIFIED", SecurityUtils.getUserId());
        updateWrapper.set("MODIFIED_TIME", new Date());
        redisService.deleteObjectByKey(CacheConstants.BD_WITHDRAWAL + SecurityUtils.getPkCountry());
        redisService.deleteObjectByKey(CacheConstants.BD_WITHDRAWAL_IS_AUTO + SecurityUtils.getPkCountry());
        redisService.deleteObjectByKey(CacheConstants.BD_WITHDRAWAL_AUTO + SecurityUtils.getPkCountry());
        return toAjax(withdrawalService.update(updateWrapper));
    }
}
