package com.project.zcustom.tools;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.common.utils.StringUtils;
import com.project.common.utils.http.HttpUtils;
import com.project.zcustom.domain.addional.LargeCar;
import com.project.zcustom.domain.addional.LargeCarDetail;
import com.project.zcustom.domain.addional.LargeCarRank;
import com.project.zcustom.domain.addional.LargeWarnDetail;
import com.project.zcustom.domain.basics.PlatAppOrg;
import com.project.zcustom.domain.plat.PlatApiRecord;
import com.project.zcustom.mapper.car.PlatCarMapper;
import com.project.zcustom.service.plat.IPlatApiRecordService;
import com.project.zcustom.service.service.basics.IPlatAppOrgService;
import com.project.zcustom.service.unit.ILargeCarDetailService;
import com.project.zcustom.service.unit.ILargeCarRankService;
import com.project.zcustom.service.unit.ILargePublicCarService;
import com.project.zcustom.service.unit.ILargeWarnDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CarService {
    @Resource
    IPlatApiRecordService iPlatApiRecordService;

    @Autowired
    private ILargePublicCarService largePlatPublicCarService;

    @Autowired
    private ILargeCarDetailService largeCarDetailService;

    @Autowired
    private ILargeWarnDetailService largeWarnDetailService;

    @Autowired
    private ILargeCarRankService largeCarRankService;

    @Autowired
    private IPlatAppOrgService platAppOrgService;

    @Autowired
    private PlatCarMapper platCarMapper;

    /**
     * 公务用车
     */
    public void getPublicCarData(){
        LocalDate currentDate = LocalDate.now();
        int year = currentDate.getYear();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        String formattedDate = currentDate.format(formatter);
        List<PlatAppOrg> orgList = platAppOrgService.selectAppCodeList();
        Map<String, String> orgMap = orgList.stream().collect(Collectors.toMap(PlatAppOrg::getAppEncode, PlatAppOrg::getAppParentOrg, (v1, v2) -> v1));
        entryA(JSON.parseArray(repeat(ApiUrlConfig.getJsonEstablishment(), "yearMonth=" + formattedDate), LargeCar.class), orgMap);
        entryA(JSON.parseArray(repeat(ApiUrlConfig.getJsonCarChange(), "year=" + year), LargeCar.class), orgMap);
        entryA(JSON.parseArray(repeat(ApiUrlConfig.getJsonCarType(), "year=" + year), LargeCar.class), orgMap);
        entryA(JSON.parseArray(repeat(ApiUrlConfig.getJsonEnterpriseCar(), "year=" + year), LargeCar.class), orgMap);
        entryA(JSON.parseArray(repeat(ApiUrlConfig.getJsonCarPowerType(), "year=" + year), LargeCar.class), orgMap);
        entryA(JSON.parseArray(repeat(ApiUrlConfig.getJsonCarOrderAndMileage(), "yearMonth=" + formattedDate), LargeCar.class), orgMap);
        entryA(JSON.parseArray(repeat(ApiUrlConfig.getJsonEstablishment(), "yearMonth=" + formattedDate), LargeCar.class), orgMap);
        entryA(JSON.parseArray(repeat(ApiUrlConfig.getJsonCarTerminal(), "yearMonth=" + formattedDate), LargeCar.class), orgMap);
        entryA(JSON.parseArray(repeat(ApiUrlConfig.getJsonCarNotArchived(), "yearMonth=" + formattedDate), LargeCar.class), orgMap);
        entryA(JSON.parseArray(repeat(ApiUrlConfig.getJsonCarWarning(), "yearMonth=" + formattedDate), LargeCar.class), orgMap);
        entryB(JSON.parseArray(repeat(ApiUrlConfig.getJsonCarIncrease(), "year=" + year), LargeCarDetail.class), orgMap, 0);
        entryB(JSON.parseArray(repeat(ApiUrlConfig.getJsonCarReduce(), "year=" + year), LargeCarDetail.class), orgMap, 1);
        entryC(JSON.parseArray(repeat(ApiUrlConfig.getJsonCarWarningTickets(), "yearMonth=" + formattedDate), LargeWarnDetail.class), orgMap, "未带工单报警");
        entryC(JSON.parseArray(repeat(ApiUrlConfig.getJsonCarWarningHoliday(), "yearMonth=" + formattedDate), LargeWarnDetail.class), orgMap, "超速报警");
        entryC(JSON.parseArray(repeat(ApiUrlConfig.getJsonCarWarningOverSpeed(), "yearMonth=" + formattedDate), LargeWarnDetail.class), orgMap, "节假日用车报警");
        entryD(JSON.parseArray(repeat(ApiUrlConfig.getJsonCarRank(), "yearMonth=" + formattedDate), LargeCarRank.class), orgMap);
    }

    public void entryA(List<LargeCar> x, Map<String, String> map){
        try {
            for (LargeCar it : x){
                if (!map.containsKey(it.getAppEncode()) || !map.get(it.getAppEncode()).equals("10001")){
                    continue;
                }
                QueryWrapper<LargeCar> lqw = new QueryWrapper<LargeCar>();
                lqw.eq("app_encode", it.getAppEncode());
                lqw.last("limit 1");
                LargeCar car = largePlatPublicCarService.getOne(lqw);
                if (car != null){
                    it.setId(car.getId());
                    largePlatPublicCarService.updateById(it);
                }
                else largePlatPublicCarService.save(it);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 车辆年度变化明细
     * @param x
     * @param map
     * @param flag
     */
    public void entryB(List<LargeCarDetail> x, Map<String, String> map, Integer flag){
        try {
            platCarMapper.deleteAllCarDetail(flag);
            for (LargeCarDetail it : x){
                if (!map.containsKey(it.getAppEncode()) || !map.get(it.getAppEncode()).equals("10001")){
                    continue;
                }
                it.setFlag(flag);
                largeCarDetailService.save(it);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 车辆告警明细
     * @param x
     * @param map
     */
    public void entryC(List<LargeWarnDetail> x, Map<String, String> map, String alertType){
        try {
            platCarMapper.deleteAllWarnDetail(alertType);
            for (LargeWarnDetail it : x){
                if (!map.containsKey(it.getAppEncode()) || !map.get(it.getAppEncode()).equals("10001")){
                    continue;
                }
                largeWarnDetailService.save(it);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 车辆排名
     * @param x
     * @param map
     */
    public void entryD(List<LargeCarRank> x, Map<String, String> map){
        try {
            platCarMapper.deleteAllCarRank();
            largeCarRankService.remove(null);
            for (LargeCarRank it : x){
                if (!map.containsKey(it.getAppEncode()) || !map.get(it.getAppEncode()).equals("10001")){
                    continue;
                }
                largeCarRankService.save(it);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String repeat(String url, String params){
        String result = null;
        try {
            if (StringUtils.isNotBlank(params)){
                String res = HttpUtils.sendPost(url, params);
                if (StringUtils.isNotBlank(res)){
                    JSONObject jsonObject = JSONObject.parseObject(res);
                    result = jsonObject.getString("data");
                }
            } else {
                String res = HttpUtils.sendGet(url);
                if (StringUtils.isNotBlank(res)){
                    JSONObject jsonObject = JSONObject.parseObject(res);
                    result = jsonObject.getString("data");
                }
            }

        } catch (Exception e){
            // 添加接口请求记录
            PlatApiRecord platApiRecord = new PlatApiRecord();
            platApiRecord.setApiUrl(url);
            platApiRecord.setApiResult(e.getMessage());
            iPlatApiRecordService.save(platApiRecord);
            return null;
        }
        // 添加接口请求记录
        PlatApiRecord platApiRecord = new PlatApiRecord();
        platApiRecord.setApiUrl(url);
        platApiRecord.setApiResult(result);
        iPlatApiRecordService.save(platApiRecord);
        return result;
    }
}
