package com.bohuikeji.delivery.backstage.controller.admin;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bohuikeji.delivery.backstage.entity.TConfig;
import com.bohuikeji.delivery.backstage.entity.TMerchantConfig;
import com.bohuikeji.delivery.backstage.entity.vo.ConfigFormVo;
import com.bohuikeji.delivery.backstage.service.ITConfigService;
import com.bohuikeji.delivery.backstage.service.ITMerchantConfigService;
import com.bohuikeji.frame.module.admin.annotation.InitLog;
import com.bohuikeji.frame.module.admin.base.ControllerBase;
import com.bohuikeji.frame.module.admin.base.InterfaceBase;
import com.bohuikeji.frame.module.admin.entity.TFranchiseeInformation;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.web.TableData;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 加盟商配置信息表
 * @author 孙劲辉
 */
@Slf4j
@RestController
@RequestMapping("/merchant/config")
@RequiredArgsConstructor
public class TMerchantConfigController extends ControllerBase {
    final ITMerchantConfigService merchantConfigService;
    final ITFranchiseeInformationService informationService;

    @GetMapping("/get/list/group")
    public InterfaceBase getLitGroup(String groupKey, Integer franId) {
        return TableData.success(merchantConfigService.page(new Page<TMerchantConfig>(1,10),
                new QueryWrapper<TMerchantConfig>().eq("fran_id",franId).eq("config_group",groupKey).orderByDesc("config_sort")));
    }

    @InitLog("修改加盟商配置")
    @PostMapping("/post/save")
    public APIEntity saveConfig(ConfigFormVo configFormVo){
        JSONObject configValue = new JSONObject();
        String[] keys=configFormVo.getKeys();
        String[] values=configFormVo.getValues();
        log.info("新的运费配置configFormVo:{}",configFormVo);
        TMerchantConfig config=merchantConfigService.getById(configFormVo.getId());
        configValue = config.getConfigValue();
        if("freight_type".equals(config.getConfigGroup())){
            JSONObject sonJson = null;
            String name = values[0];
            for (int i = 0; i < keys.length; i++) {
                if(i==0){
                    String xsName = configValue.getString(keys[i]);
                    log.info("新运费配置名称：{}",xsName);
                }else {
                    sonJson = configValue.getJSONObject(keys[i]);
                }
                log.info("￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥：{}",i);
                if(i==1){
                    log.info("#################：{}",sonJson);
                    sonJson.put("begin",values[1]);
                    sonJson.put("ending",values[2]);
                    sonJson.put("price",values[3]);
                }
                if(i==2){
                    sonJson.put("begin",values[4]);
                    sonJson.put("ending",values[5]);
                    sonJson.put("price",values[6]);
                }
                if(i==3){
                    sonJson.put("begin",values[7]);
                    sonJson.put("ending",values[8]);
                    sonJson.put("price",values[9]);
                }
                if(i==4){
                    sonJson.put("begin",values[10]);
                    sonJson.put("ending",values[11]);
                    sonJson.put("price",values[12]);
                }
                if(i==5){
                    sonJson.put("begin",values[13]);
                    sonJson.put("ending",values[14]);
                    sonJson.put("price",values[15]);
                }
                configValue.put(keys[i],sonJson);

            }
            configValue.put("显示名称",name);
            log.info("%%%%%%%%%%%%%%%%%%%%:{}",configValue);
        }else {
            for (int i = 0; i < keys.length; i++) {
                configValue.put(keys[i],values[i]);
            }
        }
        config.setConfigStatus("使用中");
        String name=configValue.getString("显示名称");
        if(StringUtils.isNotBlank(name)){
            if("premium_type".equals(config.getConfigGroup())){
                if(LocalDate.parse(configValue.getString("开始日期")).isAfter(LocalDate.parse(configValue.getString("结束日期")))){
                    return APIEntity.fail("开始日期不得小于结束日期！");
                }
                if(name.contains("加价")){
                    config.setConfigName(name);
                }else {
                    return APIEntity.fail("名称必须含有加价！");
                }
            }
            config.setConfigName(name);
        } else {
            configValue.put("显示名称",config.getConfigName());
        }
        config.setConfigValue(configValue);
        return APIEntity.success(merchantConfigService.updateById(config));
    }
    @InitLog("删除加盟商配置")
    @GetMapping("/get/delete")
    public APIEntity delete(Integer configId){
        TMerchantConfig config=merchantConfigService.getById(configId);
        if(config.getDeletePolicy().equals(-1)){
            return APIEntity.fail("本配置项目禁止删除！");
        }
        if(config.getDeletePolicy()>0){
            if("premium_type".equals(config.getConfigGroup())){
                return APIEntity.success(merchantConfigService.removeById(configId));
            }
            if("freight_type".equals(config.getConfigGroup())){
                return APIEntity.success(merchantConfigService.removeById(configId));
            }
            if("极送-平均1小时".equals(config.getConfigName())){
                return APIEntity.fail("此为对外开放平台默认配置，不可删除！");
            }
            if(merchantConfigService.getListByGroup(config.getConfigGroup(),config.getFranId()).size()<=config.getDeletePolicy()){
                return APIEntity.fail("删除失败,至少要保留"+config.getDeletePolicy()+"条配置！");
            }
        }
        if(StringUtils.isNotBlank(config.getConfigGroup())){
            TMerchantConfig superConfig=merchantConfigService.getConfigByKey(config.getConfigGroup(),config.getFranId());
            if(superConfig.getDeletePolicy().equals(-1)){
                return APIEntity.fail("本配置组禁止删除项！");
            }
            if(superConfig.getDeletePolicy()>0){
                if(merchantConfigService.getListByGroup(config.getConfigGroup(),config.getFranId()).size()<=config.getDeletePolicy()){
                    return APIEntity.fail("删除失败,至少要保留"+config.getDeletePolicy()+"条配置！");
                }
            }
        }
        return APIEntity.success(merchantConfigService.removeById(configId));
    }
    @InitLog("克隆加盟商配置")
    @GetMapping("/get/clone")
    public APIEntity clone(Integer configId){
        TMerchantConfig config=merchantConfigService.getById(configId);
        //禁止克隆电动车
        if ("car_type_ddc".equals(config.getConfigKey())){
            return APIEntity.fail("该配置项禁止克隆，请选择其他项~");
        }
        //查询该配置项是否具有子类
        List<TMerchantConfig> sons=merchantConfigService.getListByGroup(config.getConfigKey(),config.getFranId());
        if("freight_type".equals(config.getConfigGroup()) && sons.size()>0){
            return APIEntity.fail("该配置项暂时仅支持一项！");
        }
        //重命名key
        if(StringUtils.isNoneBlank(config.getConfigKey())){
            config.setConfigKey(config.getConfigKey()+"_1");
        }
        //有子类则克隆子类
        if(sons!=null&&sons.size()>0){
            sons.forEach(son->{
                son.setId(null);
                if(StringUtils.isNotBlank(son.getConfigKey())){
                    son.setConfigKey(son.getConfigKey()+"_1");
                }
                //设置子类GroupKey为父类的configKey
                son.setConfigGroup(config.getConfigKey());
                son.setConfigStatus("草稿");
            });
            //批量创建子类
            merchantConfigService.saveBatch(sons);
        }
        config.setConfigStatus("草稿");
        return APIEntity.success(merchantConfigService.save(config));
    }

    /**
     *
     * @param groupKey
     * @param franId
     * @return
     */
    @InitLog("B端新增加盟商配置")
    @GetMapping("/add/configure")
    public APIEntity addConfigure(String groupKey,Integer franId){
        log.info("@@@@@@@@groupKey:{}",groupKey);
        log.info("@@@@@@@@franId:{}",franId);
        TMerchantConfig config=merchantConfigService.getById(2);
        TFranchiseeInformation franchiseeInformation = informationService.getOne(new QueryWrapper<TFranchiseeInformation>().eq("fran_id",franId));
        //查询该配置项是否具有子类
        List<TMerchantConfig> sons=merchantConfigService.getListByGroup(groupKey,franId);
        //有子类则克隆子类
        LocalDate date = LocalDate.now();
        LocalTime time = LocalTime.now();
        String dates = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String times = time.format(DateTimeFormatter.ofPattern("HH:mm"));
        JSONObject jsonObject = new JSONObject();
        if("premium_type".equals(groupKey)){
            jsonObject.put("显示名称","");
            jsonObject.put("溢价费用","0.00");
            jsonObject.put("开始日期",dates);
            jsonObject.put("开始时间",times);
            jsonObject.put("结束日期",dates);
            jsonObject.put("结束时间",times);
            config.setConfigValue(jsonObject);
        }
        if("freight_type".equals(groupKey)){
            //JSONObject allJson = new JSONObject();
            JSONObject fatherJson = new JSONObject(true);
            JSONObject sonJson;
            for(int i=5;i>=1;i--){
                sonJson = new JSONObject();
                sonJson.put("begin","0");
                sonJson.put("ending","3");
                sonJson.put("price","5");
                fatherJson.put(i+".",sonJson);
            }
            fatherJson.put("显示名称","");
            //allJson.add(fatherJson);
            log.info("新增运费配置：{}",fatherJson);
            config.setConfigValue(fatherJson);

        }
        config.setFranId(franId);
        config.setFranName(franchiseeInformation.getFranName());
        config.setConfigName("");
        config.setConfigKey(groupKey+"_1");
        config.setConfigGroup(groupKey);
        config.setConfigStatus("草稿");
        return APIEntity.success(merchantConfigService.save(config));
    }


    @InitLog("开启、关闭加盟商配置")
    @GetMapping("/set/status")
    public APIEntity setStstus(Integer configId,String configStatus){
        TMerchantConfig config=merchantConfigService.getById(configId);
        if(!"premium_type".equals(config.getConfigGroup())){
            log.info("他咋就及进来了呢！");
            return APIEntity.fail("本配置项目禁止停用！");
        }
        config.setConfigStatus(configStatus);
        return APIEntity.success(merchantConfigService.updateById(config));
    }
    /**
     * 排序
     * @param configId
     * @param type
     * @return
     */
    @GetMapping("/get/sort")
    public APIEntity sort(Integer configId,String type){
        TMerchantConfig config=merchantConfigService.getById(configId);
        //向上一行
        if("up".equals(type)){
            //如果已经时第一行，不处理
            TMerchantConfig max=merchantConfigService.getOne(new QueryWrapper<TMerchantConfig>().eq("fran_id",config.getFranId())
                            .eq("config_group",config.getConfigGroup()).gt("config_sort",config.getConfigSort()).apply(" 1=1 limit 1"));
            if(max==null){
                return APIEntity.fail("排序已经是最大了");
            }
            config.setConfigSort(config.getConfigSort()+1);
            merchantConfigService.update(new UpdateWrapper<TMerchantConfig>()
                    .eq("fran_id",config.getFranId())
                    .eq("config_group",config.getConfigGroup())
                    .eq("config_sort",config.getConfigSort()).set("config_sort",config.getConfigSort()-1));
        }
        else{
            TMerchantConfig min=merchantConfigService.getOne(new QueryWrapper<TMerchantConfig>().eq("fran_id",config.getFranId())
                    .eq("config_group",config.getConfigGroup()).lt("config_sort",config.getConfigSort()).apply(" 1=1 limit 1"));
            if(min==null){
                return APIEntity.fail("排序已经是最小了");
            }
            config.setConfigSort(config.getConfigSort()-1);
            merchantConfigService.update(new UpdateWrapper<TMerchantConfig>()
                    .eq("fran_id",config.getFranId())
                    .eq("config_group",config.getConfigGroup())
                    .eq("config_sort",config.getConfigSort()).set("config_sort",config.getConfigSort()+1));

        }
        return APIEntity.success(merchantConfigService.updateById(config));
    }

    @InitLog("初始化默认配置")
    @GetMapping("/get/init")
    public APIEntity clone(String groups,Integer franId){
        String configKey = groups+",car_type_ddc,car_type_lashuo";
        log.info("整合参数：{}",configKey);
        List<TMerchantConfig> configList =merchantConfigService.list(new QueryWrapper<TMerchantConfig>().eq("fran_id",franId).in("config_group",configKey.split(",")));
        if (configList.size()<1){
            TFranchiseeInformation fran=informationService.getById(franId);
            List<TMerchantConfig> list=merchantConfigService.list(new QueryWrapper<TMerchantConfig>().eq("fran_id",1).in("config_group",configKey.split(",")));
            list.forEach(tConfig -> {
                tConfig.setFranId(franId);
                tConfig.setId(null);
                tConfig.setFranName(fran.getFranName());
            });
            if(merchantConfigService.saveBatch(list)){
                return APIEntity.success();
            }
        }
        return APIEntity.fail("当前配置已经存在数据，无法再次初始话！");
    }


}
