package me.zhengjie.modules.quartz.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import me.zhengjie.domain.Log;
import me.zhengjie.modules.dm.food.domain.DmFood;
import me.zhengjie.modules.dm.order.domain.DmOrderItem;
import me.zhengjie.modules.dm.order.domain.DmOrderPayment;
import me.zhengjie.modules.dm.order.domain.DmOrderRecord;
import me.zhengjie.modules.dm.order.repository.DmOrderRecordRepository;
import me.zhengjie.modules.dm.order.service.DmOrderItemService;
import me.zhengjie.modules.dm.order.service.DmOrderPaymentService;
import me.zhengjie.modules.dm.order.service.DmOrderRecordService;
import me.zhengjie.modules.dm.settlement.domain.DmSettlement;
import me.zhengjie.modules.dm.settlement.service.DmSettlementService;
import me.zhengjie.modules.dm.user.domain.DmUser;
import me.zhengjie.modules.dm.user.service.DmUserService;
import me.zhengjie.modules.dm.user.service.dto.DmUserQueryCriteria;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.repository.LogRepository;
import me.zhengjie.utils.BeanMapUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

@Slf4j
@Component
@RequiredArgsConstructor
public class CardRecordTask {

    @Value("${cardUrl}")
    private String url;
    private final DmOrderRecordService dmOrderRecordService;
    private final DmOrderItemService dmOrderItemService;
    private final DmOrderPaymentService dmOrderPaymentService;
    private final LogRepository logRepository;
    private final DmOrderRecordRepository dmOrderRecordRepository;
    private final DmUserService dmUserService;
    private final DmSettlementService dmSettlementService;
//    private final DmExpenseCalendarService dmExpenseCalendarService;

//    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 {
        log.info("param:"+param);
        String data = "";
        JSONObject dataJSON = null;
        try {
            data = BeanMapUtils.sendPost(url, param.toString());
            System.out.println("historyRecord:"+data);
            dataJSON = JSONObject.parseObject(data);
        } catch (Exception ex){
            ex.printStackTrace();
            Log log = new Log();
            log.setDescription(ex.toString());
            log.setLogType("ERROR");
            log.setMethod(url);
            log.setParams(data);
            log.setUsername("同步永天消费数据问题");
            System.out.println("日志"+log);
            logRepository.save(log);
        }
        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);
//
//        JSONObject generateProcDataJson = getData(url,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(url,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"));
//
//                    dmRechargeRecordService.create(JSON.toJavaObject(acc, DmRechargeRecord.class));
//                } else {
//                    System.out.println("dmRechargeRecord is null. seq:"+seq);
//                }
//            }
//        }
//    }
//
//    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(url,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(url,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"));
//
//                    dmRechargeRecordService.create(JSON.toJavaObject(acc, DmRechargeRecord.class));
//                } else {
//                    System.out.println("dmRechargeRecord is null. seq:"+seq);
//                }
//            }
//        }
//    }

    public void asyncExpense() throws IOException, ParseException {
//        String url = ;

        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();
//        calendar.add(Calendar.DATE,-1);
        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("startTime","2022-02-28 00:00:00");
//        data.put("endTime","2022-02-28 23:59:59");
        data.put("current",1);//当前页数
        data.put("size",limit);
        JSONObject generateProcDataJson = getData(url,data);
        System.out.println(generateProcDataJson);
        Integer total = generateProcDataJson.getJSONObject("data").getInteger("total");//总条数
        int pageTotal = (total / limit);
        if (total % limit != 0) {
            pageTotal++;
        }

        for(int i = 0;i<pageTotal;i++){//循环总页数
            //获取当前页数
            data.put("current",i+1);//当前页数
            JSONObject newGenerateProcDataJson = getData(url,data);
            JSONObject dataJSON = newGenerateProcDataJson.getJSONObject("data");//第二层
            JSONArray arr2 = dataJSON.getJSONArray("records");//第三层集合数据
            for (int j = 0;j<arr2.size();j++){//
                JSONObject attendance = arr2.getJSONObject(j);
                Long seq = attendance.getLong("seq");
                List<Map<String, Object>> list = dmOrderRecordRepository.selectOrderRecordBySeq(seq);

                if(list.size() == 0) {
                    DmSettlement dmSettlement = new DmSettlement();
                    dmSettlement.setCardCode(attendance.getString("card"));
                    dmSettlement.setOrderTime(attendance.getTimestamp("createTime"));

                    DmOrderRecord dmExpenseCalendar = new DmOrderRecord();

                    dmExpenseCalendar.setSeq(attendance.getLong("seq"));
                    dmExpenseCalendar.setCreateDate(attendance.getTimestamp("createTime"));
                    dmExpenseCalendar.setCard(attendance.getString("card"));
                    dmExpenseCalendar.setCardNo(attendance.getString("cardNo"));
                    dmExpenseCalendar.setType(attendance.getInteger("type"));
                    dmExpenseCalendar.setPart(attendance.getInteger("part"));
                    dmExpenseCalendar.setTerm(attendance.getInteger("term"));
                    dmExpenseCalendar.setShop(attendance.getInteger("shop"));
                    dmExpenseCalendar.setTermName(attendance.getString("termName"));
                    dmExpenseCalendar.setShopName(attendance.getString("shopName"));
                    dmExpenseCalendar.setAmt(attendance.getDouble("amt"));
                    dmExpenseCalendar.setMoney(String.valueOf(attendance.getDouble("amt")));
                    dmExpenseCalendar.setBalance(attendance.getDouble("balance"));
                    dmExpenseCalendar.setAccount(attendance.getInteger("account"));
                    dmExpenseCalendar.setUserName(attendance.getString("userName"));
                    dmExpenseCalendar.setMob(attendance.getString("mob"));
                    dmExpenseCalendar.setUserCode(attendance.getString("mob"));
                    dmExpenseCalendar.setTel(attendance.getString("userPhone"));
                    dmExpenseCalendar.setCardProfile(attendance.getInteger("card_profile"));
                    /**
                     * 对方未有dept字段 需要手动去数据库中查询  根据卡号查对应的 用户
                     */
                    DmUser dmUser = dmUserService.queryUserByCardId(attendance.getString("card"));
                    dmSettlement.setDmUser(dmUser);
                    dmExpenseCalendar.setDept(dmUser.getDept());
                    String bh = UUID.randomUUID().toString();
                    dmExpenseCalendar.setBh(bh);//UUID 生成 与dm_order_item关联编号
                    dmSettlement.setBh(bh);
                    JSONArray item = attendance.getJSONArray("details");
                    /**
                     * 生成个map来统计数量
                     */
                    Map<String,Integer> map = new HashMap<>();
                    for (int q = 0; q < item.size(); q++) {
                        JSONObject userData = item.getJSONObject(q);
                        String name = userData.getString("name");
                        Integer num = map.get(name) == null ?map.put(name,1):map.put(name, map.get(name)+1);
                    }
                    for (int m = 0; m < item.size(); m++) {
                        JSONObject userData = item.getJSONObject(m);
                        DmOrderItem dmOrderItem = new DmOrderItem();
//                        DmFood dmFood = new DmFood();
//                        dmFood.setId(userData.getLong("pid"));
                        dmOrderItem.setSeq(attendance.getLong("seq")); //序列号  流水号
                        dmOrderItem.setFood(userData.getLong("pid"));//商品id
                        dmOrderItem.setBh(bh);//uuid生成 与 dm_order_record关联编号
                        dmOrderItem.setName(userData.getString("name"));//商品名称
                        dmOrderItem.setPrice(userData.getString("price")); //单价
                        dmOrderItem.setAmt(userData.getDouble("amt"));//商品售价
                        dmOrderItem.setMoney(String.valueOf(userData.getDouble("amt")));//小计
                        dmOrderItem.setPjType("0");
                        dmOrderItem.setNum(map.get(dmOrderItem.getName()));
                         String foodName = dmSettlement.getFoodName() == null?"":","; //结算管理的
                         Integer foodNum = dmSettlement.getFoodNum() == null?0:dmSettlement.getFoodNum();
                         String foodPrice = dmSettlement.getFoodPrice() == null?"":",";
                        BigDecimal totalPrice = dmSettlement.getTotalPrice() == null?BigDecimal.ZERO:dmSettlement.getTotalPrice();
                        dmSettlement.setFoodName(foodName+dmOrderItem.getName());//结算管理 商品名称
                        dmSettlement.setFoodNum(foodNum+dmOrderItem.getNum());//结算管理 商品数量
                        dmSettlement.setTotalPrice(totalPrice.add(BigDecimal.valueOf(Double.valueOf(dmOrderItem.getPrice()))));//结算管理总价格
                        dmSettlement.setFoodPrice(foodPrice+dmOrderItem.getPrice());//结算管理 单价
                        dmOrderItemService.create(dmOrderItem);
                    }
                    JSONArray payment = attendance.getJSONArray("payments");

                    for (int n = 0; n < payment.size(); n++) {
                        JSONObject userData = payment.getJSONObject(n);
                        DmOrderPayment dmOrderPayment = new DmOrderPayment();
                        dmOrderPayment.setBh(bh);
                        dmOrderPayment.setType(userData.getString("type"));
                        dmOrderPayment.setAmt(userData.getDouble("amt"));
                        dmOrderPayment.setBalance(userData.getDouble("balance"));
                        dmOrderPayment.setUid(userData.getString("uid"));
                        dmOrderPaymentService.create(dmOrderPayment);
                    }
                    dmOrderRecordService.create(dmExpenseCalendar);
                    dmSettlementService.create(dmSettlement);
                }else {
                    log.info("dmOrderRecord is not null. seq:"+seq);
                }
            }
        }
    }

    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(url,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(url,data);
            JSONObject dataJSON = newGenerateProcDataJson.getJSONObject("data");//第二层
            JSONArray arr2 = dataJSON.getJSONArray("records");//第三层集合数据
            for (int j = 0;j<arr2.size();j++){//
                JSONObject attendance = arr2.getJSONObject(j);
                Long seq = attendance.getLong("seq");
                List<Map<String, Object>> list = dmOrderRecordRepository.selectOrderRecordBySeq(seq);

                if(list.size() == 0) {
                    DmOrderRecord dmExpenseCalendar = new DmOrderRecord();

                    dmExpenseCalendar.setSeq(attendance.getLong("seq"));
                    dmExpenseCalendar.setCreateDate(attendance.getTimestamp("createTime"));
                    dmExpenseCalendar.setCard(attendance.getString("card"));
                    dmExpenseCalendar.setCardNo(attendance.getString("cardNo"));
                    dmExpenseCalendar.setType(attendance.getInteger("type"));
                    dmExpenseCalendar.setPart(attendance.getInteger("part"));
                    dmExpenseCalendar.setTerm(attendance.getInteger("term"));
                    dmExpenseCalendar.setShop(attendance.getInteger("shop"));
                    dmExpenseCalendar.setTermName(attendance.getString("termName"));
                    dmExpenseCalendar.setShopName(attendance.getString("shopName"));
                    dmExpenseCalendar.setAmt(attendance.getDouble("amt"));
                    dmExpenseCalendar.setMoney(String.valueOf(attendance.getDouble("amt")));
                    dmExpenseCalendar.setBalance(attendance.getDouble("balance"));
                    dmExpenseCalendar.setAccount(attendance.getInteger("account"));
                    dmExpenseCalendar.setUserName(attendance.getString("userName"));
                    dmExpenseCalendar.setMob(attendance.getString("mob"));
                    dmExpenseCalendar.setUserCode(attendance.getString("mob"));
                    dmExpenseCalendar.setTel(attendance.getString("userPhone"));
                    dmExpenseCalendar.setCardProfile(attendance.getInteger("card_profile"));

                    String bh = UUID.randomUUID().toString();
                    dmExpenseCalendar.setBh(bh);//关联编号
                    JSONArray item = attendance.getJSONArray("details");
                    for (int m = 0; m < item.size(); m++) {
                        JSONObject userData = item.getJSONObject(m);
                        DmOrderItem dmOrderItem = new DmOrderItem();
//                        DmFood dmFood = new DmFood();
//                        dmFood.setId(userData.getLong("pid"));
                        dmOrderItem.setSeq(attendance.getLong("seq"));
                        dmOrderItem.setFood(userData.getLong("pid"));
                        dmOrderItem.setBh(bh);
                        dmOrderItem.setCode(userData.getString("pid"));
                        dmOrderItem.setName(userData.getString("name"));
                        dmOrderItem.setPrice(userData.getString("price"));
                        dmOrderItem.setAmt(userData.getDouble("amt"));
                        dmOrderItem.setMoney(String.valueOf(userData.getDouble("amt")));
                        dmOrderItem.setPjType("0");
                        dmOrderItemService.create(dmOrderItem);
                    }
                    JSONArray payment = attendance.getJSONArray("payments");
                    for (int n = 0; n < payment.size(); n++) {
                        JSONObject userData = payment.getJSONObject(n);
                        DmOrderPayment dmOrderPayment = new DmOrderPayment();
                        dmOrderPayment.setBh(bh);
                        dmOrderPayment.setType(userData.getString("type"));
                        dmOrderPayment.setAmt(userData.getDouble("amt"));
                        dmOrderPayment.setBalance(userData.getDouble("balance"));
                        dmOrderPayment.setUid(userData.getString("uid"));
                        dmOrderPaymentService.create(dmOrderPayment);
                    }
                    dmOrderRecordService.create(dmExpenseCalendar);
                }else {
                    System.out.println("dmOrderRecord is null. seq:"+seq);
                }
            }
        }
    }
}
