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


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bohuikeji.delivery.backstage.constants.KeyConst;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.vo.CourierAddressVo;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.base.InterfaceBase;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.entity.web.TableData;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.bohuikeji.frame.module.admin.utils.ZxingUtils;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhouliwu
 * 新版派送员相关接口
 * 注：所以接口类必须继承 ApiController，否则无法被接口文档识别
 */
@Slf4j
@Api(tags = {"新版派送员相关接口"})
@RestController
@RequestMapping("/api/v2/courier")
@RequiredArgsConstructor
public class CourierV2Api extends ApiController {

    @Autowired
    ITCourierService courierService;
    @Autowired
    ITOrderService orderService;
    @Autowired
    ITLogisticsService logisticsService;
    @Autowired
    ITLogisticsRecordService logisticsRecordService;
    @Autowired
    ITNewsService newsService;
    @Autowired
    ISysConfigService sysConfigService;
    @Autowired
    ITCustomerService customerService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    IGmsService gmsService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    ITConfigService configService;
    @Autowired
    ITCustomerWalletService customerWalletService;
    @Autowired
    ITPayService payService;
    @Autowired
    ITCourierrExamService courierrExamService;
    @Autowired
    ITCustomerTemplateService customerTemplateService;
    @Autowired
    ITCustomerBigService customerBigService;
    @Autowired
    IWxUserService wxUserService;
    @Autowired
    ITManageService itManageService;

    @Autowired
    ISocketService socketService;

   /* @ApiOperation("微信小程序/App补充支付（派送员代缴——暂未接通）")
    @GetMapping("/order/supple/payment")
    public APIEntity supplePayment(@RequestAttribute("JwtUserId") Integer id, Integer orderId, String price,String type, HttpServletRequest request) throws Exception {
        String openId = null;
        if (!StringUtils.isPrice(price)) {
            return APIEntity.fail("无法识别订单金额，请检查格式是否正确！！");
        }
        log.info("参数：[{}],[{}]", id, orderId);
        TOrder order = orderService.getById(orderId);
        if (order == null) {
            log.error("未找到该订单信息");
            return APIEntity.fail("未找到该订单信息！");
        }
        if (order.getCourierId() == null) {
            log.error("【派送员订单代缴接口异常】，无法找到派送员信息！");
            SysError.saveError("【派送员订单代缴接口异常】，无法找到派送员信息！，当前订单实体={0}", order);
            return APIEntity.fail("无法找到派送员信息，请尝试重新登陆或者，联系平台核实！");
        }
        if (!order.getCourierId().equals(id)) {
            log.error("订单与派送员不批配，无法完成支付");
            return APIEntity.fail("订单与派送员不批配，无法完成支付");
        }
        TPay pay = payService.createBeforePay(order, "补充支付", "骑手代付", payConst.getway(type));
        log.info("派送员代缴，是否有支付记录的查询:[{}]", pay);
        if ("JSAPI".equals(type)) {
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id", id).eq("wx_app_id", WxAppEm.MP_COURIER.getAppId()).eq("wx_app_name", WxAppEm.MP_COURIER.getName()));
            openId = wxUser.getWxUserOpenid();
        }
        if("aliClient".equals(type)){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",id).eq("wx_app_name", WxAppEm.MP_COURIER.getName()).eq("wx_app_type","ALICLIENT"));
            if(wxUser == null){
                return APIEntity.fail("请用户授权");
            }
            openId = wxUser.getWxUserOpenid();
        }
        if("kuaiShou".equals(type)){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",id).eq("wx_app_name", WxAppEm.MP_COURIER.getName()).eq("wx_app_type","KUAISHOU"));
            if(wxUser == null){
                return APIEntity.fail("请用户授权");
            }
            openId = wxUser.getWxUserOpenid();
        }
        String payNum = pay.getPayNum();
        JSONObject object = payConst.getObject(type,payNum,openId,new BigDecimal(price),request);
        return object==null?APIEntity.fail("客户调起"+payConst.getway(type)+"支付错误"):APIEntity.success(object);
    }*/


    /**
     * 新增和修改客户模板
     * @return
     */
    @ApiOperation("派送员添加计费模板")
    @PostMapping("/template/model/add")
    @ApiImplicitParams({
            @ApiImplicitParam(name="templateName",value="模板名称",dataType="String",example="测试", paramType = "query",required = true),
            @ApiImplicitParam(name="templateDesc",value="模板说明",dataType="String",example="大商户", paramType = "query",required = true)})
    public APIEntity modelAdd(@RequestAttribute("JwtUserId") Integer id,String templateName,String templateDesc){
        TCourier courier=courierService.getById(id);
        if(StringUtils.isBlank(templateName)){
            return APIEntity.fail("您好，模板名称不能为空");
        }
        if("全职".equals(courier.getCourierType())){
            return APIEntity.fail("您好，您是全职骑手，无法创建计费模板");
        }
        log.info("初始化实体之后={}",courier);
        String codeNum = "T"+ NumberUtils.getRandom(4);
        List<TConfig> configList=configService.list(new QueryWrapper<TConfig>()
                        .eq("fran_id",courier.getFranId())
                        .in("config_group","cargo_type","car_type_ddc","service_type","cargo_value","payment_method"));
        List<TConfig> superList=configService.list(new QueryWrapper<TConfig>().eq("fran_id",courier.getFranId())
                .in("config_key","cargo_type","car_type_ddc","service_type","cargo_value","payment_method"));
        configList.addAll(superList);
        List<TCustomerTemplate> templates=new ArrayList<>(configList.size());
        configList.forEach(config->{
            TCustomerTemplate cloneTemplate= new TCustomerTemplate();
            cloneTemplate.setConfigGroup(config.getConfigGroup());
            cloneTemplate.setConfigValue(config.getConfigValue());
            cloneTemplate.setConfigId(config.getId());
            cloneTemplate.setConfigName(config.getConfigName());
            cloneTemplate.setConfigKey(config.getConfigKey());
            cloneTemplate.setDeletePolicy(config.getDeletePolicy());
            cloneTemplate.setConfigSort(config.getConfigSort());
            cloneTemplate.setCreateUser(id);
            cloneTemplate.setCreateType("派送员");
            cloneTemplate.setFranId(courier.getFranId());
            cloneTemplate.setTemplateCode(codeNum);
            cloneTemplate.setTemplateName(templateName);
            cloneTemplate.setTemplateDesc(templateDesc);
            cloneTemplate.setTemplateStatus("使用中");
            templates.add(cloneTemplate);
        });
        return APIEntity.success(customerTemplateService.saveBatch(templates));
    }


    /**
     * 获取计费模板记录
     * @param id
     * @return
     */
    @ApiOperation("获取计费模板记录")
    @GetMapping("/get/template/list")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    public InterfaceBase getTemplateList(@RequestAttribute("JwtUserId") Integer id) {
        TCourier courier = courierService.getById(id);
        return TableData.success(customerTemplateService.page(new Page<TCustomerTemplate>(1,10),
                new QueryWrapper<TCustomerTemplate>().eq("fran_id",courier.getFranId()).eq("create_user",id)
                        .eq("create_type","派送员").groupBy("template_code").orderByDesc("config_sort")));
    }


    /**
     * 根据类型组获取数据
     * @param id
     * @param templateCode
     * @return
     */
    @ApiOperation("根据类型编码获取数据")
    @GetMapping("/get/list/group")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="templateCode",value="模板号",dataType="String",example="T4087", paramType = "query")})
    public APIEntity getLitGroup(@RequestAttribute("JwtUserId") Integer id,String templateCode) {
        if(StringUtils.isBlank(templateCode)){
            return APIEntity.fail("您好，您的模板编码为空，请确认模板是否创建成功");
        }
        TCourier courier = courierService.getById(id);

        List<TCustomerTemplate> templates = customerTemplateService.list(new QueryWrapper<TCustomerTemplate>().eq("template_code",templateCode).eq("config_group","service_type"));
        JSONArray jsonArray = new JSONArray();
        for(TCustomerTemplate template : templates){
            JSONObject jsonone = new JSONObject(templates.size());
            TCustomerTemplate cloneTemplate = customerTemplateService.getOne(new QueryWrapper<TCustomerTemplate>().eq("template_code",templateCode).eq("config_key","car_type_ddc_power_dianli_price"));
            jsonone.put("name",template.getConfigValue().get("显示名称"));
            jsonone.put("templateId",template.getTemplateId());
            jsonone.put("cost",template.getConfigValue().get("默认费用(元)"));
            jsonone.put("kilometre",template.getConfigValue().get("默认距离(公里)"));
            jsonone.put("kilogram",cloneTemplate.getConfigValue().get("首重(KG)"));
            jsonone.put("ContKG",template.getConfigValue().get("续重(元/KG)"));
            jsonone.put("ContKM",template.getConfigValue().get("超出默认距离续费(元/公里)"));
            jsonone.put("desc",template.getConfigValue().get("说明"));
            jsonArray.add(jsonone);
        }
        return APIEntity.success(jsonArray);
    }



    @ApiOperation("根据id修改模板数据")
    @PostMapping("/gettype/group")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="templateCode",value="模板号",dataType="String",example="T4087", paramType = "query")})
    public APIEntity<TCustomerTemplate> updateTemplate(@RequestBody JSONArray array){
        if(StringUtils.isBlank(array.toString())){
            return APIEntity.fail("传递参数错误，请联系管理员");
        }
        JSONObject object = null;
        JSONObject json = null;
        for(int i = 0; i < array.size(); i++){
            log.info("模板配置提交:[{}]",array.getJSONObject(i));
            JSONObject objects = array.getJSONObject(i);
            TCustomerTemplate cloneTemplate = customerTemplateService.getOne(new QueryWrapper<TCustomerTemplate>().eq("template_code",objects.get("templateCode")).eq("config_key","car_type_ddc_power_dianli_price"));
            TCustomerTemplate template = customerTemplateService.getOne(new QueryWrapper<TCustomerTemplate>().eq("template_code",objects.get("templateCode")).eq("template_id",objects.get("templateId")));
            if(template != null){
                if(Integer.parseInt(objects.get("cost").toString())<6){
                    return APIEntity.fail("默认金额不得低于“6”元最低限度");
                }
                object = cloneTemplate.getConfigValue();
                json = template.getConfigValue();
                object.put("首重(KG)",objects.get("kilogram"));
                json.put("显示名称",objects.get("name"));
                json.put("默认费用(元)",objects.get("cost"));
                json.put("默认费用(元)",objects.get("cost"));
                json.put("默认距离(公里)",objects.get("kilometre"));
                json.put("续重(元/KG)",objects.get("ContKG"));
                json.put("超出默认距离续费(元/公里)",objects.get("ContKM"));
                json.put("说明",objects.get("desc"));
                customerTemplateService.updateById(cloneTemplate.setConfigValue(object));
                customerTemplateService.updateById(template.setConfigValue(json));
            }else {
                return APIEntity.fail("没有可配置的默认数据");
            }
        }
        return APIEntity.success();
    }
    /**
     * 获取派送员生成模板二维码
     * @param id
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "获取派送员生成模板二维码")
    @GetMapping("/get/detail")
    public APIEntity getcode(@RequestAttribute("JwtUserId") Integer id,Integer templateId) throws IOException {
        TCustomerTemplate tCustomerTemplate = customerTemplateService.getById(templateId);
        if(tCustomerTemplate==null){
            return APIEntity.fail("无法找到派送员创建的模板！");
        }
        JSONObject jsonObject = new JSONObject(true);
        jsonObject.put("id",tCustomerTemplate.getTemplateId());
        jsonObject.put("name",tCustomerTemplate.getTemplateName());
        Base64.Encoder encoder = Base64.getEncoder();
        String text = encoder.encodeToString(FileUtils.readFileToByteArray(ZxingUtils.createQREncode(jsonObject.toString(),200,200)));
        tCustomerTemplate.setCodeUrl("data:image/png;base64,"+text);
        return APIEntity.success(tCustomerTemplate.getCodeUrl());
    }

    /**
     * 获取派送员与商户绑定列表
     * @param id
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "获取派送员与商户绑定列表")
    @GetMapping("/get/big/list")
    public APIEntity getcode(@RequestAttribute("JwtUserId") Integer id){
        TCourier courier = courierService.getById(id);
        if(courier==null){
            return APIEntity.fail("未找到骑手信息，请重新登录!");
        }
        List<TCustomerBig> customerBigs = customerBigService.list(new QueryWrapper<TCustomerBig>().eq("big_status","已签约").eq("courier_id",courier.getCourierId()));
        if(customerBigs.size()<1){
            return APIEntity.fail("无法找到骑手绑定的商户信息！");
        }
        return APIEntity.success(customerBigs);
    }

    /**
     * 获取加盟商站长列表
     * @param id
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "获取加盟商站长列表")
    @GetMapping("/get/manage/list")
    public APIEntity getManageList(@RequestAttribute("JwtUserId") Integer id){
        TCourier courier = courierService.getById(id);
        List<TManage> manages = itManageService.list(new QueryWrapper<TManage>().eq("fran_id",courier.getFranId()));
        if(manages.size()<0){
            return APIEntity.fail("未找到站点信息!");
        }
        return APIEntity.success(manages);
    }

    /**
     * 营销骑手解绑商户（账号绑定的模板id、商户id、以及商户绑定的骑手id）
     * @param id
     * @return
     */
    @ApiOperation("营销骑手解绑商户")
    @GetMapping("/unbind/big/customer")
    public APIEntity unbindBigCustomer(@RequestAttribute("JwtUserId") Integer id){
        TCourier courier = courierService.getById(id);
        if(courier==null){
            return APIEntity.fail("未找到骑手信息，请重新登录!");
        }
        TCustomerBig customerBig = customerBigService.getOne(new QueryWrapper<TCustomerBig>().eq("courier_id",courier.getCourierId()));
        if(customerBig==null){
            return APIEntity.fail("未找到需要注销的商户不存在！");
        }
        TCustomer customer = customerService.getById(customerBig.getCustomerId());
        if(customer==null){
            return APIEntity.fail("未找到客户信息，请重新登录!");
        }
        //删除绑定的计费模板
        TCustomerTemplate customerTemplate = customerTemplateService.getById(customerBig.getTemplateId());
        if(customerTemplate != null){
            customerTemplateService.remove(new QueryWrapper<TCustomerTemplate>().eq("template_code",customerTemplate.getTemplateCode()));
        }
        //修改商户信息
        customerBig.setCourierId(0);
        customerBig.setTemplateId("");
        customerBig.setBigStatus("已结束");
        customerBig.updateById();
        //修改账户信息
        customer.setTemplateId("");
        customer.setBigId(0);
        customer.updateById();
        return APIEntity.success();
    }

    /**
     * 骑手上报经纬度
     * @param id
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "骑手上报经纬度")
    @GetMapping("/report/latlon")
    public APIEntity reportLatlon(@RequestAttribute("JwtUserId") Integer id,String location){
        log.info("上传骑手经纬度：骑手id:{}，经纬度：{}",id,location);
        if(StringUtils.isBlank(location)){
            return APIEntity.success();
        }
        String lctStr=(String) redisUtil.get(KeyConst.REDIS_COURIER_REPORT+id);
        if (lctStr!=null){
            return APIEntity.success();
        }
        redisUtil.set(KeyConst.REDIS_COURIER_REPORT+id,location,TimeUnit.MINUTES.toSeconds(3));
        TCourier courier=courierService.getCacheById(id);
        AddressVo address = courierService.getAddress(location,id);
        //30分钟
        redisUtil.set(KeyConst.REDIS_COURIER_ADDRESS+id, CourierAddressVo.init(courier,address), Duration.ofHours(4).getSeconds());
        //8小时位置
        redisUtil.set(KeyConst.REDIS_COURIER_LOCATION_ADDRESS+id,address,Duration.ofHours(24).getSeconds());
        //30天
        redisUtil.set(KeyConst.REDIS_COURIER_LAST_ADDRESS+id,address, Duration.ofDays(30).getSeconds());
        return APIEntity.success(address);
    }


}
