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.winsun.auth.core.common.model.ResponseData;
import com.winsun.bean.*;
import com.winsun.bean.Package;
import com.winsun.common.CityCode;
import com.winsun.constant.OrderStatus;
import com.winsun.constant.UserType;
import com.winsun.mapper.*;
import com.winsun.smsUtils.SendSmsAndMail;
import com.winsun.smsUtils.StringUtil;
import com.winsun.utils.IDCardUtil;
import com.winsun.utils.PicturesUtil;
import com.winsun.utils.ProduceIdUtil;
import com.winsun.utils.XbkUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 套餐升级
 */
@Slf4j
@RestController
@RequestMapping("/packageNewClothes") //
public class PackageNewClothes {

    private static String PATHTYPE = "idCard";

    private static AppMapper appMapper;

    private static PackageMapper packageMapper;

    private static SchoolMapper schoolMapper;

    private static OrderMapper orderMapper;

    private static SysUserMapper userMapper;

    @Autowired
    private HhrUserMapper hhrUserMapper;

    @Autowired
    private OrderCardAddressMapper orderCardAddressMapper;

    @Autowired
    public PackageNewClothes(AppMapper appMapper, PackageMapper packageMapper,
                             OrderMapper orderMapper, SchoolMapper schoolMapper, SysUserMapper userMapper) {
        PackageNewClothes.appMapper = appMapper;
        PackageNewClothes.packageMapper = packageMapper;
        PackageNewClothes.orderMapper = orderMapper;
        PackageNewClothes.userMapper = userMapper;
        PackageNewClothes.schoolMapper = schoolMapper;
    }

    /**
     * 查询用户学校适用套餐
     *
     * @param partner
     * @return
     */
    @RequestMapping(value = "selectSchoolPackage", method = RequestMethod.POST)
    public ResponseData<List<Package>> selectSchoolPackage(@RequestParam("partner") String partner) {
        String schoolId = appMapper.selectSchoolId(partner);
        List<String> packageIds = appMapper.selectPackageId(schoolId);
        List<Package> packages = new ArrayList<>();
        packageIds.forEach(packageId -> {
            Package package1 = packageMapper.selectById(packageId);
            packages.add(package1);
        });
        return ResponseData.success(packages);
    }


    @RequestMapping(value = "checkHhr", method = RequestMethod.POST)
    public ResponseData<String> checkHhr(@RequestParam("id") String id) {

        if (StringUtils.isNotBlank(id)) {
            Wrapper<SysUser> wrapper = new EntityWrapper();
            wrapper.eq("id", id);
            Integer integer = userMapper.selectCount(wrapper);
            if (integer > 0) {
                return ResponseData.success();
            }
        }
        return ResponseData.error("找不到该合伙人");
    }

    /**
     * 手机号码获取 JT0001
     *
     * @param cardId     套餐ID
     * @param partner    用户ID
     * @param contNumber 套餐ID
     * @return
     */
    @RequestMapping(value = "getNumber", method = RequestMethod.POST)
    public ResponseData<List<String>> getNumber(@RequestParam("cardId") String cardId, @RequestParam("partner") String partner, @RequestParam(value = "contNumber", required = false) String contNumber) {
        Package aPackage = packageMapper.selectById(cardId);
        String schoolId = appMapper.selectSchoolId(partner);
        School school = schoolMapper.selectById(schoolId);
        String xbId = aPackage.getXbId();
        String netId = school.getNetId();
        JSONObject jsonObject = null;
        try {
            jsonObject = XbkUtil.getNumberJT0001(contNumber, xbId, netId);
        } catch (Exception e) {
            log.error("JT0001获取手机号码接口异常", e.getMessage());
            ResponseData.error("手机号码获取失败，请重新获取。");
        }
        List<String> list = new ArrayList<>();
        if (!"0".equals(jsonObject.getString("code"))) {
            return ResponseData.error(jsonObject.getString("msg"));
        } else {
            List<Map<String, Object>> dataArray = (List<Map<String, Object>>) jsonObject.get("dataArray");
            for (Map<String, Object> map : dataArray) {
                String phoneNumber = map.get("phoneNumber").toString();
                list.add(phoneNumber);
            }
        }
        return ResponseData.success(list);
    }


    /**
     * 查询套餐详情
     *
     * @param packageId 套餐ID
     * @return
     */
    @RequestMapping(value = "selectPackageInfo", method = RequestMethod.POST)
    public ResponseData<Package> selectPackageInfo(@RequestParam("packageId") String packageId) {
        return ResponseData.success(packageMapper.selectById(packageId));
    }


    /**
     * 新开手机卡  预制卡
     *
     * @param site          省市县
     * @param address       详细地址
     * @param kapin         套餐名
     * @param idCardz       身份证正面地址
     * @param idCardf       身份证反面地址
     * @param idCardzs      手持身份证正面地址
     * @param studentCard   学生卡
     * @param remarks       备注
     * @param customerName  用户姓名
     * @param contactNumber 联系电话
     * @param cardId        套餐ID
     * @param partner       用户ID
     * @param idCard        用户身份证
     * @param userSchool    学校
     * @return
     */
    @RequestMapping(value = "newMobilePhoneCard", method = RequestMethod.POST)
    @Transactional
    public ResponseData<String> newMobilePhoneCard(@RequestParam("contactNumber") String contactNumber, @RequestParam("site") String site
            , @RequestParam("studentCard") String studentCard, @RequestParam("address") String address, @RequestParam("cardId") String cardId
            , @RequestParam("customerName") String customerName, @RequestParam("partner") String partner
            , @RequestParam(value = "idCardzs") String idCardzs, @RequestParam(value = "idCardz") String idCardz, @RequestParam(value = "idCardf") String idCardf
            , @RequestParam(value = "remarks", required = false) String remarks, @RequestParam(value = "kapin") String kapin
            , @RequestParam(value = "idCard") String idCard, @RequestParam(value = "cardAddress") String cardAddress, @RequestParam("signUrl") String signUrl, @RequestParam("businessNumber") String businessNumber
            , @RequestParam(value = "clazz") String clazz, @RequestParam(value = "userSchool") String userSchool
            , @RequestParam(value = "isFromRh", required = false) String isFromRh
            , @RequestParam(value = "sell", required = false) String sell) {
        if (sell != null && StringUtils.isNumeric(sell)) {

        } else {
            sell = "";
        }
        if (contactNumber.length() != 11) {
            return ResponseData.error("联系号码有误，请重新输入");
        }

        /**
         * 套餐验证
         */
        ResponseData<String> pac = packageVerification(partner, cardId);
        if (!pac.isSuccess()) {
            return pac;
        }
        /**
         * 身份证验证最后一位 x =》 X
         */
        idCard = IDCardUtil.IdCardConversion(idCard);

        /**
         * 详细地址过滤掉空格
         */
        address = address.replace(" ", "");

        /**
         * 身份证验证
         */
        if (!IDCardUtil.IDCardValidate(idCard)) {
            return ResponseData.error("您的身份证输入有误，请重新输入！");
        }

        if (StringUtils.isBlank(cardAddress)) {
            return ResponseData.error("身份证地址不能为空");
        }

        /**
         *  详细地址验证
         */
        if (StringUtils.isBlank(address)) {
            return ResponseData.error("详细地址不能为空");
        } else {
            String[] sites = site.split(" ");
            for (int i = 0; i < sites.length; i++) {
                if (address.contains(sites[i])) {
                    address = address.replaceAll(sites[i], "");
                }
            }
            if (StringUtils.isBlank(address)) {
                return ResponseData.error("详细地址有误");
            }
        }

        /**
         * 黑牛卡年龄判断
         */
//         if(kapin.indexOf("黑牛") > -1) {
//             ResponseData<String> stringResponseData = heiNiuIdCardVerification(idCard, customerName);
//             if (!stringResponseData.isSuccess()) {
//                 return stringResponseData;
//             };
//         }

        /**
         * 办理中+94天内订单判断
         */
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -94);
        Date time = instance.getTime();
        Wrapper<Order> wrapper = new EntityWrapper();
        wrapper.eq("id_card", idCard);
        wrapper.ne("order_status", OrderStatus.ACCEPTEXCEPTCION.getName()).and().ne("order_status", OrderStatus.SUCCESSFULDISTRIBUTION.getName());
        wrapper.eq("user_type", UserType.NEWCUSTOMER.getId());
        List<Order> orders = orderMapper.selectList(wrapper);
        if (orders.size() != 0) {
            return ResponseData.error("您已经存在办理中的新开卡的订单，请联系客服咨询");
        }
        wrapper = new EntityWrapper();
        wrapper.eq("id_card", idCard);
        wrapper.gt("create_time", time);
        wrapper.eq("order_status", OrderStatus.SUCCESSFULDISTRIBUTION.getName());
        wrapper.eq("user_type", UserType.NEWCUSTOMER.getId());
        orders = orderMapper.selectList(wrapper);
        if (orders.size() != 0) {
            return ResponseData.error("您94天内已经存在新开卡的订单，请联系客服咨询");
        }

        SysUser sysUser = userMapper.selectById(partner);
        Order order = new Order();
        String uuid = UUID.randomUUID().toString();
        String id = uuid.split("-")[0] + uuid.split("-")[1];
        if (isFromRh.equals("true")) {
            order.setUserBussinessType("5");
        }

        OrderCardAddress orderCardAddress = new OrderCardAddress();
        orderCardAddress.setOrderId(id);
        orderCardAddress.setCardAddress(cardAddress);

        String orderNum = "YRYM" + ProduceIdUtil.getId();
        order.setId(id);
        order.setIdCard(idCard);
        order.setOrderStatus("待处理");
        order.setAddress(address);
        order.setUserSchool(userSchool);
        order.setHehuorenId(partner);
        order.setSite(site);
        order.setKapin(kapin);
        order.setPackageId(cardId);
        order.setClazz(clazz);
        order.setCustomerName(customerName);
        order.setContactNumber(contactNumber);
        order.setStudenCard(PicturesUtil.uploadPictures(studentCard, orderNum, PATHTYPE));
        order.setIdCardzs(PicturesUtil.uploadPictures(idCardzs, orderNum, PATHTYPE));
        order.setIdCardz(PicturesUtil.uploadPictures(idCardz, orderNum, PATHTYPE));
        order.setIdCardf(PicturesUtil.uploadPictures(idCardf, orderNum, PATHTYPE));
        order.setRemarks(remarks);
        order.setBusinessNumber(businessNumber);
        order.setSignImg(PicturesUtil.uploadPictures(signUrl, orderNum, "signImg"));
        order.setIsDelivery("2");
        Date date = new Date();
        order.setCreateTime(date);
        order.setUserType(UserType.NEWCUSTOMER.getId());
        order.setOrderNumber(orderNum);
        String schoolId = appMapper.selectSchoolId(partner);
        School school = schoolMapper.selectById(schoolId);
        order.setHehuorenArea(school.getSubName());
        order.setHehuorenName(sysUser.getName() + sell);
        order.setHehuorenSchool(school.getSchoolName());
        order.setHehuorenPhone(sysUser.getPhone());
        List<String> userId = appMapper.selectsupervisorBySchool(schoolId);
        if (userId != null && userId.size() == 1) {
            for (String data : userId) {
                try {
                    Wrapper<HhrUser> userWrapper = new EntityWrapper<>();
                    userWrapper.eq("id", data);
                    userWrapper.eq("position", "总经理");
                    List<HhrUser> hhrUsers = hhrUserMapper.selectList(userWrapper);
                    if (hhrUsers != null && hhrUsers.size() == 1) {
                        SysUser user = userMapper.selectById(hhrUsers.get(0).getId());
                        order.setSupervisorName(user.getName());
                    }
                } catch (Exception e) {
                    log.error("查询督导失败:" + e.getMessage(), e);
                }
            }
        }
        order.setLzgh(school.getLzgh());
        Integer orderInsert = orderMapper.insert(order);
        Integer orderCardAddressInsert = orderCardAddressMapper.insert(orderCardAddress);
        String url = "https://dx.dianyuanjiangli.com/mobile/#/hhr/handleSuccessful?orderId=" + id;
        log.info("预制卡订单查询短信地址:" + url);
        log.info("联系号码：" + contactNumber);
        SendSmsAndMail.sendSms(contactNumber, url, "2");
        if (orderInsert == 1 && orderCardAddressInsert == 1) {
            appMapper.inserOrderHis(id, "资料已提交", date, customerName);
            return ResponseData.success(id);
        }
        return ResponseData.error("开卡失败！请重新下单");
    }


    /**
     * 新开手机卡 天翼学生卡
     *
     * @param site          地址
     * @param kapin         套餐名
     * @param idCardz
     * @param idCardf
     * @param idCardzs
     * @param remarks       备注
     * @param studentNumber 学号
     * @param classNumber   班级
     * @param parentName    家长姓名
     * @param contactNumber 家长电话
     * @param cardId        套餐ID
     * @param customerName  学生姓名
     * @param partner       用户ID
     * @param idCard        家长身份证
     * @param userSchool    学校
     * @return
     */
    @RequestMapping(value = "skywingCard", method = RequestMethod.POST)
    public ResponseData<String> SkywingCard(@RequestParam("contactNumber") String contactNumber
            , @RequestParam("site") String site, @RequestParam("address") String address
            , @RequestParam("classNumber") String classNumber, @RequestParam("cardId") String cardId
            , @RequestParam("customerName") String customerName, @RequestParam("partner") String partner
            , @RequestParam(value = "idCardzs") String idCardzs, @RequestParam(value = "idCardz") String idCardz
            , @RequestParam(value = "parentName") String parentName, @RequestParam(value = "idCardf") String idCardf
            , @RequestParam(value = "remarks", required = false) String remarks, @RequestParam(value = "kapin") String kapin
            , @RequestParam(value = "idCard") String idCard, @RequestParam(value = "studentNumber") String studentNumber
            , @RequestParam("businessNumber") String businessNumber, @RequestParam("signUrl") String signUrl
            , @RequestParam(value = "userSchool") String userSchool, @RequestParam(value = "cardAddress") String cardAddress
            , @RequestParam(value = "isFromRh", required = false) String isFromRh
            , @RequestParam(value = "sell", required = false) String sell) {
        if (sell != null && StringUtils.isNumeric(sell)) {

        } else {
            sell = "";
        }
        if (contactNumber.length() != 11) {
            return ResponseData.error("联系号码有误，请重新输入");
        }
        /**
         * 套餐验证
         */
        ResponseData<String> pac = packageVerification(partner, cardId);
        if (!pac.isSuccess()) {
            return pac;
        }
        /**
         * 身份证验证最后一位 x =》 X
         */
        idCard = IDCardUtil.IdCardConversion(idCard);

        /**
         * 详细地址过滤掉空格
         */
        address = address.replace(" ", "");

        /**
         * 身份证验证
         */
        if (!IDCardUtil.IDCardValidate(idCard)) {
            return ResponseData.error("您的身份证输入有误，请重新输入！");
        }

        /**
         *  详细地址验证
         */
        if (StringUtils.isBlank(address)) {
            return ResponseData.error("详细地址不能为空");
        } else {
            String[] sites = site.split(" ");
            for (int i = 0; i < sites.length; i++) {
                if (address.contains(sites[i])) {
                    address = address.replaceAll(sites[i], "");
                }
            }
            if (StringUtils.isBlank(address)) {
                return ResponseData.error("详细地址有误");
            }
        }

        /**
         * 办理中+94天内订单判断
         */
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -94);
        Date time = instance.getTime();
        Wrapper<Order> wrapper = new EntityWrapper();
        wrapper.eq("id_card", idCard);
        wrapper.ne("order_status", OrderStatus.ACCEPTEXCEPTCION.getName()).and().ne("order_status", OrderStatus.SUCCESSFULDISTRIBUTION.getName());
        wrapper.eq("user_type", UserType.NEWCUSTOMER.getId());
        List<Order> orders = orderMapper.selectList(wrapper);
        if (orders.size() != 0) {
            return ResponseData.error("您已经存在办理中的新开卡的订单，请联系客服咨询！");
        }
        wrapper = new EntityWrapper();
        wrapper.eq("id_card", idCard);
        wrapper.gt("create_time", time);
        wrapper.eq("order_status", OrderStatus.SUCCESSFULDISTRIBUTION.getName());
        wrapper.eq("user_type", UserType.NEWCUSTOMER.getId());
        orders = orderMapper.selectList(wrapper);
        if (orders.size() != 0) {
            return ResponseData.error("您94天内已经存在新开卡的订单，请联系客服咨询！");
        }

        SysUser sysUser = userMapper.selectById(partner);
        Order order = new Order();
        String uuid = UUID.randomUUID().toString();
        String id = uuid.split("-")[0] + uuid.split("-")[1];
        order.setId(id);
        if (isFromRh.equals("true")) {
            order.setUserBussinessType("5");
        }

        OrderCardAddress orderCardAddress = new OrderCardAddress();
        orderCardAddress.setOrderId(id);
        orderCardAddress.setCardAddress(cardAddress);

        String orderNum = "YRYM" + ProduceIdUtil.getId();
        order.setIdCard(idCard);
        order.setOrderStatus("待处理");
        order.setUserSchool(userSchool);
        order.setHehuorenId(partner);
        order.setSite(site);
        order.setAddress(address);
        order.setKapin(kapin);
        order.setPackageId(cardId);
        order.setCustomerName(customerName);
        order.setContactNumber(contactNumber);
        order.setBusinessNumber(businessNumber);
        //图片处理
        order.setIdCardzs(PicturesUtil.uploadPictures(idCardzs, orderNum, PATHTYPE));
        order.setIdCardz(PicturesUtil.uploadPictures(idCardz, orderNum, PATHTYPE));
        order.setIdCardf(PicturesUtil.uploadPictures(idCardf, orderNum, PATHTYPE));

        order.setSignImg(PicturesUtil.uploadPictures(signUrl, orderNum, "signImg"));
        order.setRemarks(remarks);
        order.setClassNumber(classNumber);
        order.setParentName(parentName);
        order.setStudentNumber(studentNumber);
        Date date = new Date();
        order.setCreateTime(date);
        order.setUserType(UserType.NEWCUSTOMER.getId());
        order.setOrderNumber(orderNum);
        String schoolId = appMapper.selectSchoolId(partner);
        School school = schoolMapper.selectById(schoolId);
        order.setHehuorenArea(school.getSubName());
        order.setHehuorenName(sysUser.getName() + sell);
        order.setHehuorenSchool(school.getSchoolName());
        order.setHehuorenPhone(sysUser.getPhone());
        List<String> userId = appMapper.selectsupervisorBySchool(schoolId);
        if (userId != null && userId.size() != 0) {
            for (String data : userId) {
                try {
                    Wrapper<HhrUser> userWrapper = new EntityWrapper<>();
                    userWrapper.eq("id", data);
                    userWrapper.eq("position", "总经理");
                    List<HhrUser> hhrUsers = hhrUserMapper.selectList(userWrapper);
                    if (hhrUsers != null && hhrUsers.size() == 1) {
                        SysUser user = userMapper.selectById(hhrUsers.get(0).getId());
                        order.setSupervisorName(user.getName());
                    }
                } catch (Exception e) {
                    log.error("查询督导失败:" + e.getMessage(), e);
                }
            }
        }
        order.setLzgh(school.getLzgh());
        Integer insert = orderMapper.insert(order);
        Integer orderCardAddressInsert = orderCardAddressMapper.insert(orderCardAddress);
        String url = "https://dx.dianyuanjiangli.com/mobile/#/hhr/handleSuccessful?orderId=" + id;
        log.info("天翼学生卡订单查询短信地址:" + url);
        log.info("联系号码：" + contactNumber);
        SendSmsAndMail.sendSms(contactNumber, url, "2");
        if (insert == 1) {
            appMapper.inserOrderHis(id, "资料已提交", date, customerName);
            return ResponseData.success(id);
        }
        return ResponseData.error("开卡失败！");
    }

    /**
     * 新开手机卡 小白卡
     *
     * @param contactNumber  联系电话
     * @param site           地址
     * @param studentCard    学生卡
     * @param cardId         套餐ID
     * @param address        详细地址
     * @param customerName   用户姓名
     * @param partner        用户ID
     * @param businessNumber 办理号码
     * @param remarks        备注
     * @param kapin          套餐名
     * @param idCard         用户身份证
     * @param userSchool     学校
     * @return
     */
    @RequestMapping(value = "XiaoBaiCard", method = RequestMethod.POST)
    public ResponseData<String> XiaoBaiCard(@RequestParam("contactNumber") String contactNumber, @RequestParam("site") String site
            , @RequestParam("studentCard") String studentCard, @RequestParam("cardId") String cardId, @RequestParam("address") String address
            , @RequestParam("customerName") String customerName, @RequestParam("partner") String partner, @RequestParam("businessNumber") String businessNumber
            , @RequestParam(value = "remarks", required = false) String remarks, @RequestParam(value = "kapin") String kapin, @RequestParam("signUrl") String signUrl
            , @RequestParam(value = "idCard") String idCard, @RequestParam(value = "userSchool") String userSchool
            , @RequestParam(value = "isFromRh", required = false) String isFromRh
            , @RequestParam(value = "sell", required = false) String sell) {
        if (sell != null && StringUtils.isNumeric(sell)) {

        } else {
            sell = "";
        }

        /**
         * 身份证验证最后一位 x =》 X
         */
        idCard = IDCardUtil.IdCardConversion(idCard);

        /**
         * 详细地址过滤掉空格
         */
        address = address.replace(" ", "");

        /**
         * 待识别订单返回进入旧订单入口
         */
        Map<String, Object> mapData = new HashMap<>();
        Wrapper<Order> wrapper = new EntityWrapper();
        wrapper.eq("id_card", idCard);
        wrapper.eq("order_status", "待识别");
        wrapper.isNotNull("xb_order_id");
        wrapper.eq("user_type", UserType.NEWCUSTOMER.getId());
        List<Order> orders = orderMapper.selectList(wrapper);
        if (orders.size() != 0) {
            mapData.put("orderStatus", orders.get(0).getOrderStatus());
            return ResponseData.error("待识别");
        }
        /**
         * 办理中+94天内订单判断
         */
        wrapper = new EntityWrapper();
        wrapper.eq("id_card", idCard);
        wrapper.ne("order_status", OrderStatus.ACCEPTEXCEPTCION.getName()).and().ne("order_status", OrderStatus.SUCCESSFULDISTRIBUTION.getName());
        wrapper.eq("user_type", UserType.NEWCUSTOMER.getId());
        orders = orderMapper.selectList(wrapper);
        if (orders.size() != 0) {
            return ResponseData.error("您已经存在办理中的新开卡的订单，请联系客服咨询！");
        }
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -94);
        Date time = instance.getTime();
        wrapper = new EntityWrapper();
        wrapper.eq("id_card", idCard);
        wrapper.gt("create_time", time);
        wrapper.eq("order_status", OrderStatus.SUCCESSFULDISTRIBUTION.getName());
        wrapper.eq("user_type", UserType.NEWCUSTOMER.getId());
        orders = orderMapper.selectList(wrapper);
        if (orders.size() != 0) {
            return ResponseData.error("您94天内已经存在新开卡的订单，请联系客服咨询！");
        }

        if (contactNumber.length() != 11) {
            return ResponseData.error("联系号码有误，请重新输入");
        }
        String schoolId = appMapper.selectSchoolId(partner);
        School school = schoolMapper.selectById(schoolId);
        String netId = school.getNetId();
        Package aPackage = packageMapper.selectById(cardId);
        String xbId = aPackage.getXbId();
        /**
         * 套餐验证
         */
        ResponseData<String> pac = packageVerification(partner, cardId);
        if (!pac.isSuccess()) {
            return pac;
        }
        /**
         * 身份证验证
         */
        ResponseData<String> res = idCardVerification(idCard, customerName);
        if (!res.isSuccess()) {
            return res;
        }
        /**
         * 小白卡省渠/本地配送验证
         */
        String isDelivery = aPackage.getIsDelivery() + "";
        if (StringUtils.isBlank(isDelivery)) {
            return ResponseData.error("当前小白卡配送配置错误，请联系客服,谢谢。");
        }
        /**
         * 小白卡下单
         */
        JSONObject jsonObject = null;
        try {
            String[] sites = site.split("/");
            String shi = "";
            if (sites.length >= 2) {
                shi = sites[1];
            } else {
                return ResponseData.error("请选择邮寄地区");
            }

            String code = CityCode.getCodeByCity(shi);
            if (StringUtils.isBlank(code)) {
                return ResponseData.error("所选地区小白卡无法配送");
            }

            // 根据市获取编号
//            jsonObject = JSONObject.parseObject("{\"dataArray\":{\"salesName\":\"29元学霸星卡\",\"createTime\":\"2021-02-26 09:09:16\",\"orderStatus\":\"17\",\"coUserId\":\"245048\",\"orderCode\":\"120210226090852004565\",\"realPrice\":\"50.0\"},\"msg\":\"操作成功\",\"code\":\"0\",\"errorDescription\":\"\"}");
            jsonObject = XbkUtil.xbkOrderJT0002(businessNumber, idCard,
                    customerName, contactNumber, xbId, netId, code, address, isDelivery);
        } catch (Exception e) {
            log.error("小白卡下单接口调用异常", e.getMessage());
        }
        if (jsonObject == null) {
            return ResponseData.error("小白卡下单失败,如有疑问请联系客服,谢谢。");
        }
        if (!"0".equals(jsonObject.getString("code"))) {
            return ResponseData.error("提交失败:" + jsonObject.getString("msg"));
        }
        Map<String, Object> map = JSON.parseObject(jsonObject.getString("dataArray"), HashMap.class);

        SysUser sysUser = userMapper.selectById(partner);
        Order order = new Order();
        String uuid = UUID.randomUUID().toString();
        String id = uuid.split("-")[0] + uuid.split("-")[1];
        if (isFromRh.equals("true")) {
            order.setUserBussinessType("5");
        }
        order.setId(id);
        order.setIdCard(idCard);
        order.setXbOrderId(map.get("orderCode").toString());
        order.setOrderStatus("待识别");
        order.setUserSchool(userSchool);
        order.setHehuorenId(partner);
        order.setXbType("1");
        if (StringUtils.isNotBlank(site)) {
            order.setSite(site);
        }
        if (StringUtils.isNotBlank(address)) {
            order.setAddress(address);
        }
        String orderNum = "YRYM" + ProduceIdUtil.getId();
        order.setKapin(kapin);
        order.setPackageId(cardId);
        order.setCustomerName(customerName);
        order.setContactNumber(contactNumber);
        order.setRemarks(remarks);
        order.setStudenCard(PicturesUtil.uploadPictures(studentCard, orderNum, PATHTYPE));

        order.setSignImg(PicturesUtil.uploadPictures(signUrl, orderNum, "signImg"));
        order.setBusinessNumber(businessNumber);
        Date date = new Date();
        order.setCreateTime(date);
        order.setUserType(UserType.NEWCUSTOMER.getId());
        order.setOrderNumber(orderNum);
        order.setHehuorenArea(school.getSubName());
        order.setHehuorenName(sysUser.getName() + sell);
        order.setHehuorenSchool(school.getSchoolName());
        order.setHehuorenPhone(sysUser.getPhone());
        List<String> userId = appMapper.selectsupervisorBySchool(schoolId);
        // 查询督导
        if (userId != null && userId.size() != 0) {
            for (String data : userId) {
                try {
                    Wrapper<HhrUser> userWrapper = new EntityWrapper<>();
                    userWrapper.eq("id", data);
                    userWrapper.eq("position", "总经理");
                    List<HhrUser> hhrUsers = hhrUserMapper.selectList(userWrapper);
                    if (hhrUsers != null && hhrUsers.size() == 1) {
                        SysUser user = userMapper.selectById(hhrUsers.get(0).getId());
                        order.setSupervisorName(user.getName());
                    }
                } catch (Exception e) {
                    log.error("查询督导失败:" + e.getMessage(), e);
                }
            }
        }

        order.setLzgh(school.getLzgh());
        order.setIsDelivery(isDelivery);
        Integer insert = orderMapper.insert(order);
        String url = "https://dx.dianyuanjiangli.com/mobile/#/hhr/handleSuccessful?orderId=" + id;
        log.info("小白卡订单查询短信地址:" + url);
        log.info("联系号码：" + contactNumber);
        SendSmsAndMail.sendSms(contactNumber, url, "2");
        if (insert == 1) {
            appMapper.inserOrderHis(id, "资料提交成功,等待上传证件", date, customerName);
            if (StringUtils.isNotEmpty(isFromRh)) {
                String resMsg = "该订单是由融合进来下单";
                //SendSmsAndMail.sendSms(contactNumber, resMsg, "2");
            }
            return ResponseData.success(map.get("orderCode").toString());
        }
        return ResponseData.success("下单失败！");
    }

    /**
     * 黑牛卡身份证验证
     *
     * @param idCard       黑牛卡身份证
     * @param customerName 姓名
     * @return
     */
    public static ResponseData<String> heiNiuIdCardVerification(String idCard, String customerName) {
        JSONObject jsonObject1 = null;
        try {
            jsonObject1 = XbkUtil.idCardCheckJT0005(idCard, customerName);
        } catch (Exception e) {
            log.error("身份证验证接口调用异常", e.getMessage());
        }
        if (jsonObject1 == null) {
            log.info("身份证验证接口调用异常");
            return ResponseData.error("身份证验证失败。");
        }
        if (!"0".equals(jsonObject1.getString("code"))) {
            return ResponseData.error(jsonObject1.getString("msg"));
        }
        Integer i = Integer.parseInt(idCard.substring(6, 10));
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date timeDate = new Date();
        Integer age = Integer.parseInt(dateFormat.format(timeDate.getTime()));
        Integer time25 = Integer.parseInt(String.valueOf(i + 25) + idCard.substring(10, 14));
        if (age > time25) {
            return ResponseData.error("您已满25周岁,不符合办理条件,如有疑问请联系客服,谢谢。");
        }
        return ResponseData.success("OK");
    }

    /**
     * 身份证验证
     *
     * @param idCard       身份证
     * @param customerName 姓名
     * @return
     */
    public static ResponseData<String> idCardVerification(String idCard, String customerName) {
        JSONObject jsonObject1 = null;
        try {
            jsonObject1 = XbkUtil.idCardCheckJT0005(idCard, customerName);
        } catch (Exception e) {
            log.error("身份证验证接口调用异常", e.getMessage());
        }
        if (jsonObject1 == null) {
            log.info("身份证验证接口调用异常");
            return ResponseData.error("身份证验证失败。");
        }
        if (!"0".equals(jsonObject1.getString("code"))) {
            return ResponseData.error(jsonObject1.getString("msg"));
        }
        Integer i = Integer.parseInt(idCard.substring(6, 10));
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date timeDate = new Date();
        Integer age = Integer.parseInt(dateFormat.format(timeDate.getTime()));
        Integer time16 = Integer.parseInt(String.valueOf(i + 16) + idCard.substring(10, 14));
        Integer time27 = Integer.parseInt(String.valueOf(i + 27) + idCard.substring(10, 14));
        if (age < time16) {
            return ResponseData.error("根据工信部要求,未满16周岁的用户,应由法定代理人代为办理线上入网,如有疑问请联系客服,谢谢。");
        }
        if (age > time27) {
            return ResponseData.error("您已满27周岁,不符合办理条件,如有疑问请联系客服,谢谢。");
        }
        return ResponseData.success("OK");
    }

    /**
     * 查询当前用户是否适用此套餐
     *
     * @param partner
     * @return
     */
    public ResponseData<String> packageVerification(String partner, String packageID) {
        String schoolId = appMapper.selectSchoolId(partner);
        if (schoolId == null) {
            return ResponseData.error("当前二维码已失效，如有疑问请联系客服！");
        }
        List<String> packageIds = appMapper.selectPackageId(schoolId);
        if (packageIds.contains(packageID)) {
            return ResponseData.success("ok");
        }
        return ResponseData.error("当前二维码无法办理此套餐，如有疑问请联系客服！");
    }

}
