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.msg.ConfigMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
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.BdRange;
import com.hzs.common.domain.system.config.ext.BdRangeDetailsExt;
import com.hzs.common.domain.system.config.ext.BdRangeExt;
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.IBdNoticeService;
import com.hzs.system.config.service.IBdRangeDetailsService;
import com.hzs.system.config.service.IBdRangeService;
import com.hzs.system.config.vo.RangeVo;
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-09
 */
@Slf4j
@RestController
@RequestMapping("/manage/range")
public class BdRangeController extends BaseController {
    @Autowired
    private IBdRangeService rangeService;
    @DubboReference
    private ITransactionServiceApi iTransactionServiceApi;
    @Autowired
    private IBdRangeDetailsService rangeDetailsService;
    @Autowired
    private IBdNoticeService noticeService;

    /**
     * @description: 查询极差配置列表
     * @author: zhang jing
     * @date: 2022/8/30 10:20
     * @param: [range]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.REPURCHASE_RANGE, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BdRange range) {
        QueryWrapper<BdRange> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(range.getRangeName())) {
            queryWrapper.eq("RANGE_NAME", range.getRangeName());
        }
        queryWrapper.orderByDesc("CREATION_TIME");
        List<BdRange> list = rangeService.list(queryWrapper);
        startPage();
        List<BdRangeExt> listExt = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(list)){
            for (BdRange bdRange : list) {
                BdRangeExt rangeExt = BeanUtil.copyProperties(bdRange, BdRangeExt.class);
                BdRangeDetailsExt rangeDetailsExt = new BdRangeDetailsExt();
                rangeDetailsExt.setPkRange(bdRange.getPkId());
                List<BdRangeDetailsExt> rangeDetailsGradeList = new ArrayList<>();
                List<BdRangeDetailsExt> rangeDetailsAwardList = new ArrayList<>();
                List<BdRangeDetailsExt> bdRangeDetailsList = rangeDetailsService.getBdRangeDetailsList(rangeDetailsExt);
                if (CollectionUtil.isNotEmpty(bdRangeDetailsList)) {
                    for (BdRangeDetailsExt brde : bdRangeDetailsList) {
                        if (StringUtils.isNotNull(brde.getRangeType()) && brde.getRangeType() == ERangeType.GRADE.getValue()) {
                            //等级key
                            Integer pkRegisterGrade = noticeService.getGradeTranslateValue(brde.getPkLevel());
                            brde.setPkGrade(pkRegisterGrade);
                            rangeDetailsGradeList.add(brde);
                        }
                        if (StringUtils.isNotNull(brde.getRangeType()) && brde.getRangeType() == ERangeType.AWARDS.getValue()) {
                            //奖衔key
                            Integer pkAward = noticeService.getAwardsTranslateValue(SecurityUtils.getPkCountry(), brde.getPkLevel());
                            brde.setPkAward(pkAward);
                            rangeDetailsAwardList.add(brde);
                        }
                    }
                }
                rangeExt.setRangeDetailsAward(rangeDetailsAwardList);
                rangeExt.setRangeDetailsGrade(rangeDetailsGradeList);
                listExt.add(rangeExt);
            }
        }

        return getDataTable(listExt);
    }

    /**
     * @description: 导出复购极差
     * @author: zhang jing
     * @date: 2023/3/9 15:47
     * @param: [response, range]
     * @return: void
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.REPURCHASE_RANGE, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BdRange range) {
        QueryWrapper<BdRange> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(range.getRangeName())) {
            queryWrapper.eq("RANGE_NAME", range.getRangeName());
        }
        queryWrapper.orderByDesc("CREATION_TIME");
        List<BdRange> list = rangeService.list(queryWrapper);
        startPage();
        List<BdRangeExt> listExt = new ArrayList<>();
        for (BdRange bdRange : list) {
            BdRangeExt rangeExt = BeanUtil.copyProperties(bdRange, BdRangeExt.class);
            BdRangeDetailsExt rangeDetailsExt = new BdRangeDetailsExt();
            rangeDetailsExt.setPkRange(bdRange.getPkId());
            List<BdRangeDetailsExt> rangeDetailsGradeList = new ArrayList<>();
            List<BdRangeDetailsExt> rangeDetailsAwardList = new ArrayList<>();
            List<BdRangeDetailsExt> bdRangeDetailsList = rangeDetailsService.getBdRangeDetailsList(rangeDetailsExt);
            if (CollectionUtil.isNotEmpty(bdRangeDetailsList)) {
                for (BdRangeDetailsExt brde : bdRangeDetailsList) {
                    if (StringUtils.isNotNull(brde.getRangeType()) && brde.getRangeType().intValue() == ERangeType.GRADE.getValue()) {
                        //等级key
                        Integer pkRegisterGrade = noticeService.getGradeTranslateValue(brde.getPkLevel());
                        brde.setPkGrade(pkRegisterGrade);
                        rangeDetailsGradeList.add(brde);
                    }
                    if (StringUtils.isNotNull(brde.getRangeType()) && brde.getRangeType().intValue() == ERangeType.AWARDS.getValue()) {
                        //奖衔key
                        Integer pkAward = noticeService.getAwardsTranslateValue(SecurityUtils.getPkCountry(), brde.getPkLevel());
                        brde.setPkAward(pkAward);
                        rangeDetailsAwardList.add(brde);
                    }
                }
            }
            rangeExt.setRangeDetailsAward(rangeDetailsAwardList);
            rangeExt.setRangeDetailsGrade(rangeDetailsGradeList);
            listExt.add(rangeExt);
        }
        ExcelUtil<BdRangeExt> util = new ExcelUtil<>(BdRangeExt.class);
        util.exportExcel(response, listExt, "复购极差");
    }


    /**
     * @description: 新增极差配置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [range]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.REPURCHASE_RANGE, method = EOperationMethod.INSERT)
    @PostMapping("/generate")
    public AjaxResult generate(@RequestBody BdRangeExt rangeExt) {
        if (StringUtils.isNull(rangeExt.getRangeName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.RANGE_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(rangeExt.getMoneyRatio())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.RANGE_MONEY_RATIO_NOT_NULL));
        }
        if (StringUtils.isNull(rangeExt.getAchieveRatio())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.RANGE_ACHIEVE_RATIO_NOT_NULL));
        }
        if (StringUtils.isNull(rangeExt.getRangeValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.RANGE_VALUE_NOT_NULL));
        }
        List<Integer> gradeList = rangeExt.getGradeList();
        List<Integer> awardsList = rangeExt.getAwardsList();
        if (CollectionUtil.isEmpty(gradeList) && CollectionUtil.isEmpty(awardsList)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PK_GRADE_AWARDS_NOT_NULL));
        }
        QueryWrapper<BdRange> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.eq("RANGE_VALUE", rangeExt.getRangeValue());
        List<BdRange> list = rangeService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.RANGE_VALUE_REPEAT));
        }

        if (StringUtils.isNotNull(rangeExt.getRangeValue())) {
            rangeExt.setPkCountry(SecurityUtils.getPkCountry());
            rangeExt.setPkCreator(SecurityUtils.getUserId());
            rangeExt.setCreationTime(new Date());
            rangeService.saveRange(rangeExt);
        }
        return AjaxResult.success();
    }

    /**
     * @description: 生成极差
     * @author: zhang jing
     * @date: 2022/10/22 9:54
     * @param: [grade]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
//    @Log(module = EModuleType.RANGE, method = EMethodType.INSERT)
//    @PostMapping("/generate")
//    public AjaxResult generate(@RequestBody BdRange range) {
//        return AjaxResult.success(rangeService.generate(range));
//    }


    /**
     * @description: 修改极差配置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [range]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.REPURCHASE_RANGE, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody BdRangeExt rangeExt) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (StringUtils.isNull(rangeExt.getRangeName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.RANGE_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(rangeExt.getMoneyRatio())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.RANGE_MONEY_RATIO_NOT_NULL));
        }
        if (StringUtils.isNull(rangeExt.getAchieveRatio())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.RANGE_ACHIEVE_RATIO_NOT_NULL));
        }
        List<Integer> gradeList = rangeExt.getGradeList();
        List<Integer> awardsList = rangeExt.getAwardsList();
        if (CollectionUtil.isEmpty(gradeList) && CollectionUtil.isEmpty(awardsList)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PK_GRADE_AWARDS_NOT_NULL));
        }

        //字段翻译保存到数据库
        if(null!=rangeExt.getPkTransaction()){
            R<Boolean> b = iTransactionServiceApi.updateTransaction(pkCountry,
                    rangeExt.getRangeName(),rangeExt.getPkTransaction(), true);
        }else{
            //字段翻译保存到数据库
            R<Integer> pkTransaction = iTransactionServiceApi.createTransaction(pkCountry, ETransactionKey.RANGE,
                    rangeExt.getRangeName(), EYesNo.YES, EYesNo.NO);
            rangeExt.setPkTransaction(pkTransaction.getData());
        }
        rangeExt.setPkModified(SecurityUtils.getUserId());
        rangeExt.setPkCountry(pkCountry);
        rangeExt.setModifiedTime(new Date());
        return toAjax(rangeService.updateRange(rangeExt));
    }


    /**
     * @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.REPURCHASE_RANGE, method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Long pkId) {
        BdRange range = rangeService.getById(pkId);
        BdRangeExt rangeExt = BeanUtil.copyProperties(range, BdRangeExt.class);
        BdRangeDetailsExt rangeDetailsExt = new BdRangeDetailsExt();
        List<Integer> gradeList = new ArrayList<>();
        List<Integer> awardsList = new ArrayList<>();
        rangeDetailsExt.setPkRange(pkId.intValue());
        List<BdRangeDetailsExt> bdRangeDetailsList = rangeDetailsService.getBdRangeDetailsList(rangeDetailsExt);
        if (CollectionUtil.isNotEmpty(bdRangeDetailsList)) {
            for (BdRangeDetailsExt bdRangeDetailsExt : bdRangeDetailsList) {
                if (StringUtils.isNotNull(bdRangeDetailsExt.getRangeType()) && ERangeType.GRADE.getValue() == bdRangeDetailsExt.getRangeType()) {
                    gradeList.add(bdRangeDetailsExt.getPkLevel());
                }
                if (StringUtils.isNotNull(bdRangeDetailsExt.getRangeType()) && ERangeType.AWARDS.getValue() == bdRangeDetailsExt.getRangeType()) {
                    awardsList.add(bdRangeDetailsExt.getPkLevel());
                }
            }
        }
        rangeExt.setGradeList(gradeList);
        rangeExt.setAwardsList(awardsList);
        rangeExt.setRangeDetails(bdRangeDetailsList);
        return AjaxResult.success(rangeExt);
    }


    /**
     * @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.REPURCHASE_RANGE, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Long pkId) {
        UpdateWrapper<BdRange> 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());
        BdRange bdRange=rangeService.getById(pkId);
        //删除翻译
        List<Long> pkIdList=new ArrayList<>();
        pkIdList.add(bdRange.getPkTransaction().longValue());
        R<Boolean> b=iTransactionServiceApi.removeTransactionByPkId(pkIdList);
        return toAjax(rangeService.update(updateWrapper));
    }

    /**
     * 查询全部
     *
     * @return
     */
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.REPURCHASE_RANGE, method = EOperationMethod.SELECT)
    @GetMapping("find-all")
    public AjaxResult findAll() {
        List<RangeVo> resultList = new ArrayList<>();
        QueryWrapper<BdRange> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_COUNTRY",SecurityUtils.getPkCountry());
        for (BdRange range : rangeService.list(queryWrapper)) {
            RangeVo rangeVo = BeanUtil.copyProperties(range, RangeVo.class);
            rangeVo.setPkRange(range.getPkId());
            resultList.add(rangeVo);
        }
        return AjaxResult.success(resultList);
    }
}
