package com.reptileclient.jlifeapp.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.reptileclient.jlifeapp.constant.JlifeConstant;
import com.reptileclient.jlifeapp.dao.hm.HmBookTradeOrderMapper;
import com.reptileclient.jlifeapp.dao.hm.HmTokenMapper;
import com.reptileclient.jlifeapp.dto.HmBookTradeOrderDTO;
import com.reptileclient.jlifeapp.entity.hm.HmBookTradeOrder;
import com.reptileclient.jlifeapp.entity.hm.HmToken;
import com.reptileclient.jlifeapp.filter.Filter;
import com.reptileclient.jlifeapp.service.HmBookTradeOrderService;
import com.reptileclient.jlifeapp.service.HmDownHistoryService;
import com.reptileclient.jlifeapp.service.RetryService;
import com.reptileclient.jlifeapp.util.HttpUtil;
import com.reptileclient.jlifeapp.util.JsonUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author fuxubing
 */
@Service
public class HmBookTradeOrderServiceImpl implements HmBookTradeOrderService {
    private static final Logger logger = LoggerFactory.getLogger(HmBookTradeOrderServiceImpl.class);
    @Resource
    private HmBookTradeOrderMapper hmBookTradeOrderMapper;
    @Resource
    private Filter filter;
    @Resource
    private HmTokenMapper hmTokenMapper;
    @Resource
    private HmDownHistoryService hmDownHistoryService;
    @Resource
    private RetryService retryService;

    @Override
    public int addHmBookTradeList() {
        HmToken hmToken = hmTokenMapper.selectAll();
        String token = hmToken.getToken();
        //获取数据库最新一条盒马数据
        HmBookTradeOrder hmBookTradeOrder = hmBookTradeOrderMapper.selectNewOne(null);
        String date = DateUtil.formatDate(new Date());
        if (hmBookTradeOrder != null) {
            hmBookTradeOrderMapper.deleteByStartTime(date);
        }

        int row = 0;
        for (int i = 0; i < 2; i++) {
            if (0 != i) {
                hmBookTradeOrder = hmBookTradeOrderMapper.selectNewOne("147001");
                token = hmToken.getSubToken();
            }

            int totalPage;
            int pageIndex = JlifeConstant.PAGE_INDEX;
            int pageSize = JlifeConstant.PAGE_SIZE;

            do {
                HmBookTradeOrderDTO hmBookTradeOrderDTO = new HmBookTradeOrderDTO();
                hmBookTradeOrderDTO.setPageSize(pageSize);
                hmBookTradeOrderDTO.setPageIndex(pageIndex);
                if (0 != i) {
                    hmBookTradeOrderDTO.setStationCode("147001");
                }
//            hmBookTradeOrderDTO.setBeginTime("2020-12-14 14:06:06");
//            hmBookTradeOrderDTO.setEndTime("2020-12-14 23:59:59");

                if (null != hmBookTradeOrder) {
                    hmBookTradeOrderDTO.setBeginTime(date);
                }
                String jsonString = JSONObject.toJSONString(hmBookTradeOrderDTO);
                //JSONObject jsonObject = HttpUtil.requestPost(token, jsonString, JlifeConstant.BOOK_TRADE_URL);

                Map<String, Object> request = retryService.requestPost(token, jsonString, JlifeConstant.BOOK_TRADE_URL);

                if ("true".equals(request.get("success").toString())) {
                    JSONObject data = (JSONObject) JSON.toJSON(request.get("data"));
                    double total = Double.parseDouble(String.valueOf(data.get("total")));
                    totalPage = (int) total / pageSize;
                    logger.info("totalPage:{}", totalPage);
                    JSONArray items = data.getJSONArray("list");
                    if (CollectionUtils.isEmpty(items)) {
                    	logger.info("数据为空了。。。。。"+JsonUtil.getJson(request));
                        return 0;
                    }
                    String filter = this.filter.filter(items.toJSONString());
                    //String aliases = EmojiParser.parseToAliases(items.toJSONString());
                    List<HmBookTradeOrder> hmBookTradeOrders = JSONObject.parseArray(filter, HmBookTradeOrder.class);
                    row += hmBookTradeOrderMapper.insertByBatch(hmBookTradeOrders);

                    //成功
                    hmDownHistoryService.insertDownLog("技师作业单",
                            JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 0);
                    pageIndex++;
                } else {
                    //失败
                    hmDownHistoryService.insertDownLog("技师作业单",
                            JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 1);
                    return 0;
                }
            } while (pageIndex <= totalPage + 1);

        }
        return row;
    }

    @Override
    public int syncHmBookTradeOrderByPhone(String phone) {
        HmToken hmToken = hmTokenMapper.selectAll();
        String token = hmToken.getToken();
        hmBookTradeOrderMapper.deleteByUserPhone(phone);
        int row = 0;
        for (int i = 0; i < 2; i++) {
            if (i != 0) {
                token = hmToken.getSubToken();
            }

            int totalPage;
            int pageIndex = JlifeConstant.PAGE_INDEX;
            int pageSize = JlifeConstant.PAGE_SIZE;

            do {
                HmBookTradeOrderDTO hmBookTradeOrderDTO = new HmBookTradeOrderDTO();
                hmBookTradeOrderDTO.setPageSize(pageSize);
                hmBookTradeOrderDTO.setPageIndex(pageIndex);
                hmBookTradeOrderDTO.setUserPhone(phone);
                if (i != 0) {
                    hmBookTradeOrderDTO.setStationCode("147001");
                }

                String jsonString = JSONObject.toJSONString(hmBookTradeOrderDTO);
                //JSONObject jsonObject = HttpUtil.requestPost(token, jsonString, JlifeConstant.BOOK_TRADE_URL);

                Map<String, Object> request = HttpUtil.request(token, jsonString, JlifeConstant.BOOK_TRADE_URL);

                if ("true".equals(request.get("success").toString())) {
                    JSONObject data = (JSONObject) JSON.toJSON(request.get("data"));
                    double total = Double.parseDouble(String.valueOf(data.get("total")));
                    totalPage = (int) total / pageSize;
                    logger.info("totalPage:{}", totalPage);
                    JSONArray items = data.getJSONArray("list");
                    if (CollectionUtils.isEmpty(items)) {
                    	logger.info("数据为空了。。。。。"+JsonUtil.getJson(request));
                        return 0;
                    }
                    String filter = this.filter.filter(items.toJSONString());
                    //String aliases = EmojiParser.parseToAliases(items.toJSONString());
                    List<HmBookTradeOrder> hmBookTradeOrders = JSONObject.parseArray(filter, HmBookTradeOrder.class);
                    row += hmBookTradeOrderMapper.insertByBatch(hmBookTradeOrders);

                    //成功
                    hmDownHistoryService.insertDownLog("技师作业单",
                            JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 0);
                    pageIndex++;
                } else {
                    //失败
                    hmDownHistoryService.insertDownLog("技师作业单",
                            JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 1);
                    return 0;
                }
            } while (pageIndex <= totalPage + 1);
        }
        return row;
    }

    @Override
    public int deleteDistinctData(DateTime dateTime) {
        return hmBookTradeOrderMapper.deleteDistinctData(dateTime);
    }

    @Override
    public HmBookTradeOrder selectNewOne() {
        return hmBookTradeOrderMapper.selectNewOne(null);
    }

    @Override
    public int updateHmBookTradeList() throws InterruptedException {
        HmToken hmToken = hmTokenMapper.selectAll();
        String token = hmToken.getToken();
        //获取数据库最新一条盒马数据
        HmBookTradeOrder hmBookTradeOrder = hmBookTradeOrderMapper.selectNewOne(null);

        if (hmBookTradeOrder == null) {
            return 0;
        }

        DateTime startTime = DateUtil.lastMonth();
        DateTime endTime = DateUtil.nextMonth();
        hmBookTradeOrderMapper.deleteByBetWeenTime(startTime, endTime);

        int row = 0;
        for (int i = 0; i < 2; i++) {
            if (i != 0) {
                token = hmToken.getSubToken();
            }

            int totalPage;
            int pageIndex = JlifeConstant.PAGE_INDEX;
            int pageSize = JlifeConstant.PAGE_SIZE;

            do {
                HmBookTradeOrderDTO hmBookTradeOrderDTO = new HmBookTradeOrderDTO();
                hmBookTradeOrderDTO.setPageSize(pageSize);
                hmBookTradeOrderDTO.setPageIndex(pageIndex);
                hmBookTradeOrderDTO.setBeginTime(DateUtil.formatDateTime(startTime));
                hmBookTradeOrderDTO.setEndTime(DateUtil.formatDateTime(endTime));
                if (i != 0) {
                    hmBookTradeOrderDTO.setStationCode("147001");
                }

                String jsonString = JSONObject.toJSONString(hmBookTradeOrderDTO);
                //JSONObject jsonObject = HttpUtil.requestPost(token, jsonString, JlifeConstant.BOOK_TRADE_URL);

                Thread.sleep(3000);
                Map<String, Object> request = retryService.requestPost(token, jsonString, JlifeConstant.BOOK_TRADE_URL);

                if ("true".equals(request.get("success").toString())) {
                    JSONObject data = (JSONObject) JSON.toJSON(request.get("data"));
                    double total = Double.parseDouble(String.valueOf(data.get("total")));
                    totalPage = (int) total / pageSize;
                    logger.info("totalPage:{}", totalPage);
                    JSONArray items = data.getJSONArray("list");
                    if (CollectionUtils.isEmpty(items)) {
                    	logger.info("数据为空了。。。。。"+JsonUtil.getJson(request));
                        return 0;
                    }
                    String filter = this.filter.filter(items.toJSONString());
                    //String aliases = EmojiParser.parseToAliases(items.toJSONString());
                    List<HmBookTradeOrder> hmBookTradeOrders = JSONObject.parseArray(filter, HmBookTradeOrder.class);
                    row += hmBookTradeOrderMapper.insertByBatch(hmBookTradeOrders);

                    //成功
                    hmDownHistoryService.insertDownLog("技师作业单",
                            JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 0);
                    pageIndex++;
                } else {
                    //失败
                    hmDownHistoryService.insertDownLog("技师作业单",
                            JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 1);
                    return 0;
                }
            } while (pageIndex <= totalPage + 1);
        }
        return row;
    }
}
