package me.zhengjie.modules.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.dmAccessTraffic.domain.DmAccessTraffic;
import me.zhengjie.modules.dmExpenseCalendar.domain.DmExpenseCalendar;
import me.zhengjie.modules.dmExpenseCalendar.service.DmExpenseCalendarService;
import me.zhengjie.modules.dmExpenseCalendar.service.dto.DmExpenseCalendarDto;
import me.zhengjie.modules.dmRechargeRecord.domain.DmRechargeRecord;
import me.zhengjie.modules.dmRechargeRecord.service.DmRechargeRecordService;
import me.zhengjie.modules.dmRechargeRecord.service.dto.DmRechargeRecordDto;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.BeanMapUtils;
import me.zhengjie.utils.MessageSendUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

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

@Slf4j
@Component
@RequiredArgsConstructor
public class CardRecordTask {

    @Value("${expenseUrl}")
    private String expenseUrl;
    @Value("${rechargeUrl}")
    private String rechargeUrl;
    private final DmRechargeRecordService dmRechargeRecordService;
    private final DmExpenseCalendarService dmExpenseCalendarService;
    private final UserService userService;

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

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

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

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

    public JSONObject getData(String url , JSONObject param) throws IOException {
//        Map<String,String> formDataParam = new HashMap<>();
//        System.out.println("formDataParam:"+param.toJSONString());
//        formDataParam.put("date",param.toJSONString());
        log.info("param:"+param);
        String data = BeanMapUtils.sendPost(url, param.toString());
        System.out.println("historyRecord:"+data);
        JSONObject dataJSON = JSONObject.parseObject(data);
        return dataJSON;
    }

    public void asyncRecharge() throws IOException, ParseException {
//        String url = "https://smartpark.caih.com/dxapi/dxtop/charge/page";

        JSONObject data = new JSONObject();
        int limit = 100;//页数
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formater2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        Date start = formater2.parse(formater.format(calendar.getTime())+ " 00:00:00");
        Date end = formater2.parse(formater.format(calendar.getTime())+ " 23:59:59");
        data.put("startTime",formater2.format(start));
        data.put("endTime",formater2.format(end));
        data.put("current",1);//当前页数
        data.put("size",limit);
        try {
            JSONObject generateProcDataJson = getData(rechargeUrl,data);
            System.out.println(generateProcDataJson);

            Integer total = generateProcDataJson.getJSONObject("data").getInteger("total");//总条数
            int pageTotal = (total / limit);
            if (total % limit != 0) {
                pageTotal++;
            }
            for(int i = 1;i<=pageTotal;i++){//循环总页数
                //获取当前页数
                data.put("current",i);//当前页数
                JSONObject newGenerateProcDataJson = getData(rechargeUrl,data);
                JSONObject dataJSON = newGenerateProcDataJson.getJSONObject("data");//第二层
                JSONArray arr2 = dataJSON.getJSONArray("records");//第三层集合数据
                for (int j = 0;j<arr2.size();j++){//
                    JSONObject attendance = arr2.getJSONObject(j);
                    String seq = attendance.getString("seq");
                    DmRechargeRecord dmRechargeRecord = dmRechargeRecordService.findBySeq(seq);
                    if(dmRechargeRecord == null) {
                        //组装返回数据
                        JSONObject acc = new JSONObject();
                        acc.put("seq", seq);
                        acc.put("userName", attendance.getString("userName"));
                        acc.put("userPhone", attendance.getString("userPhone"));
                        acc.put("cardNumber", attendance.getString("cardNo"));
                        acc.put("rechargeAmount", attendance.getString("amt"));
                        acc.put("amountAfterRecharge", attendance.getString("balance"));
                        acc.put("rechargeTime", attendance.getString("createTime"));
                        DmRechargeRecordDto dmRechargeRecordDto = dmRechargeRecordService.create(JSON.toJavaObject(acc, DmRechargeRecord.class));
                        String sendContent = "您的充值操作已成功，充值金额为："+dmRechargeRecordDto.getRechargeAmount()+"元";
                        MessageSendUtils.sendChatMessage("dm_recharge_record|seq|"+seq,"System",sendContent,userService.getUsernameByCardId(dmRechargeRecordDto.getCardNumber()));
                    } else {
                        System.out.println("dmRechargeRecord is null. seq:"+seq);
                    }
                }
            }
        }catch (Exception e){
            log.info("同步昨日充值出现异常： 异常信息为 {}",e.getMessage());
        }

    }

    public void asyncRechargeAll() throws IOException, ParseException {
//        String url = "https://smartpark.caih.com/dxapi/dxtop/charge/page";

        JSONObject data = new JSONObject();
        int limit = 100;//页数
        data.put("current",1);//当前页数
        data.put("size",limit);

        JSONObject generateProcDataJson = getData(rechargeUrl,data);
        System.out.println(generateProcDataJson);

        Integer total = generateProcDataJson.getJSONObject("data").getInteger("total");//总条数
        int pageTotal = (total / limit);
        if (total % limit != 0) {
            pageTotal++;
        }

        for(int i = 1;i<=pageTotal;i++){//循环总页数
            //获取当前页数
            data.put("current",i);//当前页数
            JSONObject newGenerateProcDataJson = getData(rechargeUrl,data);
            JSONObject dataJSON = newGenerateProcDataJson.getJSONObject("data");//第二层
            JSONArray arr2 = dataJSON.getJSONArray("records");//第三层集合数据
            for (int j = 0;j<arr2.size();j++){//
                JSONObject attendance = arr2.getJSONObject(j);
                String seq = attendance.getString("seq");
                DmRechargeRecord dmRechargeRecord = dmRechargeRecordService.findBySeq(seq);
                if(dmRechargeRecord == null) {
                    //组装返回数据
                    JSONObject acc = new JSONObject();
                    acc.put("seq", seq);
                    acc.put("userName", attendance.getString("userName"));
                    acc.put("userPhone", attendance.getString("userPhone"));
                    acc.put("cardNumber", attendance.getString("cardNo"));
                    acc.put("rechargeAmount", attendance.getString("amt"));
                    acc.put("amountAfterRecharge", attendance.getString("balance"));
                    acc.put("rechargeTime", attendance.getString("createTime"));
                    DmRechargeRecordDto dmRechargeRecordDto = dmRechargeRecordService.create(JSON.toJavaObject(acc, DmRechargeRecord.class));
                    String sendContent = "您的充值操作已成功，充值金额为："+dmRechargeRecordDto.getRechargeAmount()+"元";
                    MessageSendUtils.sendChatMessage("dm_recharge_record|seq|"+seq,"System",sendContent,userService.getUsernameByCardId(dmRechargeRecordDto.getCardNumber()));
                } else {
                    System.out.println("dmRechargeRecord is null. seq:"+seq);
                }
            }
        }
    }

    public void asyncExpense() throws IOException, ParseException {
//        String url = "https://smartpark.caih.com/dxapi/dxtop/dish/page";

        JSONObject data = new JSONObject();
        int limit = 100;//页数
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formater2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        Date start = formater2.parse(formater.format(calendar.getTime())+ " 00:00:00");
        Date end = formater2.parse(formater.format(calendar.getTime())+ " 23:59:59");
        data.put("startTime",formater2.format(start));
        data.put("endTime",formater2.format(end));
        data.put("current",1);//当前页数
        data.put("size",limit);
      try{
          JSONObject generateProcDataJson = getData(expenseUrl,data);
          System.out.println(generateProcDataJson);
          Integer total = generateProcDataJson.getJSONObject("data").getInteger("total");//总条数
          int pageTotal = (total / limit);
          if (total % limit != 0) {
              pageTotal++;
          }
          Map<String,Object> map = new HashMap<>();
          for(int i = 1;i<=pageTotal;i++){//循环总页数
              //获取当前页数
              data.put("current",i);//当前页数
              log.info("第{}开始请求开始时间为:",i,System.currentTimeMillis());
              JSONObject newGenerateProcDataJson = getData(expenseUrl,data);
              log.info("第{}开始请求结束时间为:",i,System.currentTimeMillis());
              JSONObject dataJSON = newGenerateProcDataJson.getJSONObject("data");//第二层
              JSONArray arr2 = dataJSON.getJSONArray("records");//第三层集合数据
              for (int j = 0;j<arr2.size();j++){//
                  JSONObject attendance = arr2.getJSONObject(j);
                  String seq = attendance.getString("seq");
                  List<DmExpenseCalendar> dmExpenseCalendar = dmExpenseCalendarService.findBySeq(seq);
                  if(dmExpenseCalendar.size()<=0) {
                      //组装返回数据
                      JSONObject acc = new JSONObject();
                      acc.put("seq", seq);
                      acc.put("userName", attendance.getString("userName"));
                      acc.put("userPhone", attendance.getString("userPhone"));
                      acc.put("cardNumber", attendance.getString("cardNo"));
                      acc.put("rechargeAmount", attendance.getString("amt"));
                      acc.put("amountAfterRecharge", attendance.getString("balance"));
                      acc.put("rechargeTime", attendance.getString("createTime"));
                      acc.put("content", attendance.getString("shopName"));
                      if (attendance.getString("cardNo") != null) {
                          acc.put("patternPayment", "园区卡");
                      } else {
                          acc.put("patternPayment", "其他");
                      }
                      if (null == map.get(acc.getString("seq"))){
                          DmExpenseCalendarDto dmExpenseCalendarDto = dmExpenseCalendarService.create(JSON.toJavaObject(acc, DmExpenseCalendar.class));
                          if (!ObjectUtils.isEmpty(dmExpenseCalendarDto)){
                              map.put(dmExpenseCalendarDto.getSeq(),dmExpenseCalendarDto.getSeq());
                              String sendContent = "您的消费账号余额已变动，消费金额为："+dmExpenseCalendarDto.getRechargeAmount()+"元。";
                              MessageSendUtils.sendChatMessage("dm_recharge_record|seq|"+seq,"System",sendContent,userService.getUsernameByCardId(dmExpenseCalendarDto.getCardNumber()));
                          }
                      }
                  } else {
                      log.info("dmExpenseCalendar is null. seq:"+seq);
                  }
              }
          }
      } catch (Exception e){
          log.info("同步当天消费出现异常：异常信息为 {}",e.getMessage() );
      }
    }

    public void asyncExpenseAll() throws IOException, ParseException {
//        String url = "https://smartpark.caih.com/dxapi/dxtop/dish/page";

        JSONObject data = new JSONObject();
        int limit = 100;//页数
        data.put("current",1);//当前页数
        data.put("size",limit);

        JSONObject generateProcDataJson = getData(expenseUrl,data);
        System.out.println(generateProcDataJson);

        Integer total = generateProcDataJson.getJSONObject("data").getInteger("total");//总条数
        int pageTotal = (total / limit);
        if (total % limit != 0) {
            pageTotal++;
        }

        for(int i = 1;i<=pageTotal;i++){//循环总页数
            //获取当前页数
            data.put("current",i);//当前页数
            JSONObject newGenerateProcDataJson = getData(expenseUrl,data);
            JSONObject dataJSON = newGenerateProcDataJson.getJSONObject("data");//第二层
            JSONArray arr2 = dataJSON.getJSONArray("records");//第三层集合数据
            for (int j = 0;j<arr2.size();j++){//
                JSONObject attendance = arr2.getJSONObject(j);
                String seq = attendance.getString("seq");
                List<DmExpenseCalendar> dmExpenseCalendar = dmExpenseCalendarService.findBySeq(seq);
                if(dmExpenseCalendar == null) {
                    //组装返回数据
                    JSONObject acc = new JSONObject();
                    acc.put("seq", seq);
                    acc.put("userName", attendance.getString("userName"));
                    acc.put("userPhone", attendance.getString("userPhone"));
                    acc.put("cardNumber", attendance.getString("cardNo"));
                    acc.put("rechargeAmount", attendance.getString("amt"));
                    acc.put("amountAfterRecharge", attendance.getString("balance"));
                    acc.put("rechargeTime", attendance.getString("createTime"));
                    acc.put("content", attendance.getString("shopName"));
                    if (attendance.getString("card_no") != null) {
                        acc.put("patternPayment", "园区卡");
                    } else {
                        acc.put("patternPayment", "其他");
                    }
                    DmExpenseCalendarDto dmExpenseCalendarDto = dmExpenseCalendarService.create(JSON.toJavaObject(acc, DmExpenseCalendar.class));
                    String sendContent = "您的消费账号余额已变动，消费金额为："+dmExpenseCalendarDto.getRechargeAmount()+"元。";
                    MessageSendUtils.sendChatMessage("dm_recharge_record|seq|"+seq,"System",sendContent,userService.getUsernameByCardId(dmExpenseCalendarDto.getCardNumber()));
                } else {
                    log.info("dmExpenseCalendar is null. seq:"+seq);
                }
            }
        }
    }
}
