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.alibaba.fastjson.JSON;
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.*;
import com.winsun.constant.FilePath;
import com.winsun.constant.OrderType;
import com.winsun.mapper.*;
import com.winsun.rabbitmq.RabbitProducer;
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.HttpHost;
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.HttpServletRequest;
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;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @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 = "备注（受理不成功需填写不成功原因）";
    /**
     * 快递清单模板列名
     */
    private static String KD_ORDERNUMBER = "订单编号(必填)";
    private static String SL_SENDTYPE = "快递方式(必填)";
    private static String SL_COMPANY = "快递公司(快递方式为快递必须填写)";
    private static String SL_KUAIDORDER = "快递单号(快递方式为快递必须填写)";

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

    private static OrderMapper orderMapper;

    private static SchoolMapper schoolMapper;

    private static SysUserMapper sysUserMapper;

    private static AppMapper appMapper;

    private ExportExcelMapper exportExcelMapper;

    @Autowired
    private HhrUserMapper hhrUserMapper;

    @Autowired
    private YsmUserMapper ysmUserMapper;

    @Autowired
    private RabbitProducer taskImport;

    @Autowired
    private SalesListController salesListController;

    private InputStream in = this.getClass().getResourceAsStream("/txtfiledetail.properties");
    private Properties prop = new Properties();

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

    /**
     * 查询订单历史状态
     */
    @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);
        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 ("快递".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();
                        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("idCardUrl4", order.getIdCardzs());
                        map1.put("cardType", order.getKapin());

                        if (order.getPackageId().equals("49")) {
                            map1.put("userName", order.getParentName());
                        } else {
                            map1.put("userName", order.getCustomerName());
                        }
                        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(), "审核失败!", 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());
        }
        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)
    //@RequestMapping(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("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 = "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;
        }

        Wrapper<Order> wrapper = new EntityWrapper();
        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.eq(StringUtils.isNotBlank(userType), "user_type", userType);
        wrapper.eq(StringUtils.isNotBlank(orderNumber), "order_number", orderNumber);
        //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.eq(StringUtils.isNotBlank(hehuorenSchool), "hehuoren_school", hehuorenSchool);
        wrapper.like(StringUtils.isNotBlank(hehuorenName), "hehuoren_name", hehuorenName, SqlLike.DEFAULT);
        wrapper.eq(StringUtils.isNotBlank(hehuorenArea), "hehuoren_area", hehuorenArea);
        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) {

        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();
        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 hhr_img = prop.getProperty("hhr_img");
                prop.load(in);
                //重新上传图片

                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 wrapper = new EntityWrapper<>();
        wrapper.eq("id", id);
        Map<String, Object> dataMapping = new HashMap<>();
        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 {
            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("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 = "customerName", required = false) String customerName) {

        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(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);
        }
        try {
            taskImport.taskImport(map);
        } catch (Exception e) {
            log.error("订单导出队列异常", e.getMessage());
            return ResponseData.error("订单导出队列异常!");
        }
        return ResponseData.success("订单导出正在队列排队执行中，稍后请在下载列表下载！");
    }

    @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() != 4) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("a").toString().equals(KD_ORDERNUMBER)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("b").toString().equals(SL_SENDTYPE)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("c").toString().equals(SL_COMPANY)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("d").toString().equals(SL_KUAIDORDER)) {
            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 ("快递".equals(temp.get("b").toString())) {
                    if (!temp.containsKey("c")) {
                        return ResponseData.error("第" + (i + 1) + "行的快递公司不能为空");
                    }
                    if (!temp.containsKey("d")) {
                        return ResponseData.error("第" + (i + 1) + "行的快递单号不能为空");
                    }
                    if (StringUtils.isBlank(temp.get("c").toString())) {
                        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 successTime = new Date();
        for (int i = 1; i < listMap.size(); i++) {
            Map<String, Object> map = listMap.get(i);
            String orderNumber = map.get("a").toString();
            String sendType = map.get("b").toString();
            String company = null;
            String kuaidiOrder = null;
            String orderStatus = null;
            String xbOrderId = orderMapper.selectxbOrderIdByOrderNumber(orderNumber);
            if (StringUtils.isNotBlank(xbOrderId)) {
                orderStatus = "待活体";
                successTime = null;
            } else {
                orderStatus = "已完成";
            }
            if ("快递".equals(map.get("b").toString())) {
                company = map.get("c").toString();
                kuaidiOrder = map.get("d").toString();
            }
            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);
                }else {
                    integer = orderMapper.updateOrderKDIsNotNullByTime(orderNumber, company, kuaidiOrder, sendType, orderStatus,successTime);
                }
            }
            if (integer == 1) {
                number++;
                String id = orderMapper.selectIdByOrderNumber(orderNumber);
                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(number));
            dataOrder.setBusinessIccid(String.valueOf(iccid));
            dataOrder.setSendType("快递");
            dataOrder.setOrderStatus("提交中");
            try {
                // 更新订单
                Integer num = orderMapper.updateById(dataOrder);
                number+=num;
            } catch (Exception e) {
                e.printStackTrace();
            }
            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("idCardUrl4", orderData.getIdCardzs());
                    map1.put("cardType", orderData.getKapin());

                    if(orderData.getPackageId().equals("49")){
                        map1.put("userName", orderData.getParentName());
                    }else{
                        map1.put("userName", orderData.getCustomerName());
                    }
                    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();
                    }
                }
            });

            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(), "导入完成");
    }
    /**
     * 受理订单模板下载
     *
     * @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(2, 4000);
            sheet.setColumnWidth(1, 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<>();
        columns.add(KD_ORDERNUMBER);
        columns.add(SL_SENDTYPE);
        columns.add(SL_COMPANY);
        columns.add(SL_KUAIDORDER);
        ServletOutputStream os = null;
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            //创建工作表
            XSSFSheet sheet = workbook.createSheet("快递清单");
            sheet.setColumnWidth(0, 5000);
            sheet.setColumnWidth(2, 9000);
            sheet.setColumnWidth(1, 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 = "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("预制卡批量填号模板出错");
    }


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

        try {
            prop.load(in);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String hhr_img = prop.getProperty("hhr_img");

        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://ismart.mini189.cn/api/create-order.action
        //   https://ismarttest.mini189.cn/api/create-order.action
        HttpPost httpPost = new HttpPost("https://ismart.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 = Md5.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 = "业务预受理表参数返回", method = RequestMethod.GET, value = "findReportMap")
    public void findReportMap(HttpServletRequest request,HttpServletResponse response,String callback) throws IOException {
        String prices = null;
        String byStr = null;
        String mealStr = null;
        String month = null;
        String expenses = "";
        String product_price = ""; // 资费
        String identifying = ""; // 提速包：
        String identifying_price = ""; // 提速包资费
        String identifyingStr = ""; // 提速包
        String tyMeal = "";
        String university_domain_name = ""; // 后缀

        boolean speed_up = false;
        boolean product_price_CB = false;
        boolean new_clothes_CB = false;
        boolean setMealCB = false;
        Map<String, Object> QueUniversityData ;

        String isFromRh = request.getParameter("isFromRh"); // 融合
        String partner = request.getParameter("partner"); // 合伙人id
        String productTitle = request.getParameter("productTitle"); // 宽带标题
        String universityRegion = request.getParameter("universityRegion"); // 县份
        String universityName = request.getParameter("universityName"); // 学校名
        String setMeal = request.getParameter("setMeal");
        String setMealIndex = request.getParameter("setMealIndex");
        String sl = request.getParameter("sl"); // 宽带提速速率
        String ex = request.getParameter("ex"); // 宽带速率
        Map<String, Object> QueProductIdData = orderMapper.queExiteProductNameData(productTitle, universityRegion, universityName).get(0);
        QueUniversityData = orderMapper.queUniversityNameData(universityName, universityRegion).get(0);
        if(QueUniversityData != null && QueUniversityData.size()>1){
            QueUniversityData = orderMapper.queProductNameDataToUniversityNameData(productTitle, universityRegion, universityName).get(0);
        }


        String[] rateArry = ((String) QueProductIdData.get("product_rate")).split(",");    // 年月（包年,包月）
        String[] mealArry = ((String)QueProductIdData.get("product_meal")).split(",");  // 套餐 （4M，8M，20M等）
        String[] priceArry = ((String) QueProductIdData.get("product_price")).split(",");    // 金额（300,30）
        if(StringUtils.isNotBlank(isFromRh) && isFromRh=="true") {
            rateArry = ((String) QueProductIdData.get("product_rh_rate")).split(","); // 年月（包年,包月）
            priceArry = ((String) QueProductIdData.get("product_rh_price")).split(","); // 金额（300,30）
        }
        Integer index = 0;
        if(StringUtils.isNotBlank(setMealIndex)){
            index = Integer.parseInt(setMealIndex);
        }

        byStr = rateArry[index];
        mealStr = mealArry[index];
        prices = priceArry[index];
        if(byStr.equals("包年")){
            month = "12";
        }else{
            month = "1";
        }

        new_clothes_CB = true;
        tyMeal = "预付费校园";
        setMealCB = true;


        // 融合/提速  提速包：
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        identifying = QueUniversityData.get("identifying").toString();
        expenses = (String) QueUniversityData.get("expenses");
        if(StringUtils.isNotBlank(expenses)){
            expenses = expenses.replace("M","");
        }


        university_domain_name = (String)QueUniversityData.get("university_domain_name");
        if(StringUtils.isNotBlank(university_domain_name)){
            university_domain_name = university_domain_name.replace("@","");
        }

        product_price_CB = true;
        if(identifying.contains("免费")){
            identifying_price = "0";
            identifyingStr = identifying;
        }else{
            Matcher m = p.matcher(identifying);
            identifying_price = m.replaceAll("").trim();
            if(StringUtils.isNotBlank(identifying)){
                identifyingStr = identifying.substring(0,8);
            }
        }



        if(StringUtils.isNotBlank(sl)){
            new_clothes_CB = false;
        }

        //  单宽
        if(StringUtils.isBlank(isFromRh) && StringUtils.isBlank(sl)){
            identifying_price = "";
            identifyingStr = "";
            tyMeal = "";
            setMealCB = false;
            product_price_CB = false;
            expenses = "";
            university_domain_name = "";
        }


        String seal = "";
//        String url = "D:\\Projects\\wxProject\\gdtel-xyzx-hhr\\WebContent\\images\\seal\\seal.png";
        String url = this.getClass().getResource("/").getPath();
        int num =  url.indexOf("gdtel-xyzx-hhr");
        url = url.substring(0,num);
        url = url + "gdtel-xyzx-hhr/images/seal/seal.png";
//        获取协议印章图片
        seal = getPhoto(url);
//      返回的参数
        Map<String, Object> mapData = new HashMap<>();
        mapData.put("channel_number",""); // 渠道工号
        mapData.put("student_name",""); // 姓名
        mapData.put("student_number",""); // 学号
        mapData.put("contact_number",""); // 联系方式
        mapData.put("id_card",""); // 身份证号码
        mapData.put("universityName",universityName); //学校：
        mapData.put("department",""); // 系
        mapData.put("setClass",""); // 班级
        mapData.put("dormitory",""); // 宿舍
        mapData.put("setMealCB",setMealCB); // 我要办理天翼@_@套餐 checkbox
        mapData.put("tyMeal",tyMeal); // 我要办理天翼@_@套餐
        mapData.put("setMealIndex",setMealIndex); // 套餐下标
        mapData.put("upgradeCB",false); // 我要办理老用户套餐升级： checkbox
        mapData.put("upgrade",""); // 我要办理老用户套餐升级：
        mapData.put("original_package",""); // 原套餐：
        mapData.put("new_package",""); // 转新套餐：
        mapData.put("new_clothes_CB",new_clothes_CB); // 新装 checkbox
        mapData.put("change_CB",""); // 变更 checkbox
        mapData.put("product_price",prices); // 资费
        mapData.put("month",month); // 包年/包月 12/1
        mapData.put("product_other",""); // （其他）
        mapData.put("speed_up",speed_up); // 我要办理宽带提速： checkbox
        mapData.put("product_price_CB",product_price_CB); // 在原基础宽带资费外每月低消/加价 checkbox
        mapData.put("product_price_up",identifying_price); // 在原基础宽带资费外每月低消/加价____元
        mapData.put("expenses",expenses); // 宽带提速 ______M
        mapData.put("university_domain_name",university_domain_name); // 账号为______@______后缀
        mapData.put("phone_CB",false); // 只为手机号 checkbox
        mapData.put("phone_TD",""); // 只为手机号____退订
        mapData.put("phone_TD_price",""); // 退订每月____元
        mapData.put("phone_product_meal",""); // 提速至____M
        mapData.put("acceleration_package_CB",false); // 办理加速包 checkbox
        mapData.put("business_number",""); // 办理加速包 手机号为：
        mapData.put("identifying",identifying); // 办理加速包:
        mapData.put("identifying_price",identifying_price); // 办理__元
        mapData.put("identifyingStr",identifyingStr); // 办理加速包
        mapData.put("university_package_number",""); // 揽装工号：
        mapData.put("remarks",""); // 其他备注：
        mapData.put("seal",seal); // 印章

        response.setContentType("text/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");

        PrintWriter writer = response.getWriter();
        //需要把jsonp生成的参数带回前台，jsonp才能解析
        writer.print(callback + "("+ JSON.toJSONString(mapData)+")");
        writer.close();
    }
    //path 为图片在服务器的绝对路径
    public String getPhoto(String url) {
        try {
            File file = new File(url);
            FileInputStream fis;
            fis = new FileInputStream(file);

            long size = file.length();
            byte[] temp = new byte[(int) size];
            fis.read(temp, 0, (int) size);
            fis.close();
            byte[] data = temp;
            return new String(org.apache.commons.codec.binary.Base64.encodeBase64(data));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
