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


import com.alibaba.fastjson.JSON;
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.TCustomerTemplate;
import com.bohuikeji.delivery.backstage.entity.vo.ConfigFormVo;
import com.bohuikeji.delivery.backstage.service.ITCustomerTemplateService;
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.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.RegUtils;
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("/customer/template/config")
@RequiredArgsConstructor
public class TCustomerTemplateController extends ControllerBase {
    final ITFranchiseeInformationService informationService;
    final ITCustomerTemplateService templateService;

    /**
     * 查询一组配置项
     * @param groupKey 组KEY
     * @param franId 加盟商ID
     * @param templateCode 模板号
     * @return
     */
    @GetMapping("/get/list/group")
    public InterfaceBase getLitGroup(String groupKey, Integer franId,String templateCode) {
        return TableData.success(templateService.page(new Page<TCustomerTemplate>(1,10),
                new QueryWrapper<TCustomerTemplate>().eq("fran_id",franId).eq("template_code",templateCode)
                        .eq("config_group",groupKey).orderByDesc("config_sort")));
    }

    /**
     * 模板修改提交
     * @param configFormVo 模板表单实体
     * @return
     */
    @InitLog("修改客户模板配置")
    @PostMapping("/post/save")
    public APIEntity saveConfig(ConfigFormVo configFormVo){
        TCustomerTemplate template=configFormVo.getSuperId()==null?templateService.getById(configFormVo.getId()):templateService.getById(configFormVo.getSuperId());
        JSONObject configValue = template.getConfigValue();
        String[] keys=configFormVo.getKeys();
        String[] values=configFormVo.getValues();
        if("freight_type".equals(template.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]);
                }else {
                    sonJson = configValue.getJSONObject(keys[i]);
                }
                if(i==1){
                    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 {
            //遍历表单的KEY和value
            for (int i = 0; i < keys.length; i++) {
                //兼容旧版格式，先尝试转为新版json，转换失败代表为旧版数据
                try {
                    JSONObject item=configValue.getJSONObject(keys[i]);
                    String verifyStr=item.getString("verify");
                    //如果配置项携带正则，则进行校验
                    if(StringUtils.isNotBlank(verifyStr)){
                        JSONObject verify= JSON.parseObject(verifyStr);
                        if (StringUtils.isBlank(values[i])){
                            if (verify.getBoolean("required")){
                                return APIEntity.fail("请输入：【"+keys[i]+"】");
                            }
                            item.put("value","");
                            continue;
                        }
                        //默认不允许为空
                        if(!RegUtils.check(verify.getString("pattern"),values[i])){
                            return APIEntity.fail("【"+keys[i]+"】格式错误："+verify.getString("msg"));
                        }
                    }
                    item.put("value",values[i]);
                }catch (Exception e){
                    if (StringUtils.isBlank(values[i])){
                        return APIEntity.fail("请输入：【"+keys[i]+"】");
                    }
                    configValue.put(keys[i],values[i]);
                }
            }
        }
        String name=configValue.getString("显示名称");
        if(StringUtils.isNotBlank(name)){
            if("premium_type".equals(template.getConfigGroup())){
                if(LocalDate.parse(configValue.getString("开始日期")).isAfter(LocalDate.parse(configValue.getString("结束日期")))){
                    return APIEntity.fail("开始日期不得大于结束日期！");
                }
                if(name.contains("加价")){
                    template.setConfigName(name);
                }else {
                    return APIEntity.fail("名称必须含有加价！");
                }
            }
            if("service_type_jisu".equals(template.getConfigKey())){
                if(!"极送-平均1小时".equals(name)){
                    return APIEntity.fail("此为对外开放平台默认配置，不可修改！");
                }
            }
            if("car_type_ddc".equals(template.getConfigKey())){
                if(!"电动/摩托车".equals(name)){
                    return APIEntity.fail("此为对外开放平台默认配置，不可修改！");
                }
            }
            template.setConfigName(name);
        }
        else {
            configValue.put("显示名称",template.getConfigName());
        }
        template.setConfigValue(configValue);
        template.setTemplateStatus("使用中");
        if (configFormVo.getSuperId()!=null){
            template.setTemplateId(null);
            template.setId(null);
            template.setFranId(configFormVo.getFranId());
            template.setTemplateCode(configFormVo.getTemplateCode());
            templateService.save(template);
            return APIEntity.success();
        }
        return APIEntity.success(templateService.updateById(template));
    }
    @InitLog("开启、关闭加盟商配置")
    @GetMapping("/set/status")
    public APIEntity setStstus(Integer templateId,String templateStatus){
        TCustomerTemplate template=templateService.getById(templateId);
        if(!"premium_type".equals(template.getConfigGroup())){
            log.info("他咋就及进来了呢！");
            return APIEntity.fail("本配置项目禁止停用！");
        }
        template.setTemplateStatus(templateStatus);
        return APIEntity.success(templateService.updateById(template));
    }


    /**
     * 删除配置模板
     * @param id
     * @return
     */
    @InitLog("删除加盟商配置")
    @GetMapping("/get/delete")
    public APIEntity delete(Integer id){
        TCustomerTemplate customerTemplate=templateService.getById(id);
        log.info("#############################:{}",customerTemplate);
        if(customerTemplate.getDeletePolicy().equals(-1)){
            return APIEntity.fail("本配置项目禁止删除！");
        }
        if(customerTemplate.getDeletePolicy()>0){
            if("premium_type".equals(customerTemplate.getConfigGroup())){
                return APIEntity.success(templateService.removeById(id));
            }
            if("freight_type".equals(customerTemplate.getConfigGroup())){
                return APIEntity.success(templateService.removeById(id));
            }
            if("极送-平均1小时".equals(customerTemplate.getConfigName())){
                return APIEntity.fail("此为对外开放平台默认配置，不可删除！");
            }
            if("生活用品".equals(customerTemplate.getConfigName()) || "其他".equals(customerTemplate.getConfigName())){
                return APIEntity.fail("此为对外开放平台默认配置，不可删除！");
            }
            if(templateService.getListByGroup(customerTemplate.getConfigGroup(),customerTemplate.getFranId(),customerTemplate.getTemplateCode()).size()<=customerTemplate.getDeletePolicy()){
                return APIEntity.fail("删除失败,至少要保留"+customerTemplate.getDeletePolicy()+"条配置！");
            }
        }
        if(StringUtils.isNotBlank(customerTemplate.getConfigGroup())){
            TCustomerTemplate superConfig=templateService.getConfigByKey(customerTemplate.getConfigKey(),customerTemplate.getFranId(),customerTemplate.getTemplateCode());
            log.info("#############################:{}",superConfig);
            if(superConfig == null){
                return APIEntity.fail("本配置组禁止删除项！");
            }
            if(superConfig.getDeletePolicy().equals(-1)){
                return APIEntity.fail("本配置组禁止删除项！");
            }
            if(superConfig.getDeletePolicy()>0){
                if(templateService.getListByGroup(customerTemplate.getConfigGroup(),customerTemplate.getFranId(),customerTemplate.getTemplateCode()).size()<=customerTemplate.getDeletePolicy()){
                    return APIEntity.fail("删除失败,至少要保留"+customerTemplate.getDeletePolicy()+"条配置！");
                }
            }
        }
        return APIEntity.success(templateService.removeById(id));
    }

    /**
     * 克隆模板配置
     * @param id 模板ID
     * @return
     */
    @InitLog("克隆加盟商配置")
    @GetMapping("/get/clone")
    public APIEntity clone(Integer id){
        TCustomerTemplate config=templateService.getById(id);
        //禁止克隆电动车
        if ("car_type_ddc".equals(config.getConfigKey())){
            return APIEntity.fail("该配置项禁止克隆，请选择其他项~");
        }
        //获取计费项的子集
        List<TCustomerTemplate> sons=templateService.getListByGroup(config.getConfigKey(),config.getFranId(),config.getTemplateCode());
        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.setTemplateStatus("草稿");
            });
            //批量创建子类
            templateService.saveBatch(sons);
        }
        config.setTemplateStatus("草稿");
        return APIEntity.success(templateService.save(config));
    }

    /**
     *
     * @param groupKey
     * @param franId
     * @return
     */
    @InitLog("C端新增加盟商配置")
    @GetMapping("/add/configure")
    public APIEntity addConfigure(String groupKey,Integer franId,String templateCode){
        log.info("@@@@@@@@groupKey:{}",groupKey);
        log.info("@@@@@@@@franId:{}",franId);
        TCustomerTemplate template=templateService.getOne(new QueryWrapper<TCustomerTemplate>().eq("fran_id",franId).eq("template_code",templateCode).last(" limit 1"));
        //有子类则克隆子类
        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);
            template.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);
            template.setConfigValue(fatherJson);

        }
        template.setFranId(franId);
        template.setConfigName("");
        template.setConfigKey(groupKey+"_1");
        template.setConfigGroup(groupKey);
        template.setTemplateStatus("草稿");
        return APIEntity.success(templateService.save(template));
    }

    /**
     * 删除计费模板
     * @param id
     * @return
     */
    @InitLog("删除模板")
    @GetMapping("/del/id")
    public APIEntity del(Integer id){
        TCustomerTemplate config=templateService.getById(id);
        return APIEntity.success(templateService.remove(new QueryWrapper<TCustomerTemplate>().eq("fran_id",config.getFranId()).eq("template_code",config.getTemplateCode())));
    }
    /**
     * 排序
     * @param configId
     * @param type
     * @return
     */
    @GetMapping("/get/sort")
    public APIEntity sort(Integer configId,String type) {
        TCustomerTemplate config = templateService.getById(configId);log.info("################{}",config);
        //向上一行
        if ("up".equals(type)) {
            //如果已经时第一行，不处理
            TCustomerTemplate max = templateService.getOne(new QueryWrapper<TCustomerTemplate>()
                    .eq("fran_id", config.getFranId())
                    .eq("template_code",config.getTemplateCode())
                    .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);
            templateService.update(new UpdateWrapper<TCustomerTemplate>()
                    .eq("fran_id", config.getFranId())
                    .eq("template_code",config.getTemplateCode())
                    .eq("config_group", config.getConfigGroup())
                    .eq("config_sort", config.getConfigSort())
                    .set("config_sort", config.getConfigSort() - 1));
        } else {
            TCustomerTemplate min = templateService.getOne(new QueryWrapper<TCustomerTemplate>()
                    .eq("fran_id", config.getFranId())
                    .eq("template_code",config.getTemplateCode())
                    .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);
            templateService.update(new UpdateWrapper<TCustomerTemplate>()
                    .eq("fran_id", config.getFranId())
                    .eq("template_code",config.getTemplateCode())
                    .eq("config_group", config.getConfigGroup())
                    .eq("config_sort", config.getConfigSort())
                    .set("config_sort", config.getConfigSort() + 1));

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

    /**
     * 添加一个模板
     * @param groupKey
     * @param franId
     * @param templateCode
     * @return
     */
    @GetMapping("/get/add/new")
    public APIEntity addNewConfig(String groupKey, Integer franId,String templateCode){
        log.error("{},{},{}",groupKey,franId,templateCode);
        //随便获取上级加盟商一个本组的模板
        TCustomerTemplate template=templateService.getOne(new QueryWrapper<TCustomerTemplate>().eq("fran_id",1).eq("config_group",groupKey).last(" limit 1"));
        if (template==null){
            return APIEntity.fail("该组配置上级加盟商尚未配置，请联系加盟商配置！");
        }
        //改为当前加盟商的
        template.setFranId(franId);
        template.setConfigKey(NumberUtils.getShort());
        template.setTemplateCode(templateCode);
        template.setCreateTime(LocalDateTime.now());
        return APIEntity.success(template);
    }



    /*@InitLog("初始化默认配置")
    @GetMapping("/get/init")
    public APIEntity clone(String groups,Integer franId){
        int count=configService.count(new QueryWrapper<TConfig>().eq("fran_id",franId).in("config_group",groups.split(",")));
        if (count<1){
            TFranchiseeInformation fran=informationService.getById(franId);
            List<TConfig> list=configService.list(new QueryWrapper<TConfig>().eq("fran_id",1).in("config_group",groups.split(",")));
            list.forEach(tConfig -> {
                tConfig.setFranId(franId);
                tConfig.setId(null);
                tConfig.setFranName(fran.getFranName());
            });
            if(configService.saveBatch(list)){
                return APIEntity.success();
            }
        }
    return APIEntity.fail("当前配置已经存在数据，无法再次初始话！");
    }*/


}
