package com.bohuikeji.delivery.backstage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.constants.KeyConst;
import com.bohuikeji.delivery.backstage.controller.api.customer.CustomerV2Api;
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.vo.CourierAddressVo;
import com.bohuikeji.delivery.backstage.mapper.TMaltFieldMapper;
import com.bohuikeji.delivery.backstage.mapper.TPartnerMapper;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.ThirdUtils;
import com.bohuikeji.delivery.backstage.util.maiyatian.maltUtils;
import com.bohuikeji.frame.module.admin.base.ServiceImplBase;
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.utils.MapUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
@Slf4j
@Service
public class TMaltFieldServiceImpl extends ServiceImplBase<TMaltFieldMapper, TMaltField> implements ITMaltFieldService {

    @Autowired
    ITMaltFieldService maltFieldService;
    @Autowired
    CustomerV2Api customerV2Api;
    @Autowired
    ITCustomerTemplateService customerTemplateService;
    @Autowired
    ITCustomerService customerService;
    @Autowired
    ITConfigService configService;
    @Autowired
    ITOrderService orderService;
    @Autowired
    ThirdUtils thirdUtils;
    @Autowired
    ITCourierService courierService;
    @Autowired
    ITCustomerWalletService customerWalletService;
    @Autowired
    RedisUtil redisUtil;
    /**
     * 麦芽田订单信息初始化
     * @param data
     * @return
     */
    @Override
    public void saveMalt(JSONObject jsonObject, TCustomer customer) throws Exception {
        TMaltField tMaltField = maltFieldService.getOne(new QueryWrapper<TMaltField>().eq("shop_id",jsonObject.getInteger("shop_id")));
        if(tMaltField==null){
            tMaltField = new TMaltField();
            tMaltField.setCusId(customer.getCustomerId());
            tMaltField.setShopId(jsonObject.getInteger("shop_id"));
            tMaltField.setAccessToken(jsonObject.getString("token"));
            tMaltField.setRefreshToken(jsonObject.getString("refresh_token"));
            tMaltField.setExpireTime(jsonObject.getInteger("expire_time"));
            tMaltField.setRefreshExpireTime(jsonObject.getInteger("refresh_expire_time"));
            tMaltField.setMaltState("已绑定");
            save(tMaltField);
        }
        JSONObject tokenjsn = maltUtils.getRefreshToken(tMaltField.getAccessToken(),tMaltField.getRefreshToken());
        JSONObject data = JSONObject.parseObject(tokenjsn.getString("data"));
        tMaltField.setAccessToken(jsonObject.getString("token"));
        tMaltField.setRefreshToken(jsonObject.getString("refresh_token"));
        maltFieldService.updateById(tMaltField);
    }

    @Override
    public TOrder openOrderInit(JSONObject data) {
        TMaltField maltField = maltFieldService.getOne(new QueryWrapper<TMaltField>().eq("shop_id",Integer.valueOf(data.getString("shop_id"))));
        log.error("###############################商户绑定信息:{}",maltField);
        JSONObject sender = data.getJSONObject("sender");//发货门店
        JSONObject receiver = data.getJSONObject("receiver");//收获人
        JSONObject orderInfo = data.getJSONObject("order_info");//订单信息
        JSONObject goodsList = orderInfo.getJSONArray("goods_list").getJSONObject(0);//商品信息
        TOrder order = new TOrder();
        if(data.getBoolean("is_pre_order")){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String sd = sdf.format(new Date(Long.parseLong(String.valueOf(data.getInteger("delay_delivery_time")))*1000L));
            log.info("预计送达时间：{}",sd);
            order.setOrderExpectTime(LocalDateTime.parse(sd,StringUtils.dataTimeFormat));
        }
        order.setMailingName(sender.getString("name"));
        String senderLocation = sender.getString("longitude")+","+sender.getString("latitude");
        AddressVo maiAddressVo= MapUtils.getAddressReGeo(senderLocation);
        maiAddressVo.setDetail(sender.getString("address_detail"));
        order.setMailingAddress(maiAddressVo);
        order.setMailingPhone(sender.getString("phone"));

        order.setReceiptName(receiver.getString("name"));
        String receiverLocation = receiver.getString("longitude")+","+receiver.getString("latitude");
        AddressVo recAddressVo= MapUtils.getAddressReGeo(receiverLocation);
        if(StringUtils.isBlank(receiver.getString("address_detail"))){
            recAddressVo.setDetail(receiver.getString("address"));
        }else {
            recAddressVo.setDetail(receiver.getString("address_detail"));
        }
        order.setReceiptAddress(recAddressVo);
        //order.setReceiptPhone(receiver.getString("phone"));
        if(receiver.getString("phone").contains("_")){
            String str = receiver.getString("phone").replace("_","转");
            order.setReceiptPhone(str);
        }else {
            order.setReceiptPhone(receiver.getString("phone"));
        }
        order.setOrderChannel("麦芽田");
        order.setMaltFieldNum(data.getString("source_order_no"));
        order.setPlayerId(maltField.getCusId());
        order.setType("WALLET");
        order.setCargoWeight(orderInfo.getInteger("weight"));
        order.setWorthName(String.valueOf(new BigDecimal(orderInfo.getInteger("total_fee")).divide(new BigDecimal("100")))+"元");
        order.setOrderRemarks(data.getString("remark")+" "+orderInfo.getInteger("sn")+"号订单");
        if(order.getReceiptPhone().contains("_")){
            order.setOrderRemarks(order.getOrderRemarks()+" 拨打电话后请输入分机号！");
        }
        order.setPickTime("今天/立即取件");
        order.setOrdertTip(new BigDecimal(data.getInteger("tips")).divide(new BigDecimal("100")));
       /* for(int i=0;i<goodsList.size();i++){
            JSONObject job = goodsList.getJSONObject(i);

        }*/
        order.setShopId(maltField.getShopId());
        //order.setTest(true);
        order=this.maltOrderInit(maltField.getCusId(),order);
        return order;
    }

    @Override
    public JSONObject getbody(String command, JSONObject jsonObject) throws Exception {
        JSONObject responseJson = new JSONObject();//最后返回的json
        JSONObject data = new JSONObject();//响应参数
        TOrder order;
        CourierVo courierVo=null;
        switch (command){
            case "valuating":
            case "send":
                order = maltFieldService.openOrderInit(jsonObject);//初始化订单
                Object obj = customerV2Api.estimate(order).getBody();//订单计费
                JSONObject orderJson = (JSONObject) JSONObject.toJSON(obj);
                data.put("pay_amount",orderJson.getBigDecimal("monSum").multiply(new BigDecimal("100")));
                data.put("coupon",orderJson.getBigDecimal("prefAmount").multiply(new BigDecimal("100")));
                data.put("distance",orderJson.getInteger("distance")*1000);
                data.put("premium",new BigDecimal("0.00").multiply(new BigDecimal("100")));
                data.put("expect_time",System.currentTimeMillis()/1000L);
                data.put("order_no",jsonObject.getString("source_order_no"));
                if("send".equals(command)){
                    TCustomerWallet tCustomerWallet = customerWalletService.getOne(new QueryWrapper<TCustomerWallet>().eq("customer_id",order.getPlayerId()));
                    if(tCustomerWallet == null){
                        responseJson.put("code",400);
                        responseJson.put("message","同城急送钱包余额不足，请及时充值！");
                        return responseJson;
                    }
                    if(tCustomerWallet.getWalletPrice().compareTo(orderJson.getBigDecimal("monSum")) < 0){
                        responseJson.put("code",400);
                        responseJson.put("message","同城急送钱包余额不足，请及时充值！");
                        return responseJson;
                    }
                    customerV2Api.insertOrderPayment(order.getPlayerId(),order,null);
                }
                break;
            case "query_info":
                ZoneId zoneId = ZoneId.systemDefault();
                order = orderService.getByNum(jsonObject.getString("order_no"));//初始化订单
                if (order.getThird()){
                    courierVo= thirdUtils.courierInfo(order);
                }else {
                    TCourier courier=courierService.getById(order.getCourierId());
                    courierVo= VoBase.copy(courier, CourierVo.class);
                    CourierAddressVo courierAddressVo=redisUtil.get(KeyConst.REDIS_COURIER_ADDRESS+courier.getCourierId(), CourierAddressVo.class);
                    if (courierAddressVo!=null){
                        courierVo.setLastLocation(courierAddressVo.getAddress());
                    }
                }
                data.put("order_no",order.getOrderNum());
                data.put("source_order_no",order.getMaltFieldNum());
                data.put("status",maltUtils.getOrderStatus(order.getOrderStatus()));
                data.put("status_name",order.getOrderStatus());
                data.put("pay_amount",order.getOrderFactPrice().multiply(new BigDecimal("100")));
                data.put("coupon",order.getPrefAmount().multiply(new BigDecimal("100")));
                data.put("tips",order.getOrdertTip());
                data.put("distance",order.getOrderDistance());
                data.put("create_time",order.getOrderCreateTime().atZone(zoneId).toInstant().toEpochMilli());
                data.put("accept_time",order.getConfirmPickTime().atZone(zoneId).toInstant().toEpochMilli());
                data.put("fetch_time",order.getConfirmPickTime().atZone(zoneId).toInstant().toEpochMilli());
                data.put("finish_time",order.getOrderEndTime().atZone(zoneId).toInstant().toEpochMilli());
                data.put("cancel_time",order.getOrderEndTime().atZone(zoneId).toInstant().toEpochMilli());
                data.put("rider_name",courierVo.getCourierName());
                data.put("rider_phone",courierVo.getCourierPhone());
                data.put("longitude",courierVo.getLastLocation().getLng());
                data.put("latitude",courierVo.getLastLocation().getLat());break;
            case "rider_location":
                order = orderService.getByNum(jsonObject.getString("order_no"));//初始化订单
                if (order.getThird()){
                    courierVo= thirdUtils.courierInfo(order);
                }else {
                    TCourier courier=courierService.getById(order.getCourierId());
                    courierVo= VoBase.copy(courier, CourierVo.class);
                    CourierAddressVo courierAddressVo=redisUtil.get(KeyConst.REDIS_COURIER_ADDRESS+courier.getCourierId(), CourierAddressVo.class);
                    if (courierAddressVo!=null){
                        courierVo.setLastLocation(courierAddressVo.getAddress());
                    }
                }
                if(courierVo.getLastLocation() == null){
                    data.put("longitude","");
                    data.put("latitude","");
                }else {
                    data.put("longitude",courierVo.getLastLocation().getLng());
                    data.put("latitude",courierVo.getLastLocation().getLat());
                }
                data.put("order_no",order.getOrderNum());
                data.put("source_order_no",order.getMaltFieldNum());
                data.put("rider_name",courierVo.getCourierName());
                data.put("rider_phone",courierVo.getCourierPhone());

                data.put("at_time",System.currentTimeMillis()/1000L);break;
            default:
                return null;
        }
        responseJson.put("code",200);
        responseJson.put("data",data.toJSONString());
        responseJson.put("message","成功");
        return responseJson;
    }

    /**
     * 开放平台创建订单初始化
     *
     * @param customerId 客户ID
     * @return
     */
    private TOrder maltOrderInit(Integer customerId,TOrder order) {
        //获取客户计费模板ID
        Integer templateId=customerService.selectColumnById(customerId,"template_id",Integer.class);
        if(StringUtils.isBlank(order.getMailingAddress().getLat())||StringUtils.isBlank(order.getMailingAddress().getLng())){
            order.setMailingAddress(order.getMailingAddress().fillAddress());
        }
        if(StringUtils.isBlank(order.getReceiptAddress().getLat())||StringUtils.isBlank(order.getReceiptAddress().getLng())){
            order.setReceiptAddress(order.getReceiptAddress().fillAddress());
        }
        if(templateId!=null){
            log.error("麦芽田模板初始化：{},下单人：{}",templateId,order.getPlayerId());
            //获取计费客户模板Code
            String templateCode=customerTemplateService.selectColumnById(templateId,"template_code",String.class);
            //设置车辆计费项目
            TCustomerTemplate tmp=customerTemplateService.getOpenConfigByCode(templateCode,"car_type_ddc");
            order.setVehicleConfigId(tmp.getTemplateId());
            order.setVehicleName(tmp.getConfigName());
            //设置物品类型计费项
            tmp=customerTemplateService.getOpenConfigByCodetwo(templateCode,"cargo_type","生活用品");
            if(tmp==null){
                tmp=customerTemplateService.getOpenConfigByCodetwo(templateCode,"cargo_type","其他");
            }
            order.setCargoConfigId(tmp.getTemplateId());
            order.setCargoName(tmp.getConfigName());
            //设置运输方式给计费项
            tmp=customerTemplateService.getOpenConfigByCodetwo(templateCode,"service_type","极送-平均1小时");
            order.setWayConfigId(tmp.getTemplateId());
            order.setWayName(tmp.getConfigName());

            //设置计费方式
            //tmp=customerTemplateService.getOpenConfigByCode(templateCode,"payment_method");

            //暂时先走平台己寄付
            order.setPaymentConfigId(31);
            order.setPaymentType("寄付");
        }
        else {
            /**
             * 如果没有计费模板则按，当地加盟商默认计费规则进行计费。
             */
            String location=order.getMailingAddress().getLocation();
            //设置物品计费项目
            if(StringUtils.isBlank(order.getCargoName())){
                order.setCargoName("生活用品");
            }
            TConfig cargoConfig=configService.getOpenConfigByGroup(order.getCargoName(),"cargo_type",location,customerId);
            log.error("麦芽田模板初始化：{},下单人：{}",cargoConfig.getConfigName(),order.getPlayerId());
            order.setCargoConfigId(cargoConfig.getId());
            order.setCargoName(cargoConfig.getConfigName());
            //设置车辆类型计费项
            TConfig vehConfig=configService.getOpenConfigByGroup("电动车","car_type_ddc",location,customerId);
            order.setVehicleConfigId(vehConfig.getId());
            order.setVehicleName(vehConfig.getConfigName());
            //设置服务类型计费项
            TConfig wayConfig=configService.getOpenConfigByGroup("极送-平均1小时","service_type",location,customerId);
            order.setWayConfigId(wayConfig.getId());
            order.setWayName(wayConfig.getConfigName());
            //暂时先走平台己寄付
            order.setPaymentConfigId(31);
            order.setPaymentType("寄付");
        }
        return order;
    }
}
