package com.winsun.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
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.auth.core.util.IOUtils;
import com.winsun.bean.Package;
import com.winsun.bean.*;
import com.winsun.constant.DeliveryType;
import com.winsun.constant.ExamineType;
import com.winsun.constant.FilePath;
import com.winsun.constant.UserType;
import com.winsun.mapper.*;
import com.winsun.rabbitmq.RabbitProducer;
import com.winsun.service.IHhrUserService;
import com.winsun.service.ISalesListService;
import com.winsun.smsUtils.SendSmsAndMail;
import com.winsun.utils.Constant;
import com.winsun.utils.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.SSLHandshakeException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: dongyp
 * @Date: 2020/2/14 17:08
 */
@Slf4j
@RestController
@RequestMapping("/order") //
public class OrderController extends BaseController {

    private final String GATEWAY = "http://localhost:10001/";

    /**
     * 导入
     */
    private static final int HEADER_NUM = -1;
    private static final int SHEET_INDEX = 0;
    /**
     * 受理单模板列名
     */
    private static String SL_ORDERNUMBER = "订单编号(必填)";
    private static String SL_ACCEPTRESULT = "受理结果(必填)";
    private static String SL_ACCEPTNAME = "受理人(必填)";
    private static String SL_ACCERPCOMMENT = "备注（受理不成功需填写不成功原因）";
    /**
     * 快递清单模板列名 订单编号	客户姓名	联系号码	合伙人学校	快递单号	白卡ICCID
     */
    private static String KD_ORDERNUMBER = "订单编号(必填)";
    private static String KD_SENDTYPE = "快递方式(必填)";
    private static String KD_COMPANY = "快递公司(必填)";
    private static String KD_KUAIDORDER = "快递单号(必填)";
    private static String KD_CONTACTNAME = "客户姓名";
    private static String KD_CONTACTNUMBER = "联系号码";
    private static String KD_HEHUORENSCHOOL = "合伙人学校";
    private static String KD_BUSINESSICCID = "白卡ICCID(必填)";


    /**
     * 预制卡清单模板列名
     */
    private static String YZK_ORDERNUMBER = "订单编号(必填)";
    private static String BUSINESS_NUMBER = "办理号码(必填)";
    private static String BUSINESS_ICCID = "iccid(必填)";

    /**
     * 5G加装包清单模板列名
     */
    private static String ORDER_STATUS = "受理状态（已完成，异常单）";


    private static OrderMapper orderMapper;
    private static OrderViewMapper orderViewMapper;

    private static SchoolMapper schoolMapper;

    private static SysUserMapper sysUserMapper;

    private static AppMapper appMapper;

    private ExportExcelMapper exportExcelMapper;

    @Autowired
    private PackageMapper packageMapper;

    @Autowired
    private HhrUserMapper hhrUserMapper;

    @Autowired
    private YsmUserMapper ysmUserMapper;

    @Autowired
    private RabbitProducer taskImport;

    @Autowired
    private SalesListController salesListController;

    @Autowired
    private SalesListMapper salesListMapper;

    @Autowired
    private IHhrUserService hhrUserService;

    @Autowired
    private ISalesListService salesListService;


    @Autowired
    public OrderController(OrderMapper orderMapper, SchoolMapper schoolMapper, SysUserMapper sysUserMapper,
                           AppMapper appMapper, ExportExcelMapper exportExcelMapper, OrderViewMapper orderViewMapper) {
        OrderController.orderMapper = orderMapper;
        OrderController.schoolMapper = schoolMapper;
        OrderController.sysUserMapper = sysUserMapper;
        OrderController.appMapper = appMapper;
        this.exportExcelMapper = exportExcelMapper;
        OrderController.orderViewMapper = orderViewMapper;
    }

    /**
     * 查询订单历史状态
     */
    @Permission(menuname = "查询订单历史状态", value = "selectOrderHis", method = RequestMethod.POST)
    public ResponseData<List<Map<String, Object>>> selectOrderHis(@RequestParam("orderId") String orderId) {
        List<Map<String, Object>> list = orderMapper.selectOrderHis(orderId);
        return ResponseData.success(list);
    }

    /**
     * 修改配送方式
     * @param id
     * @param sendType
     * @return
     */
    @Permission(menuname = "更新配送方式", value = "updateSendType", method = RequestMethod.POST)
    public ResponseData<String> updateSendType(@RequestParam("id") String id, @RequestParam("sendType") String sendType) {
        ShiroUser user = getShiroUser();

        Order order = new Order();
        order.setSendType(sendType);
        order.setId(id);

        Order databaseOrder = orderMapper.selectById(id);
        if(databaseOrder == null) {
            return ResponseData.error("更新配送方式失败，未找到当前订单！");
        }
        if (StringUtils.isBlank(databaseOrder.getPackageId())) {
            return ResponseData.error("更新配送方式失败，当前订单不是移动卡订单！");
        }

        Package packageInfo = packageMapper.selectById(databaseOrder.getPackageId());
        // 查询产品
        if (packageInfo == null) {
            return ResponseData.error("更新配送方式失败，未找到当前订单套餐！");
        }
        // 小白卡是0，预制卡是1
        if (packageInfo.getIsXbCard() == 0) {
            // 小白卡修改为待配送状态
            // 上门则改为待活体
            order.setOrderStatus("待配送");
            // 由于业务需求，暂不允许“送货上门”
//            if ("送货上门".equals(sendType)) {
//                order.setOrderStatus("待活体");
//            }
        }else if(packageInfo.getIsXbCard() == 1){
            //预制卡 改为待选号
            order.setOrderStatus("待选号");
        }else{
            return ResponseData.error("更新配送方式失败，套餐信息有误！");
        }

        Integer integer = orderMapper.updateById(order);
        if (integer == 1) {
            appMapper.inserOrderHis(id, "销售员已接单!", new Date(), user.getName());
        } else {
            return ResponseData.error("更新配送方式失败！");
        }
        return ResponseData.success("更新配送方式成功！");
    }

    /**
     * 修改iccid
     * @param id
     * @param businessIccid
     * @param businessNumber
     * @return
     */
    @Permission(menuname = "更新iccid", value = "updateIccid", method = RequestMethod.POST)
    public ResponseData<String> updateIccid(@RequestParam("id") String id, @RequestParam("businessIccid") String businessIccid,
                                            @RequestParam("businessNumber") String businessNumber) {
        ShiroUser user = getShiroUser();
        // 初始化保存参数
        Order saveOrder = new Order();
        saveOrder.setBusinessNumber(businessNumber);
        saveOrder.setBusinessIccid(businessIccid);
        saveOrder.setId(id);

        // 获取快递方式
        Order sendTypeOrder = orderMapper.selectById(id);

        if (StringUtils.isNotBlank(sendTypeOrder.getBusinessNumber())
            && !saveOrder.getBusinessNumber().equals(sendTypeOrder.getBusinessNumber())) {
            return ResponseData.error("办理号码与客户填写不一致，无法下单。");
        }

        if ("快递".equals(sendTypeOrder.getSendType())) {
            saveOrder.setOrderStatus("提交中");
            Integer integer = orderMapper.updateById(saveOrder);
            if (integer == 1) {
                appMapper.inserOrderHis(id, "实名验证中", new Date(), user.getName());
                // 另起线程执行智能平台下单
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        log.info("线程开始执行");
                        Order order = orderMapper.selectById(id);
                        String hehuoren_id = order.getHehuorenId();
                        String business_number = order.getBusinessNumber();
                        String business_iccid = order.getBusinessIccid();
                        if (StringUtils.isBlank(business_iccid)) {
                            business_iccid = businessNumber;
                        }
                        HhrUser hhrUser = hhrUserMapper.selectById(hehuoren_id);
                        Map<String, Object> map1 = new HashMap<>();

                        int ysm = Integer.parseInt(hhrUser.getYsm());
                        YsmUser ysmUser = ysmUserMapper.selectById(ysm);
                        map1.put("ysmUser", ysmUser.getUserName());
                        map1.put("sign", ysmUser.getSign());

                        map1.put("idCardUrl1", order.getIdCardz());
                        map1.put("idCardUrl2", order.getIdCardf());
                        map1.put("idCardUrl3", order.getIdCardzs());
                        map1.put("cardType", order.getKapin());

                        if (order.getPackageId().equals("49")) {
                            map1.put("userName", order.getParentName());
                            map1.put("idCardUrl4", order.getIdCardzs());
                        } else {
                            map1.put("userName", order.getCustomerName());
                            map1.put("idCardUrl4", order.getStudenCard());
                        }
                        map1.put("linkPhone", order.getContactNumber());
                        map1.put("idCard", order.getIdCard());
                        map1.put("orderPhone", business_number);
                        map1.put("iccId", business_iccid);

                        String site = order.getSite().toString();
                        String[] split = null;
                        if(site.indexOf(" ") != -1) {
                            split = site.split(" ");
                        }else{
                            split = new String[3];
                        }

                        map1.put("sheng", split[0]);
                        map1.put("shi", split[1]);
                        if (split.length > 2) {
                            map1.put("xian", split[2]);
                        } else {
                            map1.put("xian", "无");
                        }
                        map1.put("address", order.getAddress());


                        String result = "";
                        // 发送智能平台参数
                        result = sendOrder(map1);

                        JSONObject resultDataJson = JSONObject.fromObject(result);
                        String orderNum = resultDataJson.getString("orderNumber");
                        Order updateOrder = new Order();
                        updateOrder.setId(order.getId());
                        if (Is.isNoEmpty(orderNum)) {
                            updateOrder.setOrderStatus("审核中");
                            updateOrder.setOrderId(orderNum);
                        } else {
                            updateOrder.setOrderStatus("异常单");
                            String msg = resultDataJson.getString("msg");
                            updateOrder.setMsg(msg);
                            try {
                                // 添加操作记录
                                appMapper.inserOrderHis(order.getId(), msg, new Date(), "智能平台");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            // 更新状态
                            orderMapper.updateById(updateOrder);
                        } catch (Exception e) {
                            log.error("更新状态:", e);
                        }
                    }
                }).start();
            } else {
                return ResponseData.error("更新iccid失败！");
            }
        }else if ("送货上门".equals(sendTypeOrder.getSendType())){
            saveOrder.setOrderStatus("已发货");
            if(sendTypeOrder.getUserType().equals("1")) {
                saveOrder.setOrderStatus("待受理");
            }
            Integer integer = orderMapper.updateById(saveOrder);
            if (integer > 0 && !sendTypeOrder.getUserType().equals("1")) {
                HhrUser hhrUser = hhrUserMapper.selectById(sendTypeOrder.getHehuorenId());
                int ysm = Integer.parseInt(hhrUser.getYsm());
                YsmUser ysmUser = ysmUserMapper.selectById(ysm);
                if (ysmUser.getStatus() == 1) {
                    log.info("销售订单带同步");
                    this.syncSalesOrder(sendTypeOrder.getId(), "新用户办理");
                }
            }
            // 添加操作记录
            appMapper.inserOrderHis(sendTypeOrder.getId(), "送货上门中", new Date(), user.getName());
        }else{
            ResponseData.error("请先填写配送方式");
        }
        return ResponseData.success("更新iccid成功！");
    }

    /**
     * 同步销售订单
     * @param orderId
     */
    public void syncSalesOrder(String orderId, String orderType) {
        Order order = orderMapper.selectById(orderId);
        List<Map<String, Object>> listForMap = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("a", "");
        map.put("b", order.getBusinessNumber());
        map.put("c", order.getHehuorenName());
        map.put("d", order.getHehuorenPhone());
        map.put("e", order.getHehuorenSchool());
        map.put("f", order.getHehuorenArea());
        map.put("g", orderType);
        listForMap.add(map);
        Map<String, Object> stringObjectMap = salesListController.dealUploadData(listForMap);

    }

    /**
     * 审核学生证
     */
    @Permission(menuname = "审核学生证", value = "reviewStudentIdCard", method = RequestMethod.POST)
    public ResponseData<String> reviewStudentIdCard(@RequestParam("studentCardCheckStatus") String studentCardCheckStatus, @RequestParam(name = "checkFail", required = false) String checkFail, @RequestParam("id") String id) {
        ShiroUser user = getShiroUser();
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", id);
        Map<String, Object> dataMapping = new HashMap<>();
        dataMapping.put("student_card_check_status", studentCardCheckStatus);
        if (StringUtils.isNotBlank(checkFail)) {
            dataMapping.put("check_fail", checkFail);
        }
        Integer integer = orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if (integer == 1) {
            if ("1".equals(studentCardCheckStatus)) {
                appMapper.inserOrderHis(id, "审核通过!", new Date(), user.getName());
            } else {
                appMapper.inserOrderHis(id, "审核不通过:" + checkFail, new Date(), user.getName());
            }
        } else {
            return ResponseData.error("审核失败！");
        }
        return ResponseData.success("审核成功！");
    }

    /**
     * 修改为异常单
     */
    @Permission(menuname = "修改为异常单", value = "setAbnormal", method = RequestMethod.POST)
    public ResponseData<String> abnormal(@RequestParam("orderId") String orderId,@RequestParam("errorMsg") String errorMsg) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员","系统管理员","县分管理员（订单）","受理人员"))) {
            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 == 1) {
            appMapper.inserOrderHis(orderId, "设置异常单,原因："+errorMsg, new Date(), user.getName());
            return ResponseData.success("设为异常单成功！");
        }
        return ResponseData.error("设为异常单失败！");
    }


    /**
     * @param createTimeStart  订单创建时间开始
     * @param createTimeEnd    订单创建时间结束
     * @param successTimeStart 订单完成时间开始
     * @param successTimeEnd   订单完成时间结束
     * @param userType         客户类型
     * @param orderNumber      订单编号
     * @param kapin            卡品
     * @param businessNumber   办理号码
     * @param contactNumber    联系号码
     * @param hehuorenSchool   合伙人学校
     * @param hehuorenName     合伙人姓名
     * @param orderStatus      订单状态
     * @param customerName     客户姓名
     * @param pageSize
     * @return
     */
    @Permission(menuname = "查询订单信息", value = "list", method = RequestMethod.POST)
    public Map<String,Object> listOrder(
            @RequestParam(name = "createTimeStart", required = false) String createTimeStart,
            @RequestParam(name = "createTimeEnd", required = false) String createTimeEnd,
            @RequestParam(name = "successTimeStart", required = false) String successTimeStart,
            @RequestParam(name = "successTimeEnd", required = false) String successTimeEnd,
            @RequestParam(name = "kuaidiTimeStart", required = false) String kuaidiTimeStart,
            @RequestParam(name = "kuaidiTimeEnd", required = false) String kuaidiTimeEnd,
            @RequestParam("userType") String userType,
            @RequestParam(name = "orderNumber", required = false) String orderNumber,
            @RequestParam(name = "kapin", required = false) String kapin,
            @RequestParam(name = "businessNumber", required = false) String businessNumber,
            @RequestParam(name = "contactNumber", required = false) String contactNumber,
            @RequestParam(name = "hehuorenSchool", required = false) String hehuorenSchool,
            @RequestParam(name = "hehuorenName", required = false) String hehuorenName,
            @RequestParam(name = "orderStatus", required = false) String orderStatus,
            @RequestParam(name = "hehuorenArea", required = false) String hehuorenArea,
            @RequestParam(name = "customerName", required = false) String customerName,
            @RequestParam(name = "orderId", required = false)String orderId,
            @RequestParam(name = "xbOrderId", required = false) String xbOrderId,
            @RequestParam(name = "businessPackage", required = false) String businessPackage,
            @RequestParam(name = "pageNo", required = false) int pageNo,
            @RequestParam(name = "pageSize", required = false) int pageSize) {
        Map<String,Object> map = new HashMap<>();

        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员", "系统管理员", "县分管理员（订单）", "合伙人", "快递公司"))) {
            map.put("error","无数据权限");
            return map;
        }

        // 添加查询权限
        List<Integer> userIds = hhrUserService.getUserIds(user.getId(), user.getRoleNames());

        Wrapper<Order> wrapper = new EntityWrapper();

        if (userIds.size() != 0) {
            wrapper.in("hehuoren_id", userIds);
        }

        wrapper.isNull("kd_order_id");
        wrapper.notIn("user_type",3,5,9,10);
        wrapper.ge(StringUtils.isNotBlank(createTimeStart), "create_time", createTimeStart);
        wrapper.le(StringUtils.isNotBlank(createTimeEnd), "create_time", createTimeEnd);
        wrapper.ge(StringUtils.isNotBlank(successTimeStart), "success_time", successTimeStart);
        wrapper.le(StringUtils.isNotBlank(successTimeEnd), "success_time", successTimeEnd);
        wrapper.ge(StringUtils.isNotBlank(kuaidiTimeStart), "kuaidi_time", kuaidiTimeStart);
        wrapper.le(StringUtils.isNotBlank(kuaidiTimeEnd), "kuaidi_time", kuaidiTimeEnd);
        wrapper.eq(StringUtils.isNotBlank(userType), "user_type", userType);
        wrapper.eq(StringUtils.isNotBlank(orderNumber), "order_number", orderNumber);
        wrapper.eq(StringUtils.isNotBlank(orderId),"order_id", orderId);
        wrapper.eq(StringUtils.isNotBlank(xbOrderId), "xb_order_id", xbOrderId);
        wrapper.eq(StringUtils.isNotBlank(kapin), "kapin", kapin);
        wrapper.eq(StringUtils.isNotBlank(customerName), "customer_name", customerName);
        wrapper.eq(StringUtils.isNotBlank(businessNumber), "business_number", businessNumber);
        wrapper.eq(StringUtils.isNotBlank(contactNumber), "contact_number", contactNumber);
        wrapper.like(StringUtils.isNotBlank(hehuorenSchool), "hehuoren_school", hehuorenSchool);
        wrapper.like(StringUtils.isNotBlank(hehuorenName), "hehuoren_name", hehuorenName, SqlLike.DEFAULT);
        wrapper.like(StringUtils.isNotBlank(businessPackage), "business_package", businessPackage, SqlLike.DEFAULT);

        wrapper.eq(StringUtils.isNotBlank(hehuorenArea), "hehuoren_area", hehuorenArea);

        if (user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "快递公司"))) {
            wrapper.in("order_status", "待配送,待活体,已完成");
            wrapper.eq("is_delivery","2");
        }

        wrapper.eq(StringUtils.isNotBlank(orderStatus), "order_status", orderStatus).orderBy("create_time",false);


        Page<Order> page = new Page<>(pageNo, pageSize);
        List<Order> aPackage = orderMapper.selectPage(page, wrapper);
        page.setRecords(aPackage);
        if (user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "楼长","成员","受理人员"))) {
            map.put("isAbnormal",false);
        }else {
            map.put("isAbnormal",true);
        }
        if (user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "修改身份证","超级管理员"))) {
            map.put("isEdit",true);
        }else {
            map.put("isEdit",false);
        }
        map.put("page",ResponseData.success(page,"查询成功！"));
        return map;
    }

    /**
     * 查询宽带订单
     * @param broadBandOrder
     * @return
     */
    @Permission(menuname = "查询订单信息", value = "broadBandOrder", method = RequestMethod.POST)
    public ResponseData<Page<BroadBandOrder>> getBroadBandOrder(BroadBandOrder broadBandOrder) {

        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员", "系统管理员", "县分管理员（订单）", "修改身份证", "合伙人"))) {
            ResponseData.error("无权限查询订单");
        }

        List<Integer> userIds = hhrUserService.getUserIds(user.getId(), user.getRoleNames());

        if (userIds.size() != 0) {
            broadBandOrder.setHehuorenIds(userIds);
        }

        Page<BroadBandOrder> page = new Page<>(broadBandOrder.getPageNo(), broadBandOrder.getPageSize());
        broadBandOrder.setPageStart((broadBandOrder.getPageNo() - 1) * broadBandOrder.getPageSize());
        List<BroadBandOrder> broadBandOrders = orderMapper.selectBroadBandOrderList(page, broadBandOrder);
        page.setRecords(broadBandOrders);

        return ResponseData.success(page);
    }

    /**
     * 编辑宽带订单（超级管理员、县分管理员、修改身份证）
     *
     * @return
     */
    @Permission(menuname = "编辑订单", value = "editOrder", method = RequestMethod.POST)
    public ResponseData<String> editOrder(@RequestParam("id") String id,@RequestParam(value = "studentNumber",required = false) String student_number,
                                          @RequestParam(value = "classNumber",required = false) String class_number,@RequestParam(value = "parentName",required = false) String parent_name,
                                          @RequestParam(value = "contactNumber",required = false) String contact_number, @RequestParam(value = "idCard",required = false) String id_card,
                                          @RequestParam(value = "studentCard",required = false) String student_card,@RequestParam(value = "address",required = false) String address,
                                          @RequestParam(value = "site",required = false) String site, @RequestParam(value = "remarks",required = false) String remarks,@RequestParam(value = "orderStatus",required = false) String order_status) {
        ShiroUser user = getShiroUser();

        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员","系统管理员", "县分管理员（订单）", "修改身份证"))) {
            ResponseData.error("无权限修改订单");
        }

        List<Map<String, Object>> hhrOrderId = orderMapper.findHhrOrderId(id);
        if(hhrOrderId.size()!=1){
            return ResponseData.error("无数据查询");
        }

        Map<String, Object> order = hhrOrderId.get(0);
        StringBuffer sf = new StringBuffer();
        int num = 0;
        if (StringUtils.isNotBlank(student_card)) {
            try {
                //重新上传图片

                String base64Data =  student_card.split(",")[1];
                String houzhui = student_card.split(",")[0].split("/")[1].split(";")[0];
                /**
                 * 2.解码成字节数组
                 */
                String filePath = hhrOrderId.get(0).get("studen_card").toString();
                Base64.Decoder decoder = Base64.getDecoder();
                byte[] bytes = decoder.decode(base64Data);
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(filePath);
                    fos.write(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (fos != null){
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseData.error("服务器出错！");
            }
            sf.append(",重新上传学生证");
        }
        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq("id", id);
        Map<String, Object> dataMapping = new HashMap<>();
        dataMapping.put("update_time",new Date());
        if(StringUtils.isNoneBlank(student_number) && !student_number.equals(hhrOrderId.get(0).get("student_number"))){
            dataMapping.put("student_number",student_number);
            sf.append(",用户学号由"+order.get("student_number")+"修改为"+student_number);
        }
        if(StringUtils.isNoneBlank(class_number) && !class_number.equals(hhrOrderId.get(0).get("class_number"))){
            dataMapping.put("class_number",class_number);
            sf.append(",用户班级由"+order.get("class_number")+"修改为"+class_number);
        }
        if(StringUtils.isNoneBlank(parent_name) && !parent_name.equals(hhrOrderId.get(0).get("parent_name"))){
            dataMapping.put("parent_name",parent_name);
            sf.append(",用户家长姓名由"+order.get("parent_name")+"修改为"+parent_name);
        }
        if(StringUtils.isNoneBlank(contact_number) && !contact_number.equals(hhrOrderId.get(0).get("contact_number"))){
            dataMapping.put("contact_number",contact_number);
            sf.append(",联系号码由"+order.get("contact_number")+"修改为"+contact_number);
        }
        if(StringUtils.isNoneBlank(id_card) && !id_card.equals(hhrOrderId.get(0).get("id_card"))){
            dataMapping.put("id_card",id_card);
            sf.append(",身份证号由"+order.get("id_card")+"修改为"+id_card);
        }
        if(StringUtils.isNoneBlank(address) && !address.equals(hhrOrderId.get(0).get("address"))){
            dataMapping.put("address",address);
            sf.append(",地址由"+order.get("address")+"修改为"+address);
        }
        if(StringUtils.isNoneBlank(site) && !site.equals(hhrOrderId.get(0).get("site"))){
            dataMapping.put("site",site);
            sf.append(",区域由"+order.get("site")+"修改为"+site);
        }
        if(StringUtils.isNoneBlank(remarks) && !remarks.equals(hhrOrderId.get(0).get("remarks"))){
            dataMapping.put("remarks",remarks);
            sf.append(",备注由"+order.get("remarks")+"修改为"+remarks);
        }
        if(StringUtils.isNoneBlank(order_status) && !order_status.equals(hhrOrderId.get(0).get("order_status"))){
            dataMapping.put("order_status",order_status);
            sf.append(",订单状态由"+order.get("order_status")+"修改为"+order_status);
        }
        try {
            if ("重新下单".equals(order_status)) {
                dataMapping.put("order_status","未下单");
                // 重新生成码
                Wrapper<OrderView> orderViewWrapper = new EntityWrapper<>();
                orderViewWrapper.eq("orderSeq", hhrOrderId.get(0).get("kd_order_id"));
                List<OrderView> orderViews = orderViewMapper.selectList(orderViewWrapper);
                if (orderViews == null || orderViews.size() != 1) {
                    return ResponseData.success("编辑失败，无法重新下单！");
                }

                String orderSeq = RandomUtil.RandomNumber(20);

                dataMapping.put("kd_order_id", orderSeq);

                OrderView orderView = new OrderView();
                orderView.setOrderId(orderViews.get(0).getOrderId());
                orderView.setOrderSeq(orderSeq);
                orderViewMapper.updateById(orderView);
            }
            Integer integer = orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
            if(integer == 1){
                orderMapper.inserOrderHis(id,"用户资料修改:"+sf.toString(),new Date(),user.getName());
                return ResponseData.success("编辑完毕！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error("服务器出错！");
        }
        return ResponseData.success("编辑完毕！");
    }


    @Permission(menuname = "导出订单", value = "download", method = RequestMethod.POST)
    public ResponseData<String> downloadOrderView(
            @RequestParam(name = "createTimeStart", required = false) String createTimeStart,
            @RequestParam(name = "createTimeEnd", required = false) String createTimeEnd,
            @RequestParam(name = "successTimeStart", required = false) String successTimeStart,
            @RequestParam(name = "successTimeEnd", required = false) String successTimeEnd,
            @RequestParam(name = "kuaidiTimeStart", required = false) String kuaidiTimeStart,
            @RequestParam(name = "kuaidiTimeEnd", required = false) String kuaidiTimeEnd,
            @RequestParam("userType") String userType,
            @RequestParam(name = "orderNumber", required = false) String orderNumber,
            @RequestParam(name = "kapin", required = false) String kapin,
            @RequestParam(name = "businessNumber", required = false) String businessNumber,
            @RequestParam(name = "contactNumber", required = false) String contactNumber,
            @RequestParam(name = "hehuorenSchool", required = false) String hehuorenSchool,
            @RequestParam(name = "hehuorenArea", required = false) String hehuorenArea,
            @RequestParam(name = "hehuorenName", required = false) String hehuorenName,
            @RequestParam(name = "orderStatus", required = false) String orderStatus,
            @RequestParam(name = "customerName", required = false) String customerName,
            @RequestParam(name = "businessPackage", required = false) String businessPackage) {

        String dateFormat = "YYYY-MM-DD";
        if (StringUtils.isNotBlank(createTimeStart) && StringUtils.isNotBlank(createTimeEnd)) {
            createTimeStart = createTimeStart.substring(0, dateFormat.length()) + " 00:00:00";
            createTimeEnd = createTimeEnd.substring(0, dateFormat.length()) + " 23:59:59";
        } else {
            createTimeStart = null;
            createTimeEnd = null;
        }
        Map<String, Object> map = new HashMap<>();
        ShiroUser user = getShiroUser();
        map.put("userId", user.getId());
        map.put("userName", user.getName());
        if (StringUtils.isNotBlank(createTimeStart)) {
            map.put("createTimeStart", createTimeStart);
        }
        if (StringUtils.isNotBlank(createTimeEnd)) {
            map.put("createTimeEnd", createTimeEnd);
        }
        if (StringUtils.isNotBlank(successTimeStart)) {
            map.put("successTimeStart", successTimeStart);
        }
        if (StringUtils.isNotBlank(successTimeEnd)) {
            map.put("successTimeEnd", successTimeEnd);
        }
        if (StringUtils.isNotBlank(kuaidiTimeStart)) {
            map.put("kuaidiTimeStart", kuaidiTimeStart);
        }
        if (StringUtils.isNotBlank(kuaidiTimeEnd)) {
            map.put("kuaidiTimeEnd", kuaidiTimeEnd);
        }
        if (StringUtils.isNotBlank(userType)) {
            map.put("userType", userType);
        }
        if (StringUtils.isNotBlank(orderNumber)) {
            map.put("orderNumber", orderNumber);
        }
        if (StringUtils.isNotBlank(customerName)) {
            map.put("customerName", customerName);
        }
        if (StringUtils.isNotBlank(businessNumber)) {
            map.put("businessNumber", businessNumber);
        }
        if (StringUtils.isNotBlank(contactNumber)) {
            map.put("contactNumber", contactNumber);
        }
        if (StringUtils.isNotBlank(hehuorenSchool)) {
            map.put("hehuorenSchool", hehuorenSchool);
        }
        if (StringUtils.isNotBlank(hehuorenName)) {
            map.put("hehuorenName", hehuorenName);
        }

        if (StringUtils.isNotBlank(orderStatus)) {
            map.put("orderStatus", orderStatus);
        }

        if (StringUtils.isNotBlank(businessPackage)) {
            map.put("businessPackage", businessPackage);
        }

        if (user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "快递公司"))) {
            // 快递员仅能导出 新用户办理、待配送、分公司配送订单
            map.put("userType",0);
            map.put("orderStatus", "待配送");
            map.put("isDelivery", 2);
        }
        map.put("hehuorenArea", hehuorenArea);
        try {
            ExportOrderView(map);
            taskImport.taskImport(map);
        } catch (Exception e) {
            log.error("订单导出队列异常", e.getMessage());
            return ResponseData.error("订单导出队列异常!");
        }
        return ResponseData.success("订单导出正在队列排队执行中，稍后请在下载列表下载！");
    }
    public void ExportOrderView(Map<String, Object> map) {
        String createTimeStart = "";
        if(map.containsKey("createTimeStart")){
            createTimeStart = map.get("createTimeStart").toString();
        }
        String createTimeEnd = "";
        if(map.containsKey("createTimeEnd")){
            createTimeEnd = map.get("createTimeEnd").toString();
        }
        String successTimeStart = "";
        if(map.containsKey("successTimeStart")){
            successTimeStart = map.get("successTimeStart").toString();
        }
        String successTimeEnd =  "";
        if(map.containsKey("successTimeEnd")){
            successTimeEnd =  map.get("successTimeEnd").toString();
        }
        String kuaidiTimeStart = "";
        if(map.containsKey("kuaidiTimeStart")){
            kuaidiTimeStart = map.get("kuaidiTimeStart").toString();
        }
        String kuaidiTimeEnd =  "";
        if(map.containsKey("kuaidiTimeEnd")) {
            kuaidiTimeEnd = map.get("kuaidiTimeEnd").toString();
        }
        String userType = "";
        if(map.containsKey("userType")){
            userType = map.get("userType").toString();
        }
        String orderNumber = "";
        if(map.containsKey("orderNumber")){
            orderNumber = map.get("orderNumber").toString();
        }
        String customerName = "";
        if(map.containsKey("customerName")){
            customerName = map.get("customerName").toString();
        }
        String businessNumber = "";
        if(map.containsKey("businessNumber")){
            businessNumber = map.get("businessNumber").toString();
        }
        String contactNumber = "";
        if(map.containsKey("contactNumber")){
            contactNumber = map.get("contactNumber").toString();
        }
        String hehuorenSchool = "";
        if(map.containsKey("hehuorenSchool")){
            hehuorenSchool = map.get("hehuorenSchool").toString();
        }
        String hehuorenName = "";
        if(map.containsKey("hehuorenName")){
            hehuorenName = map.get("hehuorenName").toString();
        }
        String orderStatus = "";
        if(map.containsKey("orderStatus")){
            orderStatus = map.get("orderStatus").toString();
        }
        String hehuorenArea = "";
        if (map.containsKey("hehuorenArea")) {
            hehuorenArea = map.get("hehuorenArea").toString();
        }
        String businessPackage = "";
        if (map.containsKey("businessPackage")) {
            businessPackage = map.get("businessPackage").toString();
        }
        boolean isYzk = false;
        if (map.containsKey("isYzk")) {
            isYzk = true;
        }
        String isDelivery = "";
        if (map.containsKey("isDelivery")) {
            isDelivery = map.get("isDelivery").toString();
        }

        ShiroUser user = getShiroUser();

        // 添加查询权限
        List<Integer> userIds = hhrUserService.getUserIds(user.getId(), user.getRoleNames());

        EntityWrapper<Order> wrapper = new EntityWrapper();
        wrapper.setSqlSelect("customer_name, business_number, order_status, create_time, " +
                "hehuoren_id,hehuoren_area, hehuoren_school, hehuoren_name, hehuoren_phone, " +
                "supervisor_name, user_type, kapin, business_package, contact_number, order_number, xb_order_id, site, address, " +
                "is_delivery, company, kuaidi_order, business_iccid, kuaidi_time, success_time, userSchool, student_card_check_status, " +
                "parent_name, student_number, class_number");
        wrapper.notIn( "user_type", "3,5,9,10");
        if (userIds.size() != 0) {
            wrapper.in("hehuoren_id", userIds);
        }
        wrapper.ge(StringUtils.isNotBlank(createTimeStart), "create_time", createTimeStart);
        wrapper.le(StringUtils.isNotBlank(createTimeEnd), "create_time", createTimeEnd);
        wrapper.ge(StringUtils.isNotBlank(successTimeStart), "success_time", successTimeStart);
        wrapper.le(StringUtils.isNotBlank(successTimeEnd), "success_time", successTimeEnd);
        wrapper.ge(StringUtils.isNotBlank(kuaidiTimeStart), "kuaidi_time", kuaidiTimeStart);
        wrapper.le(StringUtils.isNotBlank(kuaidiTimeEnd), "kuaidi_time", kuaidiTimeEnd);
        wrapper.eq(StringUtils.isNotBlank(userType), "user_type", userType);
        wrapper.eq(StringUtils.isNotBlank(orderNumber), "order_number", orderNumber);
//        wrapper.eq(StringUtils.isNotBlank(kapin), "kapin", kapin);
//        wrapper.isNotNull(isYzk, "order_id");
        wrapper.eq(StringUtils.isNotBlank(hehuorenArea), "hehuoren_area", hehuorenArea);
        wrapper.eq(StringUtils.isNotBlank(customerName), "customer_name", customerName);
        wrapper.eq(StringUtils.isNotBlank(businessNumber), "business_number", businessNumber);
        wrapper.eq(StringUtils.isNotBlank(contactNumber), "contact_number", contactNumber);
        wrapper.eq(StringUtils.isNotBlank(hehuorenSchool), "hehuoren_school", hehuorenSchool);
        wrapper.like(StringUtils.isNotBlank(hehuorenName), "hehuoren_name", hehuorenName, SqlLike.DEFAULT);
        wrapper.like(StringUtils.isNotBlank(businessPackage), "business_package", businessPackage, SqlLike.DEFAULT);
        wrapper.eq(StringUtils.isNotBlank(orderStatus), "order_status", orderStatus);
        wrapper.eq(StringUtils.isNotBlank(isDelivery), "is_delivery", isDelivery);
        wrapper.orderBy("create_time",false);
        List<Map<String, Object>> Orders = orderMapper.selectMaps(wrapper);
        List<String> tops = new ArrayList<>();
        tops.add("客户姓名");
        tops.add("办理号码");
        tops.add("订单状态");
        tops.add("订单创建时间");
        tops.add("县分");
        tops.add("合伙人学校");
        tops.add("合伙人姓名");
        tops.add("合伙人手机");
        tops.add("督导");
        tops.add("订单类型");
        tops.add("办理套餐");
        tops.add("升级套餐");
        tops.add("联系号码");
        tops.add("订单编号");
        tops.add("小白卡单号");
        tops.add("预制卡单号");
        tops.add("收货地区");
        tops.add("详细地址");
        tops.add("配送方式");
        tops.add("快递公司");
        tops.add("快递单号");
        tops.add("白卡ICCID");
        tops.add("快递寄出时间");
        tops.add("订单完成时间");
        tops.add("用户学校");
        tops.add("学生证审核");
        tops.add("父母名字");
        tops.add("学号");
        tops.add("班级");
        List<String> columns = new ArrayList<>();
        columns.add("customer_name");
        columns.add("business_number");
        columns.add("order_status");
        columns.add("create_time");
        columns.add("hehuoren_area");
        columns.add("hehuoren_school");
        columns.add("hehuoren_name");
        columns.add("hehuoren_phone");
        columns.add("supervisor_name");
        columns.add("user_type");
        columns.add("kapin");
        columns.add("business_package");
        columns.add("contact_number");
        columns.add("order_number");
        columns.add("xb_order_id");
        columns.add("order_id");
        columns.add("site");
        columns.add("address");
        columns.add("is_delivery");
        columns.add("company");
        columns.add("kuaidi_order");
        columns.add("business_iccid");
        columns.add("kuaidi_time");
        columns.add("success_time");
        columns.add("userSchool");
        columns.add("student_card_check_status");
        columns.add("parent_name");
        columns.add("student_number");
        columns.add("class_number");
        ServletOutputStream os = null;
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            workbook = new XSSFWorkbook();
            //创建工作表
            XSSFSheet sheet = workbook.createSheet("订单清单");
            //添加表头
            final XSSFRow row = sheet.createRow(0);
            //设置列宽度
            sheet.setColumnWidth(1, 6500);
            sheet.setColumnWidth(2, 4000);
            sheet.setColumnWidth(3, 4000);
            sheet.setColumnWidth(4, 4000);
            sheet.setColumnWidth(5, 7000);
            sheet.setColumnWidth(6, 7000);
            sheet.setColumnWidth(7, 4000);
            sheet.setColumnWidth(8, 4000);
            sheet.setColumnWidth(9, 6500);
            sheet.setColumnWidth(10, 6500);
            sheet.setColumnWidth(11, 6500);
            sheet.setColumnWidth(12, 6500);
            sheet.setColumnWidth(13, 6500);
            sheet.setColumnWidth(14, 6500);
            sheet.setColumnWidth(15, 6500);
            sheet.setColumnWidth(16, 6500);
            sheet.setColumnWidth(17, 6500);
            sheet.setColumnWidth(18, 6500);
            sheet.setColumnWidth(19, 4000);
            sheet.setColumnWidth(20, 6500);
            sheet.setColumnWidth(21, 6500);
            sheet.setColumnWidth(22, 6500);
            sheet.setColumnWidth(23, 6500);
            sheet.setColumnWidth(24, 6500);
            sheet.setColumnWidth(25, 6500);
            sheet.setColumnWidth(26, 6500);
            sheet.setColumnWidth(27, 6500);
            sheet.setColumnWidth(28, 6500);
            sheet.setColumnWidth(29, 6500);
            //第一行字段名称
            tops.forEach(column -> {
                XSSFCell cell = row.createCell(Math.max(row.getLastCellNum(), 0));
                cell.setCellValue(column);
            });
            //数据
            School school = new School();
            int rowIndex = row.getRowNum();
            for (Map<String, Object> maps : Orders) {
                String schoolId = schoolMapper.selectSchoolIdByUserId(maps.get("hehuoren_id").toString());
                school = schoolMapper.selectById(schoolId);
                maps.put("lz_user",school.getLzUser());
                maps.put("lzgh",school.getLzgh());
                String userTypeSrt = UserType.findById(maps.get("user_type").toString()).getName();
                maps.put("user_type",userTypeSrt);
                if(maps.get("is_delivery") != null && StringUtils.isNotBlank(maps.get("is_delivery").toString())){
                    String isDeliveryStr = DeliveryType.findById(maps.get("is_delivery").toString()).getName();
                    maps.put("is_delivery",isDeliveryStr);
                }
                if(maps.get("student_card_check_status") != null && StringUtils.isNotBlank(maps.get("student_card_check_status").toString())) {
                    String studentCardCheckStatusStr = ExamineType.findById(maps.get("student_card_check_status").toString()).getName();
                    maps.put("student_card_check_status",studentCardCheckStatusStr);
                }

                final XSSFRow rowdata = sheet.createRow(++rowIndex);
                for (String column : columns) {
                    XSSFCell cell = rowdata.createCell(Math.max(rowdata.getLastCellNum(), 0));
                    if (maps.get(column) != null) {
                        cell.setCellValue(maps.get(column).toString());
                    }
                }
            }
            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("文件出错！" + e.getMessage(), e);
        } finally {
            if (workbook != null) {
                try{
                    workbook.close();
                }catch(Exception e) {}
            }
            if (os != null) {
                try{
                    os.close();
                }catch(Exception e) {}
            }
        }
    }

    @Permission(menuname = "一人一码统计数据", value = "getHhrOrderInfo", method = RequestMethod.POST)
    public ResponseData<List<YrymReport>> getHhrOrderInfo(String startTime, String endTime) {
        List<YrymReport> subNameList = getReportNum(startTime, endTime);
        return ResponseData.success(subNameList, "查询完毕！");
    }

    @Permission(menuname = "导出一人一码统计报表", value = "outputHhrOrder", method = RequestMethod.POST)
    public void downloadHhrOrder(HttpServletResponse response, String startTime, String endTime) throws IOException {

        //获取数据
        List<YrymReport> reportNum = getReportNum(startTime, endTime);

        InputStream in = null;
        ExcelWriter excelWriter = null;
        ServletOutputStream outputStream = null;
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //防止中文乱码
            String fileName = URLEncoder.encode("一人一码统计报表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            in = this.getClass().getResourceAsStream("/static/一人一码统计报表模板.xlsx");
            outputStream = response.getOutputStream();
            excelWriter = EasyExcel.write(outputStream).withTemplate(in).excelType(ExcelTypeEnum.XLSX).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(reportNum, writeSheet);
            Map<String, Object> map = new HashMap<String, Object>();
            LocalDate nowTime = LocalDate.now();
            map.put("month", nowTime.getMonthValue());
            map.put("date", nowTime.getDayOfMonth());
            excelWriter.fill(map, writeSheet);
        } catch (Exception e) {
            log.error("一人一码下载文件失败", e.getMessage());
            throw e;
        } finally {
            //关闭资源
            if (excelWriter != null) {
                try {
                    excelWriter.finish();
                }catch(Exception e) {
                }
            }
            if (outputStream != null) {
                try{
                    outputStream.flush();
                }catch(Exception e) {
                }
            }
            if (in != null) {
                try{
                    in.close();
                }catch(Exception e) {
                }
            }
        }
    }

    /**
     * 根据县分名称获取一人一码发展统计表数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    private List<YrymReport> getReportNum(String startTime, String endTime) {

        List<YrymReport> resultList = new ArrayList<>();
        List<String> subNameList = YrymReport.subNameList;
        for (String tempSubName : subNameList) {
            YrymReport tempYrym = new YrymReport();
            tempYrym.setSubName(tempSubName);
            resultList.add(tempYrym);
        }

        //学校数
        Wrapper<School> schoolNumWrapper = new EntityWrapper<>();
        schoolNumWrapper.setSqlSelect("sub_name AS subName,COUNT(1) AS schoolNum");
        schoolNumWrapper.isNotNull("sub_name");
        schoolNumWrapper.groupBy("sub_name");
        List<Map<String, Object>> schoolNumList = schoolMapper.selectMaps(schoolNumWrapper);

        //学生数
        Wrapper<SysUser> studentNumWrapper = new EntityWrapper<>();
        studentNumWrapper.setSqlSelect("substName AS subName,COUNT(1) AS studentNum");
        studentNumWrapper.isNotNull("substName");
        studentNumWrapper.groupBy("substName");
        List<Map<String, Object>> studentNumList = sysUserMapper.selectMaps(studentNumWrapper);

        //通用查询模板
        Wrapper<Order> commonWrapper = new EntityWrapper();
        String selectSql = "hehuoren_area AS subName," +
                "COUNT( DISTINCT `id_card` AND CASE WHEN user_type = 0 THEN 1 END ) AS newUserNum," +
                "COUNT( DISTINCT `id_card` AND CASE WHEN user_type = 5 THEN 1 END ) AS newAloneNum," +
                "COUNT( DISTINCT `id_card` AND CASE WHEN user_type = 3 THEN 1 END ) AS newMixNum," +
                "COUNT( DISTINCT `id_card`,`now_package`,`business_package`AND CASE WHEN user_type = 1 THEN 1 END ) AS oldUserNum," +
                "COUNT( DISTINCT `id_card`,`now_package`,`business_package`AND CASE WHEN user_type = 2 THEN 1 END ) AS oldContinueNum," +
                "COUNT( DISTINCT CASE WHEN user_type IN (0, 3, 5) AND order_status IN ('已发货', '已完成') THEN 1 END ) AS finishNewNum," +
                "COUNT( CASE WHEN user_type IN (1,2) AND order_status IN ('已发货', '已完成') THEN 1 END ) AS finishOldNum," +
                "COUNT( DISTINCT `id_card` AND CASE WHEN user_type = 0 THEN 1 END ) +" +
                " COUNT( DISTINCT `id_card` AND CASE WHEN user_type = 5 THEN 1 END ) +" +
                " COUNT( DISTINCT `id_card` AND CASE WHEN user_type = 3 THEN 1 END ) +" +
                " COUNT( DISTINCT `id_card`,`now_package`,`business_package`AND CASE WHEN user_type = 1 THEN 1 END ) +" +
                " COUNT( DISTINCT `id_card`,`now_package`,`business_package`AND CASE WHEN user_type = 2 THEN 1 END ) AS sum";
        commonWrapper.setSqlSelect(selectSql);
        commonWrapper.ne("order_status", "异常单");
        commonWrapper.isNotNull("hehuoren_area");
        commonWrapper.groupBy("hehuoren_area");

        //周
        Wrapper<Order> weekWrapper = commonWrapper.clone();
        if (StringUtils.isNotBlank(endTime)) {
            weekWrapper.addFilter("DATE(success_time) >= DATE_SUB(DATE('" + endTime + "'), INTERVAL 7 DAY)");
        } else {
            weekWrapper.addFilter("DATE(success_time) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
        }
        List<Map<String, Object>> weekNumList = orderMapper.selectMaps(weekWrapper);
        //月
        Wrapper<Order> monthWrapper = commonWrapper.clone();
        if (StringUtils.isNotBlank(endTime)) {
            monthWrapper.addFilter("DATE(success_time) >= DATE_SUB(DATE('" + endTime + "'), INTERVAL 30 DAY)");
        } else {
            monthWrapper.addFilter("DATE(success_time) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)");
        }
        List<Map<String, Object>> monthNumList = orderMapper.selectMaps(monthWrapper);
        //累计
        Wrapper<Order> allWrapper = commonWrapper.clone();
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            allWrapper.between("DATE(success_time)", startTime, endTime);
        }
        List<Map<String, Object>> allNumList = orderMapper.selectMaps(allWrapper);

        YrymReportUtils.joinData(resultList, schoolNumList, 1, null);
        YrymReportUtils.joinData(resultList, studentNumList, 2, null);
        YrymReportUtils.joinData(resultList, weekNumList, 3, "week");
        YrymReportUtils.joinData(resultList, monthNumList, 3, "month");
        YrymReportUtils.joinData(resultList, allNumList, 3, "all");
        YrymReportUtils.setAllSum(resultList);
        return resultList;
    }

    /**
     * 受理订单
     *
     * @param file 上传的数据文件
     * @return
     */
    @Permission(menuname = "上传数据", value = "importDate", method = RequestMethod.POST)
    public ResponseData<String> updateDatas(@RequestParam(name = "file") MultipartFile file) {
        StringBuffer error = new StringBuffer();
        if (!StringUtils.endsWithAny(file.getOriginalFilename(), "xlsx", "xls")) {
            return ResponseData.error("手工上传数据仅支持Excel文件，其他格式不支持！");
        }
        if ( (double)file.getSize()/1048576 > 100) {
            return ResponseData.error("文件过大，无法上传");
        }
        ShiroUser user = getShiroUser();
        // 当前是否有数据权限
        boolean hasDataPermission = user.getRoleNames().stream().anyMatch(data -> StringUtils.equalsAny(data, "营业员", "县分管理员（订单）", "超级管理员"));
        if (!hasDataPermission) {
            return ResponseData.error("无数据权限！");
        }
        ImportExcel importExcel = null;
        try {
            importExcel = new ImportExcel(file, HEADER_NUM, SHEET_INDEX);
        } catch (Exception e) {
            log.error("受理单导入异常", e.getMessage());
            return ResponseData.error("导入异常！");
        }
        List<Map<String, Object>> listMap = importExcel.getDataListMap();
        if (listMap.size() == 1) {
            return ResponseData.error("文件不能为空");
        }
        if (!listMap.get(0).get("a").toString().equals(SL_ORDERNUMBER)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("b").toString().equals(SL_ACCEPTRESULT)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("c").toString().equals(SL_ACCEPTNAME)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("d").toString().equals(SL_ACCERPCOMMENT)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (listMap.get(0).size() != 4) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        //校验数据
        try {
            //校验数据
            for (int i = 1; i < listMap.size(); i++) {
                Map<String, Object> temp = listMap.get(i);
                if (!temp.containsKey("a")) {
                    return ResponseData.error("第" + (i + 1) + "行的订单编号不能为空");
                }
                if (StringUtils.isBlank(temp.get("a").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的订单编号不能为空");
                }
                if (!temp.containsKey("b")) {
                    return ResponseData.error("第" + (i + 1) + "行的受理结果不能为空");
                }
                if (StringUtils.isBlank(temp.get("b").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的受理结果不能为空");
                }
                if (!temp.containsKey("c")) {
                    return ResponseData.error("第" + (i + 1) + "行的受理人不能为空");
                }
                if (StringUtils.isBlank(temp.get("c").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的受理人不能为空");
                }
                if ("受理不成功".equals(temp.get("b").toString())) {
                    if (!temp.containsKey("d")) {
                        return ResponseData.error("第" + (i + 1) + "行的备注不能为空");
                    }
                    if (StringUtils.isBlank(temp.get("d").toString())) {
                        return ResponseData.error("第" + (i + 1) + "行的备注不能为空");
                    }
                }
            }
            //检查excel表中是否有重复人员编号
            int size = listMap.size();
            Set<String> accountSet = new HashSet<>(size);
            for (int i = 0; i < size; i++) {
                Map<String, Object> temp = listMap.get(i);
                accountSet.add((String) temp.get("a"));
            }
            if (accountSet.size() != size) {
                return ResponseData.error("文件中有重复的订单编号，请确认订单编号不能重复!");
            }
        } catch (Exception e) {
            log.error("受理单导入异常", e.getMessage());
            return ResponseData.error("导入异常！");
        }
        int number = 0;
        Date acceptDate = new Date();
        Date successTime = acceptDate;
        for (int i = 1; i < listMap.size(); i++) {
            Map<String, Object> map = listMap.get(i);
            String orderNumber = map.get("a").toString();
            String acceptResult = map.get("b").toString();
            String acceptName = map.get("c").toString();
            String acceptComment = null;
            String orderStatus = null;
            String status = null;
            if (StringUtils.isNotBlank(map.get("d").toString())) {
                acceptComment = map.get("d").toString();
            }
            if ("受理成功".equals(map.get("b").toString())) {
                orderStatus = "已完成";
                status = "受理成功";
            } else {
                orderStatus = "异常单";
                status = "受理失败，" + acceptComment;
            }
            Integer integer = null;
            if (StringUtils.isNotBlank(acceptComment)) {
                integer = orderMapper.updateOrderSUByOrderNumberIsNotNull(orderNumber, orderStatus, acceptName, acceptResult, acceptComment, acceptDate,successTime);
            } else {
                integer = orderMapper.updateOrderSUByOrderNumberIsNull(orderNumber, orderStatus, acceptName, acceptResult, acceptDate,successTime);
            }

            if (integer == 1) {
                number++;
                String id = orderMapper.selectIdByOrderNumber(orderNumber);
                appMapper.inserOrderHis(id, status, acceptDate, user.getName());
            } else {
                error.append("第" + (i + 1) + "行的更新失败,");
            }
        }
        error.append("成功更新" + number + "条数据！");
        return ResponseData.success(error.toString(), "导入完成");
    }

    /**
     * 上传快递清单
     *
     * @param file 上传的数据文件
     * @return
     */
    @Permission(menuname = "上传快递清单", value = "importExpressDelivery", method = RequestMethod.POST)
    public ResponseData<String> importExpressDelivery(@RequestParam(name = "file") MultipartFile file) {
        StringBuffer error = new StringBuffer();
        if (!StringUtils.endsWithAny(file.getOriginalFilename(), "xlsx", "xls")) {
            return ResponseData.error("手工上传数据仅支持Excel文件，其他格式不支持！");
        }
        if ( (double)file.getSize()/1048576 > 100) {
            return ResponseData.error("文件过大，无法上传");
        }
        ShiroUser user = getShiroUser();
        // 当前是否有数据权限
        boolean hasDataPermission = user.getRoleNames().stream().anyMatch(data -> StringUtils.equalsAny(data, "活动上单员", "数据管理员", "超级管理员", "快递公司"));
        if (!hasDataPermission) {
            return ResponseData.error("无数据权限！");
        }
        ImportExcel importExcel = null;
        try {
            importExcel = new ImportExcel(file, HEADER_NUM, SHEET_INDEX);
        } catch (Exception e) {
            log.error("快递单导入异常", e.getMessage());
            return ResponseData.error("导入异常！");
        }
        List<Map<String, Object>> listMap = importExcel.getDataListMap();
        if (listMap.size() == 0) {
            return ResponseData.error("文件不能为空");
        }
        if (listMap.get(0).size() != 7) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("a").toString().equals(KD_ORDERNUMBER)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("b").toString().equals(KD_CONTACTNAME)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("c").toString().equals(KD_CONTACTNUMBER)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("d").toString().equals(KD_HEHUORENSCHOOL)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("e").toString().equals(KD_COMPANY)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("f").toString().equals(KD_KUAIDORDER)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("g").toString().equals(KD_BUSINESSICCID)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
       /*
            订单编号 order_number KD_ORDERNUMBER
            客户姓名 customer_name KD_CONTACTNAME
            联系号码 contact_number KD_CONTACTNUMBER
            合伙人学校 hehuoren_school KD_HEHUORENSCHOOL
            快递公司 company KD_COMPANY
            快递单号 kuaidi_order KD_KUAIDORDER
            白卡ICCID business_iccid KD_BUSINESSICCID
        */
        //校验数据
        try {
            //校验数据
            for (int i = 1; i < listMap.size(); i++) {
                Map<String, Object> temp = listMap.get(i);
                if (!temp.containsKey("a")) {
                    return ResponseData.error("第" + (i + 1) + "行的订单编号不能为空");
                }
                if (StringUtils.isBlank(temp.get("a").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的订单编号不能为空");
                }
                if (!temp.containsKey("e")) {
                    return ResponseData.error("第" + (i + 1) + "行的快递公司不能为空");
                }
                if (StringUtils.isBlank(temp.get("e").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的快递公司不能为空");
                }
                if (!temp.containsKey("f")) {
                    return ResponseData.error("第" + (i + 1) + "行的快递单号不能为空");
                }
                if (StringUtils.isBlank(temp.get("f").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的快递单号不能为空");
                }
                if (!temp.containsKey("g")) {
                    return ResponseData.error("第" + (i + 1) + "行的白卡ICCID不能为空");
                }
                if (StringUtils.isBlank(temp.get("g").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的白卡ICCID不能为空");
                }
            }
            //检查excel表中是否有重复人员编号
            int size = listMap.size();
            Set<String> accountSet = new HashSet<>(size);
            for (int i = 0; i < size; i++) {
                Map<String, Object> temp = listMap.get(i);
                accountSet.add((String) temp.get("a"));
            }
            if (accountSet.size() != size) {
                return ResponseData.error("文件中有重复的订单编号，请确认订单编号不能重复!");
            }
        } catch (Exception e) {
            log.error("快递单导入异常", e.getMessage());
            return ResponseData.error("导入异常！");
        }
        // 添加查询权限
        List<Integer> userIds = hhrUserService.getUserIds(user.getId(), user.getRoleNames());

        int number = 0;
        Date successTime = null;
        Date kuaidiTime = null;
        for (int i = 1; i < listMap.size(); i++) {
            successTime = new Date();
            Map<String, Object> map = listMap.get(i);
            String orderNumber = map.get("a").toString();
            String sendType = "快递";
            String company = map.get("e").toString();
            String kuaidiOrder = map.get("f").toString();
            String businessIccid = map.get("g").toString();
            String orderStatus = null;
            Order order = null;
            Wrapper<Order> wrapper = new EntityWrapper<>();
            wrapper.eq("order_number", orderNumber);
            if (userIds.size() != 0) {
                wrapper.in("hehuoren_id", userIds);
            }
            if (user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "快递公司"))) {
                wrapper.eq("order_status", "待配送");
                wrapper.eq("is_delivery","2"); //只能更新分公司配送订单
            }

            List<Order> orders = orderMapper.selectList(wrapper);
            if (orders != null && orders.size() == 1) {
                order = orders.get(0);
            }else{
                error.append("第" + (i + 1) + "行的更新失败,");
                continue;
            }

            if (StringUtils.isNotBlank(order.getXbOrderId())) {
                orderStatus = "待活体";
                kuaidiTime = new Date();
                successTime = null;
            } else {
                orderStatus = "已完成";
                // 存销售清单
                insertCompleteOrder(order);
            }

            log.info("联系号码：" + order.getContactNumber());

            Integer integer = null;
            if (StringUtils.isBlank(company) || StringUtils.isBlank(kuaidiOrder)) {
                if(successTime == null){
                    integer = orderMapper.updateOrderKDNull(orderNumber, sendType, orderStatus);
                }else {
                    integer = orderMapper.updateOrderKDIsNullByTime(orderNumber, sendType, orderStatus,successTime);
                }
            } else {
                if(successTime == null){
                    integer = orderMapper.updateOrderKDNotNull(orderNumber, company, kuaidiOrder, sendType, orderStatus,kuaidiTime,businessIccid);
                }else {
                    integer = orderMapper.updateOrderKDIsNotNullByTime(orderNumber, company, kuaidiOrder, sendType, orderStatus,successTime,kuaidiTime,businessIccid);
                }
                // 发送短信
                SendSmsAndMail.sendSms2(order.getContactNumber(), company, kuaidiOrder, "11");
            }
            if (integer == 1) {
                number++;
                String id = orderMapper.selectIdByOrderNumber(orderNumber);
                if("快递".equals(sendType)) {
                    appMapper.inserOrderHis(id, "发货中，快递公司：" + company + "，快递单号：" + kuaidiOrder, new Date(), user.getName());
                }else{
                    appMapper.inserOrderHis(id, "发货中，快递方式：" + sendType, new Date(), user.getName());
                }
            } else {
                error.append("第" + (i + 1) + "行的更新失败,");
            }
        }
        error.append("成功更新" + number + "条数据！");
        return ResponseData.success(error.toString(), "导入完成");
    }

    /**
     * 上传预制卡批量选号清单
     *
     * @param file 上传预制卡批量选号的数据文件
     * @return
     */
    @Permission(menuname = "上传预制卡批量选号清单", value = "importPrefabrication", method = RequestMethod.POST)
    public ResponseData<String> importPrefabrication(@RequestParam(name = "file") MultipartFile file) {
        StringBuffer error = new StringBuffer();
        if (!StringUtils.endsWithAny(file.getOriginalFilename(), "xlsx", "xls")) {
            return ResponseData.error("手工上传数据仅支持Excel文件，其他格式不支持！");
        }
        if ((double) file.getSize() / 1048576 > 100) {
            return ResponseData.error("文件过大，无法上传");
        }
        ShiroUser user = getShiroUser();
        // 当前是否有数据权限
        boolean hasDataPermission = user.getRoleNames().stream().anyMatch(data -> StringUtils.equalsAny(data, "活动上单员", "数据管理员", "超级管理员"));
        if (!hasDataPermission) {
            return ResponseData.error("无数据权限！");
        }
        ImportExcel importExcel = null;
        try {
            importExcel = new ImportExcel(file, HEADER_NUM, SHEET_INDEX);
        } catch (Exception e) {
            log.error("预制卡批量选号清单导入异常", e.getMessage());
            return ResponseData.error("导入异常！");
        }
        List<Map<String, Object>> listMap = importExcel.getDataListMap();
        if (listMap.size() == 0) {
            return ResponseData.error("文件不能为空");
        }
        if (listMap.get(0).size() != 3) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("a").toString().equals(YZK_ORDERNUMBER)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("b").toString().equals(BUSINESS_NUMBER)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("c").toString().equals(BUSINESS_ICCID)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }

        //校验数据
        try {
            //校验数据
            for (int i = 1; i < listMap.size(); i++) {
                Map<String, Object> temp = listMap.get(i);
                if (!temp.containsKey("a")) {
                    return ResponseData.error("第" + (i + 1) + "行的订单编号不能为空");
                }
                if (StringUtils.isBlank(temp.get("a").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的订单编号不能为空");
                }
                if (!temp.containsKey("b")) {
                    return ResponseData.error("第" + (i + 1) + "行的办理号码不能为空");
                }
                if (StringUtils.isBlank(temp.get("b").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的办理号码不能为空");
                }
                if (!temp.containsKey("c")) {
                    return ResponseData.error("第" + (i + 1) + "行的iccid不能为空");
                }
                if (StringUtils.isBlank(temp.get("c").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的iccid不能为空");
                }
            }
            //检查excel表中是否有重复人员编号
            int size = listMap.size();
            Set<String> accountSet = new HashSet<>(size);
            for (int i = 0; i < size; i++) {
                Map<String, Object> temp = listMap.get(i);
                accountSet.add((String) temp.get("a"));
            }
            if (accountSet.size() != size) {
                return ResponseData.error("文件中有重复的订单编号，请确认订单编号不能重复!");
            }
        } catch (Exception e) {
            log.error("预制卡批量选号清单导入异常", e.getMessage());
            return ResponseData.error("导入异常！");
        }
        int number = 0;
        Date successTime = new Date();
        Integer integer = 0;
        // 暂用100个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        for (int i = 1; i < listMap.size(); i++) {
            Map<String, Object> map = listMap.get(i);
            String orderNumber = map.get("a").toString();
            String businessNumber = map.get("b").toString();
            String iccid = map.get("c").toString();
            List<Order> orderByNumber = orderMapper.selectOrderIdByOrderNumber(orderNumber);
            if(orderByNumber.size()==0){
                continue;
            }
            Order dataOrder = new Order();
            dataOrder.setId(orderByNumber.get(0).getId());
            dataOrder.setBusinessNumber(String.valueOf(businessNumber));
            dataOrder.setBusinessIccid(String.valueOf(iccid));
            dataOrder.setSendType("快递");
            dataOrder.setOrderStatus("提交中");
            try {
                // 更新订单
                Integer num = orderMapper.updateById(dataOrder);
                if (num > 0) {
                    executorService.execute(new Runnable() {
                        public void run() {
                            String id = dataOrder.getId();
                            Order orderData = orderMapper.selectById(dataOrder.getId());
                            String hehuoren_id = orderData.getHehuorenId();
                            String business_number = orderData.getBusinessNumber();
                            String business_iccid = orderData.getBusinessIccid();
                            Map<String, Object> partnerById = orderMapper.findPartnerById(hehuoren_id);
                            String name = orderData.getHehuorenName();
                            Map<String, Object> map1 = new HashMap<>();

                            int ysm = Integer.parseInt(partnerById.get("ysm").toString());
                            Map<String, Object> ysmById =  orderMapper.findYsmById(ysm);
                            map1.put("ysmUser",ysmById.get("user_name"));
                            map1.put("sign",ysmById.get("sign"));

                            map1.put("idCardUrl1", orderData.getIdCardz());
                            map1.put("idCardUrl2", orderData.getIdCardf());
                            map1.put("idCardUrl3", orderData.getIdCardzs());
                            map1.put("cardType", orderData.getKapin());

                            if (orderData.getPackageId().equals("49")) {
                                map1.put("userName", orderData.getParentName());
                                map1.put("idCardUrl4", orderData.getIdCardzs());
                            } else {
                                map1.put("userName", orderData.getCustomerName());
                                map1.put("idCardUrl4", orderData.getStudenCard());
                            }
                            map1.put("linkPhone", orderData.getContactNumber());
                            map1.put("idCard", orderData.getIdCard());
                            map1.put("orderPhone", business_number);
                            map1.put("iccId", business_iccid);

                            String site = orderData.getSite();
                            String[] split = site.split(" ");


                            map1.put("sheng",split[0]);
                            map1.put("shi",split[1]);
                            map1.put("xian",split[2]);

                            map1.put("address",orderData.getAddress());

                            String result="";
                            result = sendOrder(map1);

                            JSONObject resultDataJson = JSONObject.fromObject(result);
                            String orderNum = resultDataJson.getString("orderNumber");
                            Order order = new Order();
                            order.setId(id);
                            order.setUpdateTime(new Date());
                            if (Is.isNoEmpty(orderNum)) {
                                order.setSendType("快递");
                                order.setOrderStatus("审核中");
                                order.setOrderId(orderNum);
                            }else{
                                order.setOrderStatus("异常单");
                                String msg = resultDataJson.getString("msg");
                                order.setMsg(msg);
                                try {
                                    orderMapper.inserOrderHis(id,"审核失败",new Date(),"智能平台审核");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            try {
                                Wrapper<Order> wrapper = new EntityWrapper<>();
                                wrapper.eq("id", order.getId());
                                orderMapper.update(order, wrapper);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                number+=num;
            } catch (Exception e) {
                e.printStackTrace();
            }


            try {
                // 新增订单流转记录
                appMapper.inserOrderHis(dataOrder.getId(), "实名验证中", new Date(), user.getName());
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (integer == 1) {
                number++;
            } else {
                error.append("第" + (i + 1) + "行的更新失败,");
            }
        }
        error.append("成功更新" + number + "条数据！");
        return ResponseData.success(error.toString(), "导入完成");
    }

    /**
     * 上传5G加装包批量受理清单
     *
     * @param file 上传5G加装包批量受理的数据文件
     * @return
     */
    @Permission(menuname = "上传5G加装包批量受理清单", value = "importPackageOrder", method = RequestMethod.POST)
    public ResponseData<String> importPackageOrder(@RequestParam(name = "file") MultipartFile file) {
        StringBuffer error = new StringBuffer();
        if (!StringUtils.endsWithAny(file.getOriginalFilename(), "xlsx", "xls")) {
            return ResponseData.error("手工上传数据仅支持Excel文件，其他格式不支持！");
        }
        if ((double) file.getSize() / 1048576 > 100) {
            return ResponseData.error("文件过大，无法上传");
        }
        ShiroUser user = getShiroUser();
        // 当前是否有数据权限
        boolean hasDataPermission = user.getRoleNames().stream().anyMatch(data -> StringUtils.equalsAny(data, "营业员", "超级管理员"));
        if (!hasDataPermission) {
            return ResponseData.error("无数据权限！");
        }
        ImportExcel importExcel = null;
        try {
            importExcel = new ImportExcel(file, HEADER_NUM, SHEET_INDEX);
        } catch (Exception e) {
            log.error("上传5G加装包批量受理清单导入异常", e.getMessage());
            return ResponseData.error("导入异常！");
        }
        List<Map<String, Object>> listMap = importExcel.getDataListMap();
        if (listMap.size() == 0) {
            return ResponseData.error("文件不能为空");
        }
        if (listMap.get(0).size() != 2) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("a").toString().equals(BUSINESS_NUMBER)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("b").toString().equals(ORDER_STATUS)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }

        //校验数据
        try {
            //校验数据
            for (int i = 1; i < listMap.size(); i++) {
                Map<String, Object> temp = listMap.get(i);
                if (!temp.containsKey("a")) {
                    return ResponseData.error("第" + (i + 1) + "行的办理号码不能为空");
                }
                if (StringUtils.isBlank(temp.get("a").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的办理号码不能为空");
                }
                if (!temp.containsKey("b")) {
                    return ResponseData.error("第" + (i + 1) + "行的受理状态不能为空");
                }
                if (StringUtils.isBlank(temp.get("b").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的受理状态不能为空");
                }
            }
            //检查excel表中是否有重复办理号码
            int size = listMap.size();
            Set<String> accountSet = new HashSet<>(size);
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 1; i < size; i++) {
                Map<String, Object> temp = listMap.get(i);
                accountSet.add((String) temp.get("a"));
                stringBuffer = new StringBuffer(temp.get("b").toString());
                if(!("已完成".equals(stringBuffer.toString()) || "异常单".equals(stringBuffer.toString()))){
                    return ResponseData.error("文件中订单状态格式有误！");
                }
            }
            if (accountSet.size()+1 != size) {
                return ResponseData.error("文件中有重复的办理号码，请确认办理号码不能重复!");
            }
        } catch (Exception e) {
            log.error("5G加装包清单导入异常", e.getMessage());
            return ResponseData.error("导入异常！");
        }
        int number = 0;
        Integer integer = 0;

        for (int i = 1; i < listMap.size(); i++) {
            integer = 0;
            Map<String, Object> map = listMap.get(i);
            String businessNumber = map.get("a").toString();
            String orderStatus = map.get("b").toString();
            Wrapper<Order> wrapper = new EntityWrapper();
            wrapper.eq(StringUtils.isNotBlank(businessNumber),"business_number",businessNumber);
            wrapper.eq("kapin","5G加装包");
            wrapper.eq("user_type","1");
            wrapper.eq("order_status","待受理");
            List<Order> orderByNumber = orderMapper.selectList(wrapper);
            if(orderByNumber.size()==0){
                continue;
            }
            Date date = new Date();
            Order dataOrder = new Order();
            dataOrder.setId(orderByNumber.get(0).getId());
            dataOrder.setOrderStatus(orderStatus);
            dataOrder.setAcceptComment("批量受理："+orderStatus);
            dataOrder.setAcceptName(user.getName());
            dataOrder.setAcceptDate(date);
            if("已完成".equals(orderStatus.toString())){
                dataOrder.setAcceptResult("受理成功");
            }else {
                dataOrder.setAcceptResult("受理失败");
            }
            SalesList sales = new SalesList();
            SysUser sysUser = sysUserMapper.selectById(orderByNumber.get(0).getHehuorenId());

            try {
                integer = orderMapper.update(dataOrder,wrapper);
                // 新增受理记录
                appMapper.inserOrderHis(dataOrder.getId(), "5G加装包批量受理状态："+orderStatus, date, user.getName());
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (integer == 1) {
                sales.setOrderPhone(businessNumber);
                sales.setUserId(orderByNumber.get(0).getHehuorenId());
                sales.setName(orderByNumber.get(0).getHehuorenName());
                sales.setAccount(sysUser.getAccount());
                sales.setCreateTime(date);
                sales.setStatus("5");
                sales.setRemark("批量受理："+orderStatus);
                sales.setSalesSubst(orderByNumber.get(0).getHehuorenArea());
                sales.setSalesSchool(orderByNumber.get(0).getHehuorenSchool());
                sales.setOrderType("2");
                sales.setOrderNum(orderByNumber.get(0).getOrderNumber());
                sales.setUpgradeCombo(orderByNumber.get(0).getBusinessPackage());
                sales.setOldCombo(orderByNumber.get(0).getNowPackage());
                sales.setDelFlag("0");
                sales.setLockState("否");
                salesListMapper.insert(sales);
                number++;
            } else {
                error.append("第" + (i + 1) + "行的更新失败,");
            }
        }
        error.append("成功更新" + number + "条数据！");
        return ResponseData.success(error.toString(), "导入完成");
    }

    /**
     * 受理订单模板下载
     *
     * @return
     */
    @Permission(menuname = "受理单导入模板", method = RequestMethod.POST, value = "downloadMoBan")
    public ResponseData downloadMoBan() {
        ArrayList<String> columns = new ArrayList<>();
        columns.add(SL_ORDERNUMBER);
        columns.add(SL_ACCEPTRESULT);
        columns.add(SL_ACCEPTNAME);
        columns.add(SL_ACCERPCOMMENT);
        ServletOutputStream os = null;
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            //创建工作表
            XSSFSheet sheet = workbook.createSheet("一人一码受理单");
            sheet.setColumnWidth(0, 5000);
            sheet.setColumnWidth(1, 4000);
            sheet.setColumnWidth(2, 4000);
            sheet.setColumnWidth(3, 9000);
            //下拉选项
            List<String> fengju = new ArrayList<>();
            fengju.add("受理不成功");
            fengju.add("受理成功");
            sheet = this.getXSSFSheet(sheet, fengju, 1, 1);
            //添加表头
            final XSSFRow row = sheet.createRow(0);
            XSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            columns.forEach(val -> {
                XSSFCell cell = row.createCell(Math.max(row.getLastCellNum(), 0));
                cell.setCellValue(val);
            });
            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;fileName=data.xlsx");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (IOException e) {
            log.error("受理单模板文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
        return ResponseData.error("受理单模板出错");
    }

    @Permission(menuname = "快递导入模板", method = RequestMethod.POST, value = "downloadMoBanKD")
    public ResponseData downloadMoBanKD() {
        ArrayList<String> columns = new ArrayList<>();

       /*
            订单编号 order_number KD_ORDERNUMBER
            客户姓名 customer_name KD_CONTACTNAME
            联系号码 contact_number KD_CONTACTNUMBER
            合伙人学校 hehuoren_school KD_HEHUORENSCHOOL
            快递公司 company KD_COMPANY
            快递单号 kuaidi_order KD_KUAIDORDER
            白卡ICCID business_iccid KD_BUSINESSICCID
        */
        columns.add(KD_ORDERNUMBER);
        columns.add(KD_CONTACTNAME);
        columns.add(KD_CONTACTNUMBER);
        columns.add(KD_HEHUORENSCHOOL);
        columns.add(KD_COMPANY);
        columns.add(KD_KUAIDORDER);
        columns.add(KD_BUSINESSICCID);
        ServletOutputStream os = null;
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            //创建工作表
            XSSFSheet sheet = workbook.createSheet("快递导入模板");
            sheet.setColumnWidth(0, 5000);
            sheet.setColumnWidth(1, 4000);
            sheet.setColumnWidth(2, 8000);
            sheet.setColumnWidth(3, 10000);
            sheet.setColumnWidth(4, 9000);
            sheet.setColumnWidth(5, 9000);
            sheet.setColumnWidth(6, 9000);
            //下拉选项
            List<String> fengju = new ArrayList<>();
            fengju.add("快递");
//            fengju.add("送货上门");
//            sheet = this.getXSSFSheet(sheet, fengju, 1, 1);
            //添加表头
            final XSSFRow row = sheet.createRow(0);
            XSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            columns.forEach(val -> {
                XSSFCell cell = row.createCell(Math.max(row.getLastCellNum(), 0));
                cell.setCellValue(val);
            });
            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;fileName=data.xlsx");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (IOException e) {
            log.error("快递模板文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
        return ResponseData.error("快递模板出错");
    }

    @Permission(menuname = "预制卡批量填号导入模板", method = RequestMethod.POST, value = "downloadMoBanYZK")
    public ResponseData downloadMoBanYZK() {
        ArrayList<String> columns = new ArrayList<>();
        columns.add(YZK_ORDERNUMBER);
        columns.add(BUSINESS_NUMBER);
        columns.add(BUSINESS_ICCID);
        ServletOutputStream os = null;
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            //创建工作表
            XSSFSheet sheet = workbook.createSheet("预制卡批量填号清单");
            sheet.setColumnWidth(0, 5000);
            sheet.setColumnWidth(1, 4000);
            sheet.setColumnWidth(2, 9000);
            //添加表头
            final XSSFRow row = sheet.createRow(0);
            XSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            columns.forEach(val -> {
                XSSFCell cell = row.createCell(Math.max(row.getLastCellNum(), 0));
                cell.setCellValue(val);
            });
            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;fileName=data.xlsx");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (IOException e) {
            log.error("预制卡批量填号模板文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
        return ResponseData.error("预制卡批量填号模板出错");
    }

    @Permission(menuname = "5G批量受理导入模板", method = RequestMethod.POST, value = "downloadMoBanPackageOrder")
    public ResponseData downloadMoBanPackageOrder() {
        ArrayList<String> columns = new ArrayList<>();
        columns.add(BUSINESS_NUMBER);
        columns.add(ORDER_STATUS);
        ServletOutputStream os = null;
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            //创建工作表
            XSSFSheet sheet = workbook.createSheet("5G批量受理清单");
            sheet.setColumnWidth(0, 5000);
            sheet.setColumnWidth(1, 9000);
            //添加表头
            final XSSFRow row = sheet.createRow(0);
            XSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            columns.forEach(val -> {
                XSSFCell cell = row.createCell(Math.max(row.getLastCellNum(), 0));
                cell.setCellValue(val);
            });
            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;fileName=data.xlsx");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (IOException e) {
            log.error("模板文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
        return ResponseData.error("模板出错");
    }


    XSSFSheet getXSSFSheet(XSSFSheet sheet, List<String> datas, int firstcol, int lastcol) {
        if (datas.size() == 0) {
            return sheet;
        }
        String[] strdata = new String[datas.size()];
        for (int i = 0; i < datas.size(); i++) {
            strdata[i] = datas.get(i);
        }
        XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
        XSSFDataValidationConstraint dvConstraint1 = (XSSFDataValidationConstraint) dvHelper.createExplicitListConstraint(strdata);
        CellRangeAddressList addressList = new CellRangeAddressList(1, 20000, firstcol, lastcol);
        XSSFDataValidation validation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint1, addressList);
        sheet.addValidationData(validation);
        return sheet;
    }
    // 预实名接口发起
    public String sendOrder(Map<String, Object> map) {

        String str = "";

        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String timeStr = simpleDateFormat.format(new Date());
            String cardType = (String) map.get("cardType");

            if (cardType.contains("大王卡")) {
                map.put("productId", "483");
                map.put("salesId", "1185");
            } else if (cardType.contains("天翼学生证")) {
                map.put("productId", "1327");
                map.put("salesId", "4453");
            } else {
                map.put("productId", "727");
                map.put("salesId", "2137");
            }

            map.put("timeStr", timeStr);
            map.put("orderNum", "XY" + timeStr);
            map.put("imgUrl1", (String) map.get("idCardUrl1"));
            map.put("imgUrl2", (String) map.get("idCardUrl2"));
            map.put("imgUrl3", (String) map.get("idCardUrl3"));
            map.put("imgUrl4", (String) map.get("idCardUrl4"));
            str = sendAitransOrder(map, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return str;
    }

    // 保存卡品认证信息
    public String sendAitransOrder(Map<String, Object> map, int count) throws NoSuchAlgorithmException, UnsupportedEncodingException {
//        HttpHost proxy = new HttpHost("172.18.101.170", 3128);
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000)
                .setConnectionRequestTimeout(600000)
//                .setProxy(proxy)
                .build();

        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

        log.info("移动下单前已有参数：" + JSONObject.fromObject(map).toString());
        String resultStr = "";

        HttpEntity entity = null;
        //   https://icloud.mini189.cn/api/create-order.action
        //   https://ismarttest.mini189.cn/api/create-order.action
        HttpPost httpPost = new HttpPost("https://icloud.mini189.cn/api/create-order.action");

        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpPost.setConfig(requestConfig);

        Map<String, String> signMap = new HashMap<String, String>();
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, Charset.forName("UTF-8"));

        builder.addTextBody("service", "order.prepaidgift.create", contentType);// api标识，必填且唯一
        signMap.put("service", "order.prepaidgift.create");


        builder.addTextBody("userName", (String) map.get("ysmUser"), contentType);// 用户名，必填
        signMap.put("userName", (String) map.get("ysmUser"));


        builder.addTextBody("timeStamp", (String) map.get("timeStr"), contentType);// 时间戳（YYYYMMDDHHMMSS），必填

        signMap.put("timeStamp", (String) map.get("timeStr"));

        builder.addTextBody("productCategory", "预付费礼包", contentType);// 业务类型，必填且唯一

        signMap.put("productCategory", "预付费礼包");

        builder.addTextBody("govEntCustomer", "0", contentType);// 是否政企客户下单:0：否，1：是，必填

        signMap.put("govEntCustomer", "0");

        builder.addTextBody("agentName", "", contentType);// 代办人姓名（若是政企客户下单必填）
        signMap.put("agentName", "");

        builder.addTextBody("agentCardNum", "", contentType);// 代办人身份证号码（若是政企客户下单必填）
        signMap.put("agentCardNum", "");

        builder.addTextBody("customerName", (String) map.get("userName"), contentType);// 客户姓名，必填
        signMap.put("customerName", (String) map.get("userName"));

        builder.addTextBody("customerPhone", (String) map.get("linkPhone"), contentType);// 客户(代办人)电话，必填
        signMap.put("customerPhone", (String) map.get("linkPhone"));

        builder.addTextBody("customerCardType", "身份证", contentType);// 证件类型，必填
        signMap.put("customerCardType", "身份证");

        builder.addTextBody("customerCardNum", (String) map.get("idCard"), contentType);// 证件号码，必填
        signMap.put("customerCardNum", (String) map.get("idCard"));

        builder.addTextBody("landId", "44094951", contentType);// 揽装工号，必填
        signMap.put("landId", "44094951");

        builder.addTextBody("comarketingLanId", "", contentType);// 协销工号，选填
        signMap.put("comarketingLanId", "");

        builder.addTextBody("groupComarketingLanId", "", contentType);//集团协销工号，选填
        signMap.put("groupComarketingLanId", "");

        builder.addTextBody("orderOutNum", (String) map.get("orderNum"), contentType);//外部订单编号，选填!；
        //通过API接口下单，必须传入一个外部接入商的订单编号,该编号与智能营销系统编号一一对应
        signMap.put("orderOutNum", (String) map.get("orderNum"));

        builder.addTextBody("orderSource", "", contentType);// 订单来源 ，选填
        signMap.put("orderSource", "");

        builder.addTextBody("orderSourceNum", "", contentType);//
        //订单来源单号，选填；与订单来源对应，用于业务上记录订单的来源订单编号
        signMap.put("orderSourceNum", "");

        builder.addTextBody("salePointCode", "", contentType);// 销售点编码，选填
        signMap.put("salePointCode", "");

        builder.addTextBody("personCode", "", contentType);// 人员编码，选填
        signMap.put("personCode", "");

        builder.addTextBody("distributorSmsReceive", "", contentType);// 分销商短信接收号码，选填
        signMap.put("distributorSmsReceive", "");


        builder.addTextBody("batchPickUp", "0", contentType);// 是否批量提货，必填
        // 0：否，1：是
        signMap.put("batchPickUp", "0");

        builder.addTextBody("deliveryProvince", (String) map.get("sheng"), contentType);// 配送地址-省，必填
        signMap.put("deliveryProvince", (String) map.get("sheng"));

        builder.addTextBody("deliveryCity", (String) map.get("shi"), contentType);// 配送地址-市，必填
        signMap.put("deliveryCity", (String) map.get("shi"));

        builder.addTextBody("deliveryDistrict", (String) map.get("xian"), contentType);// 配送地址-区，必填
        signMap.put("deliveryDistrict", (String) map.get("xian"));

        builder.addTextBody("deliveryAddress", (String) map.get("address"), contentType);// 配送地址-详细地址，必填
        signMap.put("deliveryAddress", (String) map.get("address"));

        builder.addTextBody("deliveryContact", (String) map.get("userName"), contentType);// 联系人，必填
        signMap.put("deliveryContact", (String) map.get("userName"));

        builder.addTextBody("deliveryContactPhone", (String) map.get("linkPhone"), contentType);// 联系电话，必填
        signMap.put("deliveryContactPhone", (String) map.get("linkPhone"));

        builder.addTextBody("deliveryContactPhone2", "", contentType);// 联系电话2，选填
        signMap.put("deliveryContactPhone2", "");

        builder.addTextBody("invoiced", "0", contentType);// 是否需要发票，必填 0:不需要；1:一次性发票；2:分月发票

        signMap.put("invoiced", "0");

        builder.addTextBody("invoiceTitle", "", contentType);// 发票抬头，若需要发票必填
        signMap.put("invoiceTitle", "");

        builder.addTextBody("invoiceDeliveryAddress", "", contentType);// 电子邮箱，若需要发票必填
        signMap.put("invoiceDeliveryAddress", "");

        builder.addTextBody("deliveryType", "代理商自行发货", contentType);// 发货类型，必填，填写只能填同德仓发货或者代理商自行发货或者  现场派卡（其它信息的要求与代理商自行发货类似）
        signMap.put("deliveryType", "代理商自行发货");// 若填写代理商自行发货或现场派卡，则下单时有几个产品，就需要填写多少个实物串号

        builder.addTextBody("deliveryCompany", "", contentType);// 配送公司，必填，填写只能填顺丰速运或者如风达或者京东快递或者EMS
        signMap.put("deliveryCompany", "");// 若发货类型选择代理商自行发货，则不用填写(填写也无效)

        builder.addTextBody("collection", "", contentType);// 回收资料，选填，若填写只能填写1(表示身份证复印件)
        signMap.put("collection", "");

        builder.addTextBody("gift", "", contentType);// 礼品，选填，请通过礼品列表接口获取
        signMap.put("gift", "");

        builder.addTextBody("giftNum", "", contentType);// 礼品数量，选填，若礼品填写则必填且为正整数
        signMap.put("giftNum", "");

        List<Map<String, Object>> productList = new ArrayList<Map<String, Object>>();// 产品信息
        List<Map<String, Object>> paymentList = new ArrayList<Map<String, Object>>();// 销售品信息(费用项)
        List<Map<String, Object>> inPropertyList = new ArrayList<Map<String, Object>>();// 产品属性
        List<Map<String, Object>> appendPropertyList = new ArrayList<Map<String, Object>>();// 产品附加扩展属性
        List<Map<String, Object>> addPropertyList = new ArrayList<Map<String, Object>>();// 自定义产品属性
        // 下单产品(如有多个请建立多个map，但产品总数不能超过5个)
        Map<String, Object> productMap = new HashMap<String, Object>();
        // 产品
        productMap.put("productId", map.get("productId"));// 产品id,必填，请通过产品列表接口获取
        productMap.put("count", "");// 产品数量,选填(若不填默认为1)
        // 该数量仅供发货类型为同德仓发货且批量提货为否时填写，若选择代理商自行发货或批量提货为是，则填写无效
        productMap.put("count2", "");// 产品数量,选填(若不填默认为1);该数量仅供批量提货为是时使用
        // 若选择批量提货为否时，则填写无效
        productMap.put("sn", map.get("iccId"));// 实物串号,选填(若选择代理商自行发货，必填;其他情况填写无效)

        // 销售品信息(费用项)必填，若有终端，请将费用项填写在此
        Map<String, Object> paymentListMap = new HashMap<String, Object>();
        paymentListMap.put("id", map.get("salesId"));// 收费项ID，选填；请通过销售品列表接口获取，若不填表示终端补收款
        paymentListMap.put("saleName", "");// 销售品名称，选填，若id不填写此项必填写，且只能为终端补收款
//        paymentListMap.put("saleAmount", "");// 售价，选填
        paymentListMap.put("payType", "3");// 缴费方式，必填（例：payType：3）3：代理商打款4：穗易付7：货到付款9：第三方托收
        paymentListMap.put("payAmount", "0");// 打款金额（支付金额），若选择代理商打款或者穗易付，此项必填
        paymentListMap.put("saleAmount", "");// 打款金额，若选择货到付款，此项必填
        paymentListMap.put("payPlatform", "");// 支付平台，若选择穗易付，此项必填
        paymentListMap.put("electronicPayNumber", "");// 支付流水号，若选择穗易付，此项必填
        paymentListMap.put("payOrderNumber", "");// 穗易付订单号，若选择穗易付，此项必填
        paymentListMap.put("monthUserid", "");//用户ID，缴费方式为“第三方托收”时必填
        paymentListMap.put("monthPlatform", "");//签约平台，缴费方式为“第三方托收”时必填
        paymentListMap.put("monthFlowno", "");//签约流水号，缴费方式为“第三方托收”时必填
        paymentListMap.put("monthNumber", "");//签约协议号，缴费方式为“第三方托收”时必填
        paymentListMap.put("monthTime", "");//签约时间，缴费方式为“第三方托收”时必填
        paymentListMap.put("monthEffectiveTime", "");//签约生效时间，缴费方式为“第三方托收”时必填
        paymentListMap.put("monthUneffectiveTime", "");//签约失效时间，缴费方式为“第三方托收”时必填

        paymentList.add(paymentListMap);

        productMap.put("payment", paymentList);

        // 产品属性 必填业务号码属性,name=业务号码,value=11位数字或者随机；若还有其他属性可建立多个map添加
        // 若发货类型选择代理商自行发货,则该value值必须填写11位数字
        Map<String, Object> inPropertyListMap = new HashMap<String, Object>();
        inPropertyListMap.put("name", "业务号码");
        inPropertyListMap.put("value", map.get("orderPhone"));
        inPropertyList.add(inPropertyListMap);
        productMap.put("inpProperties", inPropertyList);

        // 产品自定义属性；选填,没有则为null
        // 注：若填写请属性名和属性值都填写，若只填写其中一项则无效
        Map<String, Object> addPropertyListMap = new HashMap<String, Object>();
        addPropertyListMap.put("name", null);
        addPropertyListMap.put("value", null);
        addPropertyList.add(addPropertyListMap);
        productMap.put("addProperties", addPropertyList);

        productList.add(productMap);

        // 将对象装换为json字符串
        String productJson = JSONArray.fromObject(productList).toString();

        log.info("移动下单产品参数：" + productJson);

        try {
            builder.addTextBody("productJson", URLEncoder.encode(productJson, "UTF-8"), contentType);// 产品信息，必填
            signMap.put("productJson", URLEncoder.encode(productJson, "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        //身份证正面，选填
        File file1 = new File(map.get("imgUrl1").toString().replace("manager/ciop", FilePath.BACKGROUNDIMG.getValue()).replace("\\", "/"));
        //身份证背面，选填
        File file2 = new File(map.get("imgUrl2").toString().replace("manager/ciop", FilePath.BACKGROUNDIMG.getValue()).replace("\\", "/"));
        //手持证件，选填
        File file3 = new File(map.get("imgUrl3").toString().replace("manager/ciop", FilePath.BACKGROUNDIMG.getValue()).replace("\\", "/"));
        //手持证件2，选填
        File file4 = new File(map.get("imgUrl4").toString().replace("manager/ciop", FilePath.BACKGROUNDIMG.getValue()).replace("\\", "/"));

        if (file1 != null) {
            ContentBody sfzzmFile = new FileBody(file1);
            builder.addPart("sfzzmFile", sfzzmFile);
        }
        if (file2 != null) {
            ContentBody sfzbmFile = new FileBody(file2);
            builder.addPart("sfzbmFile", sfzbmFile);
        }
        if (file3 != null) {
            ContentBody sfzscFile = new FileBody(file3);
            builder.addPart("sfzscFile", sfzscFile);
        }
        if (file4 != null) {
            ContentBody sfzsc2File = new FileBody(file4);
            builder.addPart("sfzsc2File", sfzsc2File);
        }

        List<String> keys = new ArrayList<String>();
        keys.addAll(signMap.keySet());
        Collections.sort(keys);// key按字符串升序
        String value, plaintext = "";

        for (String key : keys) {
            value = signMap.get(key);
            plaintext = plaintext.concat(value);
        }

        plaintext = plaintext.concat((String) map.get("sign"));

        String sign = CommonMd5.encryption(plaintext);// md5加密
        builder.addTextBody("sign", sign, contentType);// 签名，必填

        log.info("移动智能平台下单参数：" + plaintext);

        try {

            //httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(builder.build());
            //System.out.println("[CREATE_ORDER]移动产品下单接口，提交参数" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));

            long startTime = System.currentTimeMillis();
            Constant.trustEveryone();
            HttpResponse response = httpclient.execute(httpPost);
            long endTime = System.currentTimeMillis();
            log.info("接口调用时间：" + (endTime - startTime) + "ms");


            entity = response.getEntity();

            String httpResult = EntityUtils.toString(entity, "UTF-8");
            resultStr = httpResult;

            log.info("[CREATE_ORDER]预付费下单接口，返回信息:" + httpResult);
            httpclient.close();
            JSONObject resultDataJson = JSONObject.fromObject(httpResult);

            String isSuccess = resultDataJson.getString("status");
            String orderNum = resultDataJson.getString("orderNumber");
            if ("000001".equals(isSuccess)) {
                log.info("[CREATE_ORDER]下单成功,orderNum=" + orderNum);
            }
        } catch (SSLHandshakeException s) {
            count++;
            if (count < 20) {
                resultStr = sendAitransOrder(map, count);
            } else {
                log.error("[HTTP] [CREATE_ORDER] 预付费下单接口异常20次");
            }
        } catch (Exception e) {
            log.error("[HTTP] [CREATE_ORDER] 预付费下单接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }

        return resultStr;
    }
    @Permission(menuname = "更新存量升级订单状态", value = "setUpgradeStatus", method = RequestMethod.POST)
    public ResponseData setUpgradeStatus(@RequestParam("orderId")String orderId,@RequestParam("auditType")String auditType,@RequestParam("contentMsg")String contentMsg){
        ShiroUser user = getShiroUser();
        // 当前是否有数据权限
        boolean hasDataPermission = user.getRoleNames().stream().anyMatch(data -> StringUtils.equalsAny(data, "营业员", "超级管理员"));
        if (!hasDataPermission) {
            return ResponseData.error("无数据权限！");
        }
        Order order = new Order();
        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        wrapper.eq("user_type","1");
        order.setAcceptComment(contentMsg);
        order.setAcceptName(user.getName());
        order.setAcceptDate(new Date());
        if("1".equals(auditType)){
            order.setAcceptResult("受理成功");
            order.setOrderStatus("已完成");
            List<Order> orderByNumber = orderMapper.selectList(wrapper);
            SysUser sysUser = sysUserMapper.selectById(orderByNumber.get(0).getHehuorenId());
            SalesList sales = new SalesList();
            Date date = new Date();
            sales.setOrderPhone(orderByNumber.get(0).getBusinessNumber());
            sales.setUserId(orderByNumber.get(0).getHehuorenId());
            sales.setName(orderByNumber.get(0).getHehuorenName());
            sales.setAccount(sysUser.getAccount());
            sales.setCreateTime(date);
            sales.setStatus("5");
            sales.setRemark(contentMsg);
            sales.setSalesSubst(orderByNumber.get(0).getHehuorenArea());
            sales.setSalesSchool(orderByNumber.get(0).getHehuorenSchool());
            sales.setOrderType("2");
            sales.setOrderNum(orderByNumber.get(0).getOrderNumber());
            sales.setUpgradeCombo(orderByNumber.get(0).getBusinessPackage());
            sales.setOldCombo(orderByNumber.get(0).getNowPackage());
            sales.setDelFlag("0");
            sales.setLockState("否");
            salesListMapper.insert(sales);
        }else {
            order.setOrderStatus("异常单");
            order.setAcceptResult("受理失败");
        }

        appMapper.inserOrderHis(orderId, "受理意见："+contentMsg, new Date(), user.getName());
        orderMapper.update(order, wrapper);
        return ResponseData.success();
    }

    @Permission(menuname = "填写快递单号", value = "setKuanDiData", method = RequestMethod.POST)
    public ResponseData setKuanDiData(@RequestParam("orderId")String orderId,
                                      @RequestParam("company")String company,
                                      @RequestParam("kuaidiOrder")String kuaidiOrder){
        ShiroUser user = getShiroUser();
        if (user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员","系统管理员", "县分管理员（订单）","受理人员","楼长","快递公司"))) {

        }else{
            return ResponseData.error("无数据权限");
        }
        Order databaseOrder = orderMapper.selectById(orderId);
        Order order = new Order();
        if(databaseOrder == null) {
            return ResponseData.error("更新配送方式失败，未找到当前订单！");
        }
        if (StringUtils.isBlank(databaseOrder.getPackageId())) {
            return ResponseData.error("更新配送方式失败，当前订单不是移动卡订单！");
        }

        Package packageInfo = packageMapper.selectById(databaseOrder.getPackageId());
        // 查询产品
        if (packageInfo == null) {
            return ResponseData.error("更新配送方式失败，未找到当前订单套餐！");
        }
        // 小白卡是0，预制卡是1
        if (packageInfo.getIsXbCard() == 0) {
            // 小白卡修改为待活体
            order.setOrderStatus("待活体");

        }else if(packageInfo.getIsXbCard() == 1){
            order.setOrderStatus("已完成");
            //存销售清单
            insertCompleteOrder(databaseOrder);
            if ("1".equals(databaseOrder.getUserType())) {
                order.setOrderStatus("待受理");
            }
        }else{
            return ResponseData.error("更新配送方式失败，套餐信息有误！");
        }

        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        order.setCompany(company);
        order.setKuaidiOrder(kuaidiOrder);
        order.setUpdateTime(new Date());
        appMapper.inserOrderHis(orderId, "快递公司："+company+"快递单号："+kuaidiOrder, new Date(), user.getName());
        orderMapper.update(order, wrapper);

        // 发送短信
        SendSmsAndMail.sendSms2(databaseOrder.getContactNumber(), company, kuaidiOrder, "11");
        return ResponseData.success();
    }
    // 新用户完成存销售清单
    public void insertCompleteOrder(Order order){
        try{
            SysUser sysUser = sysUserMapper.selectById(order.getHehuorenId());
            ShiroUser user = getShiroUser();
            Date date = new Date();
            SalesList salesOrder = new SalesList();
            salesOrder.setOrderPhone(order.getBusinessNumber());
            salesOrder.setUserId(order.getHehuorenId());
            salesOrder.setSalesSchool(order.getHehuorenSchool());
            salesOrder.setCreateTime(date);
            salesOrder.setStatus("1");
            salesOrder.setSalesSubst(order.getHehuorenArea());
            salesOrder.setName(order.getHehuorenName());
            salesOrder.setOrderType(order.getUserType());
            salesOrder.setOrderNum(order.getOrderNumber());
            salesOrder.setOldCombo(order.getKapin());
            salesOrder.setDelFlag("0");
            salesOrder.setLockState("否");

            salesOrder.setPreType("");

            salesOrder.setMonthAmount(0D);
            salesOrder.setMonthBonus(0D);
            salesOrder.setNonSendBonus(0D);
            salesOrder.setSendBonus(0D);
            salesOrder.setAllBonus(0D);


            salesOrder.setAccount(sysUser.getAccount());
            log.info("新用户完成存销售清单:"+salesOrder);
            ResponseData<String> stringResponseData = salesListService.addSalesList(salesOrder);
            if(stringResponseData.getState() != null && "error".equals(stringResponseData.getState())){
                appMapper.inserOrderHis(order.getOrderId(), "新用户完成存销售清单:"+stringResponseData.getMsg(), new Date(), user.getName());
            }
            log.info("新用户完成存销售清单:"+order.getOrderId()+":"+stringResponseData);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
