package com.saye.hospitalgd.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.saye.hospitalgd.commons.date.DateDUtil;
import com.saye.hospitalgd.commons.excel.ExportXLSX;
import com.saye.hospitalgd.commons.excel.HashMapConversionImpl;
import com.saye.hospitalgd.commons.excel.IConversionByExport;
import com.saye.hospitalgd.commons.log.ExceptionDUtil;
import com.saye.hospitalgd.commons.log.LogUtil;
import com.saye.hospitalgd.commons.string.StringDUtil;
import com.saye.hospitalgd.model.Dicinfo;
import com.saye.hospitalgd.model.StatusDefine;
import com.saye.hospitalgd.service.InpatientBillService;
import com.saye.hospitalgd.service.system.DicinfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.*;

/**
 * @author thuang
 * @version 1.0
 * @description: 住院账单查询
 * @date 2025/11/21
 */
@Api(value = "住院账单查询相关接口")
@Controller
@RequestMapping("/inpatientBill")
public class InpatientBillController {

    @Autowired
    private InpatientBillService inpatientBillService;

    @Autowired
    private DicinfoService dicinfoService;

    /**
     * 跳转到住院账单查询页面
     */
    @RequestMapping("/toInpatientBill")
    public String toInpatientBill(ModelMap modelMap) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, -1);
        Date startDate = calendar.getTime();

        String startTime = DateDUtil.DateToStr(DateDUtil.yyyy_MM_dd, startDate);
        String endTime = DateDUtil.getCurrentDate(DateDUtil.yyyy_MM_dd);

        modelMap.addAttribute("startTime", startTime);
        modelMap.addAttribute("endTime", endTime);

        // 支付方式
        List<Dicinfo> pay_type = dicinfoService.findDicinfoTreeNodeList("PAY_TYPE");
        modelMap.addAttribute("payTypeList", pay_type);

        // 业务类型
        List<Dicinfo> biz_type = dicinfoService.findDicinfoTreeNodeList("BIZ_TYPE");
        modelMap.addAttribute("bizTypeList", biz_type);

        // 三方支付方式
        List<Dicinfo> third_pay = dicinfoService.findDicinfoTreeNodeList("THIRD_PAY");
        modelMap.addAttribute("thirdPayList", third_pay);

        return "financialReconciliation/inpatientBill";
    }

    /**
     * 查询HIS住院账单明细
     */
    @ApiOperation(value = "查询HIS住院账单明细", notes = "")
    @GetMapping("/findHisInpatientDetail")
    @ResponseBody
    public HashMap<Object, Object> findHisInpatientDetail(
            @ApiParam(value = "开始时间") String startTime,
            @ApiParam(value = "结束时间") String endTime,
            @ApiParam(value = "支付方式") String payType,
            @ApiParam(value = "业务类型") String bizType,
            @ApiParam(value = "模糊查询字段") String likeFiled,
            @ApiParam(value = "页码") int page,
            @ApiParam(value = "每页限制个数") int limit) {
        HashMap<Object, Object> responseMap = new HashMap<>();

        try {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            map.put("payType", payType);
            map.put("bizType", bizType);
            map.put("likeFiled", likeFiled);

            String militaryPaymentCode = getPayTypeCodeByNames("军保支付", "医院垫支");
            String checkPaymentCode = getPayTypeCodeByNames("支票支付", "支票");
            if (checkPaymentCode == null || "".equals(checkPaymentCode)) {
                checkPaymentCode = "无";
            }
            map.put("military_payment_code", militaryPaymentCode);
            map.put("check_payment_code", checkPaymentCode);

            PageHelper.startPage(page, limit);
            PageInfo<HashMap<Object, Object>> pageInfo = new PageInfo<>(inpatientBillService.findHisInpatientDetail(map));

            responseMap.put("code", 0);
            responseMap.put("msg", "OK");
            responseMap.put("count", pageInfo.getTotal());
            responseMap.put("data", pageInfo.getList());
        } catch (Exception e) {
            e.printStackTrace();
            String msg = e.getMessage();
            responseMap.put("code", 1);
            responseMap.put("msg", "查询失败,原因：" + msg);
        }

        return responseMap;
    }

    /**
     * 查询银行住院账单明细
     */
    @ApiOperation(value = "查询银行住院账单明细", notes = "")
    @GetMapping("/findBankInpatientDetail")
    @ResponseBody
    public HashMap<Object, Object> findBankInpatientDetail(
            @ApiParam(value = "开始时间") String startTime,
            @ApiParam(value = "结束时间") String endTime,
            @ApiParam(value = "支付方式") String c_zffs,
            @ApiParam(value = "模糊查询字段") String likeFiled,
            @ApiParam(value = "页码") int page,
            @ApiParam(value = "每页限制个数") int limit) {
        HashMap<Object, Object> responseMap = new HashMap<>();

        try {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            map.put("c_zffs", c_zffs);
            map.put("likeFiled", likeFiled);

            PageHelper.startPage(page, limit);
            PageInfo<HashMap<Object, Object>> pageInfo = new PageInfo<>(inpatientBillService.findBankInpatientDetail(map));

            responseMap.put("code", 0);
            responseMap.put("msg", "OK");
            responseMap.put("count", pageInfo.getTotal());
            responseMap.put("data", pageInfo.getList());
        } catch (Exception e) {
            e.printStackTrace();
            String msg = e.getMessage();
            responseMap.put("code", 1);
            responseMap.put("msg", "查询失败,原因：" + msg);
        }

        return responseMap;
    }

    /**
     * 查询每日汇总数据
     */
    @ApiOperation(value = "查询每日汇总数据", notes = "")
    @GetMapping("/findDailySummary")
    @ResponseBody
    public HashMap<Object, Object> findDailySummary(
            @ApiParam(value = "开始时间") String startTime,
            @ApiParam(value = "结束时间") String endTime) {
        HashMap<Object, Object> responseMap = new HashMap<>();

        try {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("startTime", startTime);
            map.put("endTime", endTime);

            String militaryPaymentCode = getPayTypeCodeByNames("军保支付", "医院垫支");
            String checkPaymentCode = getPayTypeCodeByNames("支票支付", "支票");
            if (checkPaymentCode == null || "".equals(checkPaymentCode)) {
                checkPaymentCode = "无";
            }
            map.put("military_payment_code", militaryPaymentCode);
            map.put("check_payment_code", checkPaymentCode);

            List<HashMap<Object, Object>> summaryList = inpatientBillService.findDailySummary(map);

            responseMap.put("code", 0);
            responseMap.put("msg", "OK");
            responseMap.put("data", summaryList);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = e.getMessage();
            responseMap.put("code", 1);
            responseMap.put("msg", "查询失败,原因：" + msg);
        }

        return responseMap;
    }

    /**
     * 导出HIS住院账单明细
     */
    @RequestMapping("/exportHisInpatientDetail")
    @ResponseBody
    @ApiOperation(value = "导出HIS住院账单明细", notes = "")
    public HashMap<Object, Object> exportHisInpatientDetail(@RequestBody HashMap<Object, Object> map) {
        HashMap<Object, Object> responseMap = new HashMap<>();
        String errCode = "0";
        String errMsg = "";
        String dlName = "";
        String fileName = "";

        String dowloadName = StringDUtil.changeNullToEmpty(map.get("dowloadName"));

        try {
            String militaryPaymentCode = getPayTypeCodeByNames("军保支付", "医院垫支");
            String checkPaymentCode = getPayTypeCodeByNames("支票支付", "支票");
            if (checkPaymentCode == null || "".equals(checkPaymentCode)) {
                checkPaymentCode = "无";
            }
            map.put("military_payment_code", militaryPaymentCode);
            map.put("check_payment_code", checkPaymentCode);

            List<HashMap<Object, Object>> list = inpatientBillService.findHisInpatientDetail(map);

            // 支付方式
            List<Dicinfo> pay_type = dicinfoService.findDicinfoTreeNodeList("PAY_TYPE");
            HashMap<String, String> payTypeMap = new HashMap<>();
            for (Dicinfo dicinfo : pay_type) {
                payTypeMap.put(dicinfo.getDicvalue(), dicinfo.getDicname());
            }

            // 业务类型
            List<Dicinfo> biz_type = dicinfoService.findDicinfoTreeNodeList("BIZ_TYPE");
            HashMap<String, String> bizTypeMap = new HashMap<>();
            for (Dicinfo dicinfo : biz_type) {
                bizTypeMap.put(dicinfo.getDicvalue(), dicinfo.getDicname());
            }

            for (HashMap<Object, Object> hashMap : list) {
                String tradingStatus = StringDUtil.changeNullToEmpty(hashMap.get("TRADINGSTATUS"));
                if ("1".equals(tradingStatus)) {
                    hashMap.put("TRADINGSTATUS", "收款记录");
                } else if ("2".equals(tradingStatus)) {
                    hashMap.put("TRADINGSTATUS", "退款记录");
                } else {
                    hashMap.put("TRADINGSTATUS", "");
                }

                String biztype = StringDUtil.changeNullToEmpty(hashMap.get("BIZTYPE"));
                hashMap.put("BIZTYPE", bizTypeMap.get(biztype));

                // 支付方式字典转换
                String paytype = StringDUtil.changeNullToEmpty(hashMap.get("PAYTYPE"));
                hashMap.put("PAYTYPE", payTypeMap.get(paytype));

                hashMap.put("PAYMETHOD", "住院");
            }

            if (list.size() > 0) {
                // 定义标题头和文件名
                String[] DISTANCE_HEADERNAME = {"交易状态", "业务类型", "支付方式", "交易时间", "交易日期", "操作员", "总金额", "平台交易号", "his订单号", "HIS交易ID", "患者id", "患者姓名"};
                String[] sqlKey = {"TRADINGSTATUS", "BIZTYPE", "PAYTYPE", "TRADETIME", "TRADE_DATE", "HISOPERCODE", "AMOUNT", "PLATFORMTRANSID", "HISTRANSID", "HISTRANSID", "PATIENTID", "PATIENTNAME"};

                List<Object> rulList = new ArrayList<>(list);

                // 创建工作表
                ExportXLSX exportXLS = new ExportXLSX(DISTANCE_HEADERNAME, sqlKey, ExportXLSX.A3, false);
                exportXLS.setTitleName(dowloadName);
                IConversionByExport conversion = new HashMapConversionImpl();
                exportXLS.setConversion(conversion);
                exportXLS.setData(rulList);

                exportXLS.modifyWidthOfHeader("5000", 0);
                exportXLS.modifyWidthOfHeader("5000", 1);
                exportXLS.modifyWidthOfHeader("5000", 2);
                exportXLS.modifyWidthOfHeader("5000", 3);
                exportXLS.modifyWidthOfHeader("5000", 4);
                exportXLS.modifyWidthOfHeader("5000", 5);
                exportXLS.modifyWidthOfHeader("8000", 6);
                exportXLS.modifyWidthOfHeader("5000", 7);
                exportXLS.modifyWidthOfHeader("5000", 8);
                exportXLS.modifyWidthOfHeader("5000", 9);
                exportXLS.modifyWidthOfHeader("5000", 10);
                exportXLS.modifyWidthOfHeader("10000", 11);

                // 文件名称
                String randomStr = StringDUtil.generateRandomCodeForLength(4);
                dlName = DateDUtil.DateToStr(DateDUtil.yyyyMMddHHmmss, new Date()) + randomStr;
                fileName = dlName + ".xlsx";

                String uploadPath = StatusDefine.filePath + "/InpatientBill/";
                File uploadPathFile = new File(uploadPath);
                if (!uploadPathFile.exists()) uploadPathFile.mkdirs();

                String savePath = uploadPath + fileName;
                exportXLS.execGenerateExcel(savePath);
            }

        } catch (Exception e) {
            errCode = "999";
            errMsg = "未知异常：" + ExceptionDUtil.getDetailExceptionMsg(e);
            LogUtil.error(this.getClass(), "@@@系统出错！【" + errMsg + "】");
        }

        responseMap.put("errCode", errCode);
        responseMap.put("errMsg", errMsg);
        responseMap.put("dlName", "InpatientBill/" + fileName);
        return responseMap;
    }

    private String getPayTypeCodeByNames(String... names) {
        for (String name : names) {
            HashMap<String, String> param = new HashMap<>();
            param.put("parentCode", "PAY_TYPE");
            param.put("dicname", name);
            List<HashMap<Object, Object>> list = dicinfoService.selectDicinfoListByCondition(param);
            if (list != null && list.size() > 0) {
                Object val = list.get(0).get("dicvalue");
                String code = StringDUtil.changeNullToEmpty(val);
                if (!"".equals(code)) {
                    return code;
                }
            }
        }
        return "";
    }

    /**
     * 导出银行住院账单明细
     */
    @RequestMapping("/exportBankInpatientDetail")
    @ResponseBody
    @ApiOperation(value = "导出银行住院账单明细", notes = "")
    public HashMap<Object, Object> exportBankInpatientDetail(@RequestBody HashMap<Object, Object> map) {
        HashMap<Object, Object> responseMap = new HashMap<>();
        String errCode = "0";
        String errMsg = "";
        String dlName = "";
        String fileName = "";

        String dowloadName = StringDUtil.changeNullToEmpty(map.get("dowloadName"));

        try {
            List<HashMap<Object, Object>> list = inpatientBillService.findBankInpatientDetail(map);

            // 支付方式
            List<Dicinfo> pay_type = dicinfoService.findDicinfoTreeNodeList("THIRD_PAY");
            HashMap<String, String> peyTypeMap = new HashMap<>();
            for (Dicinfo dicinfo : pay_type) {
                peyTypeMap.put(dicinfo.getDicvalue(), dicinfo.getDicname());
            }

            for (HashMap<Object, Object> hashMap : list) {
                String c_zffs = StringDUtil.changeNullToEmpty(hashMap.get("C_ZFFS"));
                hashMap.put("C_ZFFS", peyTypeMap.get(c_zffs));
            }

            if (list.size() > 0) {
                // 定义标题头和文件名
                String[] DISTANCE_HEADERNAME = {"交易日期", "交易时间", "清算日期", "流水号", "商户订单号", "银商订单号", "交易类型", "卡号", "发卡行", "交易金额", "清算金额", "手续费", "实际支付金额", "终端号", "支付方式", "卡类型"};
                String[] sqlKey = {"C_JYRQ", "C_JYSJ", "C_QSRQ", "C_LSH", "C_SHDDH", "C_YSDDH", "C_JYLX", "C_CARD", "C_FKH", "C_JYJE", "C_QSJE", "C_SXF", "C_SJZFJE", "C_ZDH", "C_ZFFS", "C_KLX"};

                List<Object> rulList = new ArrayList<>(list);

                // 创建工作表
                ExportXLSX exportXLS = new ExportXLSX(DISTANCE_HEADERNAME, sqlKey, ExportXLSX.A3, false);
                exportXLS.setTitleName(dowloadName);
                IConversionByExport conversion = new HashMapConversionImpl();
                exportXLS.setConversion(conversion);
                exportXLS.setData(rulList);

                exportXLS.modifyWidthOfHeader("5000", 0);
                exportXLS.modifyWidthOfHeader("5000", 1);
                exportXLS.modifyWidthOfHeader("5000", 2);
                exportXLS.modifyWidthOfHeader("10000", 3);
                exportXLS.modifyWidthOfHeader("6000", 4);
                exportXLS.modifyWidthOfHeader("10000", 5);
                exportXLS.modifyWidthOfHeader("5000", 6);
                exportXLS.modifyWidthOfHeader("5000", 7);
                exportXLS.modifyWidthOfHeader("5000", 8);
                exportXLS.modifyWidthOfHeader("5000", 9);
                exportXLS.modifyWidthOfHeader("5000", 10);
                exportXLS.modifyWidthOfHeader("5000", 11);
                exportXLS.modifyWidthOfHeader("5000", 12);
                exportXLS.modifyWidthOfHeader("5000", 13);
                exportXLS.modifyWidthOfHeader("5000", 14);
                exportXLS.modifyWidthOfHeader("10000", 15);

                // 文件名称
                String randomStr = StringDUtil.generateRandomCodeForLength(4);
                dlName = DateDUtil.DateToStr(DateDUtil.yyyyMMddHHmmss, new Date()) + randomStr;
                fileName = dlName + ".xlsx";

                String uploadPath = StatusDefine.filePath + "/InpatientBill/";
                File uploadPathFile = new File(uploadPath);
                if (!uploadPathFile.exists()) uploadPathFile.mkdirs();

                String savePath = uploadPath + fileName;
                exportXLS.execGenerateExcel(savePath);
            }

        } catch (Exception e) {
            errCode = "999";
            errMsg = "未知异常：" + ExceptionDUtil.getDetailExceptionMsg(e);
            LogUtil.error(this.getClass(), "@@@系统出错！【" + errMsg + "】");
        }

        responseMap.put("errCode", errCode);
        responseMap.put("errMsg", errMsg);
        responseMap.put("dlName", "InpatientBill/" + fileName);
        return responseMap;
    }
}


