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.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.BdShop;
import com.hzs.common.domain.system.config.ext.BdShopExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.system.base.service.IBdCountryService;
import com.hzs.system.base.service.IBdCurrencyService;
import com.hzs.system.config.service.IBdShopService;
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/shop")
public class BdShopController extends BaseController {

    @Autowired
    private IBdShopService iBdShopService;
    @Autowired
    private IBdCurrencyService iBdCurrencyService;
    @Autowired
    private IBdCountryService iBdCountryService;

    @Autowired
    private RedisService redisService;

    /**
     * 查询店铺配置列表
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.SHOP, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BdShop shop) {
        startPage();
        LambdaQueryWrapper<BdShop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdShop::getPkCountry, SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(shop.getShopName())) {
            queryWrapper.eq(BdShop::getShopName, shop.getShopName());
        }
        queryWrapper.orderByDesc(BdShop::getCreationTime);
        BdCountry country = iBdCountryService.getCountry(SecurityUtils.getPkCountry());
        List<BdShopExt> listExt = new ArrayList<>();
        List<BdShop> list = iBdShopService.list(queryWrapper);
        list.forEach(item -> listExt.add(BeanUtil.copyProperties(item, BdShopExt.class)));
        for (BdShopExt bs : listExt) {
            if (StringUtils.isNotNull(bs.getRegisterValue())) {
                bs.setNationalFlag2(country.getNationalFlag2());
                bs.setRegisterValueLocal(iBdCurrencyService.getDollar(bs.getRegisterValue(), SecurityUtils.getPkCountry()));
            }
        }
        return getDataTable(listExt);
    }

    /**
     * 导出配送中心等级
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.SHOP, method = EOperationMethod.SELECT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BdShop shop) {
        startPage();
        LambdaQueryWrapper<BdShop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdShop::getPkCountry, SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(shop.getShopName())) {
            queryWrapper.eq(BdShop::getShopName, shop.getShopName());
        }
        queryWrapper.orderByDesc(BdShop::getCreationTime);
        BdCountry country = iBdCountryService.getCountry(SecurityUtils.getPkCountry());
        List<BdShopExt> listExt = new ArrayList<>();
        List<BdShop> list = iBdShopService.list(queryWrapper);
        list.forEach(item -> listExt.add(BeanUtil.copyProperties(item, BdShopExt.class)));
        for (BdShopExt bs : listExt) {
            if (StringUtils.isNotNull(bs.getRegisterValue())) {
                bs.setNationalFlag2(country.getNationalFlag2());
                bs.setRegisterValueLocal(iBdCurrencyService.getDollar(bs.getRegisterValue(), SecurityUtils.getPkCountry()));
            }
        }
        ExcelUtil<BdShopExt> util = new ExcelUtil<>(BdShopExt.class);
        util.exportExcel(response, listExt, "配送中心等级");
    }


    /**
     * 新增店铺配置
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.SHOP, method = EOperationMethod.INSERT)
    @PostMapping("/generate")
    public AjaxResult generate(@RequestBody BdShop shop) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (StringUtils.isEmpty(shop.getShopName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SHOP_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(shop.getRegisterValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.REGISTER_VALUE_NOT_NULL));
        }

        if (StringUtils.isNull(shop.getCensusValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.CENSUS_VALUE_NOT_NULL));
        }
        if (StringUtils.isNull(shop.getSettleValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SHOP_SETTLE_VALUE_NOT_NULL));
        }
        if (StringUtils.isNull(shop.getDeliveryFee())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DELIVERY_FEE_NOT_NULL));
        }
        if (StringUtils.isNull(shop.getEffectiveDate())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EFFECTIVE_DATE_NOT_NULL));
        }

        LambdaQueryWrapper<BdShop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdShop::getPkCountry, pkCountry);
        if (StringUtils.isNotNull(shop.getShopName())) {
            queryWrapper.eq(BdShop::getShopName, shop.getShopName());
        }
        List<BdShop> list = iBdShopService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SHOP_NAME_REPEAT));
        }
        LambdaQueryWrapper<BdShop> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(BdShop::getPkCountry, pkCountry);
        list = iBdShopService.list(queryWrapper1);
        int count = 1;
        if (CollectionUtil.isNotEmpty(list)) {
            count = count + list.size();
        }
        for (EShop value : EShop.values()) {
            if (value.getIndex() == count) {
                shop.setShopValue(value.getValue());
            }
        }
        if (StringUtils.isNotNull(shop.getShopValue())) {
            shop.setPkCountry(pkCountry);
            shop.setPkCreator(SecurityUtils.getUserId());
            shop.setCreationTime(new Date());
            LambdaQueryWrapper<BdShop> queryWrapperCheck = new LambdaQueryWrapper<>();
            queryWrapperCheck.eq(BdShop::getShopValue, shop.getShopValue());
            queryWrapperCheck.eq(BdShop::getPkCountry, pkCountry);
            List<BdShop> list1 = iBdShopService.list(queryWrapperCheck);
            if (CollectionUtil.isEmpty(list1)) {
                iBdShopService.save(shop);
            }
            return AjaxResult.success();
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DATA_REPEAT));
        }
    }

    /**
     * 修改店铺配置
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.SHOP, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody BdShop shop) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (StringUtils.isEmpty(shop.getShopName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SHOP_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(shop.getRegisterValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.REGISTER_VALUE_NOT_NULL));
        }

        if (StringUtils.isNull(shop.getCensusValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.CENSUS_VALUE_NOT_NULL));
        }
        if (StringUtils.isNull(shop.getSettleValue())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SHOP_SETTLE_VALUE_NOT_NULL));
        }
        if (StringUtils.isNull(shop.getDeliveryFee())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DELIVERY_FEE_NOT_NULL));
        }
        if (StringUtils.isNull(shop.getEffectiveDate())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EFFECTIVE_DATE_NOT_NULL));
        }

        shop.setPkCountry(pkCountry);
        shop.setPkModified(SecurityUtils.getUserId());
        shop.setModifiedTime(new Date());
        redisService.deleteObjectByKey(CacheConstants.BD_SHOP + pkCountry);
        return toAjax(iBdShopService.updateById(shop));
    }

    /**
     * 修改启用状态
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.SHOP, method = EOperationMethod.UPDATE)
    @PostMapping("/updateState")
    public AjaxResult updateState(@RequestBody BdShop shop) {
        if (StringUtils.isNull(shop.getEnableState())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ENABLE_STATE_NOT_NULL));
        }
        if (StringUtils.isNull(shop.getPkId())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.HO_OBJECT_NOT_REPEAT));
        }
        LambdaUpdateWrapper<BdShop> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(BdShop::getEnableState, shop.getEnableState());
        updateWrapper.eq(BdShop::getPkId, shop.getPkId());
        updateWrapper.set(BdShop::getPkModified, SecurityUtils.getUserId());
        updateWrapper.set(BdShop::getModifiedTime, new Date());
        iBdShopService.update(updateWrapper);
        redisService.deleteObjectByKey(CacheConstants.BD_SHOP + SecurityUtils.getPkCountry());
        return AjaxResult.success();
    }


    /**
     * 查询单条店铺配置
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.SHOP, method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Long pkId) {
        BdShop shop = iBdShopService.getById(pkId);
        BdShopExt bdShopExt = BeanUtil.copyProperties(shop, BdShopExt.class);
        return AjaxResult.success(bdShopExt);
    }


    /**
     * 删除店铺配置
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.SHOP, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Long pkId) {
        LambdaUpdateWrapper<BdShop> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BdShop::getPkId, pkId);
        updateWrapper.set(BdShop::getDelFlag, EDelFlag.DELETE.getValue());
        updateWrapper.set(BdShop::getPkModified, SecurityUtils.getUserId());
        updateWrapper.set(BdShop::getModifiedTime, new Date());
        redisService.deleteObjectByKey(CacheConstants.BD_SHOP + SecurityUtils.getPkCountry());
        return toAjax(iBdShopService.update(updateWrapper));
    }
}
