package me.zhengjie.modules.quartz.task;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.dm.dmPlateTraffic.domain.DmPlateTraffic;
import me.zhengjie.modules.dm.dmPlateTraffic.repository.DmPlateTrafficRepository;
import me.zhengjie.modules.dm.dmPlateTraffic.service.DmPlateTrafficService;
import me.zhengjie.modules.dm.dmPlateTraffic.service.dto.DmPlateTrafficDto;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.utils.BeanMapUtils;
import me.zhengjie.utils.ConnectionUtil;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.ykt.domain.DmPlateNumber;
import me.zhengjie.ykt.service.DmPlateNumberService;
import me.zhengjie.ykt.service.dto.DmPlateNumberDto;
import me.zhengjie.ykt.service.dto.DmPlateNumberQueryCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeoutException;

@Slf4j
@RequiredArgsConstructor
@Component
public class PlateTrafficTask {
    @Value("${yueUrl}")
    private String yueUrl;
    @Value("${mfUrl}")
    private String mfUrl;
    @Value("${plateUrl}")
    private String plateUrl;
    private final DmPlateTrafficRepository dmPlateTrafficRepository;
    private final DmPlateNumberService dmPlateNumberService;

    public void run() throws ParseException, IOException {
        log.info("run 执行开始");
        syncPlateTraffic();
        log.info("run 执行结束");
    }

    public void run2() throws ParseException, IOException {
        log.info("run2 执行开始");
        mfReserveData();
        log.info("run2 执行结束");
    }

    public void run3() throws ParseException, IOException {
        log.info("run3 执行开始");
        yueReserveData();
        log.info("run3 执行结束");
    }

    public JSONObject getData(String url ,JSONObject param){
        Map<String,String> formDataParam = new HashMap<>();
        System.out.println("formDataParam:"+param.toJSONString());
        formDataParam.put("vehicleData",param.toJSONString());
        String data = BeanMapUtils.doPostForm(url,formDataParam);
        System.out.println("historyRecord:"+data);
        JSONObject dataJSON = JSONObject.parseObject(data);
        return dataJSON;
    }

    /**
     * 添加月租车
     */
    public void yueReserveData() {
//        String url = "http://10.208.128.14:9999/api/park/addmonthlycar";
        JSONObject generateProcJson = new JSONObject();
        List<DmPlateNumber> dmPlateNumbers = dmPlateNumberService.yuePlateRepository();
        for (DmPlateNumber dto : dmPlateNumbers){
            generateProcJson.put("name",dto.getUserNumber().getName());
            generateProcJson.put("phone",dto.getUserNumber().getContacts());
            generateProcJson.put("carplate",dto.getPlateNumber());
            generateProcJson.put("startdate",dto.getStartTime());
            generateProcJson.put("enddate",dto.getEndTime());
            generateProcJson.put("cardtype","A");
            generateProcJson.put("controllers","1，2，3，4");
        }
        JSONObject generateProcData = getData(yueUrl,generateProcJson);
        JSONObject generateProcDataJson = JSONObject.parseObject(String.valueOf(generateProcData));
        System.out.println("generateProcDataJson:"+generateProcDataJson);
    }

    /**
     * 添加免费车
     */
    public void mfReserveData() {
//        String url = "http://10.208.128.14:9999/api/park/addfreecar";
        JSONObject generateProcJson = new JSONObject();
        List<DmPlateNumber> dmPlateNumbers = dmPlateNumberService.mfPlateRepository();
        for (DmPlateNumber dto : dmPlateNumbers){
            generateProcJson.put("name",dto.getUserNumber().getName());
            generateProcJson.put("phone",dto.getUserNumber().getContacts());
            generateProcJson.put("carplate",dto.getPlateNumber());
            generateProcJson.put("startdate",dto.getStartTime());
            generateProcJson.put("enddate",dto.getEndTime());
            generateProcJson.put("cardtype","A");
            generateProcJson.put("controllers","1，2，3，4");
        }

        JSONObject generateProcData = getData(mfUrl,generateProcJson);
        JSONObject generateProcDataJson = JSONObject.parseObject(String.valueOf(generateProcData));
        System.out.println("generateProcDataJson:"+generateProcDataJson);
    }

    /**
     * 同步车辆通行记录
     */
    public void syncPlateTraffic() throws ParseException, IOException {
//        String url = "http://10.208.128.14:9999/api/park/getparkrecord";
        Map<String,Object> map = new HashMap<>();

        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formater2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,-24);
        Date start = formater2.parse(formater.format(calendar.getTime())+ " 00:00:00");
        Date end = formater2.parse(formater.format(calendar.getTime())+ " 23:59:59");
        System.out.println("开始时间-车辆通行记录："+formater2.format(start));//昨日开始时间
        JSONObject data = new JSONObject();
        int limit = 100;//页数
        data.put("startdate",formater2.format(start));
        data.put("enddate",formater2.format(end));
        data.put("pageindex",1);//当前页数
        data.put("pagesize",limit);

        String generateProc = BeanMapUtils.sendPost(plateUrl,data.toString());
        JSONObject generateProcDataJson = JSONObject.parseObject(generateProc);
        System.out.println("generateProcDataJson"+generateProcDataJson);
        //计算总页数
        Integer total = generateProcDataJson.getJSONObject("data").getInteger("totalrecord");//总条数
        int pageTotal = (total / limit);
        if (total % limit != 0) {
            pageTotal++;
        }
        log.info("pageTotal:"+pageTotal);

        //按页获取
        for (int k = 0; k < pageTotal; k++) {
            JSONObject newGenerateProcDataJson = JSONObject.parseObject(BeanMapUtils.sendPost(plateUrl,data.toString()));
            JSONObject dataJSON = newGenerateProcDataJson.getJSONObject("data");
            JSONArray data1 = dataJSON.getJSONArray("data");
            for (int i = 0; i < data1.size(); i++) {
                JSONObject attendance = data1.getJSONObject(i);
                if (null == map.get(attendance.getString("carplate")+attendance.getString("intime"))){
                    DmPlateTraffic plateTraffic = new DmPlateTraffic();
                    plateTraffic.setMthtype(attendance.getString("mthtype"));
                    plateTraffic.setPlateNumber(attendance.getString("carplate"));
                    plateTraffic.setIntime(attendance.getString("intime"));
                    plateTraffic.setOuttime(attendance.getString("outtime"));
                    plateTraffic.setIngatename(attendance.getString("ingatename"));
                    plateTraffic.setOutgatename(attendance.getString("outgatename"));
                    plateTraffic.setYsje(attendance.getString("ysje"));
                    plateTraffic.setSfje(attendance.getString("sfje"));
                    dmPlateTrafficRepository.save(plateTraffic);
                    map.put(attendance.getString("carplate")+attendance.getString("intime"),attendance.getString("carplate")+attendance.getString("intime"));
                }
            }
        }
    }



}
