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

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipayUserInfoShareResponse;
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.payConst;
import com.bohuikeji.delivery.backstage.controller.api.courier.CourierApi;
import com.bohuikeji.delivery.backstage.controller.api.customer.CustomerV2Api;
import com.bohuikeji.delivery.backstage.controller.callback.ThirdCallBack;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.open.VoBase;
import com.bohuikeji.delivery.backstage.entity.open.vo.CourierVo;
import com.bohuikeji.delivery.backstage.entity.socket.CourierNotice;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.entity.vo.CourierAddressVo;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.listener.order.OrderAliCenterListener;
import com.bohuikeji.delivery.backstage.listener.order.OrderAssignListener;
import com.bohuikeji.delivery.backstage.listener.order.OrderCheckPriceListener;
import com.bohuikeji.delivery.backstage.listener.order.OrderCreateListener;
import com.bohuikeji.delivery.backstage.pay.AliPay;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.*;
import com.bohuikeji.delivery.backstage.thread.ThirdThread;
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.capacity.KDHundredUtils;
import com.bohuikeji.delivery.backstage.util.capacity.SfExpressUtils;
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.config.MqConf;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.back.PageEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysConfig;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.thread.CachedThreadPool;
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.sonatype.aether.impl.internal.SimpleLocalRepositoryManager;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 通知推送测试
 * @author 10552
 */
@Slf4j
@RestController
@Api(tags = {"第三方测试"})
@RequestMapping("/third")
@RequiredArgsConstructor
public class thirdTest extends ApiController{

    @Autowired
    ITCourierService courierService;
    final ThirdUtils thirdUtils;
    @Autowired
    ITCourierCardService courierCardService;

    final RabbitTemplate rabbitTemplate;

    final ITConfigService configService;
    final ITOrderService orderService;
    final CustomerV2Api customerV2Api;
    /*final IShanSongService shanSongService;*/
    final ISysConfigService sysConfigService;

    final ThirdCallBack songCallBack;
    final ITCustomerService itCustomerService;
    final UUServer uuServer;
    final ShansongServer shansongServer;
    final RedisUtil redisUtil;
    final MqConf mqConf;
    final OrderCheckPriceListener orderCheckPriceListener;
    final JdServer jdServer;
    final ISocketService socketService;
    final ITOrderArrearsService arrearsService;
    final CourierApi courierApi;
    final ITCustomerService customerService;
    final IWxUserService wxUserService;
    final ITOrderService itOrderService;
    final ITPayService payService;
    final ITFranchiseeInformationService franchiseeInformationService;
    final ITCustomerAddressService itCustomerAddressService;
    @Autowired
    MqTool mqTool;
    @ApiOperation("麦芽田重定向")
    @GetMapping("/mai/ya/tian")
    public APIEntity maiYaTian(String url) throws UnsupportedEncodingException, MalformedURLException {
        URL path = new URL(url);
        JSONObject jsonObject = new JSONObject();
        String queryString = path.getQuery();
        String[] array = queryString.split("&");
        for (String str : array) {
            String[] pair = str.split("=");
            jsonObject.put(pair[0],pair[1]);
        }
        String urls = URLDecoder.decode(jsonObject.getString("redirect_uri"),"UTF-8");
        log.info("地址请求参数1:jsonObject：{}",jsonObject);
        log.info("地址请求参数2:url：{}",urls);
        return APIEntity.success(StrUtil.format(urls+"?&appid={}",jsonObject.getString("state")));
    }
    @ApiOperation("麦芽田公共参数")
    @GetMapping("/mai/ya/tian/")
    public APIEntity maiYaTianQue() throws Exception {
        return APIEntity.success(maltUtils.getMap(null,null,"1111111"));
    }

    @ApiOperation("麦芽田换取token")
    @GetMapping("/mai/ya/tian/token")
    public APIEntity maiYaTianToken(String code,String customerPhone) throws Exception {
        return APIEntity.success(maltUtils.getAccessToken(code,customerPhone,null,null));
    }

    @ApiOperation("麦芽田换取refreshToken")
    @GetMapping("/mai/ya/tian/refresh/token")
    public APIEntity maiYaTianRefreshToken(String token,String refreshToken) throws Exception {
        return APIEntity.success(maltUtils.getRefreshToken(token,refreshToken));
    }

    /*@ApiOperation("麦芽田授权解绑")
    @GetMapping("/mai/ya/tian/token/unbind")
    public APIEntity maiYaTianTokenUnbind(String token) throws Exception {
        return APIEntity.success(maltUtils.gettokenUnbind(token));
    }*/

    @ApiOperation("麦芽田授权解绑")
    @GetMapping("/mai/ya/tian/analysis/time")
    public APIEntity analysisTime(long times) throws Exception {
        log.info("时间戳：{}",LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
       /* ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = Instant.ofEpochMilli(Long.valueOf(times)).atZone(zoneId).toLocalDateTime();
        log.info("预计送达时间：{}",localDateTime);*/
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sd = sdf.format(new Date(Long.parseLong(String.valueOf(times))*1000L));
        return APIEntity.success(sd);
    }

    @ApiOperation("@@@@@@@@@@@@@@@@@@@")
    @GetMapping("/mai/ya/tian/get/test")
    public APIEntity getAdrass(Integer courierId) throws Exception {
        CourierAddressVo cuv=redisUtil.get(KeyConst.REDIS_COURIER_ADDRESS +courierId, CourierAddressVo.class);
        return APIEntity.success(cuv);
    }

    /**
     * 订单回调模拟
     * @param id
     * @param orderNum
     * @return
     */
    @GetMapping("/get/test")
    APIEntity noticeTest(String orderNum, Integer orderStatusCode,Integer id) throws Exception {
        TOrder order=orderService.getByNum(orderNum);
        TCustomer customer=itCustomerService.getById(order.getPlayerId());
        if (order==null){
            return APIEntity.fail("无法找到订单："+orderNum);
        }
       /* if (!order.getTest()){
            return APIEntity.fail("非测试订单无法使用，回调模拟接口！");
        }
        if (customer==null){
            return APIEntity.fail("无法找到开放平台账户，请先注册账号！");
        }*/
        String setStatus;
        switch (orderStatusCode){
            //接单
            case 1:{
                APIEntity res=courierApi.receipt(id,order.getOrderId(),order.getMailingAddress().getLocation(),"9999");
                if (res.getStatus()!=200){
                    return res;
                }
                return  APIEntity.success();
            }
            //取消订单
            case -1:{
                APIEntity res=customerV2Api.cancel(order.getOrderId()+"",customer.getCustomerId(),"open");
                if (res.getStatus()!=200){
                    return res;
                }
                return  APIEntity.success();
            }
            case 2:setStatus="去取件";break;//去取件
            case 3:setStatus="确认取件";break;//取件完成
            case 4:setStatus="去派送";break;//开始配送
            case 5:setStatus="确认收货";break;//确认送达
            default:
                return APIEntity.fail("无法识别您的订单状态");
        }
        APIEntity res=courierApi.stateFlow(order.getOrderId(),id,setStatus,null,null,null);
        if (res.getStatus()!=200){
            return res;
        }
        return  APIEntity.success();
    }


    @GetMapping("/get/test/news")
    public APIEntity sendOutNews(String phone) {
        if(!phone.contains("_")){
            return APIEntity.success(phone);
        }
        String str1 = phone.substring(0, phone.indexOf("_"));
        String str2 = phone.substring(str1.length()+1, phone.length());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("str1",str1);
        jsonObject.put("str2",str2);
        return APIEntity.success(jsonObject);
    }

    @GetMapping("/get/test/pay")
    public APIEntity sendOutPay(Integer orderId, HttpServletRequest request) throws Exception {
        TOrder order = orderService.getById(orderId);
        order.setType("aliClient");
        order.setOrderChannel("同城急送");
        TPay pay  =payService.createBeforePay(order,order.getServiceType(),"客户支付",payConst.getway(order.getType()));
        TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",260).eq("wx_app_name",order.getOrderChannel()+"（支付宝）").eq("wx_app_type","ALICLIENT"));
        log.info("@@@@@@@@@@@@@:{}",order);
        log.info("######:{}",wxUser);
        JSONObject object = payConst.getAliObject(order.getType(),order.getOrderChannel(),pay.getPayNum(),wxUser.getWxUserOpenid(),order.getOrderExpectPrice(),request);
        return APIEntity.success(object);
    }

    @GetMapping("/get/test/jisuan")
    public APIEntity sendOutPayJisuan(Integer orderId) throws Exception {
        TOrder order = orderService.getById(orderId);
        orderService.extractExtract(order);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("平台",order.getOrderSysMoney());
        jsonObject.put("加盟",order.getOrderFranMoney());
        jsonObject.put("骑手",order.getOrderCourierMoney());
        return APIEntity.success(jsonObject);
    }

    @GetMapping("/get/test/get/yijia")
    public APIEntity getJson(Integer franId, String configGroup, Integer customerId) throws Exception {
       JSONObject jsonObject = configService.getPremiumJson(franId,configGroup,customerId);
        return APIEntity.success(jsonObject);
    }
    /**
     * 获取当前配置环境
     */
    @Value("${spring.profiles.active}")
    private String active;

    @GetMapping("/get/test/get/jiexi")
    public APIEntity getjiexi() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SysConfig config = sysConfigService.getOneByKey(active);
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@当前时间:{}",LocalDateTime.now());
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@记录时间:{}",config.getConfigGroup());
        LocalDateTime takeTime= LocalDateTime.parse(config.getConfigGroup());
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@2:{}",takeTime);
        log.info("获取货拉拉TOKEN：环境:{}，信息：{},有效期：{}",active,config.getConfigDataOne(),config.getConfigGroup());
        long days = ChronoUnit.DAYS.between(LocalDateTime.now(),takeTime);
        if(days<=Long.valueOf(config.getConfigValue())){
            JSONObject res = HllUtils.getaccessToken(null,config.getConfigDataTwo());
            sysConfigService.getHuolalaToken(null,res);
        }
        return APIEntity.success(days);
    }


    @GetMapping("/get/test/get/jifei")
    public APIEntity getJifei(String configKey, String location,Integer customerId) throws Exception {
        List<TConfig> configList=configService.getFranConfigByGroupWithCustomer(configKey,location,customerId);
        return APIEntity.success();
    }

   /* @ApiOperation(value = "获取客户端小程序分享二维码",notes = "使用方法详见微信文档：https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/url-link.html")
    @GetMapping("/customer/mp/get/code")
    public APIEntity getClientCode(Integer orderId){
        TOrder order = orderService.getById(orderId);
        String path = "pages/Information/Information";
        String query = "https://wxaurl.cn/114X88dbBOg?name="+order.getReceiptName()+"&phone="+order.getReceiptPhone();
        //String query = "address="+order.getReceiptAddress().getAddress()+"&detail="+order.getReceiptAddress().getDetail()+"&lng="+order.getReceiptAddress().getLng()+"&lat="+order.getReceiptAddress().getLat()+"&name="+order.getReceiptName()+"&phone="+order.getReceiptPhone();
        //String path = "pages/Information/Information";
        return APIEntity.success(WxUtils.getCreateQRCode(WxAppEm.MP_CLIENT,path));
    }*/

    /**
     * 生成二维码
     * @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(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("未找到该地址信息！");
        }
        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(203);
        tCustomerAddress.setDefaultAddress(true);
        tCustomerAddress.setType("收件地址");
        if (true){
            itCustomerAddressService.update(new UpdateWrapper<TCustomerAddress>().set("default_address ",0).eq("type","收件地址").eq("customer_id",203));
        }
        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);
        itCustomerAddressService.updateById(tCustomerAddress.setAddressCode(templateUrl));
        return APIEntity.success(tCustomerAddress);
    }


    /**
     * 根据订单id查询订单详情
     * @return
     */
    @ApiOperation("根据订单id查询订单详情")
    @GetMapping("/getOrderDetails")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderId",value="订单id",dataType="Integer", paramType = "query")})
    public APIEntity<TOrder> getOrderDetails(Integer orderId){
        TOrder tOrder = orderService.getById(orderId);
        if (tOrder==null){
            return APIEntity.fail("未找到订单信息，可能该订单已被删除！");
        }
        TCourier tCourier = courierService.getById(tOrder.getCourierId());
        if(tCourier != null && tCourier.getCourierId()!=11392){
            CourierAddressVo courierAddressVo=redisUtil.get(KeyConst.REDIS_COURIER_ADDRESS+tCourier.getCourierId(), CourierAddressVo.class);
            if (courierAddressVo!=null){
                tCourier.setLocation(courierAddressVo.getAddress().getLocation());
                log.info("获取接单配送员的试试经纬度(自己的)：{}",tCourier.getLocation());
            }
        }
        if (tOrder.getThird()){
            OrderDetailDO detail=thirdUtils.orderDetail(tOrder);
            if (detail!=null){
                tCourier.setCourierName(detail.getCourierName());
                tCourier.setCourierPhone(detail.getCourierPhone());
                if(thirdUtils.courierInfo(tOrder)!=null){
                    log.error("查询配送员经纬度444444444：{}",thirdUtils.courierInfo(tOrder).getLastLocation());
                    tOrder.setLongitude(thirdUtils.courierInfo(tOrder).getLastLocation().getLng());
                    tOrder.setLatitude(thirdUtils.courierInfo(tOrder).getLastLocation().getLat());
                }
            }
        }
        tOrder.setCourier(tCourier);
        return APIEntity.success(tOrder);
    }
    @ApiOperation("插叙第三方订单详情")
    @GetMapping("/get/test/ditail")
    public APIEntity getaddressDis(Integer orderId,String type) throws Exception {
        TOrder tOrder = orderService.getById(orderId);
        JSONObject kdDatail;
        if("取消".equals(type)){
            kdDatail= KDHundredUtils.orderCancel(tOrder.getKdJson().getString("taskId"),tOrder.getKdJson().getString("orderId"),"用户主动取消");
        }else {
            kdDatail= KDHundredUtils.getOrderInfo(tOrder.getKdJson().getString("taskId"));
        }
        return APIEntity.success(kdDatail);
    }

    @ApiOperation("验证手机号是否为座机")
    @GetMapping("/get/test/phone")
    public APIEntity getaddressDis(String phone) throws Exception {
        String reg="(?:(\\(\\+?86\\))(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)|(?:(86-?)?(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)";
        if(Pattern.matches(reg, phone)){
            StringBuilder sb = new StringBuilder(phone);
            log.error("向闪送下单时的订单信息:手机号：{},原收件手机号：{}",sb.insert(4,"-").toString(),phone);
            phone = sb.toString();
        }
        return APIEntity.success(phone);
    }

    @ApiOperation("发送消息给骑手")
    @GetMapping("/courier")
    APIEntity testSocketAdmin(Integer orderId) {
        TOrder order = orderService.getById(orderId);
        mqTool.sendMsg(order.getOrderNum(), OrderAssignListener.class);
        return APIEntity.success();
    }
}
