package cn.superdesk.uniorder.controller._openapi.unified;

import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.enums.UnifiedCode;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskappservices.UnifiedLnssOrderAdd;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedOrderAppraiseAdd;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedOrderAppraiseSMAdd;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedOrderGoodsAppraiseAdd;
import cn.superdesk.uniorder.dubbo.consumer.order.base.UnifiedOrderDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.unified.UnifiedOrderAppraiseDubboConsumerService;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.security.crypt.SuperdeskUniorderRsaUtils;
import cn.superdesk.uniorder.common.security.crypt.rsa.UnifiedSignUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description: TODO 专门给楼闪送用的?
 * @Author: linjinyu 补充 修改
 * @CreateDate: 5/7/20 5:00 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 5/7/20 5:00 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/unifiedorder")
public class UnifiedOrderController extends BaseController {


	@Autowired
	private UnifiedOrderDubboConsumerService         unifiedOrderDubboConsumerService;
	@Autowired
	private UnifiedOrderAppraiseDubboConsumerService unifiedOrderAppraiseDubboConsumerService;

	/**
	 * TODO 楼闪送(只有) ? 新增订单
	 * <p>
	 * http://192.168.6.223/web/unifiedorder/add
	 *
	 * @return
	 */
	@Deprecated
	@PostMapping("/add")
	@ResponseBody
	public R<String> add() {

		R<String> result = new R<>();

		try {
			String message = SuperdeskUniorderRsaUtils.readInputStream(request.getInputStream(), Charset.forName("utf-8"));

			log.info("order_add : {}", message);

			UnifiedLnssOrderAdd unifiedLnssOrderAdd = AnJsonUtils.toObject(message, UnifiedLnssOrderAdd.class);

			if (unifiedLnssOrderAdd == null) {

				result.setSuccess(false);
				result.setCode(UnifiedCode.JSON_ERROR.getCode());
				result.setMessage(UnifiedCode.JSON_ERROR.getMsg());

				return result;
			}

			String signParam = "version=1.0&timestamp=" + unifiedLnssOrderAdd.getTimestamp() + "&charset=utf-8&nonce_str=" + unifiedLnssOrderAdd.getNonce_str();

			if (!UnifiedSignUtils.checkSign(signParam, unifiedLnssOrderAdd.getSign())) {

				result.setSuccess(false);
				result.setCode(UnifiedCode.SIGN_ERROR.getCode());
				result.setMessage(UnifiedCode.SIGN_ERROR.getMsg());

				return result;
			}

			log.info("楼闪送 添加 订单 入参 \n\n{}\n\n", AnJsonUtils.toPrettyJson(unifiedLnssOrderAdd));
//			{
//				"version" : "1.0",
//					"timestamp" : "1620273613",
//					"charset" : "utf-8",
//					"nonce_str" : "cHWAMUjAuHHWeAp7CTUeayvA0TWUUZIX",
//					"sign" : "Gf7lEo5Q1KYugoQ2F52yPLT1LqW6wgMmOsRNGiqbPQudFeH3qAaKVKr9GiV4nXf8RjXZnz7qUd6NVzCgJekLBSTbnWDnhpMvc4k97UXUDdSduBKlVRZxc+j6ujLnOP2Y6cUAJ23foSbEhp0qdn+hHGV74z5VUnwm14jjLgkVc6M=",
//					"purchaseVirtId" : null,
//					"purchaseVirtName" : "",
//					"purchaseUserId" : null,
//					"purchaseUserName" : "施长胜",
//					"purchasePhone" : "13658370093",
//					"recUserName" : "施长胜",
//					"recAddress" : "北区17栋736",
//					"sale" : "炒饭盖饭_301",
//					"amount" : 11.00,
//					"goods" : [ {
//				"productId" : 9999,
//						"goods_name" : "青椒玉米盖饭_9999",
//						"quantity" : "1",
//						"price" : "9.00",
//						"cost_price" : "8.77",
//						"unit" : "份",
//						"goods_params" : ""
//			} ],
//				"service_no" : "LNSS",
//					"order_type" : "闪送订单",
//					"orderSn" : null,
//					"purchase_virt" : "",
//					"purchase_user" : "施长胜_null",
//					"recUserid" : null,
//					"recUserphone" : "13658370093",
//					"cost_amount" : 8.77,
//					"transport_amount" : 1,
//					"payment_type" : "1",
//					"pay_state" : "2",
//					"appraise_state" : "2",
//					"order_state" : "1",
//					"order_state_name" : "待支付",
//					"source_channel" : "1",
//					"project_id" : "1029",
//					"user_name" : "施长胜",
//					"user_id" : null,
//					"user_type" : "1",
//					"out_sn" : "",
//					"other_params" : "",
//					"settlement_type" : ""
//			}


			Map<String, Object> returnMap = unifiedOrderDubboConsumerService.addObjTran(unifiedLnssOrderAdd);

			log.info("楼闪送 添加 订单 返回 \n\n{}\n\n", AnJsonUtils.toJson(returnMap));

			if (returnMap.get("code").equals(1)) {

				result.setData(returnMap.get("sn").toString());
				result.setSuccess(true);

			} else {

				result.setCode(Integer.parseInt(returnMap.get("code").toString()));
				result.setMessage(returnMap.get("msg").toString());
				result.setSuccess(false);

			}

		} catch (Exception e) {

			e.printStackTrace();
			log.error(ExceptionUtils.getMessage(e));

			result.setSuccess(false);
			result.setCode(UnifiedCode.OTHER_ERROR.getCode());
			result.setMessage(e.getMessage());

		}
		return result;
	}

	/**
	 * 新增评价
	 *
	 * @return
	 */
	@Deprecated
	@PostMapping("/appraise")
	@ResponseBody
	public R<String> appraise() {
		R<String> result = new R<>();
		try {
			String instr = SuperdeskUniorderRsaUtils.readInputStream(request.getInputStream(), Charset.forName("utf-8"));

			JSONObject jasonObject = JSONObject.parseObject(instr);
			if (jasonObject == null) {
				result.setSuccess(false);
				result.setCode(UnifiedCode.JSON_ERROR.getCode());
				result.setMessage(UnifiedCode.JSON_ERROR.getMsg());
				return result;
			}

			UnifiedOrderAppraiseAdd appraiseAdd = jasonObject.toJavaObject(UnifiedOrderAppraiseAdd.class);

			Map<String, Object> returnMap = unifiedOrderAppraiseDubboConsumerService.addObj(appraiseAdd);
			if (returnMap.get("code").equals(1)) {
				result.setCode(1);
				result.setSuccess(true);
			} else {
				result.setCode(Integer.parseInt(returnMap.get("code").toString()));
				result.setMessage(returnMap.get("msg").toString());
				result.setSuccess(false);
			}

		} catch (Exception e) {

			result.setSuccess(false);
			result.setCode(UnifiedCode.OTHER_ERROR.getCode());
			result.setMessage(e.getMessage());

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 新增评价-商城专用
	 *
	 * @return
	 */
	@Deprecated
	@PostMapping("/appraisesm")
	@ResponseBody
	public R<String> appraisesm(UnifiedOrderAppraiseSMAdd appraiseAdd) {
		R<String> result = new R<>();
		try {
			//String instr= MyTools.readInputStream(request.getInputStream(), Charset.forName("utf-8"));

//			JSONObject  jasonObject = JSONObject.parseObject(instr);
//			if(jasonObject==null) {
//				result.setSuccess(false);
//				result.setCode(UnifiedCode.JSON_ERROR.getCode());
//				result.setMessage(UnifiedCode.JSON_ERROR.getMsg());
//				return result;
//			}

			//UnifiedOrderAppraiseSMAdd appraiseAdd  = jasonObject.toJavaObject(UnifiedOrderAppraiseSMAdd.class);
			JSONArray                          goodsJsonArray = JSONArray.parseArray(appraiseAdd.getGoods_json());
			List<UnifiedOrderGoodsAppraiseAdd> goodsLs        = goodsJsonArray.toJavaList(UnifiedOrderGoodsAppraiseAdd.class);

			Map<String, Object> returnMap = unifiedOrderAppraiseDubboConsumerService.addObjSM(appraiseAdd, goodsLs);
			if (returnMap.get("code").equals(1)) {
				result.setCode(1);
				result.setSuccess(true);
			} else {
				result.setCode(Integer.parseInt(returnMap.get("code").toString()));
				result.setMessage(returnMap.get("msg").toString());
				result.setSuccess(false);
			}

		} catch (Exception e) {

			result.setSuccess(false);
			result.setCode(UnifiedCode.OTHER_ERROR.getCode());
			result.setMessage(e.getMessage());

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}
		return result;
	}

	/***
	 * kafka测试 ---- 楼闪送 专用
	 */
	@Autowired
	private        KafkaTemplate<String, String> kafkaTemplate;
	private static Gson                          gson = new GsonBuilder().create();


	@PostMapping("/kfktest")
	@ResponseBody
	public R<String> kfktest() {
		R<String> result = new R<>();
		try {
			String              topTic = "unifiedorderupdatedev";
			Map<String, Object> map    = new HashMap<>();
			map.put("sn", "LS2019120400001");
			map.put("pay_state", 1);
			kafkaTemplate.send(topTic, gson.toJson(map));

		} catch (Exception e) {

			result.setSuccess(false);
			result.setCode(UnifiedCode.OTHER_ERROR.getCode());
			result.setMessage(e.getMessage());
			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}
		return result;
	}


}
