package com.reptileclient.jlifeapp.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.reptileclient.jlifeapp.config.SendSms;
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.CustomerClientMapper;
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.CustomerClient;
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.HmPhoneDecryptService;
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.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author fuxubing
 */
@Slf4j
@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;

	@Resource
	private CustomerClientMapper customerClientMapper;

	@Autowired
	private HmPhoneDecryptService phoneDecryptService;

	/**
	 * 服务工单创建时间
	 * @return
	 */
	//@Async
	@Override
	public Integer addBookOrderList() throws InterruptedException {

		HmToken hmToken = hmTokenMapper.selectAll();
		String token = hmToken.getToken();
		// 增量日期范围
		DateTime startTime = DateUtil.offsetDay(new DateTime(), -2);
		//DateTime startTime = DateUtil.parse("2022-02-01","yyyy-MM-dd");
		DateTime endTime = new DateTime();

		Integer  rowCount = 0;
		int totalPage = -1;
		int pageIndex = JlifeConstant.PAGE_INDEX;
		int pageSize = JlifeConstant.PAGE_SIZE;
		do {
			//随机等待几秒
			int waitTime = new Random().nextInt(10);
			Thread.sleep((long) waitTime * 1000);

			HmBookOrderDTO hmBookOrderDTO = new HmBookOrderDTO();
			hmBookOrderDTO.setPageSize(pageSize + 10);//优化分页数据丢失
			hmBookOrderDTO.setPageIndex(pageIndex);
			hmBookOrderDTO.setStatusList("0,1");
			// 预约时间查询
			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);

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

				if (request!=null&&"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());
					List<HmBookOrder> hmBookOrders = JSONObject.parseArray(filter, HmBookOrder.class);
					for (HmBookOrder bookOrder : hmBookOrders) {
						HmBookOrder _bo = hmBookOrderMapper.selectByBookOrderNo(bookOrder.getBookOrderNo().toString());
						if (_bo != null) {
							long bid = _bo.getId();
							BeanUtils.copyProperties(bookOrder, _bo);
							_bo.setId(bid);
							hmBookOrderMapper.updateByPrimaryKey(_bo);
						} else
							rowCount += hmBookOrderMapper.insert(bookOrder);
					}

					// 成功
					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;
				}
			} catch (Exception e) {
//					SendSms.toSendMs();
				e.printStackTrace();
				pageIndex++; //如果出现异常，也要继续往下走，避免死循环
			}

		} while (pageIndex <= totalPage);//pageIndex <= totalPage + 1

		return rowCount;
	}

	/***
	 * 服务工单预约时间
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	//@Async
	@Override
	public int syncUpdateByBookTime(DateTime startTime, DateTime endTime) throws InterruptedException {
		HmToken hmToken = hmTokenMapper.selectAll();
		String token = hmToken.getToken();
		int rowCount = 0;

		// 获取数据库最新一条盒马数据
		//hmBookOrderMapper.deleteByBookTime(startTime, endTime, null);


		int totalPage = -1;
		int pageIndex = JlifeConstant.PAGE_INDEX;
		int pageSize = JlifeConstant.PAGE_SIZE;
		do {
			//随机等待几秒
			int waitTime = new Random().nextInt(10);
			Thread.sleep((long) waitTime * 1000);

			HmBookOrderDTO hmBookOrderDTO = new HmBookOrderDTO();
			hmBookOrderDTO.setPageSize(pageSize + 10);//优化分页数据丢失
			hmBookOrderDTO.setPageIndex(pageIndex);
			hmBookOrderDTO.setStatusList("2,4,9");//更新接口 只取服务已提供,已取消,服务已完成的数据
			// 预约时间查询
			hmBookOrderDTO.setBeginTime(DateUtil.formatDateTime(startTime));
			hmBookOrderDTO.setEndTime(DateUtil.formatDateTime(endTime));

			String jsonString = JSONObject.toJSONString(hmBookOrderDTO);

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

				if (request!=null&&"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);
					for (HmBookOrder bookOrder : hmBookOrders) {
						HmBookOrder _bo = hmBookOrderMapper.selectByBookOrderNo(bookOrder.getBookOrderNo().toString());
						if (_bo != null) {
							long bid = _bo.getId();
							BeanUtils.copyProperties(bookOrder, _bo);
							_bo.setId(bid);
							hmBookOrderMapper.updateByPrimaryKey(_bo);
						} else
							rowCount += hmBookOrderMapper.insert(bookOrder);
					}

					// 成功
					hmDownHistoryService.insertDownLog("服务单", JlifeConstant.BOOK_ORDER_URL, jsonString,
							hmBookOrderDTO.getStartTime(), null, 0);
					pageIndex++;
					// 同步插入客户到customer_client
					// customerClientMapper.insertClientByBatch(hmBookOrders);

				} else {
					log.error(request.toString());
					// 失败
					hmDownHistoryService.insertDownLog("服务单", JlifeConstant.BOOK_ORDER_URL, jsonString,
							hmBookOrderDTO.getStartTime(), null, 1);
					return 0;
				}
			} catch (Exception e) {
//					SendSms.toSendMs();
				e.printStackTrace();
				pageIndex++; //如果出现异常，也要继续往下走，避免死循环
			}

		} while (pageIndex <= totalPage);//pageIndex <= totalPage + 1

		return rowCount;
	}

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

		for (int i = 0; i < 1; 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;
					}

					try {
						String filter = this.filter.filter(items.toJSONString());
						// String aliases = EmojiParser.removeAllEmojis(items.toJSONString());
						List<HmBookOrder> hmBookOrders = JSONObject.parseArray(filter, HmBookOrder.class);

						List<String> bookOrderNoList = new ArrayList<String>();
						hmBookOrders.forEach(e -> {
							e.setCustomerId(cusclient.getId().intValue());
							e.setPhone(phone);
							bookOrderNoList.add(e.getBookOrderNo().toString());
						});

						row += hmBookOrderMapper.insertByBatch(hmBookOrders);

						//查询存在的，更新，不存在的insert，
						//目前有重复的，按条件删除，再新增

						// 同步插入到jz_book_order表
						jzBookOrderMapper.deleteByPhoneBookOrderNo(phone, String.join(",", bookOrderNoList));
						jzBookOrderMapper.insertHmByBatch(hmBookOrders);

						hmDownHistoryService.insertDownLog("服务单", JlifeConstant.BOOK_ORDER_URL, jsonString,
								hmBookOrderDTO.getStartTime(), null, 0);
						pageIndex++;
					} catch (Exception e) {
						e.printStackTrace();
					}

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

	}

	@Override
	public int deleteDistinctData(String 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 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) || "null".equals(stationCode)) {
			token = hmToken.getSubToken();
			return 1;
		}

		HmBookOrderDTO hmBookOrderDTO = new HmBookOrderDTO();
		hmBookOrderDTO.setPageSize(1);
		hmBookOrderDTO.setPageIndex(50);
		hmBookOrderDTO.setBookOrderNo(bookOrderNo);

		String jsonString = JSONObject.toJSONString(hmBookOrderDTO);

		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);
				if (item.getPhone().contains("**")) {
					String phone = phoneDecryptService.getPhoneByTradeNo("phone", item.getBookOrderNo().toString(), "BOOK_ORDER");
					if (phone != null)
						item.setPhone(phone);
				}


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

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