package com.bohuikeji.delivery.backstage.controller.api.v2;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.entity.TConfig;
import com.bohuikeji.delivery.backstage.service.ITConfigService;
import com.bohuikeji.delivery.backstage.service.ITCustomerService;
import com.bohuikeji.delivery.backstage.service.ITCustomerTemplateService;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysConfig;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.utils.MapUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@Api(tags = {"新版系统配置接口类"})
@RestController
@RequestMapping("/api/v2/config")
@RequiredArgsConstructor
@Slf4j
public class ConfigApi extends ApiController {


    final ITConfigService configService;
    final ISysConfigService sysConfigService;
    final ITFranchiseeInformationService informationService;
    final ITCustomerService customerService;
    final ITCustomerTemplateService templateService;


    @ApiOperation("【旧版兼容】计费类型组查询，查询服务/货物/车辆类型/价值类型")
    @GetMapping("/serviceGroup")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="configKey",value="配置组key",dataType="String", paramType = "query"),
            @ApiImplicitParam(name="location",value="经纬度",example = "111.519739,40.944464",dataType="String", paramType = "query")})
    public APIEntity<List<SysConfig>> configGroupOld(@RequestAttribute("JwtUserId")Integer userId, String configKey, String location){
        if(StringUtils.isBlank(configKey)){
            return APIEntity.fail("参数：[configKey]，不能为空！");
        }
        if(StringUtils.isBlank(location)){
            return APIEntity.fail("参数：[location]，不能为空！");
        }
        if(informationService.checkPio(MapUtils.getAddressReGeo(location))==null){
            log.error("客户端客户下单传回经纬度：{}",location);
            return APIEntity.fail("经纬度解析失败，请重新进入！");
        }
        List<TConfig> configList=configService.getFranConfigByGroupWithCustomer(configKey,location,userId);
        //如果加盟商尚未配置计费规则或者只配置了部分计费规则，则按平台计费规则计费
        if (configList.size()<1){
            log.info("有个计费模板、B端模板、C端模板有为空的:[{}]","平台");
            configList=configService.list(
                    new QueryWrapper<TConfig>()
                            .eq("config_group",configKey)
                            .eq("fran_id",1).eq("show_type",1).orderByDesc("config_sort"));
        }
        List<SysConfig> sysConfigKey=new ArrayList<>(configList.size());
        configList.forEach(config->{
            if(!"car_type_lashuo".equals(config.getConfigGroup()) && !"car_type_lashuo".equals(config.getConfigKey())){
                sysConfigKey.add(config.toOldConfig());
            }

        });
        return APIEntity.success(sysConfigKey);
    }
    @ApiOperation("【全新版本】计费类型组查询，查询服务/货物/车辆类型/价值类型")
    @GetMapping("/service/group")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="groupKey",value="配置组key",dataType="String", paramType = "query"),
            @ApiImplicitParam(name="location",value="经纬度",example = "111.519739,40.944464",dataType="String", paramType = "query")})
    public APIEntity<List<TConfig>> configGroupNew(String groupKey,String location){
        List<TConfig> configList=configService.list(
                new QueryWrapper<TConfig>()
                        .eq("config_group",groupKey)
                        .eq("fran_id",informationService.checkPio(MapUtils.getAddressReGeo(location)).getFranId()));
        /*List<SysConfig> sysConfigKey=new ArrayList<>(configList.size());
        configList.forEach(config->{
            sysConfigKey.add(config.toOldConfig());
        });*/
        return APIEntity.success(configList);
    }
    @ApiOperation("根据加盟商Id计费类型组查询，查询服务/货物/车辆类型/价值类型")
    @GetMapping("/service/getFranId")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="groupKey",value="配置组key",dataType="String", paramType = "query"),
            @ApiImplicitParam(name="franId",value="加盟商Id",example = "1",dataType="Integer", paramType = "query")})
    public APIEntity<List<TConfig>> getFranId(String groupKey,Integer franId){
        //log.info("%%%%%%%%%%groupKey：{}，franId:{}",groupKey,franId);
       /* List<TConfig> configList=configService.list(
                new QueryWrapper<TConfig>()
                        .eq("config_group",groupKey)
                        .eq("fran_id",franId));*/
        return APIEntity.success();
    }


    @ApiOperation("招商加盟配置(从事行业)")
    @GetMapping("/service/attract")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="groupKey",value="配置组key",dataType="String", paramType = "query"),})
    public APIEntity<List<SysConfig>> getAttract(String groupKey){
        List<SysConfig> sysConfigs=sysConfigService.list(
                new QueryWrapper<SysConfig>().eq("config_group",groupKey));
        return APIEntity.success(sysConfigs);
    }


    @ApiOperation("骑手入驻费用配置")
    @GetMapping("/service/cost/getset")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="groupKey",value="cost_set",dataType="String", paramType = "query"),})
    public APIEntity<List<SysConfig>> getCostSet(String groupKey){
        List<SysConfig> sysConfigs=sysConfigService.list(
                new QueryWrapper<SysConfig>().eq("config_group",groupKey));
        return APIEntity.success(sysConfigs);
    }



    @ApiOperation("骑手入驻费用列表")
    @GetMapping("/service/cost/list")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="groupKey",value="cost_set",dataType="String", paramType = "query"),})
    public APIEntity<JSONArray> getCostSetList(String groupKey){
        List<SysConfig> sysConfigs=sysConfigService.list(
                new QueryWrapper<SysConfig>().eq("config_group",groupKey));
        JSONArray jsonArray  = new JSONArray();
        for(SysConfig sysConfig : sysConfigs){
            jsonArray.add(sysConfigService.jsonObject(sysConfig));
        }
        return APIEntity.success(jsonArray);
    }



    /**
     *
     * @return
     */
    @ApiOperation("查询客服电话")
    @GetMapping("/getCustSerPhone")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="groupKey",value="配置组key",dataType="String", paramType = "query"),
            @ApiImplicitParam(name="location",value="经纬度",example = "111.519739,40.944464",dataType="String", paramType = "query")})
    public APIEntity<TConfig> getCustSerPhone(String groupKey,String location){
        TConfig config=configService.getOne(new QueryWrapper<TConfig>().eq("config_group",groupKey));
        return APIEntity.success(config);
    }


    /**
     * 根据id查询字典类型
     * @return
     */
    @ApiOperation("根据id查询字典类型")
    @GetMapping("/getConfigById")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="configId",value="字典id",dataType="Integer", paramType = "query")})
    public APIEntity<TConfig> getConfigById(Integer configId){
        TConfig config = configService.getById(configId);
        return APIEntity.success(config);
    }


    /**
     * 查询服务/货物/价值类型
     * @return
     */
    @ApiOperation("查询服务/货物/车辆类型/价值类型")
    @GetMapping("/getServiceType")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="configKey",value="configKey",dataType="String", paramType = "query")})
    public APIEntity<List<TConfig>> getServiceTypeList(String configKey){
        QueryWrapper<TConfig> queryWrapper=new QueryWrapper<TConfig>().eq("config_group",configKey);
        if("car_type".equals(configKey)){
            queryWrapper.orderByDesc("id");
        }
        List<TConfig> configs = configService.list(queryWrapper);
        return APIEntity.success(configs);
    }


    @ApiOperation("【锦贤同城急送】计费类型组查询，查询服务/货物/车辆类型/价值类型")
    @GetMapping("/sysGroup")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="configKey",value="配置组key",dataType="String", paramType = "query")})
    public APIEntity<List<SysConfig>> sysConfigGroup(@RequestAttribute("JwtUserId")Integer userId, String configKey){
        if(StringUtils.isBlank(configKey)){
            return APIEntity.fail("参数：[configKey]，不能为空！");
        }
       /* List<TConfig> configList=configService.getFranConfigByGroupCustomer(configKey,1,userId);
        //如果加盟商尚未配置计费规则或者只配置了部分计费规则，则按平台计费规则计费
        if (configList.size()<1){
            configList=configService.list(
                    new QueryWrapper<TConfig>()
                            .eq("config_group",configKey)
                            .eq("fran_id",1).orderByDesc("config_sort"));
        }*/
        List<TConfig> configList=configService.list(
                new QueryWrapper<TConfig>()
                        .eq("config_group",configKey)
                        .eq("fran_id",1).orderByDesc("config_sort"));
        List<SysConfig> sysConfigKey=new ArrayList<>(configList.size());
        configList.forEach(config->{
            sysConfigKey.add(config.toOldConfig());
        });
        return APIEntity.success(sysConfigKey);
    }


    @ApiOperation("获取优惠卷入口图")
    @GetMapping("/service/voucher/get")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    public APIEntity<SysConfig> getVoucher(){
        SysConfig config=sysConfigService.getOne(new QueryWrapper<SysConfig>().eq("config_key","entrance_image"));
        return APIEntity.success(config);
    }
}
