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.*;

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

/**
 * @author thuang
 * @version 1.0
 * @description: his账单明细
 * @date 2021/9/28 11:13
 */
@Api(value = "his账单明细相关接口")
@Controller
@RequestMapping("/hisDetail")
public class HisDetailController {

    @Autowired
    private HisDetailService hisDetailService;

    @Autowired
    private DicinfoService dicinfoService;

    @RequestMapping("/toHisDetail")
    public String toHisDetail(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);

        return "financialReconciliation/hisDetail";
    }

    /**
     * @description: 查询his 详细记录
     * @author thuang
     * @date 2021/9/17 8:55
     * @version 1.0
     */
    @ApiOperation(value = "查询his详细记录", notes = "")
    @GetMapping("/findHisDetail")
    @ResponseBody
    public HashMap<Object, Object> findHisDetail(@ApiParam(value = "付款方式") String payType, String startTime, String endTime, String likeFiled, int page, int limit) {
        HashMap<Object, Object> responseMap = new HashMap<>();

        try {
            HashMap<Object, Object> map = new HashMap<Object, Object>();
            map.put("payType", payType);
            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: 查询his记录统计数据
     * @author thuang
     * @date 2022/1/7 9:46
     * @version 1.0
     */
    @RequestMapping("/findHisCountData")
    @ResponseBody
    @ApiOperation(value = "查询his记录统计数据", notes = "")
    public HashMap<Object, Object> findHisCountData(@RequestBody HashMap<Object, Object> map) {
        HashMap<Object, Object> responseMap = new HashMap<Object, Object>();

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

        try {
            List<HashMap<Object, Object>> hisDetailCount = hisDetailService.findHisDetailCountData(map);

            responseMap.put("money", hisDetailCount.get(0).get("MONEY"));
            responseMap.put("num", hisDetailCount.get(0).get("NUM"));


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

        return responseMap;
    }

    /**
     * @description: 导出HIS明细
     * @author thuang
     * @date 2021/10/22 15:12
     * @version 1.0
     */
    @RequestMapping("/exportHisDetail")
    @ResponseBody
    @ApiOperation(value = "导出HIS明细", notes = "")
    public HashMap<Object, Object> exportHisDetail(@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 {

            List<HashMap<Object, Object>> list = hisDetailService.findHisDetail(map);

            // 支付方式
            List<Dicinfo> pay_type = dicinfoService.findDicinfoTreeNodeList("PAY_TYPE");
            HashMap<String, String> peyTypeMap = new HashMap<>();
            for (Dicinfo dicinfo : pay_type) {
                peyTypeMap.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("VISITZORG"));
                if ("1".equals(paymethod)) {
                    hashMap.put("VISITZORG", "门诊");
                } else if ("2".equals(paymethod)) {
                    hashMap.put("VISITZORG", "住院");
                } else {
                    hashMap.put("VISITZORG", "");
                }

                String tradingStatus = StringDUtil.changeNullToEmpty(hashMap.get("H_JYLX"));
                if ("1".equals(tradingStatus)) {
                    hashMap.put("H_JYLX", "收款记录");
                } else if ("2".equals(tradingStatus)) {
                    hashMap.put("H_JYLX", "退款记录");
                } else {
                    hashMap.put("H_JYLX", "");
                }

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

                String paytype = StringDUtil.changeNullToEmpty(hashMap.get("PAYTYPE"));
                hashMap.put("PAYTYPE", peyTypeMap.get(paytype));

            }

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

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

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

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

}
