package com.yutu.base.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yutu.base.entity.NoteResult;
import com.yutu.base.entity.Response;
import com.yutu.base.utils.HttpsSendData;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 订单相关业务层
 */
@Service
public class OrderService extends BaseService{

    private Logger logger = Logger.getLogger("orderService");
    @Value("${spring.urlConfig.overseasAirTicketUrl}")
    private String overseasAirTicketUrl;
    @Value("${spring.pathConfig.saleReportExcelPath}")
    private String  saleReportExcelPath;

    public Response exportOrderInfo(String requestBody){

        if(StringUtils.isBlank(requestBody)){
            return Response.error("参数不能为空");
        }
        JSONObject reqObj = JSONObject.parseObject(requestBody);
        if(reqObj == null){
            return Response.error("参数有误");
        }
        String startTime = reqObj.getString("startTime");
        String endTime = reqObj.getString("endTime");
        String customerId = reqObj.getString("customerId");
        if(StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime) || StringUtils.isBlank(customerId)){
            return Response.error("参数不能为空,必传参数:startTime、endTime、customerId");
        }

        Map<String,String> params = new HashMap<>();
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("CustomerId",customerId);
        params.put("pagination","1");
        params.put("line_number","10000");

        NoteResult nr = getOrderInfos(params);
        if(nr.getStatus() != 0){
            return  Response.error("查询数据为空");
        }
        JSONArray orderInfos = (JSONArray) nr.getData();
        String filePath = createOrderInfoExcel(orderInfos,customerId,startTime);
        Response response = Response.success();
        response.setData(filePath);
        response.setErrorMessage("生成订单信息完毕!");
        return response;
    }

    //获取指定生单时间范围的全部订单
    public NoteResult getOrderInfos(Map<String,String> paramsMap){
        NoteResult noteResult = new NoteResult(2,null,null);
        paramsMap.put("OrderStatus","2");
        String result2= HttpsSendData.send(overseasAirTicketUrl+"/orderInfo/findAllBy.do", paramsMap);
        JSONObject jsonObject2 = JSONObject.parseObject(result2);
        JSONArray jsonArray2 = jsonObject2.getJSONArray("data");
        paramsMap.put("OrderStatus","3");
        String result3= HttpsSendData.send(overseasAirTicketUrl+"/orderInfo/findAllBy.do", paramsMap);
        JSONObject jsonObject3 = JSONObject.parseObject(result3);
        JSONArray jsonArray3 = jsonObject3.getJSONArray("data");
        paramsMap.put("OrderStatus","4");
        String result4= HttpsSendData.send(overseasAirTicketUrl+"/orderInfo/findAllBy.do", paramsMap);
        JSONObject jsonObject4 = JSONObject.parseObject(result4);
        JSONArray jsonArray4 = jsonObject4.getJSONArray("data");

        jsonArray4.addAll(jsonArray2);
        jsonArray4.addAll(jsonArray3);

        if(jsonArray4!=null && jsonArray4.size() > 0){
            noteResult.setStatus(0);
            noteResult.setMsg("获取成功");
            noteResult.setData(jsonArray4);
        }
        return noteResult;
    }

    //解析订单信息生成订单信息Excel表
    public String createOrderInfoExcel(JSONArray orderInfos,String customerId,String startTime) {
        String fileBasePath = saleReportExcelPath + customerId + "/OrderInfoExcel/";;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String date = sdf.format(new Date());
        File file = new File( startTime.replace(" ","").replace(":","")+ "订单信息"+date+".xls");
        System.out.println(file);
        FileOutputStream os = null;
        HSSFWorkbook book = null;
        try{
        //创建工作薄
            book = new HSSFWorkbook();
            HSSFSheet sheet = book.createSheet("订单信息");
            sheet.setColumnWidth(2, 25 * 256);
            sheet.setColumnWidth(3, 25 * 256);
            sheet.setColumnWidth(6, 30 * 256);
            sheet.setColumnWidth(1, 21 * 256);
            sheet.setColumnWidth(9, 21 * 256);
            // 创建单元格样式
            HSSFCellStyle cellStyleTitle = book.createCellStyle();
            // 指定单元格居中对齐
//            cellStyleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            // 指定单元格垂直居中对齐
//            cellStyleTitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            // 指定当单元格内容显示不下时自动换行
            cellStyleTitle.setWrapText(true);
            // ------------------------------------------------------------------
            HSSFCellStyle cellStyle = book.createCellStyle();
            // 指定单元格居中对齐
//            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            // 指定单元格垂直居中对齐
//            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            // 指定当单元格内容显示不下时自动换行
            cellStyle.setWrapText(true);
            // ------------------------------------------------------------------
            // 设置单元格字体
            HSSFFont font = book.createFont();
//            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            font.setFontName("宋体");
            font.setColor(new Short("255"));
            font.setFontHeight((short) 200);
            cellStyleTitle.setFont(font);
            //创建标题行
            Row title = sheet.createRow(0);
            title.setRowStyle(cellStyleTitle);
            //航司
            Cell carrierTitle = title.createCell(0);
            carrierTitle.setCellStyle(cellStyleTitle);
            carrierTitle.setCellValue("序号");
            //信用余额
            Cell creditTitle = title.createCell(1);
            creditTitle.setCellStyle(cellStyleTitle);
            creditTitle.setCellValue("生单时间");
            //账户编码
            Cell accountIdTitle = title.createCell(2);
            accountIdTitle.setCellStyle(cellStyleTitle);
            accountIdTitle.setCellValue("本地订单号");
            //账户
            Cell accountTitle = title.createCell(3);
            accountTitle.setCellStyle(cellStyleTitle);
            accountTitle.setCellValue("外部订单号");
            //账户
            Cell statusTitle = title.createCell(4);
            statusTitle.setCellStyle(cellStyleTitle);
            statusTitle.setCellValue("订单状态");
            //密码
            Cell passwordTitle = title.createCell(5);
            passwordTitle.setCellStyle(cellStyleTitle);
            passwordTitle.setCellValue("渠道");
            //邮箱密码
            Cell mailPasswordTitle = title.createCell(6);
            mailPasswordTitle.setCellStyle(cellStyleTitle);
            mailPasswordTitle.setCellValue("乘客姓名(票号)");
            //积分值
            Cell pointTitle = title.createCell(7);
            pointTitle.setCellStyle(cellStyleTitle);
            pointTitle.setCellValue("行程");
            //可用旅客人数
            Cell usableNumTitle = title.createCell(8);
            usableNumTitle.setCellStyle(cellStyleTitle);
            usableNumTitle.setCellValue("航班号");

            Cell flightTimeTitle = title.createCell(9);
            flightTimeTitle.setCellStyle(cellStyleTitle);
            flightTimeTitle.setCellValue("起飞时间");

            //遍历销售规则数据列表
            for (int i = 0; i < orderInfos.size(); i++) {

                Row r = sheet.createRow(i + 1);

                Cell indeixCell = r.createCell(0);
                indeixCell.setCellStyle(cellStyle);
                indeixCell.setCellValue(i + 1);

                Cell usablePassengerNumCell = r.createCell(1);
                usablePassengerNumCell.setCellStyle(cellStyle);
                if (orderInfos.getJSONObject(i).getString("createTime") != null) {
                    usablePassengerNumCell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orderInfos.getJSONObject(i).getDate("createTime")));
                }

                Cell carrierCell = r.createCell(2);
                carrierCell.setCellStyle(cellStyle);
                if (orderInfos.getJSONObject(i).getString("orderNo") != null) {
                    carrierCell.setCellValue(orderInfos.getJSONObject(i).getString("orderNo"));
                }
                Cell accountIdCell = r.createCell(3);
                accountIdCell.setCellStyle(cellStyle);
                if (orderInfos.getJSONObject(i).getString("outerOrderNo") != null) {
                    accountIdCell.setCellValue(orderInfos.getJSONObject(i).getString("outerOrderNo"));
                }

                String status = "";
                if(orderInfos.getJSONObject(i).getInteger("orderStatus") == 2){
                    status = "待出票";
                }else if(orderInfos.getJSONObject(i).getInteger("orderStatus") == 3){
                    status = "出票中";
                }else if(orderInfos.getJSONObject(i).getInteger("orderStatus") == 4){
                    status = "已出票";
                }

                Cell statusCell = r.createCell(4);
                statusCell.setCellStyle(cellStyle);
                statusCell.setCellValue(status);

                Cell accountCell = r.createCell(5);
                accountCell.setCellStyle(cellStyle);
                if (orderInfos.getJSONObject(i).getString("orderBelong") != null) {
                    accountCell.setCellValue(orderInfos.getJSONObject(i).getString("orderBelong"));
                }

                JSONArray passengers = orderInfos.getJSONObject(i).getJSONArray("orderPassengers");
                JSONArray flights = orderInfos.getJSONObject(i).getJSONArray("orderFlightInfos");

                String passengerInfo = "";
                for (int j = 0; j < passengers.size(); j++) {
                    JSONObject pass = passengers.getJSONObject(j);
                    String name = pass.getString("passengerName");
                    String pnr = pass.getString("ticketNumber");
                    if(StringUtils.isBlank(passengerInfo)){
                        passengerInfo += name + "(" + pnr + ");";
                    }else{
                        passengerInfo += "\n\r"+ name + "(" + pnr + ");";
                    }
                }
                Cell passwordCell = r.createCell(6);
                passwordCell.setCellStyle(cellStyle);
                passwordCell.setCellValue(passengerInfo);

                String flightInfo = "";
                String flightNumber = "";
                String flightTime = "";
                for (int j = 0; j < flights.size(); j++) {
                    JSONObject flight = flights.getJSONObject(j);
                    String org = flight.getString("org");
                    String dst = flight.getString("dst");
                    if(StringUtils.isBlank(flightInfo)){
                        flightInfo += org + "-" + dst;
                    }else {
                        flightInfo += "\n\r"+ org + "-" + dst;
                    }

                    String flightNo = flight.getString("flightNo");
                    if(StringUtils.isBlank(flightNo)){
                        flightNumber += flightNo;
                    }else {
                        flightNumber += "\n\r"+ flightNo;
                    }

                    String flightTimeStr = flight.getString("flightTime");
                    if(StringUtils.isBlank(flightTimeStr)){
                        flightTime += flightTimeStr;
                    }else {
                        flightTime += "\n\r"+ flightTimeStr;
                    }

                }

                Cell emailPassCell = r.createCell(7);
                emailPassCell.setCellStyle(cellStyle);
                emailPassCell.setCellValue(flightInfo);

                Cell pointCell = r.createCell(8);
                pointCell.setCellStyle(cellStyle);
                pointCell.setCellValue(flightNumber);

                Cell flightTimeCell = r.createCell(9);
                flightTimeCell.setCellStyle(cellStyle);
                flightTimeCell.setCellValue(flightTime);
            }

            //创建输出流
            os = new FileOutputStream(fileBasePath + file);
            //将book中的数据写出
            book.write(os);
        }catch (Exception e){
            logger.info("生成订单信息Excel异常,异常信息",e);
        }finally {
            try {
                os.close();//关闭流
                book.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return fileBasePath + file;
    }

}