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.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
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.BdAwards;
import com.hzs.common.domain.system.config.BdGrade;
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.util.TransactionUtils;
import com.hzs.system.config.service.IBdAwardsService;
import com.hzs.system.config.service.IBdGradeService;
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.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;

/**
 * 新零售极差配置 前端控制器
 */
@Slf4j
@RestController
@RequestMapping("/manage/retail-range")
public class BdRetailRangeController extends BaseController {

    @Autowired
    private IBdRangeService iBdRangeService;
    @Autowired
    private IBdRangeDetailsService iBdRangeDetailsService;
    @Autowired
    private IBdGradeService iBdGradeService;
    @Autowired
    private IBdAwardsService iBdAwardsService;

    /**
     * 查询极差配置列表
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.REPURCHASE_RANGE, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BdRange range) {
        LambdaQueryWrapper<BdRange> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdRange::getPkCountry, SecurityUtils.getPkCountry());
        queryWrapper.eq(BdRange::getSystemType, ESystemType.DEFAULT.getValue());
        if (StringUtils.isNotNull(range.getRangeName())) {
            queryWrapper.eq(BdRange::getRangeName, range.getRangeName());
        }
        queryWrapper.orderByDesc(BdRange::getRangeValue, BdRange::getCreationTime);
        startPage();
        List<BdRange> list = iBdRangeService.list(queryWrapper);

        List<BdRangeExt> listExt = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (BdRange bdRange : list) {
                BdRangeExt rangeExt = BeanUtil.copyProperties(bdRange, BdRangeExt.class);
                List<BdRangeDetailsExt> rangeDetailsGradeList = new ArrayList<>();
                List<BdRangeDetailsExt> rangeDetailsAwardList = new ArrayList<>();

                BdRangeDetailsExt rangeDetailsExt = new BdRangeDetailsExt();
                rangeDetailsExt.setPkRange(bdRange.getPkId());
                List<BdRangeDetailsExt> bdRangeDetailsList = iBdRangeDetailsService.getBdRangeDetailsList(rangeDetailsExt);
                if (CollectionUtil.isNotEmpty(bdRangeDetailsList)) {
                    for (BdRangeDetailsExt brde : bdRangeDetailsList) {
                        if (StringUtils.isNotNull(brde.getRangeType()) && brde.getRangeType() == ERangeType.GRADE.getValue()) {
                            // 等级
                            BdGrade bdGrade = iBdGradeService.getBdGrade(brde.getPkLevel());
                            brde.setPkGrade(bdGrade.getPkId());
                            brde.setPkGradeVal(bdGrade.getGradeName());
                            rangeDetailsGradeList.add(brde);
                        }
                        if (StringUtils.isNotNull(brde.getRangeType()) && brde.getRangeType() == ERangeType.AWARDS.getValue()) {
                            // 奖衔
                            BdAwards bdAwards = iBdAwardsService.getBdAwardsOne(brde.getPkLevel());
                            brde.setPkAward(bdAwards.getPkId());
                            brde.setPkAwardVal(bdAwards.getAwardsName());
                            rangeDetailsAwardList.add(brde);
                        }
                    }
                }
                rangeExt.setRangeDetailsGrade(rangeDetailsGradeList);
                rangeExt.setRangeDetailsAward(rangeDetailsAwardList);
                listExt.add(rangeExt);
            }
        }
        return getDataTable(listExt);
    }

    /**
     * 导出复购极差
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.REPURCHASE_RANGE, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BdRange range) {
        LambdaQueryWrapper<BdRange> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdRange::getPkCountry, SecurityUtils.getPkCountry());
        queryWrapper.eq(BdRange::getSystemType, ESystemType.DEFAULT.getValue());
        if (StringUtils.isNotNull(range.getRangeName())) {
            queryWrapper.eq(BdRange::getRangeName, range.getRangeName());
        }
        queryWrapper.orderByDesc(BdRange::getCreationTime);
        List<BdRange> list = iBdRangeService.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 = iBdRangeDetailsService.getBdRangeDetailsList(rangeDetailsExt);
            if (CollectionUtil.isNotEmpty(bdRangeDetailsList)) {
                for (BdRangeDetailsExt brde : bdRangeDetailsList) {
                    if (StringUtils.isNotNull(brde.getRangeType()) && brde.getRangeType() == ERangeType.GRADE.getValue()) {
                        // 等级
                        BdGrade bdGrade = iBdGradeService.getBdGrade(brde.getPkLevel());
                        brde.setPkGrade(bdGrade.getPkId());
                        brde.setPkGradeVal(bdGrade.getGradeName());
                        rangeDetailsGradeList.add(brde);
                    }
                    if (StringUtils.isNotNull(brde.getRangeType()) && brde.getRangeType() == ERangeType.AWARDS.getValue()) {
                        // 奖衔
                        BdAwards bdAwards = iBdAwardsService.getBdAwardsOne(brde.getPkLevel());
                        brde.setPkAward(bdAwards.getPkId());
                        brde.setPkAwardVal(bdAwards.getAwardsName());
                        rangeDetailsAwardList.add(brde);
                    }
                }
            }
            rangeExt.setRangeDetailsGrade(rangeDetailsGradeList);
            rangeExt.setRangeDetailsAward(rangeDetailsAwardList);
            listExt.add(rangeExt);
        }
        ExcelUtil<BdRangeExt> util = new ExcelUtil<>(BdRangeExt.class);
        util.exportExcel(response, listExt, "复购级差");
    }

    /**
     * 新增极差配置
     **/
    @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));
        }
        LambdaQueryWrapper<BdRange> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdRange::getPkCountry, SecurityUtils.getPkCountry());
        queryWrapper.eq(BdRange::getRangeValue, rangeExt.getRangeValue());
        queryWrapper.eq(BdRange::getSystemType, ESystemType.DEFAULT.getValue());
        List<BdRange> list = iBdRangeService.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());
            rangeExt.setSystemType(ESystemType.DEFAULT.getValue());
            iBdRangeService.saveRange(rangeExt);
        }
        return AjaxResult.success();
    }

    /**
     * 修改极差配置
     **/
    @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));
        }

        rangeExt.setPkModified(SecurityUtils.getUserId());
        rangeExt.setPkCountry(pkCountry);
        rangeExt.setModifiedTime(new Date());
        return toAjax(iBdRangeService.updateRange(rangeExt));
    }

    /**
     * 查询单条极差配置
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.REPURCHASE_RANGE, method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Long pkId) {
        BdRange range = iBdRangeService.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 = iBdRangeDetailsService.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);
    }

    /**
     * 删除极差配置
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.REPURCHASE_RANGE, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Long pkId) {
        LambdaUpdateWrapper<BdRange> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BdRange::getPkId, pkId);
        updateWrapper.set(BdRange::getDelFlag, EDelFlag.DELETE.getValue());
        updateWrapper.set(BdRange::getPkModified, SecurityUtils.getUserId());
        updateWrapper.set(BdRange::getModifiedTime, new Date());
        BdRange bdRange = iBdRangeService.getById(pkId);
        return toAjax(iBdRangeService.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<>();
        LambdaQueryWrapper<BdRange> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdRange::getPkCountry, SecurityUtils.getPkCountry());
        queryWrapper.eq(BdRange::getSystemType, ESystemType.DEFAULT.getValue());
        for (BdRange range : iBdRangeService.list(queryWrapper)) {
            RangeVo rangeVo = BeanUtil.copyProperties(range, RangeVo.class);
            rangeVo.setPkRange(range.getPkId());
            resultList.add(rangeVo);
        }
        return AjaxResult.success(resultList);
    }

}
