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.Order;
import com.winsun.bean.School;
import com.winsun.bean.SysUser;
import com.winsun.bean.YrymReport;
import com.winsun.mapper.*;
import com.winsun.rabbitmq.RabbitProducer;
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.scheduling.concurrent.ThreadPoolTaskExecutor;
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.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

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

    /**
     * 导入
     */
    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;

    protected ThreadPoolTaskExecutor threadPool;

    protected static Basemapper basemapper;

    @Autowired
    private RabbitProducer taskImport;

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

    /**
     * 审核学生证
     */
    @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();
        /*if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }*/
        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 = "abnormal", method = RequestMethod.POST)
    public ResponseData<String> abnormal(@RequestParam("orderId") String orderId) {
        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, "异常单!", 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 ResponseData<Page<Order>> 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) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }

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

        return ResponseData.success(page, "查询完毕！");
    }

    @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.updateOrderKDIsNull(orderNumber, sendType, orderStatus);
                }else {
                    integer = orderMapper.updateOrderKDIsNull(orderNumber, sendType, orderStatus,successTime);
                }
            } else {
                if(successTime == null){
                    integer = orderMapper.updateOrderKDIsNotNull(orderNumber, company, kuaidiOrder, sendType, orderStatus);
                }else {
                    integer = orderMapper.updateOrderKDIsNotNull(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 = null;
        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<Map<String, Object>> orderByNumber = orderMapper.selectOrderIdByOrderNumber(orderNumber);
            if(orderByNumber.size()==0){
                continue;
            }
            Map<String, Object> map1 = orderByNumber.get(0);
            map1.put("business_number",number);
            map1.put("business_iccid",iccid);
            map1.put("send_type", "快递");
            map1.put("order_status", "提交中");
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    String id = map1.get("id").toString();
                    Map<String, Object> orderMap = orderMapper.selectOrderById(map1.get("id").toString());
                    String hehuoren_id = orderMap.get("hehuoren_id").toString();
                    String business_number = orderMap.get("business_number").toString();
                    String business_iccid = orderMap.get("business_iccid").toString();
                    Map<String, Object> partnerById = orderMapper.findPartnerById(hehuoren_id);
                    String name = partnerById.get("name").toString();
                    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", orderMap.get("id_cardz"));
                    map1.put("idCardUrl2", orderMap.get("id_cardf"));
                    map1.put("idCardUrl3", orderMap.get("id_cardzs"));
                    map1.put("idCardUrl4", orderMap.get("id_cardzs"));
                    map1.put("cardType", orderMap.get("kapin"));

                    if(orderMap.get("package_id").equals("49")){
                        map1.put("userName", orderMap.get("parent_name"));
                    }else{
                        map1.put("userName", orderMap.get("customer_name"));
                    }
                    map1.put("linkPhone", orderMap.get("contact_number"));
                    map1.put("idCard", orderMap.get("id_card"));
                    map1.put("orderPhone", business_number);
                    map1.put("iccId", business_iccid);

                    String site = orderMap.get("site").toString();
                    String[] split = site.split(" ");


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

                    map1.put("address",orderMap.get("address"));

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

                    JSONObject resultDataJson = JSONObject.fromObject(result);
                    String orderNum = resultDataJson.getString("orderNumber");
                    Map<String,Object> map3 = new HashMap<>();
                    if (Is.isNoEmpty(orderNum)) {
                        map3.put("id", id);
                        map3.put("send_type", "快递");
                        map3.put("order_status", "审核中");
                        map3.put("order_id",orderNum);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        map3.put("update_time", sdf.format(new Date()));
                    }else{
                        map3.put("id", id);
                        map3.put("order_status", "异常单");
                        String msg = resultDataJson.getString("msg");
                        map3.put("msg",msg);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        map3.put("update_time", sdf.format(new Date()));
                        try {
                            orderMapper.inserOrderHis(id,"审核失败",new Date(),"智能平台审核");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        basemapper.update("hhr_order",map3);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });
            int num = 0;
            try {
                num = basemapper.update("hhr_order",map1) > 0 ? 1 : 0;
                number+=num;
            } catch (Exception e) {
                e.printStackTrace();
            }

            Map<String, Object> history = new HashMap<String, Object>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            history.put("order_id", map1.get("id"));
            history.put("create_date", sdf.format(new Date()));
            history.put("status", "实名验证中");
            try {
                basemapper.insert("hhr_order_history", history);
            } 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();


        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();
        try {
            builder.addTextBody("productJson", URLEncoder.encode(productJson, "UTF-8"), contentType);// 产品信息，必填
            signMap.put("productJson", URLEncoder.encode(productJson, "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //身份证正面，选填
        File file1 = new File((String) map.get("imgUrl1"));
        //身份证背面，选填
        File file2 = new File((String) map.get("imgUrl2"));
        //手持证件，选填
        File file3 = new File((String) map.get("imgUrl3"));
        //手持证件2，选填
        File file4 = new File((String) map.get("imgUrl4"));

        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);// 签名，必填

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