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

import com.alibaba.fastjson.JSONObject;
import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;

import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dao.KylinFreightChargeDao;
import com.liquidnet.service.kylin.dto.vo.KylinExpressModuleVo;
import com.liquidnet.service.kylin.mapper.KylinFreightChargeMapper;
import com.liquidnet.service.platform.utils.JSONUtils;
import com.liquidnet.service.platform.utils.ShunfengSignUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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


@Slf4j
@Service
public class KylinFreightChargeServiceImpl {
    @Value("${liquidnet.express.shunfeng.jProvince}")
    private String jProvince;
    @Value("${liquidnet.express.shunfeng.jCity}")
    private String jCity;
    @Value("${liquidnet.express.shunfeng.jAddress}")
    private String jAddress;

    @Autowired
    private ShunfengSignUtils shunfengSignUtils;
    @Autowired
    private RedisDataSourceUtil redisDataSourceUtil;
    @Autowired
    private KylinFreightChargeMapper kylinFreightChargeMapper;
    @Autowired
    private JSONUtils jsonUtils;

    public void getFreightCharge() {
        Map<String, String> hBody = new HashMap<>();

        hBody.put("jProvince", jProvince);  //寄件地址
        hBody.put("jCity", jCity);
        hBody.put("jAddress", jAddress);
        //清空表
        kylinFreightChargeMapper.delTableData();
        String fileName = KylinFreightChargeServiceImpl.class.getClassLoader().getResource("city_2021.json").getPath();
        String s = jsonUtils.readJsonFile(fileName);
        List<HashMap> provinceListMap = JSONObject.parseArray(s, HashMap.class);
        long startTime = System.currentTimeMillis();
        Integer num=0;
        for (Map pMap : provinceListMap) {
            String dProvince = (String) pMap.get("name");
            List<HashMap> cityListMap = (List<HashMap>) pMap.get("districts");
            for (Map CMap : cityListMap) {
                String dCity = (String) CMap.get("name");
                List<HashMap> adListMap = (List<HashMap>) CMap.get("districts");
                for (Map adMap : adListMap) {
                    //获取快运所有类型
                    List<KylinExpressModuleVo> obj = (List<KylinExpressModuleVo>) redisDataSourceUtil.getRedisKylinUtil().get(KylinRedisConst.KYLIN_EXPRESS_MODULES);
                    if (null != obj) {
                        for (KylinExpressModuleVo kylinExpressModuleVo : obj) {
                            String productCode = kylinExpressModuleVo.getProductCode().toString(); //快件类型码
                            String adcode = (String) adMap.get("adcode");
                            String dAddress = (String) adMap.get("name");
                            hBody.put("expressType", productCode);
                            hBody.put("dProvince", dProvince); //省
                            hBody.put("dCity", dCity);
                            hBody.put("dAddress", dAddress);
                            KylinFreightChargeDao kylinFreightCharge = KylinFreightChargeDao.getNew();
                            HashMap hashMap = null;
                            try {
                                // 生成签名并请求
                                String result = shunfengSignUtils.generateSignatureAndRequestNew(hBody, "/public/order/v1/getFreight");
                                hashMap = JsonUtils.fromJson(result, HashMap.class);
                                HashMap<String, String> map = (HashMap<String, String>) hashMap.get("result");

                                kylinFreightCharge.setFieldsId(IDGenerator.nextTimeId2());
                                kylinFreightCharge.setProvince(dProvince);
                                kylinFreightCharge.setCity(dCity);
                                kylinFreightCharge.setAdname(dAddress);
                                kylinFreightCharge.setAdcode(adcode);
                                String price = map.get("price");
                                String p = price.replace("元",".00");
                                kylinFreightCharge.setPrice(p);
                                kylinFreightCharge.setBusinessType(map.get("businessType"));
                                kylinFreightCharge.setBusinessTypeDesc(map.get("businessTypeDesc"));

                            } catch (Exception e) {
                                log.error("顺丰接口调用失败:"+kylinFreightCharge.getProvince() + " " + kylinFreightCharge.getCity() + " " + kylinFreightCharge.getAdname()+" "+kylinExpressModuleVo.getProductCode()+kylinExpressModuleVo.getTitle());
                            }
                            //调用成功
                            if(hashMap.get("succ").toString().equals("ok")){
                               //存数据库
                               int i = kylinFreightChargeMapper.setFreightCharge(kylinFreightCharge);
                               //存redis
                               redisDataSourceUtil.getRedisKylinUtil().set(KylinRedisConst.RETURN_ADDRESS_CODE + adcode + KylinRedisConst.EXPRESS_TYPE + productCode, kylinFreightCharge);
                               num++;
                           }
                        }
                    }
                }
            }
        }
        log.info("耗时:{}", (System.currentTimeMillis() - startTime) + "毫秒"+"   "+"总条数"+num);
    }
    //读取kylin_freight_charge全表数据存redis
    public void findDataAddRedis(){
        List<KylinFreightChargeDao> l=kylinFreightChargeMapper.findSFData();
        for (KylinFreightChargeDao FreightCharge : l) {
            String adcode = FreightCharge.getAdcode();
            String businessType = FreightCharge.getBusinessType();

            //存redis
            redisDataSourceUtil.getRedisKylinUtil().set(KylinRedisConst.RETURN_ADDRESS_CODE + adcode + KylinRedisConst.EXPRESS_TYPE + businessType, FreightCharge);
        }
    }
}
