package com.winsun.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.netflix.discovery.converters.Auto;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.bean.*;
import com.winsun.mapper.*;
import com.winsun.utils.EThreeDES;
import com.winsun.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 订单同步接口
 * @author chengfengluo
 * @date 2021-02-20 9:22
 */
@RequestMapping("/sync")
@RestController
@Slf4j
public class SyncController {

    @Autowired
    private AppConfigMapper appConfigMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private HhrUserMapper hhrUserMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderViewMapper orderViewMapper;

    /**
     * 无人厅订单同步
     * @return {"msg":"同步成功", "result":0}
     */
    @PostMapping("/orderPush")
    public JSONObject UnmannedHallOrderSync(@RequestParam("param") String param) {
        JSONObject resultJson = new JSONObject();
        try {
            log.info("获取报文：" + param);
            // 查询key 密匙 （需要配置化，可随时修改）
            Wrapper<AppConfig> wrapper = new EntityWrapper<>();
            wrapper.eq("app_name", "随身厅");
            List<AppConfig> appConfigs = appConfigMapper.selectList(wrapper);

            if (appConfigs == null || appConfigs.size() == 0 || StringUtils.isBlank(appConfigs.get(0).getAppSecret())) {
                resultJson.put("result", "1");
                resultJson.put("msg", "系统未配置随身厅密匙");
                return resultJson;
            }

            if (appConfigs.size() > 1) {
                resultJson.put("result", "1");
                resultJson.put("msg", "系统配置多个密匙");
                return resultJson;
            }

            AppConfig appConfig = appConfigs.get(0);

            // 解密3DES
            byte[] bytes = null;
            try {
                bytes = EThreeDES.deBase64(param);
            } catch (IOException e) {
                log.info("订单同步解密失败：");
                e.printStackTrace();
                resultJson.put("result", "1");
                resultJson.put("msg", "数据解密失败");
                return resultJson;
            }
            byte[] paramByte = EThreeDES.decryptMode(appConfig.getAppSecret().getBytes(), bytes);
            JSONObject paramJson = JSONObject.parseObject(new String(paramByte));
            log.info("3DES解密参数：" + paramJson.toJSONString());

            // 获取termNo 查询school app_key 解密data参数
            String termNo = paramJson.getString("termNo");
            if (StringUtils.isBlank(termNo)) {
                resultJson.put("result", "1");
                resultJson.put("msg", "终端编码不能为空");
                return resultJson;
            }
            Wrapper<School> schoolWrapper = new EntityWrapper<>();
            schoolWrapper.eq("app_id", termNo);
            List<School> schools = schoolMapper.selectList(schoolWrapper);
            if (schools == null || schools.size() == 0 || StringUtils.isBlank(schools.get(0).getAppKey())) {
                resultJson.put("result", "1");
                resultJson.put("msg", "系统未配置该终端编码");
                return resultJson;
            }

            if (schools.size() > 1) {
                resultJson.put("result", "1");
                resultJson.put("msg", "终端编码重复配置");
                return resultJson;
            }

            // 校验sign
            if (!this.checkSign(paramJson, schools.get(0).getAppKey())) {
                resultJson.put("result", "1");
                resultJson.put("msg", "签名校验失败");
                return resultJson;
            }

            String data = paramJson.getString("data");
            if (data == null || StringUtils.isBlank(data)) {
                resultJson.put("result", "1");
                resultJson.put("msg", "订单参数为空");
                return resultJson;
            }

            byte[] orderByte = EThreeDES.decryptMode(schools.get(0).getAppKey().substring(0, 24).getBytes(), EThreeDES.deBase64(data));

            // 获取订单数据
            JSONObject jsonObject = JSONObject.parseObject(new String(orderByte));
            log.info("订单数据：" + jsonObject.toJSONString());
            // 校验必填参数
            if (checkOrderSyncParams(jsonObject)) {
                resultJson.put("result", "1");
                resultJson.put("msg", "订单参数不全");
                return resultJson;
            }

            // 查询合伙人信息
            String username = jsonObject.getString("username");
            Wrapper<SysUser> sysUserWrapper = new EntityWrapper<>();
            sysUserWrapper.eq("account", username);
            List<SysUser> sysUsers = sysUserMapper.selectList(sysUserWrapper);
            if (sysUsers == null || sysUsers.size() != 1) {
                resultJson.put("result", "1");
                resultJson.put("msg", "合伙人账号错误");
                return resultJson;
            }

            SysUser sysUser = sysUsers.get(0);

            // 查询合伙人学校
            List<Map<String, Object>> maps = hhrUserMapper.selectHehuorenSchool(sysUser.getId());

            if (maps == null || maps.size() != 1) {
                resultJson.put("result", "1");
                resultJson.put("msg", "当前合伙人配置学校错误");
                return resultJson;
            }

            Map<String, Object> school = maps.get(0);

            // 组装hhr_order
            Order order = new Order();
            String uuid = UUID.randomUUID().toString();
            String id = uuid.split("-")[0] + uuid.split("-")[1];
            SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
            SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String orderNumber = "YRYM" + sd.format(new Date()) + id.substring(1, 12);
            order.setId(id);
            order.setHehuorenId(sysUser.getId());
            order.setOrderId(jsonObject.getString("recNo"));
            order.setOrderNumber(orderNumber);
            order.setCustomerName(jsonObject.getString("custName"));
            order.setContactNumber(jsonObject.getString("accNbr"));
            order.setIdCard(jsonObject.getString("certNo"));
            order.setCreateTime(yyyyMMdd.parse(jsonObject.getString("orderTime")));
            order.setUserType("11"); // 订单类型：无人厅
            order.setKapin("宽带办理");
            order.setUserSchool(school.get("school_name").toString());
//            order.setKdOrderId(orderView.getOrderSeq().toString());
            order.setHehuorenPhone(sysUser.getPhone());
            order.setHehuorenSchool(school.get("school_name").toString());
            order.setHehuorenName(sysUser.getName());
            order.setHehuorenArea(sysUser.getSubstName());
            order.setLzgh(school.get("lzgh") != null ? school.get("lzgh").toString() : null);
            order.setOrderStatus("已完成");
            orderMapper.insert(order);

            // 组装order_view
            OrderView orderView = new OrderView();
            orderView.setOrderName(order.getCustomerName());
            orderView.setOrderPhone(order.getContactNumber());
            orderView.setOrderNumber(order.getIdCard());
            orderView.setProductName(jsonObject.getString("prodName"));
            orderView.setOrderSetMeal("无人厅");
            orderView.setOrderDate(order.getCreateTime());
            orderView.setOrderUniversityName(order.getHehuorenSchool());
            orderView.setHehuorenId(sysUser.getId());
            orderView.setOrderRegion(school.get("sub_name") != null ? school.get("sub_name").toString() : null);
            orderView.setWebOrderAmount(jsonObject.getString("payAmount"));
            if (jsonObject.getString("payAmount").equals("0")) {
                orderView.setIPay("0");
            } else {
                orderView.setIPay("1");
            }
            orderView.setCustomerId("xyzxyql");
            orderView.setOrderCustomerType("学生");
            orderViewMapper.insert(orderView);

            resultJson.put("result", "0");
            resultJson.put("msg", "同步成功");
        }catch(Exception e) {
            log.info("订单同步失败：");
            resultJson.put("result", "1");
            resultJson.put("msg", "未知异常");
            e.printStackTrace();
            return resultJson;
        } finally{
            log.info(resultJson.toJSONString());
        }
        return resultJson;
    }

    /**
     * 校验签名
     * @param jsonObject
     * @return
     */
    private boolean checkSign(JSONObject jsonObject, String key2) {

        if (StringUtils.isBlank(jsonObject.getString("timestamp"))) {
            return false;
        }

        String param = "" + jsonObject.get("termNo") + jsonObject.get("timestamp") + key2;
        String s = MD5Utils.md5(param);

        if (StringUtils.equals(s, jsonObject.getString("sign"))) {
            return true;
        }

        return false;
    }

    /**
     * 校验订单同步参数
     * @param jsonObject
     * @return
     */
    private boolean checkOrderSyncParams(JSONObject jsonObject) {

        if (jsonObject.getString("termNo") == null // 终端编码
            || jsonObject.getString("orderTime") == null // 订单时间
            || jsonObject.getString("prodName") == null // 产品名
            || jsonObject.getString("custName") == null //客户姓名
            || jsonObject.getString("recNo") == null // 订单流水号
            || jsonObject.getString("userName") == null // 合伙人账号
            || jsonObject.getString("certNo") == null // 客户身份证
            || jsonObject.getString("accNbr") == null // 客户手机号码
            || jsonObject.getString("orderState") == null // 订单状态
            || jsonObject.getString("payAmount") == null ) {// 支付金额
            return true;
        }
        return false;
    }
}
