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.base.BdCountry;
import com.hzs.common.domain.system.config.BdGrade;
import com.hzs.common.domain.system.config.BdGradeScope;
import com.hzs.common.domain.system.config.ext.BdBonusExpandExt;
import com.hzs.common.domain.system.config.ext.BdGradeExt;
import com.hzs.common.domain.system.ext.BdGradeScopeExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.system.base.ITransactionServiceApi;
import com.hzs.system.base.service.IBdCountryService;
import com.hzs.system.base.service.IBdNoticeService;
import com.hzs.system.config.service.IBdAwardsService;
import com.hzs.system.config.service.IBdGradeScopeService;
import com.hzs.system.config.service.IBdGradeService;
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.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 等级配置表 前端控制器
 * </p>
 *
 * @author zhangjing
 * @since 2022-09-08
 */
@Slf4j
@RestController
@RequestMapping("/manage/grade")
public class BdGradeController extends BaseController {

    @Autowired
    private IBdGradeService gradeService;
    @DubboReference
    private ITransactionServiceApi iTransactionServiceApi;
    @Autowired
    IBdCountryService countryService;
    @Autowired
    IBdGradeScopeService gradeScopeService;
    @Autowired
    IBdAwardsService awardsService;
    @Autowired
    private IBdNoticeService noticeService;
    private RedisService redisService;

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

    /**
     * @description: 查询等级配置列表
     * @author: zhang jing
     * @date: 2022/8/30 10:20
     * @param: [grade]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/

    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.GRADE, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BdGrade grade) {
        startPage();
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(grade.getGradeName())) {
            queryWrapper.eq("GRADE_NAME", grade.getGradeName());
        }
        if (StringUtils.isNotNull(grade.getPkAwards())) {
            queryWrapper.eq("PK_AWARDS", grade.getPkAwards());
        }
        queryWrapper.orderByAsc("GRADE_VALUE");
        List<BdGrade> grList = gradeService.list(queryWrapper);
        List<BdGradeExt> list = new ArrayList<>();
        for (BdGrade gr : grList) {
            //暂时注释掉国家信息统一使用页面值
            BdCountry country = countryService.getCountry(gr.getPkCountry());
            //奖衔key
            Integer pkRegisterGrade = noticeService.getAwardsTranslateValue(SecurityUtils.getPkCountry(), gr.getPkAwards());
            gr.setPkAwards(pkRegisterGrade);
            //统计
            BdGradeExt gradeExt = BeanUtil.copyProperties(gr, BdGradeExt.class);
            gradeExt.setNationalFlag2(country.getNationalFlag2());
            //等级范围
            BdGradeScopeExt gradeScopeExt = new BdGradeScopeExt();
            gradeScopeExt.setPkGrade(gr.getPkId());
            List<BdGradeScopeExt> gseList = gradeScopeService.selectGradeScopeList(gradeScopeExt);
            if (CollectionUtil.isNotEmpty(gseList)) {
                for (BdGradeScopeExt gse : gseList) {
                    //等级key
                    Integer pkGrade = noticeService.getGradeTranslateValue(gse.getPkScope());
                    gse.setPkScope(pkGrade);
                }
            }
            gradeExt.setGseList(gseList);
            list.add(gradeExt);
        }
        return getDataTable(list);
    }

    /**
     * @description: 导出等级配置列表
     * @author: zhang jing
     * @date: 2022/8/30 10:20
     * @param: [grade]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.GRADE, method = EOperationMethod.SELECT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BdGrade grade) {
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(grade.getGradeName())) {
            queryWrapper.eq("GRADE_NAME", grade.getGradeName());
        }
        if (StringUtils.isNotNull(grade.getPkAwards())) {
            queryWrapper.eq("PK_AWARDS", grade.getPkAwards());
        }
        queryWrapper.orderByAsc("GRADE_VALUE");
        List<BdGrade> grList = gradeService.list(queryWrapper);
        List<BdGradeExt> list = new ArrayList<>();
        for (BdGrade gr : grList) {
            //暂时注释掉国家信息统一使用页面值
            BdCountry country = countryService.getCountry(gr.getPkCountry());
            //奖衔key
            Integer pkRegisterGrade = noticeService.getAwardsTranslateValue(SecurityUtils.getPkCountry(), gr.getPkAwards());
            gr.setPkAwards(pkRegisterGrade);
            //统计
            BdGradeExt gradeExt = BeanUtil.copyProperties(gr, BdGradeExt.class);
            gradeExt.setNationalFlag2(country.getNationalFlag2());
            //等级范围
            BdGradeScopeExt gradeScopeExt = new BdGradeScopeExt();
            gradeScopeExt.setPkGrade(gr.getPkId());
            List<BdGradeScopeExt> gseList = gradeScopeService.selectGradeScopeList(gradeScopeExt);
            if (CollectionUtil.isNotEmpty(gseList)) {
                for (BdGradeScopeExt gse : gseList) {
                    //等级key
                    Integer pkGrade = noticeService.getGradeTranslateValue(gse.getPkScope());
                    gse.setPkScope(pkGrade);
                }
            }
            gradeExt.setGseList(gseList);
            list.add(gradeExt);
        }
        ExcelUtil<BdGradeExt> util = new ExcelUtil<>(BdGradeExt.class);
        util.exportExcel(response, list, "等级配置");
    }

    /**
     * @description: 拓展列表
     * @author: zhang jing
     * @date: 2022/10/31 16:32
     * @param: [grade]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.GRADE, method = EOperationMethod.SELECT)
    @GetMapping("/expandList")
    public TableDataInfo expandList(BdGrade grade) {
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(grade.getGradeName())) {
            queryWrapper.eq("GRADE_NAME", grade.getGradeName());
        }
        if (StringUtils.isNotNull(grade.getPkAwards())) {
            queryWrapper.eq("PK_AWARDS", grade.getPkAwards());
        }
        queryWrapper.orderByAsc("GRADE_VALUE");
        List<BdGrade> grList = gradeService.list(queryWrapper);
        List<BdGradeExt> list = new ArrayList<>();
        for (BdGrade gr : grList) {
            //统计
            BdGradeExt gradeExt = BeanUtil.copyProperties(gr, BdGradeExt.class);
            list.add(gradeExt);
        }
        return getDataTable(list);
    }

    /**
     * @description: 等级(直推)范围列表
     * @author: zhang jing
     * @date: 2022/10/26 13:36
     * @param: [grade]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.GRADE, method = EOperationMethod.SELECT)
    @GetMapping("/gradeRanglist")
    public AjaxResult gradeRanglist() {
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.orderByAsc("GRADE_VALUE");
        List<BdGrade> grList = gradeService.list(queryWrapper);
        List<BdGradeExt> list = new ArrayList<>();
        for (BdGrade gr : grList) {
            BdGradeExt gre = new BdGradeExt();
            gre.setPkId(gr.getPkId());
            gre.setGradeName(gr.getGradeName());
            gre.setGradeValue(gr.getGradeValue());
            gre.setColor(gr.getColor());
            list.add(gre);
        }
        return AjaxResult.success(list);
    }

    /**
     * @description: 生成等级配置 等级值按照20，30，40，50，60，70生成
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [grade]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.GRADE, method = EOperationMethod.INSERT)
    @PostMapping("/generate")
    public AjaxResult generate(@RequestBody BdGradeExt gradeExt) {
        gradeExt.setPkCountry(SecurityUtils.getPkCountry());
        gradeExt.setPkCreator(SecurityUtils.getUserId());
        gradeExt.setCreationTime(new Date());
        if (StringUtils.isNull(gradeExt.getCensusValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.CENSUS_VALUE_NOT_NULL));
        }
        if (StringUtils.isNull(gradeExt.getStartValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.START_VALUE_NOT_NULL));
        }
        if (StringUtils.isNull(gradeExt.getPkAwards())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.AWARDS_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(gradeExt.getGradeValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.GRADE_VALUE_NOT_NULL));
        }

        if (StringUtils.isNull(gradeExt.getRegisterAuthority())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.REGISTER_AUTHORITY_NOT_NULL));
        }
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.eq("GRADE_VALUE", gradeExt.getGradeValue());
        List<BdGrade> list = gradeService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DATA_REPEAT));
        }
        gradeService.saveBdGrade(gradeExt);
        return AjaxResult.success();
    }

    /**
     * @description: 修改等级配置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [grade]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.GRADE, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody BdGradeExt gradeExt) {
        if (StringUtils.isNull(gradeExt.getGradeValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.GRADE_VALUE_NOT_NULL));
        }
        if (StringUtils.isNull(gradeExt.getCensusValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.CENSUS_VALUE_NOT_NULL));
        }
        if (StringUtils.isNull(gradeExt.getStartValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.START_VALUE_NOT_NULL));
        }
        if (StringUtils.isNull(gradeExt.getPkAwards())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.AWARDS_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(gradeExt.getRegisterAuthority())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.REGISTER_AUTHORITY_NOT_NULL));
        }
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.eq("GRADE_VALUE", gradeExt.getGradeValue());
        queryWrapper.ne("PK_ID",gradeExt.getPkId());
        List<BdGrade> list = gradeService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DATA_REPEAT));
        }
        gradeExt.setPkCountry(SecurityUtils.getPkCountry());
        gradeExt.setPkModified(SecurityUtils.getUserId());
        gradeExt.setModifiedTime(new Date());
        redisService.deleteObjectByKey(CacheConstants.BD_GRADE + gradeExt.getPkId());
        return AjaxResult.success(gradeService.updateBdGrade(gradeExt));
    }

    /**
     * @description: 修改禁用启用状态
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [grade]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.GRADE, method = EOperationMethod.UPDATE)
    @PostMapping("/updateState")
    public AjaxResult updateState(@RequestBody BdGradeExt gradeExt) {
        if (StringUtils.isNull(gradeExt.getEnableState())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ENABLE_STATE_NOT_NULL));
        }
        if (StringUtils.isNull(gradeExt.getPkId())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.HO_OBJECT_NOT_REPEAT));
        }
        UpdateWrapper<BdGrade> updateWrapper=new UpdateWrapper();
        updateWrapper.eq("PK_ID",gradeExt.getPkId());
        updateWrapper.set("ENABLE_STATE",gradeExt.getEnableState());
        updateWrapper.set("PK_MODIFIED",SecurityUtils.getUserId());
        updateWrapper.set("MODIFIED_TIME",new Date());
        gradeService.update(updateWrapper);
        redisService.deleteObjectByKey(CacheConstants.BD_GRADE + gradeExt.getPkId());
        return AjaxResult.success();
    }


    /**
     * @description: 修改拓展配置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [grade]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.GRADE, method = EOperationMethod.UPDATE)
    @PostMapping("/updateExpand")
    public AjaxResult updateExpand(@RequestBody BdGradeExt gradeExt) {
//        if (CollectionUtil.isNotEmpty(gradeExt.getBonusExpands())) {
//            for (BdBonusExpandExt bee : gradeExt.getBonusExpands()) {
//                if (StringUtils.isNull(bee.getExpandNumber())) {
//                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EXPAND_NUMBER_NOT_NULL));
//                }
//                if (StringUtils.isNull(bee.getExpandRatio())) {
//                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EXPAND_RATIO_NOT_NULL));
//                }
//            }
//        } else {
//            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.BONUS_EXPANDS_NOT_NULL));
//        }
        if (CollectionUtil.isNotEmpty(gradeExt.getExpandList())) {
            for (BdGrade bg : gradeExt.getExpandList()) {
                if (StringUtils.isNull(bg.getPkId())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PK_GRADE_AWARDS_NOT_NULL));
                }
//                if (StringUtils.isNull(bg.getExpandRatio())) {
//                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EXPAND_RATIO_NOT_NULL));
//                }
                if (StringUtils.isNull(bg.getExpandCapping())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EXPAND_CAPPING_NOT_NULL));
                }
//                if (StringUtils.isNull(bg.getRepurchaseRatio())) {
//                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.REPURCHASE_RATIO_NOT_NULL));
//                }
//                if (StringUtils.isNull(bg.getRepurchaseCapping())) {
//                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.REPURCHASE_CAPPING_NOT_NULL));
//                }
            }
            return AjaxResult.success(gradeService.updateExpand(gradeExt));
        } else {
            return AjaxResult.error();
        }
    }


    /**
     * @description: 查询单条等级配置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.GRADE, method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Long pkId) {
        BdGrade grade = gradeService.getById(pkId);
        BdGradeExt bdGradeExt = BeanUtil.copyProperties(grade, BdGradeExt.class);
        //等级范围
        BdGradeScopeExt gradeScopeExt = new BdGradeScopeExt();
        gradeScopeExt.setPkGrade(pkId.intValue());
        QueryWrapper<BdGradeScope> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_GRADE", pkId);
        List<BdGradeScope> gbsList = gradeScopeService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(gbsList)) {
            Integer gradeRang[] = new Integer[gbsList.size()];
            for (int i = 0; i < gbsList.size(); i++) {
                gradeRang[i] = gbsList.get(i).getPkScope();
            }
            bdGradeExt.setGradeRang(gradeRang);
        } else {
            Integer gradeRang[] = new Integer[0];
            bdGradeExt.setGradeRang(gradeRang);
        }
        return AjaxResult.success(bdGradeExt);
    }


    /**
     * @description: 删除等级配置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.GRADE, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Long pkId) {
        Integer count = awardsService.checkGradeAwards(pkId, pkId, null);
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ENABLE_STATE_NOT_DELETE));
        }
        return AjaxResult.success(gradeService.updateGrade(pkId));
    }


}
