package com.winsun.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.bean.*;
import com.winsun.mapper.*;
import com.winsun.utils.EThreeDES;
import com.winsun.utils.MD5Utils;
import com.winsun.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.IllegalBlockSizeException;
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(value = "/orderPush", produces= "application/json")
    public JSONObject UnmannedHallOrderSync(@RequestBody String param) {

        JSONObject jsonObject1 = JSONObject.parseObject(param);

        JSONObject resultJson = new JSONObject();
        try {
            log.info("获取报文：" + jsonObject1.get("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(jsonObject1.get("param").toString());
            } catch (IOException e) {
                log.info("订单同步解密失败：");
                e.printStackTrace();
                resultJson.put("result", "1");
                resultJson.put("msg", "数据解密失败");
                return resultJson;
            }
            byte[] paramByte = null;
            try {
                paramByte = EThreeDES.decryptMode(appConfig.getAppSecret().getBytes(), bytes);
            }catch (IllegalBlockSizeException e) {
                log.info("订单同步解密失败：");
                e.printStackTrace();
                resultJson.put("result", "1");
                resultJson.put("msg", "Input length must be multiple of 8 when decrypting with padded cipher");
                return resultJson;
            }

            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);

            if (!schools.get(0).getId().equals(school.get("id"))) {
                resultJson.put("result", "1");
                resultJson.put("msg", "合伙人学校与下单学校不匹配");
                return resultJson;
            }

            Order order = new Order();;
            boolean isInsert = true;
            Wrapper<Order> orderWrapper = new EntityWrapper<>();
            orderWrapper.eq("order_id", jsonObject.getString("recNo"));
            List<Order> orders = orderMapper.selectList(orderWrapper);
            if (orders != null && orders.size() > 0) {
                order = orders.get(0);
                isInsert = false;
            }

            // 组装hhr_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.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(RandomUtil.RandomNumber(20));
            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("已完成");

            if (isInsert) {
                order.setId(id);
                orderMapper.insert(order);
            }else{
                orderMapper.updateById(order);
            }

            Wrapper<OrderView> orderViewWrapper = new EntityWrapper<>();
            orderViewWrapper.eq("orderSeq", order.getKdOrderId());
            List<OrderView> orderViews = orderViewMapper.selectList(orderViewWrapper);
            OrderView orderView = new OrderView();
            if (orderViews != null && orderViews.size() > 0) {
                orderView = orderViews.get(0);
            }

            // 组装order_view
            orderView.setOrderSeq(order.getKdOrderId());
            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("学生");

            if (orderView.getOrderId() != null) {
                orderViewMapper.updateById(orderView);
            }else{
                orderViewMapper.insert(orderView);
            }

            resultJson.put("result", "0");
            resultJson.put("msg", "同步成功");
        }catch(Exception e) {
            log.info("订单同步失败：");
            resultJson.put("result", "1");
            resultJson.put("msg", e.toString());
            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;
    }
}
