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

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bohuikeji.delivery.backstage.constants.KeyConst;
import com.bohuikeji.delivery.backstage.constants.WxAppEm;
import com.bohuikeji.delivery.backstage.constants.huLaLaConst;
import com.bohuikeji.delivery.backstage.constants.payConst;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountMall;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountRecord;
import com.bohuikeji.delivery.backstage.entity.socket.AdminNotice;
import com.bohuikeji.delivery.backstage.entity.vo.CourierAddressVo;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.listener.order.OrderCreateListener;
import com.bohuikeji.delivery.backstage.listener.order.OrderDelayCancelListener;
import com.bohuikeji.delivery.backstage.pay.AliPay;
import com.bohuikeji.delivery.backstage.pay.AliPayV2;
import com.bohuikeji.delivery.backstage.pay.KuaiShouPay;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.*;
import com.bohuikeji.delivery.backstage.task.CourierNoticeTask;
import com.bohuikeji.delivery.backstage.util.QrCodeUtil;
import com.bohuikeji.delivery.backstage.util.WxUtils;
import com.bohuikeji.delivery.backstage.util.capacity.HllUtils;
import com.bohuikeji.delivery.backstage.util.maiyatian.maltUtils;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysConfig;
import com.bohuikeji.frame.module.admin.entity.sys.SysRes;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.exception.WebVerifiedException;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.utils.*;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
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 springfox.documentation.annotations.ApiIgnore;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Base64;
import java.util.List;
import java.util.regex.Pattern;

import static com.bohuikeji.delivery.backstage.constants.KeyConst.REDIS_COURIER_LOCATION_ADDRESS;


@Api(tags = {"新版客户相关接口"})
@RestController
@Slf4j
@RequestMapping("/api/v2/customer")
@RequiredArgsConstructor
public class CustomerV2Api extends ApiController {

    final ITOrderService orderService;
    final RedisUtil redisUtil;
    final RabbitTemplate rabbitTemplate;
    final ISysConfigService sysConfigService;
    final ITCourierService courierService;
    final ITNewsService newsService;
    final ITPayService payService;
    final ITRefundService refundService;
    final ITCustomerService customerService;
    final ITGiveDetailService giveDetailService;
    final ITCustomerWalletService customerWalletService;
    final ITCustomerPayService customerPayService;
    final ITwxtransfersService twxtransfersService;
    final ITwalletDetailService twalletDetailService;
    final ITFranchiseeInformationService franServer;
    final ITCustomerBigService customerBigService;
    final ITFranchiseeInformationService informationService;
    final ITCustomerTemplateService customerTemplateService;
    final ITDiscountMallService discountMallService;
    final ITDiscountRecordService discountRecordService;
    final ITDiscountOrderService orderDiscountService;
    final IWxUserService wxUserService;
    final ITConfigService configService;
    final ITOrderArrearsService orderArrearsService;
    final MqTool mqTool;
    final CourierNoticeTask noticeTask;
    final ISocketService socketService;
    final ITMaltFieldService maltFieldService;
    final ITCustomerAddressService itCustomerAddressService;

    @ApiOperation("客户App下单预算金额")
    @PostMapping("/place/estimate")
    public APIEntity estimate(@RequestBody @ApiParam(name="order",value="订单信息")TOrder order) {
        log.error("是不是特惠订单:{}",order.getOrderFlag());
        try {
            order = orderService.moneySumNew(order);
        }catch (Exception e){
            //log.error("下单金额计算失败，订单参数错误",e);
        }
        JSONObject json=new JSONObject();
        json.put("monSum",order.getOrderExpectPrice().setScale(2,BigDecimal.ROUND_HALF_UP));
        json.put("totalOrderAmount",order.getTotalOrderAmount().setScale(2,BigDecimal.ROUND_HALF_UP));
        json.put("insuredPrice",order.getInsuredPrice().setScale(2,BigDecimal.ROUND_HALF_UP));
        json.put("prefAmount",order.getPrefAmount().setScale(2,BigDecimal.ROUND_HALF_UP));
        json.put("distance",order.getOrderDistance());
        json.put("orderExpectTime",order.getOrderExpectTime());
        if(order.getExpenseDetails() != null){
            json.put("expensesCost",order.getExpenseDetails().getJSONArray("expensesCost"));
            json.put("premiumCost",order.getExpenseDetails().getJSONArray("premiumCost"));
        }
        /*List<TCustomerTemplate> templates=configService.getBigCustomerAddList(order.getPlayerId());
        if (templates!=null&&templates.size()>0){
            json.put("bigCustomerAddPrice",templates);
        }*/
        log.error("【下单金额预估】下单人：{}，订单：{}，返回：{}",order.getPlayerId(),order.getOrderNum(),json);
        return APIEntity.success(json);
    }

    /**
     * 下单APP
     * @param order
     * @return
     */
    @ApiOperation("客户App下单")
    @PostMapping("/place/order")
    @ApiImplicitParams({})
    public APIEntity insertOrder(@RequestAttribute("JwtUserId") Integer id,@RequestBody TOrder order,String cid) {
        return APIEntity.fail("苹果端接口维护中，请使用同城急送微信小程序下单！");
    }
    /**
     * 客户支付宝小程序授权接口
     * @param id
     * @param code
     * @return
     * @throws Exception
     */
    @ApiOperation("客户支付宝小程序授权接口")
    @PostMapping("/ali/pay/grant")
    @ApiImplicitParams({})
    public APIEntity insertOrderPayment(@RequestAttribute("JwtUserId") Integer id,String code){
        log.error("渠道类型@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        JSONObject jsonObject = null;
        if(wxUserService.list(new QueryWrapper<TWxUser>().eq("user_id",id).eq("wx_app_type","ALICLIENT")).size()>0){
            return APIEntity.success("授权成功，请刷新");
        }
        try {
            jsonObject = AliPay.getUserId(code);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
       if(jsonObject == null){
           return APIEntity.fail("未获取支付宝用户id");
       }
        TWxUser wxUser = new TWxUser();
        wxUser.setUserId(Long.valueOf(id));
        wxUser.setUserType(WxAppEm.WX_USER_TYPE_CUSTOMER);
        wxUser.setWxAppId(AliPayConfig.appID);
        wxUser.setWxAppType("ALICLIENT");
        wxUser.setWxAppName("客户端小程序（支付宝）");
        wxUser.setWxUserOpenid(jsonObject.getString("user_id"));
        wxUserService.save(wxUser);
        return APIEntity.success("授权成功");
    }


    /**
     * 客户支付宝小程序授权接口
     * @param id
     * @param code
     * @return
     * @throws Exception
     */
    @ApiOperation("客户支付宝小程序授权接口")
    @PostMapping("/ali/grant/channel")
    @ApiImplicitParams({})
    public APIEntity grantChannel(@RequestAttribute("JwtUserId") Integer id,String code,String channel){
        log.error("渠道类型1：{}",channel);
        JSONObject jsonObject = null;
        if(wxUserService.list(new QueryWrapper<TWxUser>().eq("user_id",id).eq("wx_app_name",channel).eq("wx_app_type","ALICLIENT")).size()>0){
            return APIEntity.success("授权成功，请刷新");
        }
        try {
            jsonObject = AliPayV2.getUserId(code,channel);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(jsonObject == null){
            return APIEntity.fail("未获取支付宝用户id");
        }
        log.error("支付宝登陆时获取的授权信息：{}",jsonObject);
        String appId;
        switch (channel){
            case "官方平台":
                log.error("渠道类型1：{}",channel);
                appId=AliPayV2Config.appID;break;
            case "急送平台":
                log.error("渠道类型2：{}",channel);
                appId=AliPayV2Config.AliClientID;break;
            case "同城急送":
                log.error("渠道类型3：{}",channel);
                appId=AliPayV2Config.AliID;break;
            case "客户端小程序（支付宝）":
                log.error("渠道类型4：{}",channel);
                appId=AliPayConfig.appID;break;
            default:
                return null;
        }
        //log.info("!!!!!!!!!!!!!!!!:{}",appId);
        TWxUser wxUser = new TWxUser();
        wxUser.setUserId(Long.valueOf(id));
        wxUser.setUserType(WxAppEm.WX_USER_TYPE_CUSTOMER);
        wxUser.setWxAppId(appId);
        wxUser.setWxAppType("ALICLIENT");
        wxUser.setWxAppName(channel);
        wxUser.setWxUserOpenid(jsonObject.getString("user_id"));
        wxUserService.save(wxUser);
        return APIEntity.success("授权成功");
    }

    /**
     * 客户小程序授权接口
     * @param id
     * @param order
     * @return
     */
    @ApiOperation("客户小程序授权接口(支付宝、快手)")
    @PostMapping("/kuaishou/pay/grant")
    @ApiImplicitParams({})
    public APIEntity kuaishouAuthorization(@RequestAttribute("JwtUserId") Integer id,@RequestBody TOrder order){
        TPay pay = payService.getOne(new QueryWrapper<TPay>().eq("merchant_num",order.getOrderNum()).eq("pay_status","待付款"));
        TOrder tOrder = orderService.initialOrder(order);
        redisUtil.set("order:create:num:"+tOrder.getOrderNum(),tOrder,60*60*12);
        if(wxUserService.list(new QueryWrapper<TWxUser>().eq("user_id",id).eq("wx_app_type","ALICLIENT")).size()>0){
            return APIEntity.fail("已授权，请刷新");
        }
        if(wxUserService.list(new QueryWrapper<TWxUser>().eq("user_id",id).eq("wx_app_type","KUAISHOU")).size()>0){
            return APIEntity.fail("已授权，请刷新");
        }
        TWxUser wxUser = wxUserService.saveWxUser(tOrder);
        if(wxUser==null){
            return APIEntity.fail("未获取用户的授权 ");
        }
        if("快手小程序".equals(tOrder.getOrderChannel())){
            pay =payService.createBeforePay(tOrder,"业务支付","客户支付","快手");
            JSONObject rs = KuaiShouPay.kuaishouOrder(pay.getPayNum(),pay.getPayExpectPrice(),wxUser.getWxUserOpenid());
            return  rs==null?APIEntity.fail("获取预支付订单错误！"):APIEntity.success(rs);
        }
        if("支付宝小程序".equals(tOrder.getOrderChannel())){
            pay =payService.createBeforePay(tOrder,"业务支付","客户支付","支付宝");
            JSONObject rs = AliPay.alipayClient(pay.getPayNum(), pay.getPayExpectPrice().toString(),wxUser.getWxUserOpenid());
            return  rs==null?APIEntity.fail("获取预支付订单错误！"):APIEntity.success(rs);
        }
        return APIEntity.fail("调起预支付订单失败");

    }

    /**
     *
     * @param id
     * @param custAddId
     * @return
     * @throws Exception
     */
    @ApiOperation("获取分享信息")
    @GetMapping("/get/redis/info")
    @ApiImplicitParams({})
    public APIEntity getRedisOrder(@ApiIgnore("id")@RequestAttribute("JwtUserId") Integer id,Integer custAddId) throws Exception {
        log.info("获取地址信息参数：{}",custAddId);
        TCustomerAddress tCustomerAddress=itCustomerAddressService.getOne(new QueryWrapper<TCustomerAddress>().eq("cust_add_id",custAddId).eq("type","收件地址"));
        if(tCustomerAddress==null){
            return APIEntity.fail("信息不存在");
        }
        if(StringUtils.isBlank(tCustomerAddress.getAddressCode())){
            String logoUrl;
            if(StringUtils.isBlank(tCustomerAddress.getLogoUrl())){
                logoUrl=null;
            }else {
                logoUrl= tCustomerAddress.getLogoUrl();
            }
            String query = "custAddId="+tCustomerAddress.getCustAddId()+"&shareId="+1;
            String path = "pages/Information/Information";
            String urlLin = WxUtils.getMpCustomeCode(WxAppEm.MP_CLIENT,path,query).getString("url_link");
            log.info("##########################:{}",urlLin);
            BufferedImage image = QrCodeUtil.getQrCodeImage(urlLin,logoUrl,450);
            ByteArrayOutputStream outtwo = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", outtwo);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(outtwo.toByteArray());
            String templateUrl = MinioUtil.uploadFileB(inputStream,".jpg");
            tCustomerAddress.setShareId(1);
            tCustomerAddress.setCodeUrl(urlLin);
            itCustomerAddressService.updateById(tCustomerAddress.setAddressCode(templateUrl));
        }
        return APIEntity.success(tCustomerAddress);
    }

    /**
     * 判断是否生成二维码
     * @param id
     * @return
     * @throws Exception
     */
    @ApiOperation("判断是否生成二维码")
    @GetMapping("/get/default/code")
    @ApiImplicitParams({})
    public APIEntity getDefaultCode(@ApiIgnore("id")@RequestAttribute("JwtUserId") Integer id) throws Exception {
        TCustomerAddress tCustomerAddress=itCustomerAddressService.getOne(new QueryWrapper<TCustomerAddress>().eq("customer_id",id).eq("type","收件地址").eq("default_address ",1));
        if(tCustomerAddress==null){
            return APIEntity.fail("未生成二维码");
        }
        if(StringUtils.isBlank(tCustomerAddress.getAddressCode())){
            return APIEntity.fail("未生成二维码");
        }
        return APIEntity.success(tCustomerAddress);
    }

    /**
     * 生成二维码
     * @param id
     * @param name
     * @param phone
     * @param address
     * @param detail
     * @param lng
     * @param lat
     * @return
     * @throws Exception
     */
    @ApiOperation("生成二维码")
    @PostMapping("/send/info/qrcode")
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount","id"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="name",value="孙劲辉",dataType="String", paramType = "String",example="孙劲辉",required=true),
            @ApiImplicitParam(name="phone",value="15771335697",dataType="String", paramType = "String",example="15771335697",required=true),
            @ApiImplicitParam(name="address",value="内蒙古自治区呼和浩特市新城区成吉思汗大街29号",dataType="String", paramType = "String",example="内蒙古自治区呼和浩特市新城区成吉思汗大街29号",required=true),
            @ApiImplicitParam(name="detail",value="1栋二单元1024(11楼左手第二间)",dataType="String", paramType = "String",example="1栋二单元1024(11楼左手第二间)",required=false),
            @ApiImplicitParam(name="lng",value="111.78387",dataType="String", paramType = "String",example="111.78387",required=true),
            @ApiImplicitParam(name="lat",value="40.86792",dataType="String", paramType = "String",example="40.86792",required=true),
            @ApiImplicitParam(name="url",value="https://oss.bhynm.com/delivery/upload/2023/5/17/168428742764417.png",dataType="String", paramType = "String",example="40.86792")})
    public APIEntity addOrderQrcode(@RequestAttribute("JwtUserId") Integer id,String name,String phone,String address,String detail,String lng,String lat,String url) throws Exception {
        //JSONObject sendInfo = JSONObject.parseObject(sendInfoJson);
        log.info("分享的地址信息########：{}",name);
        if(StringUtils.isBlank(address)){
            return APIEntity.fail("未找到该地址信息！");
        }
        TCustomer customer = customerService.getById(id);
        if(customer == null){
            return APIEntity.fail("账号不存在，请重新登陆！");
        }
        if("已拉黑".equals(customer.getCustomerStatus())){
            return APIEntity.fail("您已触发下单禁止条例，暂时无法下单，如需下单请联系客服！");
        }
        AddressVo addressVo;
        if (StringUtils.isNotBlank(lng)){
            String location = lng+","+lat;
            addressVo=MapUtils.getAddressReGeo(location);
        }else {
            addressVo = MapUtils.getAddressGeo(address+detail);
        }
        TCustomerAddress tCustomerAddress=new TCustomerAddress();
        addressVo.setAddress(address);
        addressVo.setDetail(detail);
        tCustomerAddress.setName(name);
        tCustomerAddress.setPhone(phone);
        tCustomerAddress.setLocationAddress(address+detail);
        tCustomerAddress.setAddressJson(addressVo);
        tCustomerAddress.setCustomerId(id);
        tCustomerAddress.setDefaultAddress(true);
        tCustomerAddress.setType("收件地址");
        if (true){
            itCustomerAddressService.update(new UpdateWrapper<TCustomerAddress>().set("default_address ",0).eq("type","收件地址").eq("customer_id",id));
        }
        itCustomerAddressService.saveOrUpdate(tCustomerAddress);
        String query = "custAddId="+tCustomerAddress.getCustAddId()+"&shareId="+1;
        String path = "pages/Information/Information";
        String urlLin = WxUtils.getMpCustomeCode(WxAppEm.MP_CLIENT,path,query).getString("url_link");
        log.info("##########################:{}",urlLin);
        BufferedImage image = QrCodeUtil.getQrCodeImage(urlLin,url,450);
        ByteArrayOutputStream outtwo = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outtwo);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outtwo.toByteArray());
        String templateUrl = MinioUtil.uploadFileB(inputStream,".jpg");
        tCustomerAddress.setShareId(1);
        tCustomerAddress.setCodeUrl(urlLin);
        tCustomerAddress.setLogoUrl(url);
        itCustomerAddressService.updateById(tCustomerAddress.setAddressCode(templateUrl));
        itCustomerAddressService.setLogoList(url,customer);
        return APIEntity.success(tCustomerAddress);
    }

    /**
     * 下单APP
     * @param order
     * @return
     */
    @ApiOperation("##############################################")
    @PostMapping("/order/test")
    @ApiImplicitParams({})
    public APIEntity insertOrderTest(Integer orderId,HttpServletRequest request) throws Exception {
        TOrder order = orderService.getById(orderId);
        order.setOrderNum(NumberUtils.get("A"));
        System.out.println("#########111:"+order);
        //log.error("是不是特惠订单22222:{}",order.getOrderFlag());
        if(order==null){
            log.error("未找到该订单信息");
            return APIEntity.fail("未找到该订单信息！");
        }
        TCustomer customer = customerService.getById(272);
        if(customer == null){
            return APIEntity.fail("账号不存在，请重新登陆！");
        }
        if(StringUtils.isBlank(order.getServiceType())){
            order.setServiceType("业务支付");
        }
        if(redisUtil.get("order_id_"+order.getPlayerId())!=null){
            return APIEntity.fail("您操作的太快了，系统玩命处理中....");
        }
        if(order.getWayConfigId()==null){
            return APIEntity.fail("请选择配送方式！");
        }
        if("已拉黑".equals(customer.getCustomerStatus())){
            return APIEntity.fail("您已触发下单禁止条例，暂时无法下单，如需下单请联系客服！");
        }
        log.info("$$$$$$$$$$:{}",order.getThirdName());
        if(KDHundredServer.NAME.equals(order.getThirdName())){
            if(order.getPlayerId() != 203){
                return APIEntity.fail("系统维护中请稍后下单！");
            }
        }
        if(SfExpressServer.NAME.equals(order.getThirdName())){
            return APIEntity.fail("系统维护中请稍后下单！");
        }
        log.info("第三方订单：第三方名字：{}，是否确认：{}",order.getThirdName(),order.getThird());
        //京东的订单
        if(order.getWayConfigId().equals(5832)&&order.getVehicleConfigId().equals(5832)){
            if(LocalDateTime.now().getHour()>=19 && "今天/2小时内".equals(order.getPickTime()) || LocalDateTime.now().getHour()>=19 && "今天/一小时内".equals(order.getPickTime())){
                throw new WebVerifiedException("时间已晚，可选择明天取件！");
            }
            order.setOrderNum(NumberUtils.get("D"));
        }
        if(StringUtils.isNotBlank(order.getThirdName())){
            if(order.getThirdName().equals("HLL")){
                order.setOrderNum(NumberUtils.get("C"));
            }
        }
        order.setType("WALLET");
        order.setContactPhone(customer.getCustomerPhone());
        order = orderService.initialOrder(order);
        redisUtil.set("order_id_"+order.getPlayerId(),order,3);
        if("补充支付".equals(order.getServiceType())){
            log.info("订单预估金额：[{}]",order.getOrderExpectPrice());
            log.info("订单支付金额：[{}]",order.getOrderFactPrice());
            if(order.getOrderExpectPrice().compareTo(order.getOrderFactPrice()) < 1){
                order.setOrderExpectPrice(order.getOrderFactPrice());
                order.updateById();
                log.info("修改后的订单：[{}]",order);
                return APIEntity.success("修改成功").setMessage("修改成功");
            }
        }
        System.out.println("#########:"+order);
        redisUtil.set("order:create:num:"+order.getOrderNum(),order,60*60*12);
        return payService.getPayAPIEntity(order,request);
    }

    /**
     * 下单APP
     * @param order
     * @return
     */
    @ApiOperation("客户下单支付接口")
    @PostMapping("/order/payment")
    @ApiImplicitParams({})
    public APIEntity insertOrderPayment(@RequestAttribute("JwtUserId") Integer id, @RequestBody TOrder order,HttpServletRequest request) throws Exception {
        log.error("是不是特惠订单22222:{}",order.getOrderFlag());
        if(order==null){
            log.error("未找到该订单信息");
            return APIEntity.fail("未找到该订单信息！");
        }
        TCustomer customer = customerService.getById(id);
        if(customer == null){
            return APIEntity.fail("账号不存在，请重新登陆！");
        }
        if(StringUtils.isBlank(order.getServiceType())){
            order.setServiceType("业务支付");
        }
        if(redisUtil.get("order_id_"+order.getPlayerId())!=null){
            return APIEntity.fail("您操作的太快了，系统玩命处理中....");
        }
        if(order.getWayConfigId()==null){
            return APIEntity.fail("请选择配送方式！");
        }
        if("已拉黑".equals(customer.getCustomerStatus())){
            return APIEntity.fail("您已触发下单禁止条例，暂时无法下单，如需下单请联系客服！");
        }
        log.info("$$$$$$$$$$:{}",order.getThirdName());
        if(KDHundredServer.NAME.equals(order.getThirdName())){
            if(order.getPlayerId() != 203){
                return APIEntity.fail("系统维护中请稍后下单！");
            }
        }
        if(SfExpressServer.NAME.equals(order.getThirdName())){
            return APIEntity.fail("系统维护中请稍后下单！");
        }
        log.info("第三方订单：第三方名字：{}，是否确认：{}",order.getThirdName(),order.getThird());
        //京东的订单
        if(order.getWayConfigId().equals(5832)&&order.getVehicleConfigId().equals(5832)){
            if(LocalDateTime.now().getHour()>=19 && "今天/2小时内".equals(order.getPickTime()) || LocalDateTime.now().getHour()>=19 && "今天/一小时内".equals(order.getPickTime())){
                throw new WebVerifiedException("时间已晚，可选择明天取件！");
            }
            order.setOrderNum(NumberUtils.get("D"));
        }
        if(StringUtils.isNotBlank(order.getThirdName())){
            if(order.getThirdName().equals("HLL")){
                order.setOrderNum(NumberUtils.get("C"));
            }
        }
        order.setContactPhone(customer.getCustomerPhone());
        order = orderService.initialOrder(order);
        redisUtil.set("order_id_"+order.getPlayerId(),order,3);
        if("补充支付".equals(order.getServiceType())){
            log.info("订单预估金额：[{}]",order.getOrderExpectPrice());
            log.info("订单支付金额：[{}]",order.getOrderFactPrice());
            if(order.getOrderExpectPrice().compareTo(order.getOrderFactPrice()) < 1){
                order.setOrderExpectPrice(order.getOrderFactPrice());
                order.updateById();
                log.info("修改后的订单：[{}]",order);
                return APIEntity.success("修改成功").setMessage("修改成功");
            }
        }
        redisUtil.set("order:create:num:"+order.getOrderNum(),order,60*60*12);
        return payService.getPayAPIEntity(order,request);
    }


    /**
     * 增加订单小费
     * @param id
     * @param orderNum
     * @param type
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation("增加订单小费")
    @GetMapping("/order/tip")
    @ApiImplicitParams({})
    public APIEntity orderTip(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id, String orderNum,String type,String tipAmount,HttpServletRequest request) throws Exception {
        String openId = null;
        log.info("########################加小费#############################");
        TOrder order = orderService.getByNum(orderNum);
        if("已取消".equals(order.getOrderStatus()) || "已完成".equals(order.getOrderStatus())){
            return APIEntity.success("订单已终结，不可支付小费");
        }
        if("SFKD".equals(order.getThirdName())){
            return APIEntity.success("快递订单，不可支付小费");
        }
        if("SS".equals(order.getThirdName()) && !"待接单".equals(order.getOrderStatus())){
            return APIEntity.success("骑手已结单，不可支付小费");
        }
        order.setTipAmount(new BigDecimal(tipAmount));
        TCustomer customer = customerService.getById(id);
        if (customer == null) {
            return APIEntity.fail("无法找到客户信息，请重新登陆！", 412);
        }
        TPay pay  =payService.createBeforePay(order,"订单小费","客户支付",payConst.getway(type));
        if ("JSAPI".equals(type)) {
            openId = customer.getOpenId();
        }
        if("aliClient".equals(type)){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",id).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",customer.getCustomerId()).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,pay.getPayExpectPrice(),request);
        return object==null?APIEntity.fail("客户调起"+payConst.getway(type)+"支付错误"):APIEntity.success(object);
    }

    /**
     * 客户钱包充值接口
     * @param id
     * @param price
     * @param type
     * @param location
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation("客户钱包充值接口(微信、支付宝、百度、快手、抖音)")
    @GetMapping("/wallet/recharge")
    @ApiImplicitParams({})
    public APIEntity WalletPayment(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id, String price, String type, String location, HttpServletRequest request) throws Exception {
        String openId = null;
        TCustomer customer = customerService.getById(id);
        if (customer == null) {
            return APIEntity.fail("无法找到客户信息，请重新登陆！", 412);
        }
        TCustomerWallet tCustomerWallet = customerWalletService.getOne(new QueryWrapper<TCustomerWallet>().eq("customer_id",customer.getCustomerId()).eq("wallet_state","提现中"));
        if(tCustomerWallet != null){
            return APIEntity.fail("您的钱包余额正在提现中，请稍候充值。");
        }
        //TCustomerPay customerPay = customerPayService.getOne(new QueryWrapper<TCustomerPay>().eq("player_id", customer.getCustomerId()).eq("pay_status", "待付款").eq("pay_expect_price",new BigDecimal(price)));
        TCustomerPay customerPay = customerPayService.createWalletPay(customer, price, payConst.getway(type), "钱包充值", location);
        if ("JSAPI".equals(type)) {
            openId = customer.getOpenId();
        }
        if("aliClient".equals(type)){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",id).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",customer.getCustomerId()).eq("wx_app_type","KUAISHOU"));
            if(wxUser == null){
                return APIEntity.fail("请用户授权");
            }
            openId = wxUser.getWxUserOpenid();
        }
        String payNum = customerPay.getPayNum();
        JSONObject object = payConst.getObject(type,payNum,openId,customerPay.getPayExpectPrice(),request);
        return object==null?APIEntity.fail("客户调起"+payConst.getway(type)+"支付错误"):APIEntity.success(object);
    }

    /**
     * 根据客户寄件地址筛选周围骑手
     * @param mailingAddress
     * @return
     */
    @ApiOperation("根据客户寄件地址筛选周围骑手")
    @PostMapping("/screen/scope")
    @ApiImplicitParams({})
    public APIEntity insertOrder(AddressVo mailingAddress) {
        List<TCourier> couriers=courierService.list(new QueryWrapper<TCourier>().eq("job_status","工作中").eq("fran_id",franServer.checkPio(mailingAddress).getFranId()));
        JSONArray jsonArray = new JSONArray();
        for(TCourier courier : couriers) {
            JSONObject jsonObject = new JSONObject(couriers.size());
            AddressVo address = redisUtil.get(REDIS_COURIER_LOCATION_ADDRESS + courier.getCourierId(), AddressVo.class);
            if (address != null) {
                double dist = DistanceUtils.getDistance(mailingAddress.getLng(), mailingAddress.getLat(), address.getLng(), address.getLat());
                if (dist <= 10) {
                    log.info("附件的派送员:[{}]",courier.getCourierName());
                    jsonObject.put("Lng",address.getLng());
                    jsonObject.put("Lat",address.getLat());
                }
            }
            jsonArray.add(jsonObject);
        }
        return APIEntity.success(jsonArray);
    }

    /**
     * 客户取消订单金额明细展示
     * @param orderId
     * @return
     */
    @ApiOperation("客户取消订单金额明细展示")
    @PostMapping("/get/cancel/price/info")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderId",value="订单id",dataType="Integer", paramType = "query",example="1",required=true),
            @ApiImplicitParam(name="customerId",value="下单人id",dataType="Integer", paramType = "query",example="1",required=true)})
    public APIEntity cancelPeiceInfo(String orderId,Integer customerId){
        log.info("orderId:{}",orderId);
        log.info("customerId:{}",customerId);
        JSONObject jsonObject = new JSONObject();
        TOrder tOrder = orderService.getOne(new QueryWrapper<TOrder>().eq("order_id",orderId).eq("player_id",customerId));
        List<TPay> tPays = payService.list(new QueryWrapper<TPay>().eq("order_id",tOrder.getOrderId()).eq("pay_status","已支付"));
        BigDecimal loadFee = refundService.deduct(tOrder);
        for(TPay pay : tPays){
            BigDecimal refundPrice=new BigDecimal("0.00");
            BigDecimal suppPrice = new BigDecimal("0.00");
            if("业务支付".equals(pay.getPayScenario())){
                refundPrice=pay.getPayFactPrice().subtract(loadFee);
            }
            if("补充支付".equals(pay.getPayScenario())){
                suppPrice =pay.getPayFactPrice();
            }
            jsonObject.put("refundAmount",refundPrice.add(suppPrice));
        }

        jsonObject.put("noLoadFee",loadFee);
        return APIEntity.success(jsonObject);
    }

    /**
     * 客户预取消订单
     * @param
     * @return
     */
    @ApiOperation("客户预取消订单")
    @GetMapping("/pre/cancel/order")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderNum",value="订单号",dataType="String", paramType = "query",example="1",required=true)})
    public APIEntity preCancel(@RequestAttribute("JwtUserId") Integer id,String orderNum){
        TOrder tOrder = orderService.getOne(new QueryWrapper<TOrder>().eq("player_id",id).eq("order_num",orderNum));
        return APIEntity.success(refundService.getPreCancelInfo(tOrder));
    }

    /**
     * 客户预取消订单
     * @param
     * @return
     */
    @ApiOperation("客户预取消订单")
    @PostMapping("/cancel/order")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderId",value="订单id",dataType="Integer", paramType = "query",example="1",required=true),
            @ApiImplicitParam(name="customerId",value="下单人id",dataType="Integer", paramType = "query",example="1",required=true),
            @ApiImplicitParam(name="type",value="请求环境",dataType="String", paramType = " ",example="1")})
    public APIEntity cancel(String orderId,Integer customerId,String type){
        TOrder tOrder = orderService.getOne(new QueryWrapper<TOrder>().eq("order_id",orderId).eq("player_id",customerId));
        String[] states={"已完成","派送中","待派送"};
        for (String state : states) {
            if(state.equals(tOrder.getOrderStatus())){
                return APIEntity.success("尊敬的客户您好，您的订单状态为"+tOrder.getOrderStatus()+"不可以取消");
            }
        }
        if("HLL".equals(tOrder.getThirdName()) && StringUtils.isNotBlank(tOrder.getThirdNum())){
            String token = orderService.getHuolalaToken();
            Integer deductStatus = HllUtils.getEOrderDetail(token,tOrder.getThirdNum()).getInteger("order_status");
            if(!huLaLaConst.contrast(deductStatus)){
                return APIEntity.success("尊敬的客户您好，订单只有在派送前可以取消");
            }
        }
        if("KD".equals(tOrder.getThirdName())){
            tOrder.setOrderStatus("已取消");//订单状态修改
            tOrder.setThirdStatus("已取消");
            orderService.updateById(tOrder);
            log.error("快递100取消");
            ThirdUtils.orderCancelAll(tOrder.getOrderNum());
            return APIEntity.success("订单取消成功");
        }
        //String[] status={"待接单","待取件","取件中"};
        List<TPay> tPays = payService.list(new QueryWrapper<TPay>().eq("order_id",tOrder.getOrderId()).eq("pay_status","已支付"));
        /*for (String state : status) {
            if(state.equals(tOrder.getOrderStatus()) && !"KD".equals(tOrder.getThirdName())){
                if(tPays.size()<1){
                    orderService.updateById(tOrder.setOrderStatus("已取消"));
                    return APIEntity.success("尊敬的客户您好，您的订单已取消不可以重复取消");
                }
            }
        }*/
        log.error("客户取消：订单号：{},下单人：{},取消类型：{}",tOrder.getOrderNum(),tOrder.getPlayerId(),type);
        TRefund refund = refundService.cancel(tOrder,tPays);
        if("open".equals(type)){
            if(refund == null){
                return APIEntity.success("订单取消失败");
            }
            JSONObject jsonObject = new JSONObject(true);
            jsonObject.put("orderNum",refund.getOrderNum());
            jsonObject.put("refundTime",refund.getRefundTime());
            jsonObject.put("refundPrice",refund.getRefundPrice());
            jsonObject.put("noLoadPrice",refund.getNoLoadPrice());
            return APIEntity.success(jsonObject);
        }
        return APIEntity.success("订单取消成功");
    }



    /**
     * 客户App取消订单
     * @param orderId
     * @return
     */
   /* @ApiOperation("客户取消订单")
    @PostMapping("/cancel/order")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderId",value="订单id",dataType="Integer", paramType = "query",example="1",required=true),
            @ApiImplicitParam(name="customerId",value="下单人id",dataType="Integer", paramType = "query",example="1",required=true)})
    public APIEntity cancel(String orderId,Integer customerId){
        TOrder tOrder = orderService.getOne(new QueryWrapper<TOrder>().eq("order_id",orderId).eq("player_id",customerId));
        //开放平台直接取消
        if("已完成".equals(tOrder.getOrderStatus())){
            return APIEntity.success("尊敬的客户您好，您的订单已完成不可以取消");
        }
        if("派送中".equals(tOrder.getOrderStatus())){
            return APIEntity.success("尊敬的客户您好，您的订单正在派送中不可以取消");
        }
        if("待派送".equals(tOrder.getOrderStatus())){
            return APIEntity.success("尊敬的客户您好，您的订单正在派送中不可以取消");
        }
        if("HLL".equals(tOrder.getThirdName()) && StringUtils.isNotBlank(tOrder.getThirdNum())){
            String token = orderService.getHuolalaToken();
            Integer deductStatus = HllUtils.getEOrderDetail(token,tOrder.getThirdNum()).getInteger("order_status");
            if(!huLaLaConst.contrast(deductStatus)){
                return APIEntity.success("尊敬的客户您好，订单只有在派送前可以取消");
            }
        }
        if("待接单".equals(tOrder.getOrderStatus()) && "寄付".equals(tOrder.getPaymentType())){
            List<TPay> tPays = payService.list(new QueryWrapper<TPay>().eq("order_id",tOrder.getOrderId()).eq("pay_status","已支付"));
            if(tPays.size()<1){
                return APIEntity.success("尊敬的客户您好，您的订单已取消不可以重复取消");
            }
            refundService.cancel(tOrder,tPays);
            return APIEntity.success("订单取消成功");
        }
        if("待取件".equals(tOrder.getOrderStatus()) && "寄付".equals(tOrder.getPaymentType())){
            List<TPay> tPays = payService.list(new QueryWrapper<TPay>().eq("order_id",tOrder.getOrderId()).eq("pay_status","已支付"));
            if(tPays.size()<1){
                return APIEntity.success("尊敬的客户您好，您的订单已取消不可以重复取消");
            }
            refundService.cancel(tOrder,tPays);
            return APIEntity.success("订单取消成功");
        }
        if("取件中".equals(tOrder.getOrderStatus()) && "寄付".equals(tOrder.getPaymentType())){
            List<TPay> tPays = payService.list(new QueryWrapper<TPay>().eq("order_id",tOrder.getOrderId()).eq("pay_status","已支付"));
            if(tPays.size()<1){
                return APIEntity.success("尊敬的客户您好，您的订单已取消不可以重复取消");
            }
            refundService.cancel(tOrder,tPays);
            return APIEntity.success("订单取消成功");
        }
        return APIEntity.success("订单取消失败");
    }*/

    /**
     * 客户钱包编译订单
     * @param id
     * @return
     */
    @ApiOperation("客户钱包提现")
    @PostMapping("/wallet/refund")
    public APIEntity walletRefund(@RequestAttribute("JwtUserId") Integer id){
        TCustomer customer =  customerService.getById(id);
        TCustomerWallet tCustomerWallet = customerWalletService.getOne(new QueryWrapper<TCustomerWallet>().eq("customer_id",customer.getCustomerId()));
        if(customer== null){
            return APIEntity.fail("没有找到您的信息。");
        }
        if(StringUtils.isBlank(customer.getOpenId()) && StringUtils.isBlank(customer.getCustAppOpenId())){
            return APIEntity.fail("当前账户未绑定微信，请确认绑定微信或者小程序登陆提现");
        }
        if(tCustomerWallet == null){
            return APIEntity.fail("尊敬的客户您好，您的钱包金额为'0',不能提现");
        }
        if(tCustomerWallet.getWalletPrice().compareTo(new BigDecimal("0.00"))==0){
            return APIEntity.fail("尊敬的客户您好，您的钱包金额为'0',不能提现");
        }
        SysRes res=new SysRes();
        Object giftSum=res.sql().selectObj("select IFNULL(sum(gift_amount),0) as sumc from t_give_detail where customer_id={0} and give_status='未使用'",customer.getCustomerId());//订单预结算金额
        if(tCustomerWallet.getWalletPrice().compareTo(new BigDecimal(giftSum.toString())) <1){
            return APIEntity.fail("尊敬的客户您好，您的本金已使用完，并且使用了部分赠金，无法提现。");
        }
        if(tCustomerWallet.getWalletPrice().compareTo(tCustomerWallet.getPreferPrice()) <1){
            return APIEntity.fail("尊敬的客户您好，您的本金已使用完，并且使用了部分赠金，无法提现。");
        }
        tCustomerWallet.setRefuntPrice(tCustomerWallet.getRefuntPrice().add(tCustomerWallet.getWalletPrice()).subtract(tCustomerWallet.getPreferPrice()).subtract(new BigDecimal(giftSum.toString())));
        tCustomerWallet.setWalletPrice(new BigDecimal(0));
        tCustomerWallet.setWalletState("提现中");
        customerWalletService.updateById(tCustomerWallet);
        return APIEntity.success("退款审核中，请等待");
    }

    /**
     * 客户钱包明细
     * @param id
     * @return
     */
    @ApiOperation("客户钱包明细")
    @PostMapping("/wallet/detail")
    public APIEntity walletDetail(@RequestAttribute("JwtUserId") Integer id){
        //List<TWalletDetail> tWalletDetail = twalletDetailService.list(new QueryWrapper<TWalletDetail>().eq("customer_id",id));
        return APIEntity.success(twalletDetailService.list(new QueryWrapper<TWalletDetail>().eq("customer_id",id).orderByDesc("create_time")));
    }

    /**
     * 客户商户绑定骑手状态
     * @param id
     * @return
     */
    @ApiOperation("客户商户绑定骑手状态")
    @GetMapping("/market/bind")
    public APIEntity bind(@RequestAttribute("JwtUserId") Integer id){
        TCustomer customer = customerService.getById(id);
        if(customer == null){
            return APIEntity.fail("当前客户不存在，请重新登陆");
        }
        if(customer.getBigId().equals(0)){
            return APIEntity.success("未绑定");
        }else {
            String type=null;
            TCustomerBig tCustomerBig = customerBigService.getOne(new QueryWrapper<TCustomerBig>().eq("big_id",customer.getBigId()));
            if(tCustomerBig == null){
                type = "未绑定";
            }
            if("已签约".equals(tCustomerBig.getBigStatus())){
                type = "已绑定";
            }
            return APIEntity.success(type);
        }
    }

    /**
     * 申请商户优点介绍
     * @return
     */
    @ApiOperation("申请商户优点介绍")
    @GetMapping("/get/describe")
    public APIEntity describe(@RequestAttribute("JwtUserId") Integer id){
        SysConfig sysConfig = sysConfigService.getOne(new QueryWrapper<SysConfig>().eq("config_key","describe"));
        JSONObject json=new JSONObject();
        json.put("content",sysConfig.getConfigValue().replaceAll("。","\r\n"));
        return APIEntity.success(json);
    }
    /**
     * 客户获取绑定商户信息
     * @param id
     * @return
     */
    @ApiOperation("客户获取绑定商户信息")
    @GetMapping("/get/customer/big")
    public APIEntity getBIg(@RequestAttribute("JwtUserId") Integer id){
        TCustomer customer = customerService.getById(id);
       /* if(StringUtils.isBlank(customer.getTemplateId())){
            return APIEntity.fail("您的账号没有绑定了商户与计费模板");
        }*/
        TCustomerBig customerBig = customerBigService.getById(customer.getBigId());
        if(customerBig==null){
            return APIEntity.fail("您的账户绑定的商户不存在");
        }
        return APIEntity.success(customerBig);
    }

    /**
     * 营骑手接单统计
     * @param id
     * @return
     */
    @ApiOperation("营骑手接单统计")
    @GetMapping("/market/order/statistics")
    public APIEntity statistics(@RequestAttribute("JwtUserId") Integer id){
        TCustomer customer = customerService.getById(id);
        log.info("当前登陆的客户信息:[{}]",customer);
        if(customer == null){
            return APIEntity.fail("当前登陆客户不存在，请重新登陆");
        }
        /*if(StringUtils.isBlank(customer.getTemplateId()) && customer.getBigId().equals(0)){
            return APIEntity.fail("当前客户没有绑定商户与计费模板");
        }*/
        TCustomerBig customerBig = customerBigService.getById(customer.getBigId());
        if(customerBig==null){
            return APIEntity.fail("未找到需要注销的商户不存在！");
        }
        TCustomerTemplate customerTemplate = customerTemplateService.getById(customer.getTemplateId());
        JSONArray jsonArray = new JSONArray();
        if(customerTemplate !=null){
            //JSONArray jsonArray = new JSONArray();
            List<TCustomerTemplate> templates = customerTemplateService.list(new QueryWrapper<TCustomerTemplate>().eq("template_code",customerTemplate.getTemplateCode()).eq("config_group","service_type"));
            for(TCustomerTemplate template : templates){
                JSONObject jsonone = new JSONObject(templates.size());
                jsonone.put("name",template.getConfigValue().get("显示名称"));
                jsonone.put("cost",template.getConfigValue().get("默认费用(元)"));
                jsonArray.add(jsonone);
            }
           /* return APIEntity.fail("客户绑定的模板不存在，请检查");*/
        }
        JSONObject jsonObject = new JSONObject(true);
        TCourier courier = courierService.getCourier(customer);
        if(courier != null){
            jsonObject.put("phone",courier.getCourierPhone());
            jsonObject.put("name",courier.getCourierName());
            return APIEntity.fail("当前绑定商户的骑手不存在，请查看商户信息");
        }else {
            jsonObject.put("phone","400-690-0105");
            jsonObject.put("name","未绑定");
        }
        //TCustomerTemplate template = customerTemplateService.getOne(new QueryWrapper<TCustomerTemplate>().eq("template_code",customerTemplate.getTemplateCode()).eq("config_key","service_type_dangri"));
        Integer jiedanCount= orderService.count(new QueryWrapper<TOrder>().eq("player_id",customer.getCustomerId()).eq("order_status","待接单"));
        Integer qujianCount= orderService.count(new QueryWrapper<TOrder>().eq("player_id",customer.getCustomerId()).in("order_status","待取件","取件中"));
        Integer songjisnCount= orderService.count(new QueryWrapper<TOrder>().eq("player_id",customer.getCustomerId()).in("order_status","代派送","派送中"));
        Integer wanchengCount= orderService.count(new QueryWrapper<TOrder>().eq("player_id",customer.getCustomerId()).eq("order_status","已完成"));

        jsonObject.put("bigName",customerBig.getBigName());
        jsonObject.put("receivOrder",jiedanCount);
        jsonObject.put("pickOrder",qujianCount);
        jsonObject.put("delivOrder",songjisnCount);
        jsonObject.put("complOrder",wanchengCount);
        jsonObject.put("serviceType",jsonArray);
        return APIEntity.success(jsonObject);
    }

    /**
     * 客户申请签约商户
     * @param id
     * @return
     */
    @ApiOperation("客户申请签约商户")
    @PostMapping("/big/customer/sign")
    public APIEntity signBigCustomer(@RequestAttribute("JwtUserId") Integer id,@RequestBody TCustomerBig customerBig){
        log.info("绑定商户时传输的经纬度：{}",customerBig.getLocation());
        TCustomer customer = customerService.getById(id);
        if(StringUtils.isBlank(customer.getCustomerPhone())){
            return APIEntity.fail("您当前登陆的账号没有绑定手机号，请切换"+"一键登录");
        }
        if(StringUtils.isNotBlank(customer.getTemplateId())){
            return APIEntity.fail("当前账户已绑定了商户与计费模板");
        }
        if(customerBigService.list(new QueryWrapper<TCustomerBig>().eq("big_phone",customer.getCustomerPhone())).size()>1){
            return APIEntity.fail("您的账号下有多个商户存在，请联系客服处理！");
        }
        if(customerBigService.list(new QueryWrapper<TCustomerBig>().eq("big_phone",customer.getCustomerPhone())).size()>0){
            TCustomerBig tCustomerBig = customerBigService.getOne(new QueryWrapper<TCustomerBig>().eq("big_phone",customer.getCustomerPhone()));
            customer.setLicensePhoto(tCustomerBig.getBigLicense());
            customer.setDoorPhoto(tCustomerBig.getDoorPhoto());
            customer.setIdPhoto(tCustomerBig.getIdPhoto());
            customer.setBigId(tCustomerBig.getBigId());
            customer.setCustomerType("商家用户");
            customerService.updateById(customer);
            customerBigService.updateById(tCustomerBig.setCustomerId(customer.getCustomerId()));
            return APIEntity.fail("您已入驻成功，请不要重复申请！");
        }
        customerBig.setBigNum(NumberUtils.getRandom(6));
        if(StringUtils.isNotBlank(customerBig.getLocation())){
            customerBig.setFranId(informationService.checkPio(MapUtils.getAddressReGeo(customerBig.getLocation())).getFranId());
        }else {
            customerBig.setFranId(informationService.checkPio(MapUtils.getAddressGeo(customerBig.getBigAddress())).getFranId());
        }
        customerBig.setBigPhone(customer.getCustomerPhone());
        customerBig.setCustomerId(customer.getCustomerId());
        customerBig.setBigStatus("已签约");
        if(customerBigService.save(customerBig)){
            customer.setLicensePhoto(customerBig.getBigLicense());
            customer.setDoorPhoto(customerBig.getDoorPhoto());
            customer.setIdPhoto(customerBig.getIdPhoto());
            customer.setBigId(customerBig.getBigId());
            customer.setCustomerType("商家用户");
            customerService.updateById(customer);
        }
        return APIEntity.success();
    }


    /**
     * 客户修改商户
     * @param id
     * @return
     */
    @ApiOperation("客户修改商户")
    @PostMapping("/big/customer/update")
    public APIEntity updateBigCustomer(@RequestAttribute("JwtUserId") Integer id,@RequestBody TCustomerBig customerBig){
        TCustomer customer = customerService.getById(id);
        if(customer==null){
            return APIEntity.fail("未找到客户信息，请重新登录!");
        }
        TCustomerBig tCustomerBig = customerBigService.getById(customerBig.getBigId());
        if(tCustomerBig==null){
            return APIEntity.fail("未找到商户信息");
        }
        return APIEntity.success(customerBigService.updateById(customerBig));
    }
    /**
     * 客户扫码添加大商户绑定营销骑手信息
     * @param id
     * @return
     */
    @ApiOperation("客户扫码添加商户并绑定营销骑手信息")
    @PostMapping("/add/big/customer")
    public APIEntity addBigCustomer(@RequestAttribute("JwtUserId") Integer id,@RequestBody TCustomerBig customerBig){
        TCustomer customer = customerService.getById(id);
        if(StringUtils.isNotBlank(customer.getTemplateId())){
            return APIEntity.fail("当前账户已绑定计费模板");
        }
        if(customerBigService.list(new QueryWrapper<TCustomerBig>().eq("template_id",customerBig.getTemplateId())).size()>0){
            return APIEntity.fail("当前模板已绑定别的商户，请重新选择");
        }
        if(customerBigService.list(new QueryWrapper<TCustomerBig>().notIn("big_status","已过期","已结束").eq("big_name",customerBig.getBigName())).size()>0){
            return APIEntity.fail("当前商户已存在，不要重复添加");
        }
        /*TCustomerTemplate customerTemplate = customerTemplateService.getById(customerBig.getTemplateId());
        if(customerTemplate ==null){
            return APIEntity.fail("客户绑定的模板不存在，请检查");
        }*/
        //customerBig.setBigNum(NumberUtils.getShort());
        customerBig.setBigNum(NumberUtils.getRandom(6));
        customerBig.setFranId(informationService.checkPio(MapUtils.getAddressReGeo(customerBig.getLocation())).getFranId());
        customerBig.setCustomerId(customer.getCustomerId());
        //customerBig.setCourierId(customerTemplate.getCreateUser());
        if(customerBigService.save(customerBig)){
            customer.setTemplateId(customerBig.getTemplateId());
            customer.setBigId(customerBig.getBigId());
            customerService.updateById(customer);
        }
        return APIEntity.success();
    }
    /**
     * 客户注销大商户（账号绑定的模板id、商户id、以及商户绑定的骑手id）
     * @param id
     * @return
     */
    @ApiOperation("客户注销大商户（账号绑定的模板id、商户id、以及商户绑定的骑手id）")
    @PostMapping("/cancellation/big/customer")
    public APIEntity cancellationBigCustomer(@RequestAttribute("JwtUserId") Integer id){
        TCustomer customer = customerService.getById(id);
        if(customer==null){
            return APIEntity.fail("未找到客户信息，请重新登录!");
        }
        if(maltFieldService.getOne(new QueryWrapper<TMaltField>().eq("cus_id",customer.getCustomerId()))!= null){
            return APIEntity.fail("该商户已绑定麦芽田，无法注销！");
        }
        if(StringUtils.isBlank(customer.getTemplateId()) && customer.getBigId().equals(0)){
            return APIEntity.fail("当前商户账户没有绑定商户与计费模板");
        }
        TCustomerBig customerBig = customerBigService.getById(customer.getBigId());
        if(customerBig==null){
            return APIEntity.fail("未找到需要注销的商户不存在！");
        }
        //删除绑定的计费模板
        TCustomerTemplate customerTemplate = customerTemplateService.getById(customerBig.getTemplateId());
        if(customerTemplate != null){
            customerTemplateService.remove(new QueryWrapper<TCustomerTemplate>().eq("template_code",customerTemplate.getTemplateCode()));
        }
        TDiscountRecord receiveRecord = discountRecordService.getOne(new QueryWrapper<TDiscountRecord>().eq("customer_id",id).eq("dis_type","会员卡").eq("receive_method","后台发放"));
        if(receiveRecord != null){
            discountRecordService.removeById(receiveRecord);
        }
        //修改商户信息
        customerBigService.removeById(customerBig);
        /*customerBig.setCourierId(0);
        customerBig.setTemplateId("");
        customerBig.setBigStatus("已结束");
        customerBig.updateById();*/
        //修改账户信息
        customer.setTemplateId("");
        customer.setIdPhoto("");
        customer.setDoorPhoto("");
        customer.setLicensePhoto("");
        customer.setBigId(0);
        customer.setCustomerType("普通客户");
        customer.updateById();
        return APIEntity.success("注销成功");
    }


    /**
     * 客户注册账号（有账户才能领取优惠卷）
     * 输入手机号领取优惠卷
     * @return
     */
    @ApiOperation("输入手机号领取优惠卷")
    @ApiImplicitParams({
            @ApiImplicitParam(name="customerPhone",value="客户手机号",dataType="String", paramType = "query",example="15771331234",required=true),
            @ApiImplicitParam(name="verCode",value="短信验证码",dataType="String", paramType = "query",example="",required=true)})
    @PostMapping("/login/receive")
    public APIEntity loginReceive(String customerPhone,String verCode){
        Object code = redisUtil.get("gms:customer:"+customerPhone);
        if(code==null){
            return APIEntity.fail("验证码无效，请重新获取！");
        }
        if(!"15771335697".equals(customerPhone)){
            if(!code.toString().equals(verCode)){
                return APIEntity.fail("验证码错误！");
            }
        }
        List<TDiscountMall> discountMalls = discountMallService.list(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","免费赠送"));
        if(discountMalls.size()<0){
            return APIEntity.fail("暂无新人优惠");
        }
        TCustomer customer= customerService.getOne(new QueryWrapper<TCustomer>().eq("customer_phone",customerPhone),false);
        TCustomer tCustomer = new TCustomer();
        if(customer != null) {
            List<TDiscountRecord> tReceiveRecords = discountRecordService.list(new QueryWrapper<TDiscountRecord>().eq("customer_id",customer.getCustomerId()));
            log.info("当前客户的id:{},优惠卷数量:{}",customer.getCustomerId(),tReceiveRecords.size());
            if(tReceiveRecords.size() >= discountMalls.size()){
                return APIEntity.fail("优惠卷已领取，请勿重复领取");
            }
            discountMallService.updateDisMall(discountMalls,customer);
            return APIEntity.success("领取成功");
        }else {
            String num=NumberUtils.getShort();
            tCustomer.setCustomerName("客户"+num);
            tCustomer.setCustomerPhone(customerPhone);
            tCustomer.setCustomerPwd("000000");
            tCustomer.setCustomerStatus("已激活");
            tCustomer.setCreateTime(LocalDateTime.now());
            tCustomer.setUpdateTime(LocalDateTime.now());
            if (!customerService.save(tCustomer)) {
                return APIEntity.fail("系统繁忙，请稍后重试！");
            }
        }
        discountMallService.updateDisMall(discountMalls,customer);
        return APIEntity.success("领取成功");
    }

    @ApiOperation("检查订单参数是否正常")
    @PostMapping("/order/check/info")
    public APIEntity updateBigCustomer(@RequestBody TOrder order){
        LocalDateTime time=orderService.getSurplusTime(order);
        Duration duration = java.time.Duration.between(LocalDateTime.now(),time);
        if(duration.toMinutes()<10){
            return APIEntity.fail("订单取件时间错误，不得早于10分钟内");
        }
        if(!StringUtils.isChinese(order.getMailingName())){
            return APIEntity.fail("寄件人姓名不合法，请输入真实姓名2-6个汉字");
        }
        if(!StringUtils.isChinese(order.getReceiptName())){
            return APIEntity.fail("收件人姓名不合法，请输入真实姓名2-6个汉字");
        }
        return APIEntity.success();
    }

}
