package com.winsun.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.winsun.auth.core.annotion.Permission;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.bean.Order;
import com.winsun.bean.Package;
import com.winsun.bean.YsmUser;
import com.winsun.constant.Constant;
import com.winsun.mapper.OrderMapper;
import com.winsun.mapper.PackageMapper;
import com.winsun.mapper.SchoolMapper;
import com.winsun.mapper.YsmUserMapper;
import com.winsun.smsUtils.SendSmsAndMail;
import com.winsun.utils.MD5Utils;
import com.winsun.utils.MyBatisPlusUpdateUtils;
import com.winsun.utils.OrderManage;
import com.winsun.utils.RSAUtils;
import kong.unirest.Unirest;
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 org.springframework.web.client.ResourceAccessException;
import sun.misc.BASE64Encoder;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date: 2020年3月11日15:12:46
 */
@Slf4j
@RestController
@RequestMapping("/supervisor")
public class supervisorController extends BaseController {

    private static String REPLACE = "new/ciop";

    private static PackageMapper packageMapper;

    private static OrderMapper orderMapper;

    private static YsmUserMapper ysmUserMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    final String publicKey =
            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAok8DnvM2OBwtzNoJb4nA" +
                    "jn4lgCkSxLyRw5lLiUfsi+40h00CGAC1arvbinTTbtrSnm4YDYlaJwveiOeDKdk0" +
                    "f2Yglb/8loEbNTqb1OqNxUeM1wYLRBXvAkkZ5fZllajWzFMkoNU/JQ4+T8sMATxm" +
                    "1d1XRcgM6zlgVwX6siDoLZ5Dm23CTS7SXhyMLtS9cgLefHcOckPQyXoB/IJqb0K1" +
                    "P0Sk0PE1OSRzpsI9JVzhsSW164fwYpxEbygj9O9JAmAszixwItt2j5zLJ6zRnK3R" +
                    "OrcAVMN/vpXTN2dCLGZXQrsTK9sAWASzIWTiQRzmnwxsQY7y4u2h+k41n8Z5tw03" +
                    "wwIDAQAB";

    @Autowired
    public supervisorController(PackageMapper packageMapper, OrderMapper orderMapper, YsmUserMapper ysmUserMapper) {
        supervisorController.packageMapper = packageMapper;
        supervisorController.orderMapper = orderMapper;
        supervisorController.ysmUserMapper = ysmUserMapper;
    }

    /**
     * 督导订单详情查询
     *
     * @param orderId
     * @return
     */
    @Permission(menuname = "督导订单详情查询", value = "selectOrderInfo", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> selectOrderInfo(@RequestParam("orderId") String orderId) {
       /* ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }*/

        if (StringUtils.isNotBlank(orderId)) {
            ResponseData<String> verification = verification(orderId);
            if (!verification.isSuccess()) {
                return ResponseData.error("订单不存在或异常！");
            }
        } else {
            return ResponseData.error("页面已失效，请重新登录！");
        }
        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        List<Map<String, Object>> list = orderMapper.selectMaps(wrapper);
        Map<String, Object> map = list.get(0);
        if (map.size() == 0) {
            return ResponseData.error("当前订单不存在！");
        }
        if (map.get("packageId") != null) {
            Package aPackage = packageMapper.selectById(Integer.parseInt(map.get("packageId").toString()));
            map.put("packageName", aPackage.getPackageName());
            map.put("advImg", aPackage.getAdvImg());
            map.put("explains", aPackage.getExplains());
        }

        //测试用
        if (StringUtils.isBlank(map.get("idCard").toString())) {
            map.put("idCard", "000000000000000000".substring(0, 14) + "****");
        } else {
            if (map.get("idCard").toString().length() == 18) {
                map.put("idCard", map.get("idCard").toString().substring(0, 14) + "****");
            } else {
                map.put("idCard", map.get("idCard").toString().substring(0, 11) + "****");
            }
        }

        //查询历史状态
        List<Map<String, Object>> orderHis = orderMapper.selectOrderHis(orderId);
        map.put("orderHis", orderHis);
        return ResponseData.success(map);
    }

    /**
     * 督导订单置为异常单
     *
     * @param orderId
     * @return
     */
    @Permission(menuname = "督导订单置为异常单", value = "updateOrderState", method = RequestMethod.POST)
    public ResponseData<String> updateOrderState(@RequestParam("orderId") String orderId) {
        /* ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }*/
        if (StringUtils.isNotBlank(orderId)) {
            ResponseData<String> verification = verification(orderId);
            if (!verification.isSuccess()) {
                return ResponseData.error("订单不存在或异常！");
            }
        } else {
            return ResponseData.error("页面已失效，请重新登录！");
        }
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        Map<String, Object> dataMapping = new HashMap<>();
        dataMapping.put("order_status", "异常单");
        dataMapping.put("success_time", new Date());
        Integer integer = orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if (integer == 0) {
            return ResponseData.error("置为异常单失败！");
        } else {
            //orderMapper.inserOrderHis(orderId,"已置为异常单",new Date(),user.getName());
            orderMapper.inserOrderHis(orderId, "已置为异常单", new Date(), "测试");
            return ResponseData.success("置为异常单成功！");
        }
    }

    /**
     * 待处理
     *
     * @param orderId
     * @param type    0 是线上 1是线下
     * @return
     */
    @Permission(menuname = "待处理", value = "daichuliUpdate", method = RequestMethod.POST)
    public ResponseData<String> daiChuLiUpdate(@RequestParam("orderId") String orderId, @RequestParam("type") String type) {
        /* ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }*/
        ShiroUser shiroUser = getShiroUser();
        if (StringUtils.isNotBlank(orderId)) {
            ResponseData<String> verification = verification(orderId);
            if (!verification.isSuccess()) {
                return ResponseData.error("订单不存在或异常！");
            }
        } else {
            return ResponseData.error("页面已失效，请重新登录！");
        }
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        Order order = orderMapper.selectById(orderId);
        Map<String, Object> dataMapping = new HashMap<>();
        String xb = order.getXbType();
        if ("0".equals(type)) {
            if ("1".equals(xb)) {
                dataMapping.put("order_status", "待配送");
                dataMapping.put("send_type", "快递");
            } else {
                dataMapping.put("order_status", "待选号");
                dataMapping.put("send_type", "快递");
            }
        }
        if ("1".equals(type)) {
            if ("1".equals(xb)) {
                dataMapping.put("order_status", "待活体");
                dataMapping.put("send_type", "送货上门");
            } else {
                dataMapping.put("order_status", "待选号");
                dataMapping.put("send_type", "送货上门");
            }
        }
        Integer integer = orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if (integer == 0) {
            return ResponseData.error("配送方式修改失败！");
        } else {
            //user.getName()
            orderMapper.inserOrderHis(orderId, "修改配送方式，" + dataMapping.get("order_status"), new Date(), shiroUser.getName());
            return ResponseData.success("配送方式修改成功！");
        }
    }

    /**
     * 待选号
     *
     * @param orderId
     * @return
     */
    @Permission(menuname = "待选号", value = "daiXuanHaoUpdate", method = RequestMethod.POST)
    public ResponseData<String> daiXuanHaoUpdate(@RequestParam("orderId") String orderId, @RequestParam("businessNumber") String businessNumber, @RequestParam(value = "iccid", required = false) String iccid) throws Exception {
        /* ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }*/
        if (StringUtils.isNotBlank(orderId)) {
            ResponseData<String> verification = verification(orderId);
            if (!verification.isSuccess()) {
                return ResponseData.error("订单不存在或异常！");
            }
        } else {
            return ResponseData.error("页面已失效，请重新登录！");
        }
        Order order = orderMapper.selectById(orderId);
        if (StringUtils.isBlank(businessNumber)) {
            return ResponseData.error("请输入办理号码！");
        }
        //String s = yZPlaceAnOrder(orderId, businessNumber, iccid);
        kong.unirest.HttpResponse<String> response = yZPlaceAnOrder(orderId, businessNumber, iccid);
        //Map map = JSON.parseObject(s, Map.class);
        if (response.getStatus() != 200) {
            return ResponseData.error("选号失败！下单不成功请联系管理员");
        }
        String orderNum = response.getBody();
        JSONObject queryOrderJsonObject = getQueryOrderInfo(orderNum, 1);
        Map<String, Object> map = JSONObject.parseObject(queryOrderJsonObject.getString("data"));
        List<Object> list = (List<Object>) map.get("q");
        Map<String, Object> q = (Map<String, Object>) list.get(0);
        Map<String, Object> orderStatus = (Map<String, Object>) q.get("订单当前状态");
        if (orderStatus.containsKey("订单当前状态|状态备注")) {
            orderMapper.inserOrderHis(orderId, "选号提交失败，" + orderStatus.get("订单当前状态|状态备注").toString(), new Date(), "测试");
            return ResponseData.error(orderStatus.get("订单当前状态|状态备注").toString());
        }
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        Map<String, Object> dataMapping = new HashMap<>();
        dataMapping.put("order_id", orderNum);
        if ("快递".equals(order.getSendType())) {
            dataMapping.put("order_status", "审核中");
            dataMapping.put("business_iccid", iccid);
        } else {
            dataMapping.put("order_status", "已完成");
            dataMapping.put("success_time", new Date());
        }
        dataMapping.put("business_number", businessNumber);
        Integer integer = orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if (integer == 0) {
            return ResponseData.error("选号提交失败！");
        } else {
            //user.getName()
            orderMapper.inserOrderHis(orderId, "选号提交成功，" + dataMapping.get("order_status"), new Date(), "测试");
            return ResponseData.success("选号提交成功！");
        }
    }

    /**
     * 待配送
     *
     * @param orderId
     * @return
     */
    @Permission(menuname = "待配送", value = "daiPeiSongUpdate", method = RequestMethod.POST)
    public ResponseData<String> daiPeiSongUpdate(@RequestParam("orderId") String orderId, @RequestParam("kuaidiOrder") String kuaidiOrder, @RequestParam(value = "expressDelivery") String expressDelivery) throws Exception {
        /* ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }*/
        if (StringUtils.isNotBlank(orderId)) {
            ResponseData<String> verification = verification(orderId);
            if (!verification.isSuccess()) {
                return ResponseData.error("订单不存在或异常！");
            }
        } else {
            return ResponseData.error("页面已失效，请重新登录！");
        }
        Order order = orderMapper.selectById(orderId);
        if (StringUtils.isBlank(kuaidiOrder)) {
            return ResponseData.error("请输入快递单号！");
        }
        if (StringUtils.isBlank(expressDelivery)) {
            return ResponseData.error("请选择快递公司！");
        }
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        Map<String, Object> dataMapping = new HashMap<>();
        String xbType = order.getXbType();
        if ("1".equals(xbType)) {
            dataMapping.put("order_status", "待活体");
        } else {
            dataMapping.put("order_status", "已完成");
            dataMapping.put("success_time", new Date());
        }
        dataMapping.put("company", expressDelivery);
        dataMapping.put("kuaidi_order", kuaidiOrder);
        Integer integer = orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if (integer == 0) {
            return ResponseData.error("修改快递单号失败！");
        } else {
            //user.getName()
            log.info("联系号码：" + order.getContactNumber());
            // 发送短信
            SendSmsAndMail.sendSms(order.getContactNumber(), expressDelivery, kuaidiOrder, "11");
            orderMapper.inserOrderHis(orderId, "提交成功，" + dataMapping.get("order_status"), new Date(), "测试");
            return ResponseData.success("修改快递单号成功！");
        }
    }

    /**
     * 验证订单
     *
     * @param orderId
     * @return
     */
    public ResponseData<String> verification(String orderId) {
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        List list = orderMapper.selectList(wrapper);
        if (list.size() == 1) {
            return ResponseData.success("ok");
        } else if (list.size() == 0) {
            return ResponseData.error("订单不存在！");
        } else {
            return ResponseData.error("订单异常！");
        }
    }

    /**
     * 预制卡下单
     *
     * @param orderId
     * @param businessNumber
     * @param iccid
     * @return
     */
    public kong.unirest.HttpResponse<String> yZPlaceAnOrder(String orderId, String businessNumber, String iccid) {
        Order order = orderMapper.selectById(orderId);
        String s = orderMapper.selectYsmById(order.getHehuorenId());
        YsmUser ysmUser = ysmUserMapper.selectById(s);
        Map<String, Object> map = new HashMap<>();
        map.put("ysmUser", ysmUser.getUserName());
        map.put("linkPhone", order.getContactNumber());// 客户(代办人)电话，必填
        map.put("idCard", order.getIdCard());
        String[] split = order.getSite().split(" ");
        map.put("sheng", split[0]);
        map.put("shi", split[1]);
        map.put("xian", split[2]);
        map.put("address", order.getAddress());
        map.put("iccId", iccid);
        map.put("orderPhone", order.getBusinessNumber());
        map.put("orderNum", order.getOrderNumber());
        /*map.put("imgUrl1", order.getIdCardz());
        map.put("imgUrl2", order.getIdCardf());
        map.put("imgUrl3", order.getIdCardzs());*/
        map.put("idCardUrl1", order.getIdCardz().replace("manager", "app"));
        map.put("idCardUrl2", order.getIdCardf().replace("manager", "app"));
        map.put("idCardUrl3", order.getIdCardzs().replace("manager", "app"));
        if (order.getPackageId().equals("49")) {
            map.put("userName", order.getParentName());
            map.put("idCardUrl4", order.getIdCardzs().replace("manager", "app"));
            //map.put("imgUrl4", order.getIdCardzs());
        } else {
            map.put("userName", order.getCustomerName());// 客户姓名，必填// 联系人，必填
            map.put("idCardUrl4", order.getStudenCard().replace("manager", "app"));
            //map.put("imgUrl4", order.getStudenCard());
        }
        map.put("sign", ysmUser.getSign());
        map.put("cardType", order.getKapin());
        map.put("address", order.getAddress());

        Map<String, String> schoolMap = schoolMapper.selectByHeHuorenId(order.getHehuorenId());
        if (StringUtils.isNotEmpty(schoolMap.get("lzgh")) && StringUtils.isNotEmpty(schoolMap.get("lz_user"))) {
            map.put("lzgh", schoolMap.get("lzgh"));
            map.put("lzUser", schoolMap.get("lz_user"));
        } else {
            map.put("lzgh", "44100621");
            map.put("lzUser", "黄友健");
        }
        try {
            OrderManage orderManage = new OrderManage();
            return orderManage.sendOrder(map);
        } catch (Exception e) {
            log.error("预制卡下单失败", e.getMessage());
        }
        return null;
    }


    public JSONObject getQueryOrderInfo(String orderNum, int count) throws Exception {
        ObjectMapper OBJECT_MAPPER = new ObjectMapper();

        Map<String, Object> data = new HashMap<>();
        data.put("route", "代理商订单信息查询");
        data.put("代理商账号", "hyoujian");
        data.put("订单编码", orderNum);
        data.put("使用人证件号", "440802199006080830");
        data.put("使用人姓名", "黄友健");
        String bodyJson = JSONObject.toJSONString(data);

        String eurl_data = URLEncoder.encode(bodyJson, "UTF-8");
        String url_data = "data=" + eurl_data;
        // 获得md5串
        String sign = MD5Utils.md5(url_data);
        // 获得小写md5串
        sign = sign.toLowerCase();
        // RSA加密
        byte[] encodedData = RSAUtils.encryptByPublicKey(sign, publicKey);
        sign = (new BASE64Encoder()).encodeBuffer(encodedData);
        log.info("签名：" + sign);
        //去除换行
        sign = sign.replaceAll("\\r|\\n", "");
        log.info("签名2  ：" + sign);

        JSONObject jsonObject = null;
        try {
            log.info("提交参数:" + data);
            Constant.trustEveryone();
            kong.unirest.HttpResponse<String> responese = Unirest.get("http://132.97.20.21/query/query-order-info?" + url_data)
                    //kong.unirest.HttpResponse<String> responese = Unirest.get("https://applet.mini189.cn/prod/query/query-order-info?" + url_data)
                    .header("Content-Type", "application/json")
                    .header("X-Sign", sign)
                    .asString();
            log.info("宽带订单状态查询接口，返回信息:" + responese.getBody());
            String body = responese.getBody();
            jsonObject = JSONObject.parseObject(body);
            Map<String, Object> dataJson = (Map<String, Object>) jsonObject.get("data");
            if (StringUtils.isEmpty(JSON.toJSONString(dataJson.get("q")))) {
                count++;
                if (count < 20) {
                    getQueryOrderInfo(orderNum, count);
                } else {
                    log.error("宽带订单状态查询接口尝试20次未查询到订单。请重新下单或检查下单接口");
                }
            }
        } catch (ResourceAccessException s) {
            count++;
            if (count < 20) {
                getQueryOrderInfo(orderNum, count);
            } else {
                log.error("单宽订单状态查询接口尝试20次失误。请检查接口");
            }
        } catch (Exception e) {
            log.error("接口异常   " + e.getMessage());
            e.printStackTrace();
        }
        return jsonObject;
    }
}
