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.HisDetailService;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * @author thuang
 * @version 1.0
 * @description: 军保对账统计
 * @date 2024/10/16 15:00
 */
@Api(value = "军保对账统计相关接口")
@Controller
@RequestMapping("/militaryInsurance")
public class MilitaryInsuranceController {

    @Autowired
    private HisDetailService hisDetailService;

    @Autowired
    private DicinfoService dicinfoService;

    @RequestMapping("/toMilitaryInsurance")
    public String toMilitaryInsurance(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> biz_type = dicinfoService.findDicinfoTreeNodeList("BIZ_TYPE");
        modelMap.addAttribute("bizTypeList", biz_type);

        return "financialReconciliation/militaryInsurance";
    }

    /**
     * @description: 查询军保明细记录 (paytype=3)
     * @author thuang
     * @date 2024/10/16 15:00
     * @version 1.0
     */
    @ApiOperation(value = "查询军保明细记录", notes = "")
    @GetMapping("/findMilitaryInsuranceDetail")
    @ResponseBody
    public HashMap<Object, Object> findMilitaryInsuranceDetail(@ApiParam(value = "开始时间") String startTime, 
                                                               @ApiParam(value = "结束时间") String endTime, 
                                                               @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<Object, Object>();
            List<String> payTypeList = Arrays.asList("3", "8");
            map.put("payTypeList", payTypeList);
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            map.put("likeFiled", likeFiled);

            PageHelper.startPage(page, limit);
            PageInfo<HashMap<Object, Object>> pageInfo = new PageInfo<HashMap<Object, Object>>(hisDetailService.findHisDetail(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;
    }

    /**
     * @description: 查询军保记录统计数据
     * @author thuang
     * @date 2024/10/16 15:00
     * @version 1.0
     */
    @RequestMapping("/findMilitaryInsuranceCountData")
    @ResponseBody
    @ApiOperation(value = "查询军保记录统计数据", notes = "")
    public HashMap<Object, Object> findMilitaryInsuranceCountData(@RequestBody HashMap<Object, Object> map) {
        HashMap<Object, Object> responseMap = new HashMap<Object, Object>();

        String errCode = "0";
        String errMsg = "";

        try {
            // 固定查询paytype=3的数据
            map.put("payType", "3");
            
            // 如果没有传递时间参数，设置默认查询今日数据
            if (map.get("startTime") == null || "".equals(map.get("startTime"))) {
                map.put("startTime", DateDUtil.getCurrentDate(DateDUtil.yyyy_MM_dd));
            }
            if (map.get("endTime") == null || "".equals(map.get("endTime"))) {
                map.put("endTime", DateDUtil.getCurrentDate(DateDUtil.yyyy_MM_dd));
            }
            
            // 处理前端传递的带时间格式的日期，提取日期部分
            if (map.get("startTime") != null && map.get("startTime").toString().contains(" ")) {
                String startTime = map.get("startTime").toString();
                map.put("startTime", startTime.substring(0, 10)); // 提取日期部分
            }
            if (map.get("endTime") != null && map.get("endTime").toString().contains(" ")) {
                String endTime = map.get("endTime").toString();
                map.put("endTime", endTime.substring(0, 10)); // 提取日期部分
            }
            
            List<HashMap<Object, Object>> hisDetailCount = hisDetailService.findHisDetailCountData(map);

            if (hisDetailCount != null && hisDetailCount.size() > 0) {
                responseMap.put("money", hisDetailCount.get(0).get("MONEY"));
                responseMap.put("num", hisDetailCount.get(0).get("NUM"));
            } else {
                responseMap.put("money", "0");
                responseMap.put("num", "0");
            }

        } catch (Exception e) {
            e.printStackTrace();
            errCode = "999";
            errMsg = "查询军保记录统计数据失败，原因：" + e.getMessage();
            responseMap.put("money", "0");
            responseMap.put("num", "0");
        }
        responseMap.put("errCode", errCode);
        responseMap.put("errMsg", errMsg);

        return responseMap;
    }

    /**
     * @description: 导出军保明细
     * @author thuang
     * @date 2024/10/16 15:00
     * @version 1.0
     */
    @RequestMapping("/exportMilitaryInsuranceDetail")
    @ResponseBody
    @ApiOperation(value = "导出军保明细", notes = "")
    public HashMap<Object, Object> exportMilitaryInsuranceDetail(@RequestBody HashMap<Object, Object> map) {
        HashMap<Object, Object> responseMap = new HashMap<Object, Object>();
        String errCode = "0";
        String errMsg = "";
        String dlName = "";
        String fileName = "";

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

        try {
            // 固定查询paytype=3的数据
            map.put("payType", "3");
            List<HashMap<Object, Object>> list = hisDetailService.findHisDetail(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 paymethod = StringDUtil.changeNullToEmpty(hashMap.get("PAYMETHOD"));
                if ("1".equals(paymethod)) {
                    hashMap.put("PAYMETHOD", "门诊");
                } else if ("2".equals(paymethod)) {
                    hashMap.put("PAYMETHOD", "住院");
                } else {
                    hashMap.put("PAYMETHOD", "");
                }

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

            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", "SOURCE", "CLR_TYPE", "INSUTYPE"};

                List<Object> rulList = new ArrayList<Object>(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);
                exportXLS.modifyWidthOfHeader("5000", 12);  // 来源
                exportXLS.modifyWidthOfHeader("5000", 13);  // 清算类别
                exportXLS.modifyWidthOfHeader("5000", 14);  // 险种类型

                // 文件名称
                // 产生4位长度的随机码（由字母和数字组成）
                String randomStr = StringDUtil.generateRandomCodeForLength(4);
                dlName = DateDUtil.DateToStr(DateDUtil.yyyyMMddHHmmss, new Date()) + randomStr;
                fileName = dlName + ".xlsx";

                String uploadPath = StatusDefine.filePath + "/MilitaryInsurance/";
                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", "MilitaryInsurance/" + fileName);
        return responseMap;
    }

}
