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.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.core.utils.TransactionUtils;
import com.hzs.system.base.ITransactionServiceApi;
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.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-15
 */
@Slf4j
@RestController
@RequestMapping("/manage/shop")
public class BdShopController extends BaseController {
    @Autowired
    private IBdShopService shopService;
    @DubboReference
    private ITransactionServiceApi iTransactionServiceApi;
    @Autowired
    IBdCurrencyService currencyService;
    private RedisService redisService;
    @Autowired
    IBdCountryService countryService;

    @Autowired
    public void setRedisService(RedisService redisService) {
        this.redisService = redisService;
    }

    /**
     * @description: 查询店铺配置列表
     * @author: zhang jing
     * @date: 2022/8/30 10:20
     * @param: [shop]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.SHOP, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BdShop shop) {
        startPage();
        QueryWrapper<BdShop> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(shop.getShopName())) {
            queryWrapper.eq("SHOP_NAME", shop.getShopName());
        }
        queryWrapper.orderByDesc("CREATION_TIME");
        BdCountry country = countryService.getCountry(SecurityUtils.getPkCountry());
        List<BdShopExt> listExt = new ArrayList<>();
        List<BdShop> list = shopService.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(currencyService.getDollar(bs.getRegisterValue(), SecurityUtils.getPkCountry()));
            }
        }
        return getDataTable(listExt);
    }

    /**
     * @description: 导出配送中心等级
     * @author: zhang jing
     * @date: 2023/3/9 16:08
     * @param: [response, shop]
     * @return: void
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG,business = EOperationBusiness.SHOP, method = EOperationMethod.SELECT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BdShop shop) {
        startPage();
        QueryWrapper<BdShop> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(shop.getShopName())) {
            queryWrapper.eq("SHOP_NAME", shop.getShopName());
        }
        queryWrapper.orderByDesc("CREATION_TIME");
        BdCountry country = countryService.getCountry(SecurityUtils.getPkCountry());
        List<BdShopExt> listExt = new ArrayList<>();
        List<BdShop> list = shopService.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(currencyService.getDollar(bs.getRegisterValue(), SecurityUtils.getPkCountry()));
            }
        }
        ExcelUtil<BdShopExt> util = new ExcelUtil<>(BdShopExt.class);
        util.exportExcel(response, listExt, "配送中心等级");
    }


    /**
     * @description: 新增店铺配置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [shop]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @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));
        }

        QueryWrapper<BdShop> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", pkCountry);
        if (StringUtils.isNotNull(shop.getShopName())) {
            queryWrapper.eq("SHOP_NAME", shop.getShopName());
        }
        List<BdShop> list = shopService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SHOP_NAME_REPEAT));
        }
        QueryWrapper<BdShop> queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("PK_COUNTRY", pkCountry);
        list = shopService.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())) {
            //字段翻译保存到数据库
            R<Integer> pkTransaction = iTransactionServiceApi.createTransaction(pkCountry, ETransactionKey.SHOP,
                    shop.getShopName(), EYesNo.NO, EYesNo.NO);
            shop.setPkTransaction(pkTransaction.getData());
            shop.setPkCountry(pkCountry);
            shop.setPkCreator(SecurityUtils.getUserId());
            shop.setCreationTime(new Date());
            QueryWrapper<BdShop> queryWrapperCheck = new QueryWrapper();
            queryWrapperCheck.eq("SHOP_VALUE", shop.getShopValue());
            queryWrapperCheck.eq("PK_COUNTRY",pkCountry);
            List<BdShop> list1 = shopService.list(queryWrapperCheck);
            if (CollectionUtil.isEmpty(list1)) {
                shopService.save(shop);
            }
            return AjaxResult.success();
        }else{
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DATA_REPEAT));
        }
    }

    /**
     * @description: 生成店铺（配送中心）
     * @author: zhang jing
     * @date: 2022/10/22 9:54
     * @param: [grade]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
//    @Log(module = EModuleType.SHOP, method = EMethodType.INSERT)
//    @PostMapping("/generate")
//    public AjaxResult generate(@RequestBody BdShop shop) {
//        return AjaxResult.success(shopService.generate(shop));
//    }


    /**
     * @description: 修改店铺配置
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [shop]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @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));
        }

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

    /**
     * @description:修改启用状态
     * @author: zhang jing
     * @date: 2023/4/24 14:54
     * @param: [shop]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @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));
        }
        UpdateWrapper<BdShop> updateWrapper=new UpdateWrapper();
        updateWrapper.set("ENABLE_STATE",shop.getEnableState());
        updateWrapper.eq("PK_ID",shop.getPkId());
        updateWrapper.set("PK_MODIFIED",SecurityUtils.getUserId());
        updateWrapper.set("MODIFIED_TIME",new Date());
        shopService.update(updateWrapper);
        redisService.deleteObjectByKey(CacheConstants.BD_SHOP + SecurityUtils.getPkCountry());
        return AjaxResult.success();
    }


    /**
     * @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.SHOP, method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Long pkId) {
        BdShop shop = shopService.getById(pkId);
        BdShopExt bdShopExt = BeanUtil.copyProperties(shop, BdShopExt.class);
        return AjaxResult.success(bdShopExt);
    }


    /**
     * @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.SHOP, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Long pkId) {
        UpdateWrapper<BdShop> 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_SHOP + SecurityUtils.getPkCountry());
        return toAjax(shopService.update(updateWrapper));
    }
}
