package com.zfire.jiasm.syncdata.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zfire.jiasm.syncdata.base.BaseService;
import com.zfire.jiasm.syncdata.constant.InterFaceTypeEnum;
import com.zfire.jiasm.syncdata.constant.TaskConfigEnum;
import com.zfire.jiasm.syncdata.data.Token;
import com.zfire.jiasm.syncdata.plus.entity.Brand;
import com.zfire.jiasm.syncdata.plus.entity.City;
import com.zfire.jiasm.syncdata.plus.entity.Province;
import com.zfire.jiasm.syncdata.plus.service.BrandService;
import com.zfire.jiasm.syncdata.plus.service.CityService;
import com.zfire.jiasm.syncdata.plus.service.ProvinceService;
import com.zfire.jiasm.syncdata.service.*;
import com.zfire.jiasm.syncdata.utils.HttpUtil;
import com.zfire.jiasm.syncdata.utils.JSONResult;
import com.zfire.jiasm.syncdata.utils.TokenCenter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class BaseDownServiceImpl implements BaseDownService {
    @Value("${baseurl}")
    private String baseurl = "";
    @Value("${netfsxc}")
    private String netfsxc = "";
    @Value("${fsxwxgc}")
    private String fsxwxgc = "";
    @Value("${lbdlc}")
    private String lbdlc = "";
    @Value("${azxslxc}")
    private String azxslxc = "";
    @Value("${xqdlc}")
    private String xqdlc = "";
    @Value("${yhsxc}")
    private String yhsxc = "";
    @Value("${sxc}")
    private String sxc = "";

    @Resource
    TokenCenter tokenCenter;
    @Resource
    GLPPGFWebsitService glppgfWebsitService;
    @Autowired
    BrandService brandService;
    @Resource
    GLPPGFWebsitWorkerService glppgfWebsitWorkerService;
    @Resource
    GLPPLeiBieService glppLeiBieService;
    @Resource
    GLPPXSLXDownloadService glppxslxDownloadService;
    @Resource
    GLPPXuQiuLeiBieService glppXuQiuLeiBieService;
    @Resource
    GLPPYHSXXXQDService glppyhsxxxqdService;
    @Resource
    ProvinceCityAreaTownService provinceCityAreaTownService;
    @Resource
    CityService cityService;
    @Resource
    ProvinceService provinceService;
    @Resource
    BaseService baseService;
    @Resource
    private PublicService publicService;



    @Override
    public void downData() throws Exception {

        // 格力品牌广佛网点基础资料下载(销售与售后) 单独启动
        // processGLPPGFWebsit();

        // 格力品牌广佛网点维修工基础资料下载（销售与售后网点维修工） 单独启动
        // processGLPPGFWebsitWorker();

        // 格力品牌固障代码基础资料下载  同步一次不再同步，PC端使用 单独启动
        //  processGLPPGuZhandDaiMa();

        // 格力品牌类别系列基础资料下载（大类、小类、系列、机型） 单独开任务处理了，这里不需要再执行(GLPPLeiBie) 单独启动
        // processGLPPLeiBie();

        // 格力品牌安装销售类型基础资料下载 OK
        processGLPPXSLXDownload();

        // 格力品牌 需求类别 - 需求类别基础资料下载（需求大类、需求小类）  单独启动
        // processGLPPXuQiuLeiBie();

        // 格力品牌用户属性、信息渠道 基础资料下载（用户属性、用户等级、信息渠道、信息来源）
        processGLPPYHSXXXQD();

        // 省、市、区、镇、数据同步
        processProvinceCityAreaTown();
    }

    public void processProvinceCityAreaTown() throws Exception {
        if (sxc.equals(TaskConfigEnum.FALSE.getCode())){
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, String> paramMap = new HashMap<String, String>();
        List<String> req = new ArrayList<>();

        req.add(InterFaceTypeEnum.TBL_PROVINCE.getCode());
        req.add(InterFaceTypeEnum.TBL_CITY.getCode());
        req.add(InterFaceTypeEnum.TBL_COUNTY.getCode());
        req.add(InterFaceTypeEnum.TBL_CITY_JDXZ.getCode());

        log.info("开始下载地理位置基础资料信息: \uF0B7{}",sdf.format(new Date()));

        Token token = tokenCenter.getCurrentToken();
        for (String bc :req){
            try {

                if (bc.equals(InterFaceTypeEnum.TBL_CITY.getCode())){
                    // 提取省份信息
                    List<Province> provinceRec =  provinceService.lambdaQuery().list();
                    // 省份信息未同步时先不同步
                    if (CollectionUtils.isEmpty(provinceRec)){
                        provinceRec.clear();
                        continue;
                    }
                }

                if (bc.equals(InterFaceTypeEnum.TBL_COUNTY.getCode()) ||
                        bc.equals(InterFaceTypeEnum.TBL_CITY_JDXZ.getCode()) ){
                    // 提取市信息
                    List<City> cityRec =  cityService.lambdaQuery().list();
                    // 市信息未同步时先不同步
                    if (CollectionUtils.isEmpty(cityRec)){
                        cityRec.clear();
                        continue;
                    }
                }

                String url = baseurl + bc + "/querylist";
                String paramJson= JSON.toJSONString(paramMap);

                JSONResult jsonResult = HttpUtil.httpRequestWithToken(url, "POST", paramJson, token);
                if (jsonResult.getStatus() == null || !jsonResult.getStatus().toString().equals("200")) {
                    log.info("下载地理位置基础资料信息失败！: {}",jsonResult.getMessage());
                    continue;
                }

                JSONArray jsonArray = (JSONArray) jsonResult.getData();
                if (jsonArray != null) {
                    if (bc.equals(InterFaceTypeEnum.TBL_PROVINCE.getCode())){
                        log.info("省信息下载了{}条数据",jsonArray.size());
                        provinceCityAreaTownService.extractedProvince(jsonArray);
                    } else if (bc.equals(InterFaceTypeEnum.TBL_CITY.getCode())){
                        log.info("市信息下载了{}条数据",jsonArray.size());
                        provinceCityAreaTownService.extractedCity(jsonArray);
                    } else if (bc.equals(InterFaceTypeEnum.TBL_COUNTY.getCode())){
                        log.info("区信息下载了{}条数据",jsonArray.size());
                        provinceCityAreaTownService.extractedCounty(jsonArray);
                    } else if (bc.equals(InterFaceTypeEnum.TBL_CITY_JDXZ.getCode())){
                        log.info("乡镇信息下载了{}条数据",jsonArray.size());
                        provinceCityAreaTownService.extractedStreet(jsonArray);
                    }
                    jsonArray.clear();
                }else {
                    log.info("["+url+"]无数据");
                }
            } catch (Exception ex) {
                log.info("地理位置基础资料信息处理失败");
                ex.printStackTrace();
            }
        }

        log.info("地理位置基础资料信息处理完成: \uF0B7{}",sdf.format(new Date()));
    }

    public void processGLPPYHSXXXQD() throws Exception {
        if (yhsxc.equals(TaskConfigEnum.FALSE.getCode())){
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, String> paramMap = new HashMap<String, String>();
        List<String> req = new ArrayList<>();

        req.add(InterFaceTypeEnum.GLPP_YHSX.getCode());
        req.add(InterFaceTypeEnum.GLPP_YHDJ.getCode());
        req.add(InterFaceTypeEnum.GLPP_XXQD.getCode());
        req.add(InterFaceTypeEnum.GLPP_XXLY.getCode());


        log.info("开始下载格力品牌用户属性信息: \uF0B7{}",sdf.format(new Date()));

        Token token = tokenCenter.getCurrentToken();
        for (String bc :req){
            try {
                String url = baseurl + bc + "/querylist";
                String paramJson= JSON.toJSONString(paramMap);

                JSONResult jsonResult = HttpUtil.httpRequestWithToken(url, "POST", paramJson, token);
                if (jsonResult.getStatus() == null || !jsonResult.getStatus().toString().equals("200")) {
                    log.info("下载格力品牌用户属性信息失败！: {}",jsonResult.getMessage());
                    continue;
                }

                JSONArray jsonArray = (JSONArray) jsonResult.getData();
                if (jsonArray != null) {
                    log.info("格力品牌用户属性信息下载了{}条数据",jsonArray.size());

                    if (bc.equals(InterFaceTypeEnum.GLPP_YHSX.getCode())){
                        glppyhsxxxqdService.extractedYHSX(jsonArray);
                    } else if (bc.equals(InterFaceTypeEnum.GLPP_YHDJ.getCode())){
                        glppyhsxxxqdService.extractedYHDJ(jsonArray);
                    } else if (bc.equals(InterFaceTypeEnum.GLPP_XXQD.getCode())){
                        glppyhsxxxqdService.extractedXXQD(jsonArray);
                    } else if (bc.equals(InterFaceTypeEnum.GLPP_XXLY.getCode())){
                        glppyhsxxxqdService.extractedXXLY(jsonArray);
                    }
                    jsonArray.clear();
                }else {
                    log.info("["+url+"]无数据");
                }
            } catch (Exception ex) {
                log.info("格力品牌用户属性信息处理失败");
                ex.printStackTrace();
            }
        }

        log.info("格力品牌用户属性信息处理完成: \uF0B7{}",sdf.format(new Date()));
    }

    public void processGLPPXuQiuLeiBie() throws Exception {
        if (xqdlc.equals(TaskConfigEnum.FALSE.getCode())){
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, String> paramMap = new HashMap<String, String>();
        List<String> req = new ArrayList<>();

        req.add(InterFaceTypeEnum.GELI_XQDL.getCode());
        req.add(InterFaceTypeEnum.GELI_XQXL.getCode());


        log.info("开始下载格力品牌需求类别信息: \uF0B7{}",sdf.format(new Date()));

        // 提取品牌信息
        Brand brandRec = baseService.getBrand();
        if (brandRec == null){
            log.info("格力品牌信息不存在【brand】");
            return;
        }

        Token token = tokenCenter.getCurrentToken();

        for (String bc :req){
            try{
                String url = baseurl + bc + "/querylist";
                String paramJson= JSON.toJSONString(paramMap);

                JSONResult jsonResult = HttpUtil.httpRequestWithToken(url, "POST", paramJson, token);
                if (jsonResult.getStatus() == null || !jsonResult.getStatus().toString().equals("200")) {
                    log.info("下载格力品牌需求类别信息失败！: {}",jsonResult.getMessage());
                    continue;
                }
                JSONArray jsonArray = (JSONArray) jsonResult.getData();

                if (jsonArray != null) {
                    log.info("格力品牌需求类别下载了{}条数据",jsonArray.size());

                    if (bc.equals(InterFaceTypeEnum.GELI_XQDL.getCode())){
                        glppXuQiuLeiBieService.extractedXQDL(brandRec,jsonArray);
                    } else if (bc.equals(InterFaceTypeEnum.GELI_XQXL.getCode())){
                        glppXuQiuLeiBieService.extractedXQXL(brandRec,jsonArray);
                    }
                    jsonArray.clear();
                }else {
                    log.info("["+url+"]无数据");
                }
            } catch (Exception ex) {
                log.info("格力品牌需求类别信息处理失败");
                ex.printStackTrace();
            }
        }

        log.info("格力品牌需求类别处理完成: \uF0B7{}",sdf.format(new Date()));
    }

    public void processGLPPXSLXDownload() throws Exception {
        if (azxslxc.equals(TaskConfigEnum.FALSE.getCode())){
            return;
        }

        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Map<String, String> paramMap = new HashMap<String, String>();

            log.info("开始下载格力品牌安装销售类型信息: \uF0B7{}",sdf.format(new Date()));

            Token token = tokenCenter.getCurrentToken();
            String url = baseurl + InterFaceTypeEnum.GLPP_XSLX.getCode() + "/querylist";
            String paramJson= JSON.toJSONString(paramMap);

            JSONResult jsonResult = HttpUtil.httpRequestWithToken(url, "POST", paramJson, token);
            if (jsonResult.getStatus() == null || !jsonResult.getStatus().toString().equals("200")) {
                log.info("下载格力品牌安装销售类型信息失败！: {}",jsonResult.getMessage());
                return;
            }
            JSONArray jsonArray = (JSONArray) jsonResult.getData();

            if (jsonArray != null) {
                log.info("格力品牌安装销售类型下载了{}条数据",jsonArray.size());
                glppxslxDownloadService.extractedXSLX(jsonArray);
                jsonArray.clear();
                log.info("格力品牌安装销售类型信息处理完成: \uF0B7{}",sdf.format(new Date()));
            }else {
                log.info("["+url+"]无数据");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info("格力品牌安装销售类型处理失败");
        }

    }

    public void processGLPPLeiBie() throws Exception {
        if (lbdlc.equals(TaskConfigEnum.FALSE.getCode())){
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, String> paramMap = new HashMap<String, String>();
        List<String> req = new ArrayList<>();

        req.add(InterFaceTypeEnum.GELI_DL.getCode());
        req.add(InterFaceTypeEnum.GELI_XL.getCode());
        req.add(InterFaceTypeEnum.GELI_PPXL.getCode());
        req.add(InterFaceTypeEnum.GELI_PPJX.getCode());

        log.info("开始下载格力产品类别基础资料信息: \uF0B7{}",sdf.format(new Date()));

        Token token = tokenCenter.getCurrentToken();
        for (String bc :req){
            try{
                String url = baseurl + bc + "/querylist";
                String paramJson= JSON.toJSONString(paramMap);

                JSONResult jsonResult = HttpUtil.httpRequestWithToken(url, "POST", paramJson, token);
                if (jsonResult.getStatus() == null || !jsonResult.getStatus().toString().equals("200")) {
                    log.info("下载格力产品类别基础资料信息失败！: {}",jsonResult.getMessage());
                    continue;
                }

                JSONArray jsonArray = (JSONArray) jsonResult.getData();
                if (jsonArray != null) {
                    log.info("下载了{}条数据",jsonArray.size());

                    if (bc.equals(InterFaceTypeEnum.GELI_DL.getCode())){
                        glppLeiBieService.extractedDL(jsonArray);
                    } else if (bc.equals(InterFaceTypeEnum.GELI_XL.getCode())){
                        glppLeiBieService.extractedXL(jsonArray);
                    } else if (bc.equals(InterFaceTypeEnum.GELI_PPXL.getCode())){
                        glppLeiBieService.extractedXiLie(jsonArray);
                    } else if (bc.equals(InterFaceTypeEnum.GELI_PPJX.getCode())){
                        glppLeiBieService.extractedJX(jsonArray);
                    }
                    jsonArray.clear();
                }else {
                    log.info("["+url+"]无数据");
                }
            } catch (Exception ex) {
                log.info("格力产品类别基础资料信息处理失败");
                ex.printStackTrace();
            }
        }

        log.info("格力产品类别基础资料信息处理完成: \uF0B7{}",sdf.format(new Date()));
    }


    public void processGLPPGFWebsitWorker() throws Exception {
        if (fsxwxgc.equals(TaskConfigEnum.FALSE.getCode())){
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<String> req = new ArrayList<>();
        Map<String, String> paramMap = new HashMap<String, String>();

        req.add(InterFaceTypeEnum.FSXS_WEBSIT_CODE.getCode());
        req.add(InterFaceTypeEnum.GZXS_WEBSIT_CODE.getCode());
        req.add(InterFaceTypeEnum.FSSH_WEBSIT_CODE.getCode());
        req.add(InterFaceTypeEnum.GSSH_WEBSIT_CODE.getCode());

        log.info("开始下载网点维修工基础资料信息: \uF0B7{}",sdf.format(new Date()));

        Token token = tokenCenter.getCurrentToken();
        String url = baseurl + InterFaceTypeEnum.GLXSSH_WEBSIT_WORK.getCode() + "/querylist";
        for (String bc :req){
            try{
                paramMap.put("belongCompany", bc);
                String paramJson= JSON.toJSONString(paramMap);

                JSONResult jsonResult = HttpUtil.httpRequestWithToken(url, "POST", paramJson, token);
                if (jsonResult.getStatus() == null || !jsonResult.getStatus().toString().equals("200")) {
                    log.info("下载佛山销售网点维修工基础资料信息失败！: {}",jsonResult.getMessage());
                    continue;
                }

                JSONArray jsonArray = (JSONArray) jsonResult.getData();
                if (jsonArray != null) {
                    log.info("网点维修工下载了{}条数据",jsonArray.size());

                    if (bc.equals(InterFaceTypeEnum.FSXS_WEBSIT_CODE.getCode())){
                        glppgfWebsitWorkerService.extractedFSXS(jsonArray);
                    } else if (bc.equals(InterFaceTypeEnum.GZXS_WEBSIT_CODE.getCode())){
                        glppgfWebsitWorkerService.extractedGZXS(jsonArray);
                    } else if (bc.equals(InterFaceTypeEnum.FSSH_WEBSIT_CODE.getCode())){
                        glppgfWebsitWorkerService.extractedFSSH(jsonArray);
                    } else if (bc.equals(InterFaceTypeEnum.GSSH_WEBSIT_CODE.getCode())){
                        glppgfWebsitWorkerService.extractedGZSH(jsonArray);
                    }
                    jsonArray.clear();
                }else {
                    log.info("["+url+"]无数据");
                }
            } catch (Exception ex) {
                log.info("网点维修工基础资料信息处理失败");
                ex.printStackTrace();
            }
        }

        log.info("网点维修工基础资料信息处理完成: \uF0B7{}",sdf.format(new Date()));
    }


    public void processGLPPGFWebsit() throws Exception {
        if (netfsxc.equals(TaskConfigEnum.FALSE.getCode())){
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, String> paramMap = new HashMap<String, String>();
        List<String> req = new ArrayList<>();

        // 提取品牌信息
        Brand record = baseService.getBrand();
        if (record == null){
            log.info("格力品牌信息不存在【brand】");
            return;
        }

        req.add(InterFaceTypeEnum.FSXS_WEBSIT_CODE.getCode());
        req.add(InterFaceTypeEnum.GZXS_WEBSIT_CODE.getCode());
        req.add(InterFaceTypeEnum.FSSH_WEBSIT_CODE.getCode());
        req.add(InterFaceTypeEnum.GSSH_WEBSIT_CODE.getCode());
        String synTaskNo = publicService.getUUID();

        log.info("开始下载网点基础资料信息: \uF0B7{}",sdf.format(new Date()));

        Token token = tokenCenter.getCurrentToken();
        String url = baseurl + InterFaceTypeEnum.GLXSSH_WEBSIT.getCode() + "/querylist";
        for (String bc :req){
            try{
                paramMap.put("belongCompany", bc);
                String paramJson= JSON.toJSONString(paramMap);

                JSONResult jsonResult = HttpUtil.httpRequestWithToken(url, "POST", paramJson, token);
                if (jsonResult.getStatus() == null || !jsonResult.getStatus().toString().equals("200")) {
                    log.info("下载网点基础资料信息失败！: {}",jsonResult.getMessage());
                    continue;
                }

                JSONArray jsonArray = (JSONArray) jsonResult.getData();
                if (jsonArray != null) {
                    log.info("网点下载了{}条数据",jsonArray.size());
                    if (bc.equals(InterFaceTypeEnum.FSXS_WEBSIT_CODE.getCode())){
                        glppgfWebsitService.extractedFSXS(jsonArray, record, synTaskNo);
                    } else if (bc.equals(InterFaceTypeEnum.GZXS_WEBSIT_CODE.getCode())){
                        glppgfWebsitService.extractedGZXS(jsonArray, record, synTaskNo);
                    } else if (bc.equals(InterFaceTypeEnum.FSSH_WEBSIT_CODE.getCode())){
                        glppgfWebsitService.extractedFSSH(jsonArray, record, synTaskNo);
                    } else if (bc.equals(InterFaceTypeEnum.GSSH_WEBSIT_CODE.getCode())){
                        glppgfWebsitService.extractedGZSH(jsonArray, record, synTaskNo);
                    }
                    jsonArray.clear();
                }else {
                    log.info("["+url+"]无数据");
                }
            } catch (Exception ex) {
                log.info("网点基础资料信息处理失败");
                ex.printStackTrace();
            }
        }

        log.info("网点基础资料信息处理完成: \uF0B7{}",sdf.format(new Date()));
    }
}
