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.EnumsPrefixConstants;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.domain.R;
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.domain.EnumEntity;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.system.config.BdAccount;
import com.hzs.common.domain.system.config.ext.BdAccountExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.system.base.ITransactionServiceApi;
import com.hzs.system.config.service.IBdAccountService;
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 com.hzs.system.config.param.PkBdAccountParam;

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

/**
 * <p>
 * 币种配置表 前端控制器
 * </p>
 *
 * @author zhangjing
 * @since 2022-08-25
 */
@Slf4j
@RestController
@RequestMapping("/manage/account")
public class BdAccountController extends BaseController {

    @Autowired
    private IBdAccountService accountService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;

    @DubboReference
    private ITransactionServiceApi iTransactionServiceApi;
    private RedisService redisService;

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


    /**
     * @description: 查询币种配置列表
     * @author: zhang jing
     * @date: 2022/8/29 9:56
     * @param: [account]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CURRENCY_CONFIG, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BdAccountExt bdAccountExt) {
        startPage();
        bdAccountExt.setPkCountry(SecurityUtils.getPkCountry());
        List<BdAccountExt> list = accountService.selectBdAccountList(bdAccountExt);
        return getDataTable(list);
    }

    /**
     * 导出
     *
     * @param response
     * @param bdAccountExt
     */
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CURRENCY_CONFIG, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BdAccountExt bdAccountExt) {
        List<BdAccountExt> list = accountService.selectBdAccountList(bdAccountExt);
        ExcelUtil<BdAccountExt> util = new ExcelUtil<>(BdAccountExt.class);
        util.exportExcel(response, list, "币种配置");
    }

    /**
     * @description: 查询转换币种列表
     * @author: zhang jing
     * @date: 2022/10/25 16:20
     * @param: []
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CURRENCY_CONFIG, method = EOperationMethod.SELECT)
    @GetMapping("/pkBdAccountList")
    public TableDataInfo list() {
        QueryWrapper<BdAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.eq("SHOW_STATUS", EShowStatus.SHOW.getValue());
        queryWrapper.orderByAsc("SORT");
        List<BdAccount> list = accountService.list(queryWrapper);
        List<PkBdAccountParam> paList = new ArrayList<>();
        list.forEach(item -> paList.add(BeanUtil.copyProperties(item, PkBdAccountParam.class)));
        return getDataTable(paList);
    }


    /**
     * @description: 充值列表
     * @author: zhang jing
     * @date: 2023/7/12 14:06
     * @param: []
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CURRENCY_CONFIG, method = EOperationMethod.SELECT)
    @GetMapping("/rechargeList")
    public TableDataInfo rechargeList(PkBdAccountParam accountParam) {
        List<BdAccount> list = accountService.queryAccountByType(accountParam.getAccountProperty(), SecurityUtils.getPkCountry());
        List<PkBdAccountParam> paList = new ArrayList<>();
        list.forEach(item -> paList.add(BeanUtil.copyProperties(item, PkBdAccountParam.class)));
        return getDataTable(paList);
    }

    /**
     * @description: 新增币种配置
     * @author: zhang jing
     * @date: 2022/8/29 9:58
     * @param: [account]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CURRENCY_CONFIG, method = EOperationMethod.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody BdAccount account) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (StringUtils.isEmpty(account.getAccountName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ACCOUNT_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(account.getFieldValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ACCOUNT_VALUE_NOT_NULL));
        }
        if (StringUtils.isNull(account.getSort())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SORT_NOT_NULL));
        }
        if (StringUtils.isNull(account.getEffectiveDate())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EFFECTIVE_DATE_NOT_NULL));
        }

        QueryWrapper<BdAccount> queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("SORT", account.getSort());
        queryWrapper1.eq("PK_COUNTRY", pkCountry);
        List<BdAccount> list1 = accountService.list(queryWrapper1);
        if (CollectionUtil.isNotEmpty(list1)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SORT_NOT_REPEAT));
        }
        //校验在线充值
        if (StringUtils.isNotNull(account.getOnLineRecharge()) && account.getOnLineRecharge() == EYesNo.YES.getIntValue()) {
            QueryWrapper<BdAccount> queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("ON_LINE_RECHARGE", account.getOnLineRecharge());
            queryWrapper2.eq("PK_COUNTRY", pkCountry);
            List<BdAccount> list2 = accountService.list(queryWrapper2);
            if (CollectionUtil.isNotEmpty(list2)) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.RECHARGE_NOT_REPEAT));
            }
        }

        QueryWrapper<BdAccount> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", pkCountry);
        queryWrapper.eq("FIELD_VALUE", account.getFieldValue());
        List<BdAccount> list = accountService.list(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            account.setPkCountry(pkCountry);
            account.setPkCreator(SecurityUtils.getUserId());
            account.setCreationTime(new Date());
            //字段翻译保存到数据库
            R<Integer> pkTransactionKey = iTransactionServiceApi.createTransaction(pkCountry, ETransactionKey.ACCOUNT,
                    account.getAccountName(), EYesNo.YES, EYesNo.NO);
            account.setPkTransactionKey(pkTransactionKey.getData());
            accountService.save(account);
        }
        return AjaxResult.success();
    }

    /**
     * @description: 修改币种配置
     * @author: zhang jing
     * @date: 2022/8/29 9:58
     * @param: [account]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CURRENCY_CONFIG, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody BdAccount account) {
        if (StringUtils.isNull(account.getFieldValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ACCOUNT_VALUE_NOT_NULL));
        }
        if (StringUtils.isEmpty(account.getAccountName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ACCOUNT_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(account.getSort())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SORT_NOT_NULL));
        }
        if (StringUtils.isNull(account.getEffectiveDate())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EFFECTIVE_DATE_NOT_NULL));
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        QueryWrapper<BdAccount> queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("PK_COUNTRY", pkCountry);
        queryWrapper1.eq("SORT", account.getSort());
        queryWrapper1.ne("PK_ID", account.getPkId());
        List<BdAccount> list1 = accountService.list(queryWrapper1);
        if (CollectionUtil.isNotEmpty(list1)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SORT_NOT_REPEAT));
        }

        //校验在线充值
        if (account.getOnLineRecharge() == EYesNo.YES.getIntValue()) {
            QueryWrapper<BdAccount> queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("ON_LINE_RECHARGE", account.getOnLineRecharge());
            queryWrapper2.eq("PK_COUNTRY", pkCountry);
            queryWrapper2.ne("PK_ID", account.getPkId());
            List<BdAccount> list2 = accountService.list(queryWrapper2);
            if (CollectionUtil.isNotEmpty(list2)) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.RECHARGE_NOT_REPEAT));
            }
        }

        account.setPkModified(SecurityUtils.getUserId());
        account.setModifiedTime(new Date());
        //字段翻译保存到数据库
        if (null != account.getPkTransactionKey()) {
            R<Boolean> b = iTransactionServiceApi.updateTransaction(pkCountry,
                    account.getAccountName(), account.getPkTransactionKey(), true);
        } else {
            //字段翻译保存到数据库
            R<Integer> pkTransactionKey = iTransactionServiceApi.createTransaction(pkCountry, ETransactionKey.ACCOUNT,
                    account.getAccountName(), EYesNo.YES, EYesNo.NO);
            account.setPkTransactionKey(pkTransactionKey.getData());
        }
        redisService.deleteObject(CacheConstants.BD_ACCOUNT + account.getPkId());
        redisService.deleteObject(CacheConstants.BD_ACCOUNT_CHANGE + account.getPkId());
        return toAjax(accountService.updateById(account));
    }

    /**
     * @description: 获取单条币种配置信息
     * @author: zhang jing
     * @date: 2022/8/29 9:58
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CURRENCY_CONFIG, method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Long pkId) {
        BdAccount account = accountService.getById(pkId);
        BdAccountExt accountExt = BeanUtil.copyProperties(account, BdAccountExt.class);
        return AjaxResult.success(accountExt);
    }

    /**
     * @description: 修改启用禁用状态
     * @author: zhang jing
     * @date: 2022/8/29 9:58
     * @param: [pkId, enable]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CURRENCY_CONFIG, method = EOperationMethod.UPDATE)
    @PostMapping("/updateEnable/{pkId}/{enable}")
    public AjaxResult updateEnable(@PathVariable Integer pkId, @PathVariable Integer enable) {
        BdAccount account = new BdAccount();
        account.setPkId(pkId);
        account.setEnableState(enable);
        account.setPkModified(SecurityUtils.getUserId());
        account.setModifiedTime(new Date());
        accountService.updateById(account);
        redisService.deleteObject(CacheConstants.BD_ACCOUNT + pkId);
        redisService.deleteObject(CacheConstants.BD_ACCOUNT_CHANGE + account.getPkId());
        return AjaxResult.success();
    }

    /**
     * @description: 删除币种配置
     * @author: zhang jing
     * @date: 2022/8/29 9:58
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.WALLET_CONFIG, business = EOperationBusiness.CURRENCY_CONFIG, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Long pkId) {
        BdAccount account = accountService.getById(pkId);
        BdAccountExt bdAccountExt = new BdAccountExt();
        Integer accountCount = 0;
        if (StringUtils.isNotNull(account)) {
            if (account.getFieldValue() == EAccount.CONSUME.getValue()) {
                bdAccountExt.setAccount1(account.getFieldValue());
            }
            if (account.getFieldValue() == EAccount.POLICY.getValue()) {
                bdAccountExt.setAccount3(account.getFieldValue());
            }
            if (account.getFieldValue() == EAccount.BONUS.getValue()) {
                bdAccountExt.setAccount4(account.getFieldValue());
            }
            accountCount = accountService.selectMemberAccountCount(bdAccountExt);
        }
        if (accountCount > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ENABLE_STATE_NOT_DELETE));
        } else {
            UpdateWrapper<BdAccount> 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.deleteObject(CacheConstants.BD_ACCOUNT + pkId);
            redisService.deleteObject(CacheConstants.BD_ACCOUNT_CHANGE + account.getPkId());
            return AjaxResult.success(accountService.update(updateWrapper));
        }
    }


    /**
     * 查询账户名称
     *
     * @param pkIdList 地区ID列表
     * @return
     */
    @GetMapping("/query-name")
    public AjaxResult queryName(@RequestParam List<Integer> pkIdList) {
        // 返回数据
        List<EnumEntity> enumEntityList = new ArrayList<>();

        QueryWrapper<BdAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(SystemFieldConstants.PK_ID, pkIdList);
        List<BdAccount> list = accountService.list(queryWrapper);

        // 翻译MAP
        Map<Integer, String> transactionMap = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_ACC);

        for (BdAccount bdAccount : list) {
            enumEntityList.add(new EnumEntity(bdAccount.getPkId(), transactionMap.get(bdAccount.getPkTransactionKey())));
        }

        return AjaxResult.success(enumEntityList);
    }

}
