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.HmBookOrderMapper;
import com.reptileclient.jlifeapp.dao.hm.HmTokenMapper;
import com.reptileclient.jlifeapp.dao.jz.JzBookOrderMapper;
import com.reptileclient.jlifeapp.dto.HmBookOrderDTO;
import com.reptileclient.jlifeapp.entity.hm.HmBookOrder;
import com.reptileclient.jlifeapp.entity.hm.HmToken;
import com.reptileclient.jlifeapp.entity.jz.JzBookOrder;
import com.reptileclient.jlifeapp.filter.Filter;
import com.reptileclient.jlifeapp.service.HmBookOrderService;
import com.reptileclient.jlifeapp.service.HmDownHistoryService;
import com.reptileclient.jlifeapp.service.RetryService;
import com.reptileclient.jlifeapp.util.JsonUtil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * @author fuxubing
 */
@Service
public class HmBookOrderServiceImpl implements HmBookOrderService {
    private static final Logger logger = LoggerFactory.getLogger(HmBookOrderServiceImpl.class);
    @Resource
    private HmBookOrderMapper hmBookOrderMapper;
    @Resource
    private Filter filter;
    @Resource
    private HmDownHistoryService hmDownHistoryService;
    @Resource
    private HmTokenMapper hmTokenMapper;
    @Resource
    private RetryService retryService;
    @Resource
    private JzBookOrderMapper jzBookOrderMapper;

    @Override
    public int addBookOrderList() {

        HmToken hmToken = hmTokenMapper.selectAll();
        String token = hmToken.getToken();
        int row = 0;
        //增量日期范围
        DateTime startTime = DateUtil.lastMonth();
        DateTime endTime = new DateTime();

        //获取数据库最新一条盒马数据
        HmBookOrder hmBookOrder = hmBookOrderMapper.selectNewOne(null);
        if (null != hmBookOrder) {
            hmBookOrderMapper.deleteByBetWeenTime(startTime, endTime);
            jzBookOrderMapper.deleteByBetWeenTime(startTime, endTime);
        }
        for (int i = 0; i < 2; i++) {
            if (0 != i) {
                hmBookOrder = hmBookOrderMapper.selectNewOne("鲸致生活聚福店");
                if (null != hmBookOrder) {
                    hmBookOrderMapper.deleteByCreateTime(hmBookOrder.getCreateTime(), "鲸致生活聚福店");
                    jzBookOrderMapper.deleteByCreateTime(hmBookOrder.getCreateTime(), "鲸致生活聚福店");
                }
                token = hmToken.getSubToken();
            }
            int totalPage;
            int pageIndex = JlifeConstant.PAGE_INDEX;
            int pageSize = JlifeConstant.PAGE_SIZE;
            do {
                HmBookOrderDTO hmBookOrderDTO = new HmBookOrderDTO();
                hmBookOrderDTO.setPageSize(pageSize);
                hmBookOrderDTO.setPageIndex(pageIndex);
                //hmBookOrderDTO.setBookOrderNo("4351068");
                if (null != hmBookOrder) {
                    hmBookOrderDTO.setStartTime(DateUtil.formatDateTime(startTime));
                    hmBookOrderDTO.setExpireTime(DateUtil.formatDateTime(endTime));
                }
                String jsonString = JSONObject.toJSONString(hmBookOrderDTO);
                //JSONObject jsonObject = HttpUtil.requestPost(token, jsonString, JlifeConstant.BOOK_ORDER_URL);

                Map<String, Object> request = retryService.requestPost(token, jsonString, JlifeConstant.BOOK_ORDER_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)) {
                        return 0;
                    }
                    String filter = this.filter.filter(items.toJSONString());
                    //String aliases = EmojiParser.removeAllEmojis(items.toJSONString());
                    List<HmBookOrder> hmBookOrders = JSONObject.parseArray(filter, HmBookOrder.class);

                    row += hmBookOrderMapper.insertByBatch(hmBookOrders);

                    //同步插入到jz_book_order表
                    jzBookOrderMapper.insertHmByBatch(hmBookOrders);

                    //成功
                    hmDownHistoryService.insertDownLog("服务单",
                            JlifeConstant.BOOK_ORDER_URL, jsonString, hmBookOrderDTO.getStartTime(), null, 0);
                    pageIndex++;
                    //同步插入客户到customer_client
                    //customerClientMapper.insertClientByBatch(hmBookOrders);
                } else {
                    //失败
                    hmDownHistoryService.insertDownLog("服务单",
                            JlifeConstant.BOOK_ORDER_URL, jsonString, hmBookOrderDTO.getStartTime(), null, 1);
                    return 0;
                }
            }
            while (pageIndex <= totalPage + 1);
        }
        return row;
    }

    @Override
    public int syncHmBookOrderByPhone(String phone) {
        HmToken hmToken = hmTokenMapper.selectAll();
        String token = hmToken.getToken();
        hmBookOrderMapper.deleteByPhone(phone);
        int row = 0;

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

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

            do {
                HmBookOrderDTO hmBookOrderDTO = new HmBookOrderDTO();
                hmBookOrderDTO.setPageSize(pageSize);
                hmBookOrderDTO.setPageIndex(pageIndex);
                hmBookOrderDTO.setPhone(phone);

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

                Map<String, Object> request = retryService.requestPost(token, jsonString, JlifeConstant.BOOK_ORDER_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.removeAllEmojis(items.toJSONString());
                    List<HmBookOrder> hmBookOrders = JSONObject.parseArray(filter, HmBookOrder.class);

                    row += hmBookOrderMapper.insertByBatch(hmBookOrders);

                    //同步插入到jz_book_order表
                    jzBookOrderMapper.insertHmByBatch(hmBookOrders);

                    //成功
                    hmDownHistoryService.insertDownLog("服务单",
                            JlifeConstant.BOOK_ORDER_URL, jsonString, hmBookOrderDTO.getStartTime(), null, 0);
                    pageIndex++;
                } else {
                    //失败
                    hmDownHistoryService.insertDownLog("服务单",
                            JlifeConstant.BOOK_ORDER_URL, jsonString, hmBookOrderDTO.getStartTime(), null, 1);
                    return 0;
                }
            }
            while (pageIndex <= totalPage + 1);
        }
        return row;

    }

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

    @Override
    public HmBookOrder selectNewOne(String shopName) {
        return hmBookOrderMapper.selectNewOne(shopName);
    }

    @Override
    public int insertClientByBatch(String createTime) {
        return hmBookOrderMapper.insertClientByBatch(createTime);
    }

    @Override
    public int updateBookOrder() {
        HmToken hmToken = hmTokenMapper.selectAll();
        String token = hmToken.getToken();
        //获取数据库最新一条盒马数据
        HmBookOrder hmBookOrder = hmBookOrderMapper.selectNewOne(null);

        if (hmBookOrder == null) {
            return 0;
        }
        DateTime startTime = DateUtil.lastMonth();
        DateTime endTime = new DateTime();
        hmBookOrderMapper.deleteByBetWeenTime(startTime, endTime);

        int row = 0;

        for (int i = 0; i < 2; i++) {
            if (0 != i) {
                token = hmToken.getSubToken();
            }
            int totalPage;
            int pageIndex = JlifeConstant.PAGE_INDEX;
            int pageSize = JlifeConstant.PAGE_SIZE;

            do {
                HmBookOrderDTO hmBookOrderDTO = new HmBookOrderDTO();
                hmBookOrderDTO.setPageSize(pageSize);
                hmBookOrderDTO.setPageIndex(pageIndex);
                hmBookOrderDTO.setStartTime(DateUtil.formatDateTime(startTime));
                hmBookOrderDTO.setExpireTime(DateUtil.formatDateTime(endTime));
                String jsonString = JSONObject.toJSONString(hmBookOrderDTO);
                //JSONObject jsonObject = HttpUtil.requestPost(token, jsonString, JlifeConstant.BOOK_ORDER_URL);

                Map<String, Object> request = retryService.requestPost(token, jsonString, JlifeConstant.BOOK_ORDER_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.removeAllEmojis(items.toJSONString());
                    List<HmBookOrder> hmBookOrders = JSONObject.parseArray(filter, HmBookOrder.class);

                    row += hmBookOrderMapper.insertByBatch(hmBookOrders);

                    //同步插入到jz_book_order表
                    jzBookOrderMapper.insertHmByBatch(hmBookOrders);

                    //成功
                    hmDownHistoryService.insertDownLog("服务单",
                            JlifeConstant.BOOK_ORDER_URL, jsonString, hmBookOrderDTO.getStartTime(), null, 0);
                    pageIndex++;
                    //同步插入客户到customer_client
                    //customerClientMapper.insertClientByBatch(hmBookOrders);
                } else {
                    //失败
                    hmDownHistoryService.insertDownLog("服务单",
                            JlifeConstant.BOOK_ORDER_URL, jsonString, hmBookOrderDTO.getStartTime(), null, 1);
                    return 0;
                }
            }
            while (pageIndex <= totalPage + 1);
        }

        return row;
    }

    @Override
    public int deleteByCreateTime(String createTime, String shopName) {
        return hmBookOrderMapper.deleteByCreateTime(createTime, shopName);
    }

    @Override
    public List<Map<String, Object>> match() {
        return hmBookOrderMapper.selectMatchList();
    }

    @Override
    public int updateByBookOrderNo(String bookOrderNo, String stationCode) {
        HmToken hmToken = hmTokenMapper.selectAll();
        String token = hmToken.getToken();
        if ("147001".equals(stationCode) || StringUtils.isBlank(stationCode)) {
            token = hmToken.getSubToken();
        }

        HmBookOrderDTO hmBookOrderDTO = new HmBookOrderDTO();
        hmBookOrderDTO.setBookOrderNo(bookOrderNo);
        String jsonString = JSONObject.toJSONString(hmBookOrderDTO);
        //JSONObject jsonObject = HttpUtil.requestPost(token, jsonString, JlifeConstant.BOOK_ORDER_URL);

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

        if ("true".equals(request.get("success").toString())) {
            JSONObject data = (JSONObject) JSON.toJSON(request.get("data"));

            JSONArray items = data.getJSONArray("list");
            if (CollectionUtils.isEmpty(items)) {
                logger.info("数据为空了。。。。。" + JsonUtil.getJson(request));
                return 0;
            }

            List<HmBookOrder> hmBookOrders = JSONObject.parseArray(items.toJSONString(), HmBookOrder.class);

            hmBookOrders.forEach(item -> {
                JzBookOrder jzBookOrder = new JzBookOrder();
                BeanUtils.copyProperties(item, jzBookOrder);

                hmBookOrderMapper.deleteByBookOrderNo(bookOrderNo);
                hmBookOrderMapper.insertSelective(item);
                //同步插入到jz_book_order表
                jzBookOrderMapper.deleteByBookOrderNo(bookOrderNo);
                jzBookOrderMapper.insertSelective(jzBookOrder);
            });
            //成功
            hmDownHistoryService.insertDownLog("服务单",
                    JlifeConstant.BOOK_ORDER_URL, jsonString, hmBookOrderDTO.getStartTime(), null, 0);
            //同步插入客户到customer_client
            //customerClientMapper.insertClientByBatch(hmBookOrders);

            return 1;
        } else {
            //失败
            hmDownHistoryService.insertDownLog("服务单",
                    JlifeConstant.BOOK_ORDER_URL, jsonString, hmBookOrderDTO.getStartTime(), null, 1);
            return 0;
        }
    }
}
