package com.cweb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.RedisUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.BsOrderGoods;
import com.hfkj.entity.GoodsLogistics;
import com.hfkj.entity.GoodsUserAddress;
import com.hfkj.model.ResponseData;
import com.hfkj.qianzhu.QianZhuService;
import com.hfkj.service.CommonService;
import com.hfkj.service.goods.BsOrderGoodsService;
import com.hfkj.service.goods.GoodsUserAddressService;
import com.hfkj.service.hlt.HuiLianTongUnionCardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value="/common")
@Api(value="共用接口")
public class CommonController {

	Logger log = LoggerFactory.getLogger(CommonController.class);

	@Resource
	private CommonService commonService;

	@Autowired
	private RedisUtil redisUtil;

	@Resource
	private BsOrderGoodsService bsOrderGoodsService;

	@Resource
	private GoodsUserAddressService addressService;

	@RequestMapping(value = "/test", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "test")
	public ResponseData test() {
		try {
		/*	String goodsDesc = "";
			String tranDesc = "";
			String businessType = "HiSen_phg_goods";
			String instCode = "11101608";
			// 工会卡支付
			JSONObject consumption = HuiLianTongUnionCardService.consumption("240803201355633339_1", "8800030115015087807", new BigDecimal("27.40"), businessType, instCode, goodsDesc, tranDesc);
			if (!consumption.getString("respCode").equals("0000")) {
				throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, consumption.getString("respMessage"));
			}
			// 响应参数
			JSONObject consumptionResult = HuiLianTongUnionCardService.resolveResponse(consumption.getString("data"));
			if (consumptionResult.getBoolean("success") != true) {
				throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, consumptionResult.getString("message"));
			}
*/
			JSONObject refundObj = HuiLianTongUnionCardService.refund("R240816093659997", "240808134614258487");
			if (!refundObj.getString("respCode").equals("0000")) {
				throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, refundObj.getString("respMessage"));
			}
			JSONObject consumptionResult = HuiLianTongUnionCardService.resolveResponse(refundObj.getString("data"));
			if (consumptionResult.getBoolean("success") != true) {
				throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "交易失败!"+consumptionResult.getString("message"));
			}
			return ResponseMsgUtil.success(consumptionResult);

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

	@RequestMapping(value = "/getAllCity", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "查询所有城市")
	public ResponseData getAllCity() {
		try {

			Object data = redisUtil.get("regional");

			if (data == null) {

				List<JSONObject> jsonObjects = commonService.getCity("key" , "title" , "children");
				redisUtil.set("regional", jsonObjects);

				return ResponseMsgUtil.success(jsonObjects);

			} else {
				return ResponseMsgUtil.success(data);
			}

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

	@RequestMapping(value="/getLogisticsMsg",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "查询物流")
	public ResponseData getLogisticsMsg(@RequestParam(value = "logisticsNo" , required = true) String logisticsNo) {
		try {

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

			BsOrderGoods orderGoods = bsOrderGoodsService.findGoodsOrderLogisticsNo(logisticsNo);

			if (orderGoods == null) {
				throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , "暂无物流信息！");
			}

			GoodsUserAddress userAddress = addressService.queryDetail(orderGoods.getDeliveryAddressId());

			if (userAddress == null) {
				throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , "暂无物流信息！");
			}

			GoodsLogistics logistics = (GoodsLogistics) bsOrderGoodsService.getLogisticsMsg(logisticsNo , userAddress.getPhone());

			params.put("logistics", logistics);
			JSONArray object = JSONArray.parseArray(logistics.getLogisticsTraceDetails());
			params.put("logisticsTraceDetails",  object);
			return ResponseMsgUtil.success(params);

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

	@RequestMapping(value = "/getAllQzCities", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "查询千猪中国大陆所有城市")
	public ResponseData getAllQzCities() {
		try {

			Object data = redisUtil.get("qianZhuCity");

			if (data == null) {

				JSONObject jsonObjects = QianZhuService.getAllCities();

				JSONArray array = jsonObjects.getJSONArray("data");
				List<JSONObject> list = new ArrayList<>();

				for (Object obj : array) {
					list.add((JSONObject) obj);
				}
				List<JSONObject> objectList = list.stream()
						.filter(n -> n.getInteger("cityId") != null)
						.collect(Collectors.toList());


				redisUtil.set("qianZhuCity", objectList , 60*60*6);

				return ResponseMsgUtil.success(objectList);

			} else {
				return ResponseMsgUtil.success(data);
			}

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


	@RequestMapping(value = "/locateByLngAndLat", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "根据经纬度定位城市")
	public ResponseData locateByLngAndLat(@RequestParam(name = "lng", required = true) String lng, @RequestParam(name = "lat", required = true) String lat) {
		try {



			JSONObject params = commonService.locateByLngAndLat(lng + "," + lat);
			System.out.println(params);

			if (params.getInteger("status") == 0) {
				throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未查询到任何城市！");
			}

			JSONObject addressComponent = params.getJSONObject("regeocode").getJSONObject("addressComponent");

			Object value = addressComponent.get("city");
			String cityName;
			if (value instanceof String) {
				cityName = addressComponent.getString("city");
			} else {
				cityName = addressComponent.getString("province");
			}

			ResponseData data = getAllQzCities();

			if (Objects.equals(data.getReturn_code(), "000000")) {
				List<JSONObject> array = (List<JSONObject>) data.getReturn_data();

				for (JSONObject s : array) {
                    if (Objects.equals(s.getString("cityName"), cityName)) {
						return ResponseMsgUtil.success(s);
					}
				}

				return ResponseMsgUtil.success("未查询到任何内容！");

			} else {
				return ResponseMsgUtil.success(data.getReturn_msg());
			}


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

	@RequestMapping(value = "/listByCityId", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "查询城市区域")
	public ResponseData listByCityId(@RequestParam(value = "cityId", required = false) Integer cityId) {
		try {

			Map<String, Object> params = new HashMap<>();
			params.put("cityId", cityId);
			return ResponseMsgUtil.success(QianZhuService.listByCityId(params));

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


}
