package com.bweb.controller;

import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.channel.gas.newlink.NewLinkRequestService;
import com.hfkj.channel.gas.shell.CqShellPetroleumRequestService;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.pay.util.SignatureUtil;
import com.hfkj.common.utils.HttpUtils;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.common.utils.MD5Util;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.MqttProviderConfig;
import com.hfkj.dao.SecRegionMapper;
import com.hfkj.device.sanmisen.PrinterTemplate;
import com.hfkj.entity.*;
import com.hfkj.model.GasClassGroupTaskDataCount;
import com.hfkj.model.ResponseData;
import com.hfkj.pay.HuiPayService;
import com.hfkj.service.BsDeviceService;
import com.hfkj.service.CommonService;
import com.hfkj.service.gas.BsGasClassGroupTaskService;
import com.hfkj.service.gas.BsGasOrderService;
import com.hfkj.service.gas.BsGasService;
import com.hfkj.service.merchant.BsMerchantService;
import com.hfkj.service.order.BsOrderSettleService;
import com.hfkj.service.sec.SecUserLoginLogService;
import com.hfkj.service.sec.SecUserService;
import com.hfkj.sysenum.SecUserObjectTypeEnum;
import com.hfkj.sysenum.SecUserStatusEnum;
import com.hfkj.sysenum.gas.GasOilPriceStatusEnum;
import com.hfkj.sysenum.merchant.MerchantSourceTypeEnum;
import com.hfkj.sysenum.merchant.MerchantStatusEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value="/test")
@Api(value="测试")
public class TestController {
	Logger log = LoggerFactory.getLogger(TestController.class);

	@Resource
	private SecUserService secUserService;
	@Resource
	private SecUserLoginLogService secUserLoginLogService;

	@Resource
	private BsDeviceService deviceService;
	@Resource
	private BsGasOrderService gasOrderService;
	@Resource
	private BsMerchantService merchantService;
	@Resource
	private BsGasService gasService;
	@Resource
	private CommonService commonService;

	@RequestMapping(value="testAgentNotify",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "测试api推送")
	public ResponseData testAgentNotify(@RequestBody JSONObject body) {
		try {

			System.out.println("收到参数：" + body.toJSONString());
			return ResponseMsgUtil.success("");

		} catch (Exception e) {
			log.error("error!",e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value="testApiPush",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "测试api推送")
	public ResponseData testApiPush() {
		try {
			// 最新全量加油站数据
			List<Object> gasDataList = new ArrayList<>();
			// 初始化页数
			Integer totalPageNum = 3;
			for (int pageIndex = 1; pageIndex <= totalPageNum;pageIndex++) {
				Map<String,Object> paramMap = new HashMap<>();
				paramMap.put("appId", "hffeab7fdb44d4f1");
				paramMap.put("pageNum", pageIndex);
				paramMap.put("pageSize", 100);
				paramMap.put("sign", SignatureUtil.createSign(paramMap, "3a9b2772b9a2d319a9b18e55fa30246d"));
				// 查询油站
				JSONObject object = HttpsUtils.doPost("https://oil.dctpay.com/openapi/gas/queryList", JSON.toJSONString(paramMap));
				// 总页数
				totalPageNum = object.getJSONObject("return_data").getInteger("totalPageNum");
				// 加入全量数据集合
				gasDataList.addAll(object.getJSONObject("return_data").getJSONArray("gasInfoList"));
			}
			return ResponseMsgUtil.success(gasDataList);
		/*	Map<String,Object> param = new HashMap<>();
			param.put("appId", "hf7356c71fb97ab0");
			param.put("gasNo", "10019");
			param.put("gunNo", "4");
			param.put("oilNo", "95");
			param.put("orderNo", System.currentTimeMillis());
			param.put("refuelingAmount", "100");
			param.put("userPhone", "17726395120");
			param.put("sign", "string");
			return ResponseMsgUtil.success(HttpsUtils.doPost("http://localhost:9805/openapi/gasOrder/push", JSONObject.toJSONString(param)));
*/
		} catch (Exception e) {
			log.error("error!",e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value="test",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "加油站全量缓存")
	public ResponseData test() {
		try {
			List<BsMerchant> merchantList = merchantService.getMerchantList(new HashMap<>());
			for (BsMerchant merchant : merchantList) {
				// 缓存
				gasService.getGasDetail(merchant.getMerNo());
			}
			return ResponseMsgUtil.success("");

		} catch (Exception e) {
			log.error("error!",e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value="testDevice",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "testDevice")
	public ResponseData testDevice(@RequestParam(name = "deviceNo", required = true) String deviceNo) {
		try {
			BsGasOrder gasOrder = JSONObject.parseObject("{\"abnormal\":false,\"actualPayPrice\":452.83,\"agentId\":13,\"agentName\":\"胡某\",\"agentStaffId\":190,\"agentStaffName\":\"袁业务员\",\"channelType\":1,\"createTime\":1728460158000,\"deductionCouponPrice\":0.00,\"deductionOilPrice\":47.17,\"gasAgentSettlePrice\":452.83,\"gasClassGroupId\":26,\"gasClassGroupName\":\"中班\",\"gasClassGroupTaskId\":188,\"gasDiscount\":0.9684,\"gasGunNo\":\"1\",\"gasLitersPreferences\":0.80,\"gasOilLiters\":58.96,\"gasOilNo\":\"92\",\"gasOilSubsidy\":0.00,\"gasOilType\":1,\"gasPriceGun\":8.48,\"gasPriceOfficial\":8.48,\"gasPricePlatform\":7.68,\"gasPricePreferences\":7.68,\"gasPriceVip\":7.93,\"gasRefuelPrice\":500.00,\"gasServiceFeePrice\":0.00,\"gasServiceFeeRate\":0.00,\"gasSettlePrice\":467.57,\"id\":25691,\"merAddress\":\"四川省南充市顺庆区南充北站\",\"merId\":19,\"merName\":\"R的油站\",\"merNo\":\"10019\",\"orderChildNo\":\"4301992\",\"orderNo\":\"241009154917861199\",\"payChannelOrderNo\":\"83620241009737898443\",\"payIntegral\":0,\"paySerialNo\":\"4200002424202410091052109539\",\"payTime\":1728460168000,\"payType\":2,\"payablePrice\":452.83,\"receiptStatus\":0,\"refundRemarks\":\"\",\"refundTime\":1728460376000,\"status\":4,\"totalDeductionPrice\":47.17}",BsGasOrder.class);

			Map<String, Object> receiptMap = new HashMap<>();

			JSONObject param = new JSONObject();
			param.put("id", System.currentTimeMillis());
			param.put("type", 5);
			param.put("vType", 0);
			param.put("vMessage", "嗨加油新订单，加油金额"+gasOrder.getGasRefuelPrice()+"元，请注意查收");
			param.put("contents", PrinterTemplate.oilReceipt(1, gasOrder , receiptMap, false));

			mqttProviderConfig.publish(1, false, deviceNo+"/submsg", param.toJSONString());

			return ResponseMsgUtil.success(param.toJSONString());

		} catch (Exception e) {
			log.error("error!",e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value="gasSyncPayment",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "壳牌推送")
	public ResponseData gasSyncPayment() {
		try {

			JSONObject response = HttpsUtils.doGet("https://oil.dctpay.com/crest/gasOrder/queryOilOrder?orderNo=240804110524374697");

			BsGasOrder gasOrder = JSONObject.parseObject(response.getJSONObject("return_data").toJSONString(), BsGasOrder.class);

			// 推送加好油【重庆壳牌】
			JSONObject object = CqShellPetroleumRequestService.gasSyncPayment("CT"+gasOrder.getOrderNo(),
					gasOrder.getMerNo(),
					gasOrder.getPayTime(),
					gasOrder.getGasRefuelPrice(),
					gasOrder.getGasOilNo(),
					gasOrder.getGasGunNo(),
					gasOrder.getPayablePrice(),
					gasOrder.getTotalDeductionPrice()
			);
			return ResponseMsgUtil.success(object);

		} catch (Exception e) {
			log.error("error!",e);
			return ResponseMsgUtil.exception(e);
		}
	}


	@RequestMapping(value="printOrder",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "壳牌推送")
	public ResponseData printOrder(@RequestParam(name = "orderNo", required = true) String orderNo) {
		try {
			// 查询加油订单
			BsGasOrder gasOrder = gasOrderService.getDetailByOrderNo(orderNo);
			if (gasOrder == null) {
				throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的加油的订单");
			}
			deviceService.printGasOrder(gasOrder.getMerId(), gasOrder, true);
			return ResponseMsgUtil.success("");

		} catch (Exception e) {
			log.error("error!",e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@Resource
	private MqttProviderConfig mqttProviderConfig;
	
	@Resource
	private BsGasClassGroupTaskService gasClassGroupTaskService;
	@RequestMapping(value="oilReceipt",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "壳牌推送")
	public ResponseData oilReceipt() {
		try {
			JSONObject param = new JSONObject();
			param.put("id", System.currentTimeMillis());
			param.put("type", 5);
			//param.put("vType", 0);
			//param.put("vMessage", "嗨加油新订单，加油金额"+gasOrder.getGasRefuelPrice()+"元，请注意查收");

			// param.put("contents", PrinterTemplate.oilReceipt(1, gasOrderService.getDetailByOrderNo("240726140647722244"), new HashMap<>(), false));
			BsGasClassGroupTask groupTask = gasClassGroupTaskService.getDetailById(187L);
			GasClassGroupTaskDataCount dataCount = gasClassGroupTaskService.countGroupTaskData(groupTask.getMerId(), groupTask.getClassNum(), groupTask.getId(), groupTask.getStatus(), groupTask.getStartTime(), groupTask.getEndTime());

			param.put("contents", PrinterTemplate.classGroupCountTemp(dataCount ,true));
			mqttProviderConfig.publish(1, false, "SW242300044/submsg", param.toJSONString());

			return ResponseMsgUtil.success("");

		} catch (Exception e) {
			log.error("error!",e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@Resource
	private BsOrderSettleService orderSettleService;
	@RequestMapping(value="separate",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "分账")
	public ResponseData separate(@RequestParam(name = "orderNo", required = true) String orderNo) {
		try {
			//orderSettleService.separate(orderSettleService.getData("250731141540888578"));
			orderSettleService.separate(orderSettleService.getData(orderNo));

			//return ResponseMsgUtil.success(HuiPayService.profitSharingCancel(orderSettleService.getData("250731141540888578")));
			return ResponseMsgUtil.success(null);

		} catch (Exception e) {
			log.error("error!",e);
			return ResponseMsgUtil.exception(e);
		}
	}



}
