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.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.page.TableDataInfo;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.common.domain.system.config.ext.BdAwardsExt;
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.IBdAwardsDetailService;
import com.hzs.system.config.service.IBdAwardsService;
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/awards")
public class BdAwardsController extends BaseController {

    @Autowired
    private IBdAwardsService awardsService;
    @DubboReference
    private ITransactionServiceApi iTransactionServiceApi;
    @Autowired
    private IBdAwardsDetailService awardsDetailService;
    @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: [awards]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.AWARD_CONTROL, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BdAwards awards) {
        startPage();
        QueryWrapper<BdAwards> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(awards.getAwardsName())) {
            queryWrapper.eq("AWARDS_NAME", awards.getAwardsName());
        }
        queryWrapper.orderByAsc("AWARDS_VALUE");
        List<BdAwardsExt> listExt = new ArrayList<>();
        List<BdAwards> list = awardsService.list(queryWrapper);
        list.forEach(item -> listExt.add(BeanUtil.copyProperties(item, BdAwardsExt.class)));
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (CollectionUtil.isNotEmpty(listExt)) {
            for (BdAwardsExt ae : listExt) {
                if (StringUtils.isNotNull(ae.getPkCheckAwardsLeft())) {
                    ae.setPkCheckAwardsLeft(noticeService.getAwardsTranslateValue(pkCountry, ae.getPkCheckAwardsLeft()));
                }
                if (StringUtils.isNotNull(ae.getPkCheckAwardsRight())) {
                    ae.setPkCheckAwardsRight(noticeService.getAwardsTranslateValue(pkCountry, ae.getPkCheckAwardsRight()));
                }
            }
        }
        return getDataTable(listExt);
    }

    /**
     * @description: 导出奖衔配置
     * @author: zhang jing
     * @date: 2023/3/9 15:32
     * @param: [response, awards]
     * @return: void
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.AWARD_CONTROL, method = EOperationMethod.SELECT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BdAwards awards) {
        startPage();
        QueryWrapper<BdAwards> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(awards.getAwardsName())) {
            queryWrapper.eq("AWARDS_NAME", awards.getAwardsName());
        }
        queryWrapper.orderByAsc("AWARDS_VALUE");
        List<BdAwardsExt> listExt = new ArrayList<>();
        List<BdAwards> list = awardsService.list(queryWrapper);
        list.forEach(item -> listExt.add(BeanUtil.copyProperties(item, BdAwardsExt.class)));
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (CollectionUtil.isNotEmpty(listExt)) {
            for (BdAwardsExt ae : listExt) {
                ae.setPkCheckAwardsLeft(noticeService.getAwardsTranslateValue(pkCountry, ae.getPkCheckAwardsLeft()));
                ae.setPkCheckAwardsRight(noticeService.getAwardsTranslateValue(pkCountry, ae.getPkCheckAwardsRight()));
            }
        }
        ExcelUtil<BdAwardsExt> util = new ExcelUtil<>(BdAwardsExt.class);
        util.exportExcel(response, listExt, "奖衔配置");
    }

    /**
     * @description: 真实奖衔下拉选
     * @author: zhang jing
     * @date: 2022/10/27 10:15
     * @param: [awards]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.AWARD_CONTROL, method = EOperationMethod.SELECT)
    @GetMapping("/awardsList")
    public TableDataInfo awardsList(BdAwards awards) {
        QueryWrapper<BdAwards> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.orderByAsc("AWARDS_VALUE");
        List<BdAwards> list = awardsService.list(queryWrapper);
        List<BdAwardsExt> listExt = new ArrayList<>();
        for (BdAwards ba : list) {
            BdAwardsExt baExt = new BdAwardsExt();
            baExt.setPkId(ba.getPkId());
            baExt.setAwardsValue(ba.getAwardsValue());
            baExt.setAwardsName(ba.getAwardsName());
            listExt.add(baExt);
        }
        return getDataTable(listExt);
    }

    /**
     * @description: 辅导分红列表
     * @author: zhang jing
     * @date: 2022/10/27 10:15
     * @param: [awards]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.AWARD_CONTROL, method = EOperationMethod.SELECT)
    @GetMapping("/coachBonusList")
    public TableDataInfo coachBonusList(BdAwards awards) {
        QueryWrapper<BdAwards> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.orderByAsc("AWARDS_VALUE");
        List<BdAwards> list = awardsService.list(queryWrapper);
        List<BdAwardsExt> listExt = new ArrayList<>();
        for (BdAwards ba : list) {
            BdAwardsExt baExt = new BdAwardsExt();
            baExt.setPkId(ba.getPkId());
            baExt.setAwardsName(ba.getAwardsName());
            baExt.setCoachAlgebra(ba.getCoachAlgebra());
            baExt.setCoachRatio(ba.getCoachRatio());
            baExt.setAbonusRatio(ba.getAbonusRatio());
            listExt.add(baExt);
        }
        return getDataTable(listExt);
    }

    /**
     * @description: 环球积分列表+车奖积分列表
     * @author: zhang jing
     * @date: 2022/11/2 9:16
     * @param: [awards]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.AWARD_CONTROL, method = EOperationMethod.SELECT)
    @GetMapping("/integralList")
    public TableDataInfo integralList(BdAwards awards) {
        QueryWrapper<BdAwards> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.orderByAsc("AWARDS_VALUE");
        List<BdAwards> list = awardsService.list(queryWrapper);
        List<BdAwardsExt> listExt = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (BdAwards ba : list) {
                BdAwardsExt baExt = new BdAwardsExt();
                baExt.setPkId(ba.getPkId());
                baExt.setAwardsName(ba.getAwardsName());
                baExt.setGlobalIntegral(ba.getGlobalIntegral());
                baExt.setCarAwardPoints(ba.getCarAwardPoints());
                listExt.add(baExt);
            }
        }
        return getDataTable(listExt);
    }


    /**
     * @description: 新增奖衔配置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [awards]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.AWARD_CONTROL, method = EOperationMethod.INSERT)
    @PostMapping("/generate")
    public AjaxResult generate(@RequestBody BdAwards awards) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (StringUtils.isNull(awards.getAwardsValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.AWARDS_VALUE_NOT_NULL));
        }
        if (StringUtils.isEmpty(awards.getAwardsName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.AWARDS_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(awards.getCommunityCheck())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.COMMUNITY_CHECK_NOT_NULL));
        }
//        if (StringUtils.isNull(awards.getPurchaseCheck())) {
//            return AjaxResult.error(ConfigMsgConstants.PURCHASE_CHECK_NOT_NULL);
//        }
//        if (StringUtils.isNull(awards.getShareCheck())) {
//            return AjaxResult.error(ConfigMsgConstants.SHARE_CHECK_NOT_NULL);
//        }
        if (StringUtils.isNull(awards.getColor())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.COLOR_NOT_NULL));
        }

        if ((null == awards.getPkCheckAwardsLeft() || null == awards.getPkCheckAwardsRight()) && StringUtils.isNotNull(awards.getRelationType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LEFT_RIGHT_AWARDS_NAME_NOT_NULL));
        }
        awards.setPkCountry(SecurityUtils.getPkCountry());
        awards.setPkCreator(SecurityUtils.getUserId());
        awards.setCreationTime(new Date());

        QueryWrapper<BdAwards> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.eq("AWARDS_VALUE", awards.getAwardsValue());
        List<BdAwards> list1 = awardsService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list1)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DATA_REPEAT));
        }
//        字段翻译保存到数据库
        R<Integer> pkTransaction = iTransactionServiceApi.createTransaction(pkCountry, ETransactionKey.AWARDS,
                awards.getAwardsName(), EYesNo.YES, EYesNo.NO);
        awards.setPkTransaction(pkTransaction.getData());
        redisService.deleteObjectByKey(CacheConstants.BD_AWARDS + pkCountry);
        awardsService.save(awards);
        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.AWARDS, method = EMethodType.INSERT)
//    @PostMapping("/generate")
//    public AjaxResult generate(@RequestBody BdAwards awards) {
//        return AjaxResult.success(awardsService.generate(awards));
//    }


    /**
     * @description: 修改奖衔配置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [awards]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.AWARD_CONTROL, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody BdAwards awards) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (StringUtils.isNull(awards.getAwardsValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.AWARDS_VALUE_NOT_NULL));
        }
        if (StringUtils.isEmpty(awards.getAwardsName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.AWARDS_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(awards.getCommunityCheck())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.COMMUNITY_CHECK_NOT_NULL));
        }
//        if (StringUtils.isNull(awards.getPurchaseCheck())) {
//            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PURCHASE_CHECK_NOT_NULL));
//        }
//        if (StringUtils.isNull(awards.getShareCheck())) {
//            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SHARE_CHECK_NOT_NULL));
//        }
        if (StringUtils.isNull(awards.getColor())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.COLOR_NOT_NULL));
        }
        if ((null == awards.getPkCheckAwardsLeft() || null == awards.getPkCheckAwardsRight()) && StringUtils.isNotNull(awards.getRelationType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LEFT_RIGHT_AWARDS_NAME_NOT_NULL));
        }

        QueryWrapper<BdAwards> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.eq("AWARDS_VALUE", awards.getAwardsValue());
        queryWrapper.ne("PK_ID", awards.getPkId());
        List<BdAwards> list1 = awardsService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list1)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DATA_REPEAT));
        }

        //字段翻译保存到数据库
        if (null != awards.getPkTransaction()) {
            R<Boolean> b = iTransactionServiceApi.updateTransaction(pkCountry,
                    awards.getAwardsName(), awards.getPkTransaction(), true);
        } else {
            R<Integer> pkTransaction = iTransactionServiceApi.createTransaction(pkCountry, ETransactionKey.AWARDS,
                    awards.getAwardsName(), EYesNo.YES, EYesNo.NO);
            awards.setPkTransaction(pkTransaction.getData());
        }
        awards.setPkModified(SecurityUtils.getUserId());
        awards.setModifiedTime(new Date());
        redisService.deleteObjectByKey(CacheConstants.BD_AWARDS + pkCountry);
        return toAjax(awardsService.updateById(awards));
    }

    /**
     * @description: 修改启用禁用
     * @author: zhang jing
     * @date: 2023/4/24 14:30
     * @param: [gradeExt]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.AWARD_CONTROL, method = EOperationMethod.UPDATE)
    @PostMapping("/updateState")
    public AjaxResult updateState(@RequestBody BdAwards awards) {
        if (StringUtils.isNull(awards.getEnableState())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ENABLE_STATE_NOT_NULL));
        }
        if (StringUtils.isNull(awards.getPkId())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.HO_OBJECT_NOT_REPEAT));
        }
        UpdateWrapper<BdAwards> updateWrapper = new UpdateWrapper();
        updateWrapper.set("ENABLE_STATE", awards.getEnableState());
        updateWrapper.eq("PK_ID", awards.getPkId());
        updateWrapper.set("PK_MODIFIED", SecurityUtils.getUserId());
        updateWrapper.set("MODIFIED_TIME", new Date());
        awardsService.update(updateWrapper);
        redisService.deleteObjectByKey(CacheConstants.BD_AWARDS + SecurityUtils.getPkCountry());
        return AjaxResult.success();
    }

    /**
     * @description: 修改辅导分红
     * @author: zhang jing
     * @date: 2022/10/31 19:39
     * @param: [awards]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.AWARD_CONTROL, method = EOperationMethod.UPDATE)
    @PostMapping("/updateCoachBonus")
    public AjaxResult updateCoachBonus(@RequestBody BdAwardsExt awardsExt) {
        if (CollectionUtil.isNotEmpty(awardsExt.getAwardsList())) {
            for (BdAwards awards : awardsExt.getAwardsList()) {
                if (StringUtils.isNull(awards.getPkId())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PK_GRADE_AWARDS_NOT_NULL));
                }
                if (StringUtils.isNull(awards.getCoachAlgebra())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.COACH_ALGEBRA_NOT_NULL));
                }
                if (StringUtils.isNull(awards.getCoachRatio())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.COACH_RATIO_NOT_NULL));
                }
                if (StringUtils.isNull(awards.getAbonusRatio())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ABONUS_RATIO_NOT_NULL));
                }
                awards.setPkCountry(SecurityUtils.getPkCountry());
                awards.setPkModified(SecurityUtils.getUserId());
                awards.setModifiedTime(new Date());
            }
            redisService.deleteObjectByKey(CacheConstants.BD_AWARDS_COACH + SecurityUtils.getPkCountry());
            return AjaxResult.success(awardsService.updateAwards(awardsExt));
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * @description: 修改环球积分
     * @author: zhang jing
     * @date: 2022/11/2 9:38
     * @param: [awardsExt]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.AWARD_CONTROL, method = EOperationMethod.UPDATE)
    @PostMapping("/updategLobalIntegral")
    public AjaxResult updategLobalIntegral(@RequestBody BdAwardsExt awardsExt) {
        if (CollectionUtil.isNotEmpty(awardsExt.getLobalIntegralList())) {
            for (BdAwards awards : awardsExt.getLobalIntegralList()) {
                if (StringUtils.isNull(awards.getPkId())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PK_GRADE_AWARDS_NOT_NULL));
                }
                if (StringUtils.isNull(awards.getGlobalIntegral())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.GLOBAL_INTEGRAL_NOT_NULL));
                }

                awards.setPkCountry(SecurityUtils.getPkCountry());
                awards.setPkModified(SecurityUtils.getUserId());
                awards.setModifiedTime(new Date());
            }
            return AjaxResult.success(awardsService.updateLobalIntegral(awardsExt));
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * @description: 修改车奖积分
     * @author: zhang jing
     * @date: 2022/11/2 9:38
     * @param: [awardsExt]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.AWARD_CONTROL, method = EOperationMethod.UPDATE)
    @PostMapping("/updategCarAwardPoints")
    public AjaxResult updateCarAwardPoints(@RequestBody BdAwardsExt awardsExt) {
        if (CollectionUtil.isNotEmpty(awardsExt.getCarAwardPointsList())) {
            for (BdAwards awards : awardsExt.getCarAwardPointsList()) {
                if (StringUtils.isNull(awards.getPkId())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PK_GRADE_AWARDS_NOT_NULL));
                }
                if (StringUtils.isNull(awards.getCarAwardPoints())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.CAR_AWARD_POINTS_NOT_NULL));
                }

                awards.setPkCountry(SecurityUtils.getPkCountry());
                awards.setPkModified(SecurityUtils.getUserId());
                awards.setModifiedTime(new Date());
            }
            return AjaxResult.success(awardsService.updateGlobalIntegral(awardsExt));
        } 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.AWARD_CONTROL, method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Long pkId) {
        BdAwards awards = awardsService.getById(pkId);
        return AjaxResult.success(awards);
    }


    /**
     * @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.AWARD_CONTROL, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Long pkId) {
        UpdateWrapper<BdAwards> 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.deleteObjectByKey(CacheConstants.BD_AWARDS + SecurityUtils.getPkCountry());
        redisService.deleteObjectByKey(CacheConstants.BD_AWARDS_COACH + SecurityUtils.getPkCountry());
        Integer count = awardsService.checkGradeAwards(null, null, pkId);
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ENABLE_STATE_NOT_DELETE));
        }
        return AjaxResult.success(awardsService.update(updateWrapper));
    }
}
