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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzs.common.core.annotation.AccessPermissions;
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.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.system.base.BdCountry;
import com.hzs.common.domain.system.base.BdCurrency;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.config.pub.controller.ConfigBaseController;
import com.hzs.system.base.service.IBdCountryService;
import com.hzs.system.base.service.IBdCurrencyService;
import com.hzs.system.base.vo.BdCurrencyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * Created with IntelliJ IDEA.
 * Author: yuhui
 * Description: 币种控制器
 */
@RestController("BdCurrencyController")
@RequestMapping("/manage/currency")
public class BdCurrencyController extends ConfigBaseController {

    @Autowired
    private RedisService redisService;
    @Autowired
    private IBdCurrencyService currencyService;
    @Autowired
    private IBdCountryService countryService;

    /**
     * 查询所有币种控制器
     *
     * @return
     */
    @AccessPermissions("Exchangerate")
    @Log(module = EOperationModule.CURRENCY_LIST, method = EOperationMethod.SELECT)
    @GetMapping("list")
    public TableDataInfo list(BdCurrency currency, Date createStartDate, Date createEndDate
            , Date effectiveStartDate, Date effectiveEndDate) {
        LambdaQueryWrapper<BdCurrency> queryWrapper = new LambdaQueryWrapper<>();
        // 名称
        if (StringUtils.isNotBlank(currency.getName())) {
            queryWrapper.eq(BdCurrency::getName, currency.getName());
        }
        // 货币编码
        if (StringUtils.isNotBlank(currency.getCurrencyCode())) {
            queryWrapper.eq(BdCurrency::getCurrencyCode, currency.getCurrencyCode());
        }
        // 国家
//        if (currency.getPkCountry() != null){
//
//        }
        queryWrapper.eq(BdCurrency::getPkCountry, SecurityUtils.getPkCountry());
        // 启用状态
        if (currency.getEnableState() != null) {
            queryWrapper.eq(BdCurrency::getEnableState, currency.getEnableState());
        }
        // 生效筛选
        if (effectiveStartDate != null && effectiveEndDate != null) {
            queryWrapper.between(BdCurrency::getEffectiveDate, effectiveStartDate, effectiveEndDate);
        }
        // 创建时间筛选
        if (createStartDate != null && createEndDate != null) {
            queryWrapper.between(BdCurrency::getCreationTime, createStartDate, createEndDate);
        }
        //启用状态放最前面
        queryWrapper.orderByDesc(BdCurrency::getEffectiveDate);

        startPage();
        List<BdCurrency> list = currencyService.list(queryWrapper);
        List<BdCurrencyVo> resultList = new ArrayList<>();
        for (BdCurrency bdCurrency : list) {
            BdCurrencyVo currencyVo = BeanUtil.copyProperties(bdCurrency, BdCurrencyVo.class);
            BdCountry country = countryService.getCountry(currencyVo.getPkCountry());
            if (country != null) {
                currencyVo.setCountryName(country.getShortName());
                currencyVo.setCountryNationalFlag(country.getNationalFlag2());
            }
            resultList.add(currencyVo);
        }
        return getDataTable(resultList);
    }

    /**
     * 新增币种
     *
     * @return
     */
    @Log(module = EOperationModule.CURRENCY_SAVE, method = EOperationMethod.INSERT)
    @PostMapping("save")
    public AjaxResult save(@RequestBody BdCurrency bdCurrency) {
        //  LoginUser loginUser = userTokenService.getLoginUser();
        Integer pkCountry = SecurityUtils.getPkCountry();
        bdCurrency.setPkCreator(SecurityUtils.getUserId());
        bdCurrency.setCreationTime(DateUtils.currentDateTime());
        bdCurrency.setPkCountry(pkCountry);
//        bdCurrency.setEffectiveDate(new Date());
        currencyService.save(bdCurrency);
        String countryKey = CacheConstants.BD_CURRENCY + bdCurrency.getPkCountry();
        String currencyKey = CacheConstants.BD_CURRENCY_PK + bdCurrency.getPkId();
        String currencyKeyPk = CacheConstants.BD_HISTORY_CURRENCY_PK + bdCurrency.getPkId();
        long effectiveDate = bdCurrency.getEffectiveDate().getTime();
        long thisTime = DateUtils.currentDate().getTime();
        if (effectiveDate < thisTime) {
            // 删除根据国家获取币种缓存
            redisService.deleteObject(countryKey);
            // 删除根据id获取币种缓存
            redisService.deleteObject(currencyKey);
            redisService.deleteObject(currencyKeyPk);
        } else {
            if (!sendDelayedMessage(bdCurrency, EDelayBusType.CURRENCY.getValue(), countryKey, currencyKey)) {
                // 删除根据国家获取币种缓存
                redisService.deleteObject(countryKey);
                // 删除根据id获取币种缓存
                redisService.deleteObject(currencyKey);
                redisService.deleteObject(currencyKeyPk);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改币种
     *
     * @param bdCurrency
     * @return
     */
    @Log(module = EOperationModule.CURRENCY_UPDATE, method = EOperationMethod.UPDATE)
    @PostMapping("update")
    public AjaxResult update(@RequestBody BdCurrency bdCurrency) {
        bdCurrency.setPkModified(SecurityUtils.getUserId());
        bdCurrency.setModifiedTime(DateUtils.currentDateTime());
        String countryKey = CacheConstants.BD_CURRENCY + SecurityUtils.getPkCountry();
        String currencyKey = CacheConstants.BD_CURRENCY_PK + bdCurrency.getPkId();
        String currencyKeyPk = CacheConstants.BD_HISTORY_CURRENCY_PK + bdCurrency.getPkId();
        long effectiveDate = bdCurrency.getEffectiveDate().getTime();
        long thisTime = DateUtils.currentDate().getTime();
        if (effectiveDate < thisTime) {
            // 生效时间大于当前时间 立即生效 缓存
            // 删除根据国家获取币种缓存
            redisService.deleteObject(countryKey);
            // 删除根据id获取币种缓存
            redisService.deleteObject(currencyKey);
            redisService.deleteObject(currencyKeyPk);
        } else {
            if (!sendDelayedMessage(bdCurrency, EDelayBusType.CURRENCY.getValue(), countryKey, currencyKey)) {
                // 删除根据国家获取币种缓存
                redisService.deleteObject(countryKey);
                // 删除根据id获取币种缓存
                redisService.deleteObject(currencyKey);
                redisService.deleteObject(currencyKeyPk);
            }
        }
        currencyService.updateById(bdCurrency);
        return toAjax(1);
    }

    /**
     * 删除币种
     *
     * @param pkId
     * @return
     */
    @Log(module = EOperationModule.CURRENCY_REMOVE, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Integer pkId) {
        BdCurrency currency = currencyService.getById(pkId);
        // 删除根据国家获取币种缓存
        redisService.deleteObject(CacheConstants.BD_CURRENCY + currency.getPkCountry());
        // 删除根据id获取币种缓存
        redisService.deleteObject(CacheConstants.BD_CURRENCY_PK + currency.getPkId());
        redisService.deleteObject(CacheConstants.BD_HISTORY_CURRENCY_PK + currency.getPkId());
        return toAjax(currencyService.removeById(pkId));
    }

    /**
     * 更新状态 启用状态（0=是,1=否）
     *
     * @param pkId
     * @param enable
     * @return
     */
    @Log(module = EOperationModule.CURRENCY_UPDATE_ENABLE, method = EOperationMethod.UPDATE)
    @PostMapping("/updateEnable/{pkId}/{enable}")
    public AjaxResult updateEnable(@PathVariable Integer pkId, @PathVariable Integer enable) {
        BdCurrency currency = currencyService.getById(pkId);
        if (currency.getEnableState() == EYesNo.NO.getIntValue()) {
            LambdaQueryWrapper<BdCurrency> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BdCurrency::getEnableState, EYesNo.YES.getIntValue());
            queryWrapper.eq(BdCurrency::getPkCountry, SecurityUtils.getPkCountry());
            int count = currencyService.count(queryWrapper);
            if (count == 1) {
                // 如果是已生效的只存在一条 则无法失效
                return AjaxResult.error(ConfigMsgConstants.CURRENCY_UNABLE_TO_FAIL);
            }
        }
        BdCurrency bdCurrency = new BdCurrency();
        bdCurrency.setPkId(pkId);
        bdCurrency.setEnableState(enable);
        currencyService.updateById(bdCurrency);
        // 删除根据国家获取币种缓存
        redisService.deleteObject(CacheConstants.BD_CURRENCY + currency.getPkCountry());
        // 删除根据id获取币种缓存
        redisService.deleteObject(CacheConstants.BD_CURRENCY_PK + currency.getPkId());
        redisService.deleteObject(CacheConstants.BD_HISTORY_CURRENCY_PK + currency.getPkId());
        return AjaxResult.success();
    }

    /**
     * 汇率配置详情
     *
     * @param pkId
     * @return
     */
    @GetMapping("detail")
    public AjaxResult detail(Integer pkId) {
        BdCurrency bdCurrency = currencyService.getById(pkId);
        BdCountry country = countryService.getCountry(bdCurrency.getPkCountry());
        BdCurrencyVo currencyVo = BeanUtil.copyProperties(bdCurrency, BdCurrencyVo.class);
        if (country != null) {
            currencyVo.setCountryName(country.getShortName());
            currencyVo.setCountryNationalFlag(country.getNationalFlag2());
        }
        return AjaxResult.success(currencyVo);
    }

    /**
     * 导出列表
     *
     * @param response
     * @return
     */
    @PostMapping("/export")
    public void export(BdCurrency currency, Date createStartDate, Date createEndDate
            , Date effectiveStartDate, Date effectiveEndDate, HttpServletResponse response) {
        LambdaQueryWrapper<BdCurrency> queryWrapper = new LambdaQueryWrapper<>();
        // 名称
        if (StringUtils.isNotBlank(currency.getName())) {
            queryWrapper.eq(BdCurrency::getName, currency.getName());
        }
        // 货币编码
        if (StringUtils.isNotBlank(currency.getCurrencyCode())) {
            queryWrapper.eq(BdCurrency::getCurrencyCode, currency.getCurrencyCode());
        }

        queryWrapper.eq(BdCurrency::getPkCountry, SecurityUtils.getPkCountry());
        // 启用状态
        if (currency.getEnableState() != null) {
            queryWrapper.eq(BdCurrency::getEnableState, currency.getEnableState());
        }
        // 生效筛选
        if (effectiveStartDate != null && effectiveEndDate != null) {
            queryWrapper.between(BdCurrency::getEffectiveDate, effectiveStartDate, effectiveEndDate);
        }
        // 创建时间筛选
        if (createStartDate != null && createEndDate != null) {
            queryWrapper.between(BdCurrency::getCreationTime, createStartDate, createEndDate);
        }

        //启用状态放最前面
        queryWrapper.orderByDesc(BdCurrency::getEffectiveDate);
        List<BdCurrency> list = currencyService.list(queryWrapper);
        List<BdCurrencyVo> resultList = new ArrayList<>();
        for (BdCurrency bdCurrency : list) {
            BdCurrencyVo currencyVo = BeanUtil.copyProperties(bdCurrency, BdCurrencyVo.class);
            BdCountry country = countryService.getCountry(currencyVo.getPkCountry());
            if (country != null) {
                currencyVo.setCountryName(country.getShortName());
                currencyVo.setCountryNationalFlag(country.getNationalFlag2());
            }
            resultList.add(currencyVo);
        }
        ExcelUtil<BdCurrencyVo> util = new ExcelUtil<BdCurrencyVo>(BdCurrencyVo.class);
        util.exportExcel(response, resultList, "汇率配置导出");
    }
}
