package com.liquidnet.service.kylin.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.commons.lang.util.HttpUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.dao.PerformanceAdminListDao;
import com.liquidnet.service.kylin.dto.vo.tmp.*;
import com.liquidnet.service.kylin.entity.ExpressBatches;
import com.liquidnet.service.kylin.entity.ExpressTimelines;
import com.liquidnet.service.kylin.entity.Expresses;
import com.liquidnet.service.kylin.mapper.ExpressBatchesMapper;
import com.liquidnet.service.kylin.mapper.ExpressTimelinesMapper;
import com.liquidnet.service.kylin.mapper.ExpressesMapper;
import com.liquidnet.service.kylin.service.IExpressesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.client.utils.URLEncodedUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 快递表 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-05-26
 */
@Service
public class ExpressesServiceImpl extends ServiceImpl<ExpressesMapper, Expresses> implements IExpressesService {

    @Value("")
    private String localUrl;
    @Autowired
    private ExpressesMapper expressesMapper;
    @Autowired
    private ExpressTimelinesMapper expressTimelinesMapper;
    @Autowired
    private ExpressBatchesMapper expressBatchesMapper;

    @Override
    public ResponseDto<CourierListVo> courierList(String orderId, String type) {
        List<Expresses> list = expressesMapper.selectListOrder(orderId, type);
        CourierListVo vo = new CourierListVo();
        if (list.size() > 0) {
            Expresses expresses = list.get(0);
            Integer expressId = expresses.getId();
            String expressNumber = expresses.getNumber();
            String expressCompany = expresses.getName();
            vo.setExpressNumber(expressNumber);
            vo.setExpressCompany(expressCompany);
            List<ExpressTimelines> expressTimelines = expressTimelinesMapper.selectListOrder(expressId);
            vo.setExpressTimeLine(expressTimelines);
        } else {
            vo.setExpressNumber("");
            vo.setExpressCompany("");
        }
        return ResponseDto.success(vo);
    }

    @Override
    public KuaidiReturn observer(String company, String number) {
        String param = "{\"company\":\"" + company + "\", \"number\":\"" + number + "\",\"from\":\"\", \"to\":\"\", \"key\":\"" + "DxjgEfKw8868" + "\", \"parameters\":{\"callbackurl\":\"http://" + localUrl + "/common/kuaidiCallBack\"}}";
        LinkedMultiValueMap<String, String> postData = new LinkedMultiValueMap<>();
        postData.add("schema", "json");
        postData.add("param", param);
        String url = "http://www.kuaidi100.com/poll";

//        String o = "";
//        for(Map.Entry<String, String> entry : postData.entrySet()){
//            String mapKey = entry.getKey();
//            String mapValue = entry.getValue();
//            o += ""+mapKey+"=" + URLEncodedUtils.formatSegments(mapValue) + "&";
//        }
//        String postDataString = o.substring(0,o.length()-1);
        String result = HttpUtil.post(url, postData);
        System.out.println("\n\n" + result + "\n\n");
        return JsonUtils.fromJson(result, KuaidiReturn.class);
    }

    @Override
    public void observerResult(String param) {
        Kuaidi100Param kuaidiParam = JsonUtils.fromJson(param, Kuaidi100Param.class);
        try {
            LastResultParam lastResultParam = kuaidiParam.getLastResultParam();
            List<KuaidiDatasParam> datas = lastResultParam.getData();
            String nu = lastResultParam.getNu();
            String com = lastResultParam.getCom();

            ExpressTimelines timeLineData = new ExpressTimelines();

            Expresses expresses = expressesMapper.selectListNumByCom(com, nu);
            Integer expressId = expresses.getId();
            if (!expresses.getStatus().equals(lastResultParam.getState())) {
                Integer statusInt = 0;
                if (lastResultParam.getState() >= 4 && lastResultParam.getState() <= 7) {
                    statusInt = 0;
                } else {
                    statusInt = lastResultParam.getState();
                }

                Expresses changeData = new Expresses();
                changeData.setStatus(statusInt);
                expressesMapper.update(changeData, new UpdateWrapper<Expresses>().eq("id", expresses.getId()));

                timeLineData.setExpressId(expressId);
                HashMap<String, Object> deleteMap = new HashMap<>();
                deleteMap.put("express_id", expressId);
                expressTimelinesMapper.deleteByMap(deleteMap);

                for (KuaidiDatasParam item : datas) {
                    timeLineData.setContext(item.getContext());
                    timeLineData.setTime(item.getTime());
                    timeLineData.setFtime(LocalDateTime.parse(item.getFtime()));
                    expressTimelinesMapper.insert(timeLineData);
                }
                System.out.println("{\"result\":\"true\",\t\"returnCode\":\"200\",\"message\":\"成功\"}");
            }
        } catch (Exception e) {
            System.out.println("{\"result\":\"false\",\t\"returnCode\":\"500\",\"message\":\"失败\"}");
        }
    }

    @Override
    public String addExpress(KuaidiAdminParam param) {
        String message = "创建快递信息失败";
        String name = getExpressCompany(param.getCompany());
        try {
            if (name.equals("order")) {
                return "不支持填写的快递公司";
            }
            Expresses expresses = new Expresses();
            BeanUtils.copyProperties(param, expresses);
            expresses.setName(name);
            int count = expressesMapper.insert(expresses);
            if (count == 1) {
                KuaidiReturn result100 = observer(expresses.getCompany(), expresses.getNumber());
                if(result100.isBoolResult() && result100.getReturnCode()==200){
                    return "OK";
                }else{
                    return message;
                }
            } else {
                return message;
            }
        } catch (Exception e) {
            return message;
        }
    }

    @Override
    public String editExpress(KuaidiAdminParam param) {
        String message = "创建快递信息失败";
        String name = getExpressCompany(param.getCompany());
        try {
            if (name.equals("order")) {
                return "不支持填写的快递公司";
            }
            Expresses expresses = new Expresses();
            BeanUtils.copyProperties(param, expresses);
            expresses.setName(name);
            int count = expressesMapper.update(expresses,new UpdateWrapper<Expresses>().eq("order_id",expresses.getOrderId()).eq("order_type",expresses.getOrderType()));
            if (count == 1) {
                KuaidiReturn result100 = observer(expresses.getCompany(), expresses.getNumber());
                if(result100.isBoolResult() && result100.getReturnCode()==200){
                    return "OK";
                }else{
                    return message;
                }
            } else {
                return message;
            }
        } catch (Exception e) {
            return message;
        }
    }

    @Override
    public String getExpressCompany(String name) {
        String company;
        switch (name) {
            case "shunfeng": {
                company = "顺丰";
                break;
            }
            case "shentong": {
                company = "申通";
                break;
            }
            case "yuantong": {
                company = "圆通";
                break;
            }
            case "zhongtong": {
                company = "中通";
                break;
            }
            case "yunda": {
                company = "韵达";
                break;
            }
            case "huitongkuaidi": {
                company = "汇通";
                break;
            }
            case "debangwuliu": {
                company = "德邦";
                break;
            }
            case "tiantian": {
                company = "天天";
                break;
            }
            case "rufengda": {
                company = "如风达";
                break;
            }
            case "ems": {
                company = "EMS";
                break;
            }
            case "jd": {
                company = "京东";
                break;
            }
            default: {
                company = "other";
                break;
            }
        }
        return company;
    }

    @Override
    public String getExpressCompanyEn(String name) {
        if (name.contains("顺丰")) {
            return "shunfeng";
        } else if (name.contains("申通")) {
            return "shentong";
        } else if (name.contains("圆通")) {
            return "yuantong";
        } else if (name.contains("中通")) {
            return "zhongtong";
        } else if (name.contains("韵达")) {
            return "yunda";
        } else if (name.contains("汇通")) {
            return "huitongkuaidi";
        } else if (name.contains("德邦")) {
            return "debangwuliu";
        } else if (name.contains("天天")) {
            return "tiantian";
        } else if (name.contains("如风达")) {
            return "rufengda";
        } else if (name.contains("EMS")) {
            return "ems";
        } else if (name.contains("京东")) {
            return "jd";
        } else if (name.contains("百世")) {
            return "baishi";
        } else {
            return "";
        }
    }

    @Override
    public String innerAddExpress(KuaidiAdminParam param) {
        String message = param.getNumber().toString();
        String name = getExpressCompany(param.getCompany());
        try {
            if (name.equals("order")) {
                return "不支持填写的快递公司";
            }
            Expresses expresses = new Expresses();
            BeanUtils.copyProperties(param, expresses);
            expresses.setName(name);
            int count = expressesMapper.insert(expresses);
            if (count == 1) {
                KuaidiReturn result100 = observer(expresses.getCompany(), expresses.getNumber());
                if(result100.isBoolResult() && result100.getReturnCode()==200){
                    return "OK";
                }else{
                    return message;
                }
            } else {
                return message;
            }
        } catch (Exception e) {
            return message;
        }
    }

    @Override
    public PageInfo<ExpressBatches> expressObserveUnSuccess(int page, int size) {
        PageInfo<ExpressBatches> pageInfoTmp = null;
        try {
            PageHelper.startPage(page, size);
            List<ExpressBatches> voList = expressBatchesMapper.selectStatusOrder();
            pageInfoTmp = new PageInfo(voList);
        } catch (Exception e) {
            return null;
        }
        return pageInfoTmp;
    }


}
