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.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.BdStoreLevel;
import com.hzs.common.domain.system.config.BdStoreLevelDetail;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.system.base.ITransactionServiceApi;
import com.hzs.system.config.service.IBdStoreLevelDetailService;
import com.hzs.system.config.service.IBdStoreLevelService;
import com.hzs.system.config.vo.BdStoreLevelVO;
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 hzs
 * @since 2023-05-04
 */
@RestController
@RequestMapping("/manage/store-level")
public class BdStoreLevelController extends BaseController {

    @Autowired
    private IBdStoreLevelService storeLevelService;
    @DubboReference
    private ITransactionServiceApi iTransactionServiceApi;
    @Autowired
    private IBdStoreLevelDetailService storeLevelDetailService;

    /**
     * @description: 查询店铺等级配置列表
     * @author: zhang jing
     * @date: 2022/8/30 10:20
     * @param: [storeLevel]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.STORE_LEVEL, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BdStoreLevelVO storeLevel) {
        startPage();
        QueryWrapper<BdStoreLevel> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(storeLevel.getStoreLevelName())) {
            queryWrapper.eq("SHOP_NAME", storeLevel.getStoreLevelName());
        }
        if (StringUtils.isNotNull(storeLevel.getLevelValue())) {
            queryWrapper.eq("LEVEL_VALUE", storeLevel.getLevelValue());
        }
        queryWrapper.orderByDesc("CREATION_TIME");
        List<BdStoreLevel> list = storeLevelService.list(queryWrapper);
        List<BdStoreLevelVO> listVO = new ArrayList<>();
        list.forEach(item -> listVO.add(BeanUtil.copyProperties(item, BdStoreLevelVO.class)));
        listVO.forEach(
                itm -> {
                    QueryWrapper<BdStoreLevelDetail> queryWrapper1 = new QueryWrapper();
                    queryWrapper1.eq("PK_STORE_LEVEL", itm.getPkId());
                    List<BdStoreLevelDetail> detailsList = storeLevelDetailService.list(queryWrapper1);
                    itm.setDetailList(detailsList);
                }
        );
        TableDataInfo tableDataInfo = getDataTable(list);
        tableDataInfo.setRows(listVO);
        return tableDataInfo;
    }

    /**
     * @description: 店铺等级下拉选
     * @author: zhang jing
     * @date: 2023/5/15 14:23
     * @param: [storeLevel]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.STORE_LEVEL, method = EOperationMethod.SELECT)
    @GetMapping("/listNoPage")
    public AjaxResult listNoPage(BdStoreLevel storeLevel) {
        QueryWrapper<BdStoreLevel> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.orderByAsc("LEVEL_VALUE");
        List<BdStoreLevel> list = storeLevelService.list(queryWrapper);
        List<BdStoreLevelVO> listVO = new ArrayList<>();
        list.forEach(item -> listVO.add(BeanUtil.copyProperties(item, BdStoreLevelVO.class)));
        return AjaxResult.success(listVO);
    }


    /**
     * @description: 导出配送中心等级
     * @author: zhang jing
     * @date: 2023/3/9 16:08
     * @param: [response, storeLevel]
     * @return: void
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.STORE_LEVEL, method = EOperationMethod.SELECT)
    @GetMapping("/export")
    public void export(HttpServletResponse response, BdStoreLevel storeLevel) {
        QueryWrapper<BdStoreLevel> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(storeLevel.getStoreLevelName())) {
            queryWrapper.eq("SHOP_NAME", storeLevel.getStoreLevelName());
        }
        queryWrapper.orderByDesc("CREATION_TIME");
        List<BdStoreLevel> list = storeLevelService.list(queryWrapper);
        List<BdStoreLevelVO> listVO = new ArrayList<>();
        list.forEach(item -> listVO.add(BeanUtil.copyProperties(item, BdStoreLevelVO.class)));
        listVO.forEach(
                itm -> {
                    QueryWrapper<BdStoreLevelDetail> queryWrapper1 = new QueryWrapper();
                    queryWrapper1.eq("PK_STORE_LEVEL", itm.getPkId());
                    List<BdStoreLevelDetail> detailsList = storeLevelDetailService.list(queryWrapper1);
                    itm.setDetailList(detailsList);
                }
        );
        ExcelUtil<BdStoreLevelVO> util = new ExcelUtil<>(BdStoreLevelVO.class);
        util.exportExcel(response, listVO, "店铺等级");
    }


    /**
     * @description: 新增店铺等级配置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [storeLevel]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.STORE_LEVEL, method = EOperationMethod.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody BdStoreLevelVO storeLevel) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (StringUtils.isEmpty(storeLevel.getStoreLevelName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.STORE_LEVEL_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(storeLevel.getLevelValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LEVEL_VALUE_NOT_NULL));
        }

        if(CollectionUtil.isEmpty(storeLevel.getDetailList())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.STORE_DETAIL_NOT_NULL));
        }
        for(BdStoreLevelDetail sd:storeLevel.getDetailList()){
            if(StringUtils.isNull(sd.getRatio())){
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.STORE_DETAIL_NOT_NULL));
            }
        }

        QueryWrapper<BdStoreLevel> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", pkCountry);
        queryWrapper.eq("LEVEL_VALUE", storeLevel.getLevelValue());
        List<BdStoreLevel> list = storeLevelService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LEVEL_VALUE_REPEAT));
        }
        //字段翻译保存到数据库
        R<Integer> pkTransaction = iTransactionServiceApi.createTransaction(pkCountry, ETransactionKey.STORE_LEVEL,
                storeLevel.getStoreLevelName(), EYesNo.NO, EYesNo.NO);
        storeLevel.setPkTransaction(pkTransaction.getData());
        storeLevel.setPkCountry(pkCountry);
        storeLevel.setPkCreator(SecurityUtils.getUserId());
        storeLevel.setCreationTime(new Date());
        storeLevelService.saveStoreLevel(storeLevel);
        return AjaxResult.success();
    }

    /**
     * @description: 修改店铺等级配置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [storeLevel]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.STORE_LEVEL, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody BdStoreLevelVO storeLevel) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (StringUtils.isEmpty(storeLevel.getStoreLevelName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.STORE_LEVEL_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(storeLevel.getLevelValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LEVEL_VALUE_NOT_NULL));
        }
        if(CollectionUtil.isEmpty(storeLevel.getDetailList())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.STORE_DETAIL_NOT_NULL));
        }
        for(BdStoreLevelDetail sd:storeLevel.getDetailList()){
            if(StringUtils.isNull(sd.getRatio())){
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.STORE_DETAIL_NOT_NULL));
            }
        }

        QueryWrapper<BdStoreLevel> queryWrapper = new QueryWrapper();
        queryWrapper.ne("PK_ID", storeLevel.getPkId());
        queryWrapper.eq("PK_COUNTRY", pkCountry);
        queryWrapper.eq("LEVEL_VALUE", storeLevel.getLevelValue());
        List<BdStoreLevel> list = storeLevelService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LEVEL_VALUE_REPEAT));
        }

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

    /**
     * @description:修改启用状态
     * @author: zhang jing
     * @date: 2023/4/24 14:54
     * @param: [storeLevel]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.STORE_LEVEL, method = EOperationMethod.UPDATE)
    @PostMapping("/updateState")
    public AjaxResult updateState(@RequestBody BdStoreLevel storeLevel) {
        if (StringUtils.isNull(storeLevel.getEnableState())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ENABLE_STATE_NOT_NULL));
        }
        if (StringUtils.isNull(storeLevel.getPkId())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.HO_OBJECT_NOT_REPEAT));
        }

        storeLevel.setPkCountry(SecurityUtils.getPkCountry());
        storeLevel.setPkModified(SecurityUtils.getUserId());
        storeLevel.setModifiedTime(new Date());
        return AjaxResult.success(storeLevelService.updateById(storeLevel));
    }


    /**
     * @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.STORE_LEVEL, method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Long pkId) {
        BdStoreLevel storeLevel = storeLevelService.getById(pkId);
        BdStoreLevelVO stVO=BeanUtil.copyProperties(storeLevel, BdStoreLevelVO.class);
        QueryWrapper<BdStoreLevelDetail> queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("PK_STORE_LEVEL", pkId);
        List<BdStoreLevelDetail> detailsList = storeLevelDetailService.list(queryWrapper1);
        stVO.setDetailList(detailsList);
        return AjaxResult.success(stVO);
    }


    /**
     * @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.STORE_LEVEL, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Integer pkId) {
        BdStoreLevelVO stVO=new BdStoreLevelVO();
        stVO.setPkId(pkId);
        stVO.setPkModified(SecurityUtils.getUserId());
        stVO.setModifiedTime(new Date());
        return toAjax(storeLevelService.delStoreLevel(stVO));
    }
}
