package com.ywt.mg.web.controllers;


import com.ywt.mg.core.MGRight;
import com.ywt.mg.core.MGRightTypeDef;
import com.ywt.mg.core.PagedList;
import com.ywt.mg.core.utils.AsyncUtil;
import com.ywt.mg.core.utils.Checker;
import com.ywt.mg.core.utils.CollectionUtil;
import com.ywt.mg.core.utils.FormatUtil;
import com.ywt.mg.core.utils.serializers.JsonSerializer;
import com.ywt.mg.domain.entities.*;
import com.ywt.mg.domain.models.ConstantDef;
import com.ywt.mg.domain.models.ExcelDataMap;
import com.ywt.mg.domain.models.ExcelStyleMap;
import com.ywt.mg.domain.models.enums.DownloadRecordStatusEnum;
import com.ywt.mg.domain.models.enums.OfflineConsultationSourceEnum;
import com.ywt.mg.domain.models.enums.PaymentStatusEnum;
import com.ywt.mg.domain.models.enums.RefundStatusEnum;
import com.ywt.mg.domain.models.pojo.ExcelCollectPojo;
import com.ywt.mg.params.offline.DownloadOfflineListNewRequest;
import com.ywt.mg.services.*;
import com.ywt.mg.web.BaseResponse;
import com.ywt.mg.web.DataResponse;
import com.ywt.mg.web.PageDataResponse;
import com.ywt.mg.web.common.ExcelDownloadSrv;
import com.ywt.mg.web.common.FileSrv;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.*;
import jxl.format.VerticalAlignment;
import jxl.write.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;

/**
 * 线下就诊相关方法类(公司后台查询所有的，通过hospital_id来区分，公司后台hospital_id = -1)
 */
@RestController("/offline")
@RequestMapping({"/offline"})
@MGRight
public class OfflineController {

    private static Logger logger = LoggerFactory.getLogger(OfflineController.class);

    @Autowired
    private AuthService authService;

    @Autowired
    private OfflineNewService offlineNewService;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private DownloadRecordService downloadRecordService;



    /**
     * 查询线下就诊列表
     *
     * @param orderNo          订单号
     * @param patientName      患者姓名
     * @param patientMobile    患者手机号
     * @param paymentStatus    支付状态 {@link PaymentStatusEnum}
     * @param status           订单状态
     * @param doctorName       医生姓名
     * @param searchHospitalId 搜索的医院id
     * @param payTimeStart     支付查询开始时间
     * @param payTimeEnd       支付查询结束时间
     */
   /*
    @RequestMapping({"/downloadOfflineList"})
    public void downloadOfflineList(@RequestParam(name = "orderNo", defaultValue = "") String orderNo,
                                    @RequestParam(name = "patientName", defaultValue = "") String patientName,
                                    @RequestParam(name = "patientMobile", defaultValue = "") String patientMobile,
                                    @RequestParam(name = "paymentStatus", defaultValue = "") String paymentStatus,
                                    @RequestParam(name = "status", defaultValue = "") String status,
                                    @RequestParam(name = "doctorName", defaultValue = "") String doctorName,
                                    @RequestParam(name = "hospitalId", defaultValue = "-1") int searchHospitalId,
                                    @RequestParam(name = "hisClinicCode", defaultValue = "") String hisClinicCode,
                                    @RequestParam(name = "payTimeStart", defaultValue = "") String payTimeStart,
                                    @RequestParam(name = "payTimeEnd", defaultValue = "") String payTimeEnd,
                                    @RequestParam(name = "refundTimeStart", defaultValue = "") String refundTimeStart,
                                    @RequestParam(name = "refundTimeEnd", defaultValue = "") String refundTimeEnd,
                                    @RequestParam(name = "source", defaultValue = "") String source,
                                    HttpServletResponse httpServletResponse) {
        downloadOfflineListCommon(orderNo, patientName, patientMobile, paymentStatus, status,
                doctorName, searchHospitalId, hisClinicCode, payTimeStart, payTimeEnd, refundTimeStart,
                refundTimeEnd, source, httpServletResponse);
    }

    public void downloadOfflineListCommon(String orderNo, String patientName, String patientMobile, String paymentStatus, String status,
                                          String doctorName, int searchHospitalId, String hisClinicCode, String payTimeStart, String payTimeEnd,
                                          String refundTimeStart, String refundTimeEnd, String source, HttpServletResponse httpServletResponse) {
        OutputStream out = null;
        String filename = "线下就诊记录.xls";
        try {
            httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "iso-8859-1"));
            httpServletResponse.setContentType("application/vnd.ms-excel;charset=UTF-8");
            httpServletResponse.setHeader("Pragma", "no-cache");
            httpServletResponse.setHeader("Cache-Control", "no-cache");
            httpServletResponse.setDateHeader("Expires", 0);

            out = httpServletResponse.getOutputStream();
            // 创建写工作簿对象
            WritableWorkbook workbook = Workbook.createWorkbook(out);
            // 工作表
            WritableSheet sheet = workbook.createSheet("线下就诊记录", 0);
            //设置字体;
            WritableFont font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);

            WritableCellFormat cellFormat = new WritableCellFormat(font);
            //设置背景颜色;
            cellFormat.setBackground(Colour.WHITE);
            //设置边框;
            cellFormat.setBorder(Border.ALL, BorderLineStyle.DASH_DOT);
            //设置自动换行;
            cellFormat.setWrap(true);
            //设置文字居中对齐方式;
            cellFormat.setAlignment(Alignment.CENTRE);
            //设置垂直居中;
            cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
            //分别给1,5,9,15列设置不同的宽度;
            sheet.setColumnView(0, 40);
            sheet.setColumnView(1, 40);
            sheet.setColumnView(4, 40);
            sheet.setColumnView(8, 40);
            sheet.setColumnView(12, 30);
            sheet.setColumnView(13, 30);
            sheet.setColumnView(14, 30);
            //给sheet电子版中所有的列设置默认的列的宽度;
            sheet.getSettings().setDefaultColumnWidth(20);
            sheet.getSettings().setDefaultRowHeight(30 * 20);


            // 单元格
            Label label0 = new Label(0, 0, "订单号", cellFormat);
            Label label1 = new Label(1, 0, "支付流水号", cellFormat);
            Label label2 = new Label(2, 0, "患者姓名", cellFormat);
            Label label3 = new Label(3, 0, "患者手机号", cellFormat);
            Label label4 = new Label(4, 0, "身份证号", cellFormat);
            Label label5 = new Label(5, 0, "医院流水号", cellFormat);
            Label label6 = new Label(6, 0, "医生姓名", cellFormat);
            Label label7 = new Label(7, 0, "科室", cellFormat);
            Label label8 = new Label(8, 0, "医院", cellFormat);
            Label label9 = new Label(9, 0, "诊查费", cellFormat);
            Label label10 = new Label(10, 0, "状态", cellFormat);
            Label label11 = new Label(11, 0, "支付状态", cellFormat);
            Label label12 = new Label(12, 0, "支付时间", cellFormat);
            Label label13 = new Label(13, 0, "退款时间", cellFormat);
            Label label14 = new Label(14, 0, "备注", cellFormat);
            Label label15 = new Label(15, 0, "来源", cellFormat);

            sheet.addCell(label0);
            sheet.addCell(label1);
            sheet.addCell(label2);
            sheet.addCell(label3);
            sheet.addCell(label4);
            sheet.addCell(label5);
            sheet.addCell(label6);
            sheet.addCell(label7);
            sheet.addCell(label8);
            sheet.addCell(label9);
            sheet.addCell(label10);
            sheet.addCell(label11);
            sheet.addCell(label12);
            sheet.addCell(label13);
            sheet.addCell(label14);
            sheet.addCell(label15);

            //上面是产生表头
            //得到里面的数据
            int n = 1;

            //给第二行设置背景、字体颜色、对齐方式等等;
            WritableFont font2 = new WritableFont(WritableFont.ARIAL, 14, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            WritableCellFormat cellFormat2 = new WritableCellFormat(font2);
            //设置文字居中对齐方式;
            cellFormat2.setAlignment(Alignment.CENTRE);
            //设置垂直居中;
            cellFormat2.setVerticalAlignment(VerticalAlignment.CENTRE);
            cellFormat2.setBackground(Colour.WHITE);
            cellFormat2.setBorder(Border.ALL, BorderLineStyle.THIN);
            cellFormat2.setWrap(true);

            // 按条件查找记录
            int hospitalId = -1;
            List<OfflineConsultation> offlineList = hospOfflineService.queryDownloadOfflineList(orderNo, patientName, patientMobile,
                    paymentStatus, status, doctorName, searchHospitalId, hisClinicCode,
                    payTimeStart, payTimeEnd, refundTimeStart, refundTimeEnd, hospitalId, source);

            int payTotal = 0, refundTotal = 0;
            if (!Checker.isNone(offlineList)) {
                // 遍历
                for (OfflineConsultation v : offlineList) {
                    String orderNoStr = Checker.getStringValue(v.getOrderNo());
                    Label valuel0 = new Label(0, n, orderNoStr, cellFormat);

                    String paymentNoStr = Checker.getStringValue(v.getPaymentNo());
                    Label valuel1 = new Label(1, n, paymentNoStr, cellFormat);

                    String patientNameNoStr = Checker.getStringValue(v.getRealName());
                    Label valuel2 = new Label(2, n, patientNameNoStr, cellFormat);

                    String patientMobileStr = Checker.getStringValue(v.getMobile());
                    Label valuel3 = new Label(3, n, patientMobileStr, cellFormat);

                    String idNoStr = Checker.getStringValue(v.getIdNo());
                    Label valuel4 = new Label(4, n, idNoStr, cellFormat);

                    String hisClinicCodeStr = Checker.getStringValue(v.getHisClinicCode() + "");
                    Label valuel5 = new Label(5, n, hisClinicCodeStr, cellFormat);

                    String doctorNameStr = Checker.getStringValue(v.getDoctorName());
                    Label valuel6 = new Label(6, n, doctorNameStr, cellFormat);

                    String deptNameStr = Checker.getStringValue(v.getDeptName());
                    Label valuel7 = new Label(7, n, deptNameStr, cellFormat);

                    String hospitalNameStr = hospitalCacheService.getCacheHospitalNameByHospitalId(Checker.getIntegerValue(v.getHospitalId()));
                    Label valuel8 = new Label(8, n, hospitalNameStr, cellFormat);

                    String totalStr = FormatUtil.intShrink100ToStr(v.getTotal());
                    Label valuel9 = new Label(9, n, totalStr, cellFormat);

                    String orderStatusStr = hospOfflineService.getOfflineStatusStr(v);
                    Label valuel10 = new Label(10, n, orderStatusStr, cellFormat);

                    String paymentStatusStr = PaymentStatusEnum.getPaymentStatus(Checker.getIntegerValue(v.getPaymentStatus())).getDisplayName();
                    Label valuel11 = new Label(11, n, paymentStatusStr, cellFormat);

                    String payTimeStr = FormatUtil.createTimeFormatList(v.getPayTime());
                    Label valuel12 = new Label(12, n, payTimeStr, cellFormat);

                    String refundTimeStr = FormatUtil.createTimeFormatList(v.getRefundTime());
                    Label valuel13 = new Label(13, n, refundTimeStr, cellFormat);

                    String remarkStr = Checker.getStringValue(v.getRefundRemark());
                    Label valuel14 = new Label(14, n, remarkStr, cellFormat);

                    String sourceStr = OfflineConsultationSourceEnum.getDisplayName(Checker.getIntegerValue(v.getSource()));
                    Label value15 = new Label(15, n, sourceStr, cellFormat);

                    if (Checker.getIntegerValue(v.getPaymentStatus()) == PaymentStatusEnum.Success.getValue()) {
                        payTotal += Checker.getIntegerValue(v.getTotal());
                    }
                    if (Checker.getIntegerValue(v.getRefundStatus()) == RefundStatusEnum.SUCCESS.getValue()){
                        refundTotal += Checker.getIntegerValue(v.getTotal());
                    }

                    sheet.addCell(valuel0);
                    sheet.addCell(valuel1);
                    sheet.addCell(valuel2);
                    sheet.addCell(valuel3);
                    sheet.addCell(valuel4);
                    sheet.addCell(valuel5);
                    sheet.addCell(valuel6);
                    sheet.addCell(valuel7);
                    sheet.addCell(valuel8);
                    sheet.addCell(valuel9);
                    sheet.addCell(valuel10);
                    sheet.addCell(valuel11);
                    sheet.addCell(valuel12);
                    sheet.addCell(valuel13);
                    sheet.addCell(valuel14);
                    sheet.addCell(value15);
                    n++;
                }
            }

            n = n + 2;
            Label valuel3 = new Label(3, n, "支付总额", cellFormat);
            Label valuel4 = new Label(4, n, FormatUtil.intShrink100ToStr(payTotal), cellFormat);
            Label valuel5 = new Label(5, n, "退款总额", cellFormat);
            Label valuel6 = new Label(6, n, FormatUtil.intShrink100ToStr(refundTotal), cellFormat);
            Label valuel7 = new Label(7, n, "实际支付金额", cellFormat);
            Label valuel8 = new Label(8, n, FormatUtil.intShrink100ToStr(payTotal-refundTotal), cellFormat);

            sheet.addCell(valuel3);
            sheet.addCell(valuel4);
            sheet.addCell(valuel5);
            sheet.addCell(valuel6);
            sheet.addCell(valuel7);
            sheet.addCell(valuel8);
            //开始执行写入操作
            workbook.write();
            //关闭流
            workbook.close();

        } catch (Exception e) {
            logger.error("/offline/downloadOfflineList(): {}", e.getMessage(), e);
            e.printStackTrace();
        }
    }
*/
    @RequestMapping({"/downloadOfflineList"})
    public BaseResponse downloadOfflineList(@RequestBody DownloadOfflineListNewRequest request) {
        int currentAdminId = Checker.getIntegerValue(authService.getCurrentAdminId());
        request.setCurrentAdminId(currentAdminId);
        // 插入记录
        int downloadRecordId = idGenerator.genDownloadRecordId();
        String name = "线下就诊";
        String fileName = "线下就诊";
        String excelSuffixFormat = ConstantDef.EXCEL_SUFFIX_FORMAT;
        String paramUrl = "/offline/downloadOfflineList";
        String paramJson = JsonSerializer.toJson(request);
        downloadRecordService.getOrInsertDownloadRecord(downloadRecordId, name, fileName + excelSuffixFormat, paramUrl, paramJson);
        Thread t = new Thread() {
            @Override
            public void run() {
                offlineNewService.downloadOfflineListCommon(downloadRecordId, fileName, request);
            }
        };
        t.start();
        return new BaseResponse().succeed("后台下载中...");
    }


}
