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.OperatorService;
import com.saye.hospitalgd.service.TransactionDetailService;
import com.saye.hospitalgd.service.system.DicinfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
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.math.BigDecimal;
import java.util.*;

/**
 * @author thuang
 * @version 1.0
 * @description: 交易明细
 * @date 2021/9/13 15:52
 */
@Controller
@RequestMapping("/transactionDetail")
@Api(tags = "交易明细")
public class TransactionDetailController {

    @Autowired
    private TransactionDetailService transactionDetailService;

    @Autowired
    private DicinfoService dicinfoService;

    @Autowired
    private OperatorService operatorService;

    @RequestMapping("/toTransactionDetail")
    public String toTransactionDetail(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> third_pay = dicinfoService.findDicinfoTreeNodeList("THIRD_PAY");
//        System.out.println("!!!!!!!!!"+third_pay);
        modelMap.addAttribute("thirdPayList", third_pay);

        List<Dicinfo> biz_type = dicinfoService.findDicinfoTreeNodeList("BIZ_TYPE");
        modelMap.addAttribute("bizTypeList", biz_type);

        //操作员选择
        HashMap<Object, Object> map = new HashMap<>();
        map.put("is_active", "1");
        List<HashMap<Object, Object>> allOperator = null;
        try {
            allOperator = operatorService.findAllOperator(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        modelMap.addAttribute("operList", allOperator);
//        System.out.println("_________"+allOperator);

        return "financialReconciliation/transactionDetail";
    }

    /**
     * @description: 交易明细
     * @author thuang
     * @date 2021/9/28 10:55
     * @version 1.0
     */
    @RequestMapping("/findHisAndThirdJoinData")
    @ResponseBody
    @ApiOperation("交易明细")
    public HashMap<Object, Object> findHisAndThirdJoinData(String BizType, String operCode, String payType, String thirdPay, String startTime, String endTime, 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("BizType", BizType);
            map.put("thirdPay", thirdPay);
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            map.put("operCode", operCode);


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

            List<HashMap<Object, Object>> list = pageInfo.getList();

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


        return responseMap;
    }

    /**
     * @description: 交易明细统计
     * @author thuang
     * @date 2021/10/15 9:52
     * @version 1.0
     */
    @PostMapping("/findHisAndThirdJoinCountData")
    @ResponseBody
    @ApiOperation("交易明细统计")
    public HashMap<Object, Object> findHisAndThirdJoinData(@RequestBody HashMap<Object, Object> map) {
        HashMap<Object, Object> responseMap = new HashMap<>();
        String errCode = "0";
        String errMsg = "";

        try {
            //查询所有
            List<HashMap<Object, Object>> list = transactionDetailService.findHisAndThirdJoinData(map);

            int thirdNum = 0;
            int HISNum = 0;
            BigDecimal thirdMoney = new BigDecimal(0);
            BigDecimal thirdReceiveMoney = new BigDecimal(0);
            BigDecimal thirdRefundMoney = new BigDecimal(0);
            BigDecimal HISMoney = new BigDecimal(0);
            BigDecimal HISReceiveMoney = new BigDecimal(0);
            BigDecimal HISRefundMoney = new BigDecimal(0);

            for (HashMap<Object, Object> hashMap : list) {

                String amount = StringDUtil.changeNullToEmpty(hashMap.get("AMOUNT"));
                String i_jyje = StringDUtil.changeNullToEmpty(hashMap.get("I_JYJE"));
                if (!StringUtils.isEmpty(i_jyje)) {
                    thirdMoney = thirdMoney.add(new BigDecimal(i_jyje));

                    if (new BigDecimal(i_jyje).compareTo(BigDecimal.ZERO) > 0) {
                        thirdReceiveMoney = thirdReceiveMoney.add(new BigDecimal(i_jyje));
                    } else {
                        thirdRefundMoney = thirdRefundMoney.add(new BigDecimal(i_jyje));
                    }

                    thirdNum++;
                }
                if (!StringUtils.isEmpty(amount)) {
                    HISMoney = HISMoney.add(new BigDecimal(amount));
                    if (new BigDecimal(amount).compareTo(BigDecimal.ZERO) > 0) {
                        HISReceiveMoney = HISReceiveMoney.add(new BigDecimal(amount));
                    } else {
                        HISRefundMoney = HISRefundMoney.add(new BigDecimal(amount));
                    }
                    HISNum++;
                }

            }
            responseMap.put("thirdNum", thirdNum);
            responseMap.put("thirdMoney", thirdMoney);
            responseMap.put("thirdReceiveMoney", thirdReceiveMoney);
            responseMap.put("thirdRefundMoney", thirdRefundMoney);
            responseMap.put("HISNum", HISNum);
            responseMap.put("HISMoney", HISMoney);
            responseMap.put("HISReceiveMoney", HISReceiveMoney);
            responseMap.put("HISRefundMoney", HISRefundMoney);
        } catch (Exception e) {
            e.printStackTrace();
            errCode = "999";
            errMsg = "查询交易明细统计失败，原因：" + e.getMessage();
        }
        responseMap.put("errCode", errCode);
        responseMap.put("errMsg", errMsg);

        return responseMap;
    }


    /**
     * @description: 导出交易明细
     * @author thuang
     * @date 2021/10/22 8:52
     * @version 1.0
     */
    @RequestMapping("/exportHisAndThirdJoinCount")
    @ResponseBody
    @ApiOperation("导出交易明细")
    public HashMap<Object, Object> exportHisAndThirdJoinCount(@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 = transactionDetailService.findHisAndThirdJoinData(map);
            HashMap<Object, Object> hm = new HashMap<>();


            int thirdNum = 0;
            int HISNum = 0;
            BigDecimal thirdMoney = new BigDecimal(0);
            BigDecimal thirdReceiveMoney = new BigDecimal(0);
            BigDecimal thirdRefundMoney = new BigDecimal(0);
            BigDecimal HISMoney = new BigDecimal(0);
            BigDecimal HISReceiveMoney = new BigDecimal(0);
            BigDecimal HISRefundMoney = new BigDecimal(0);

            for (HashMap<Object, Object> hashMap : list) {

                String amount = StringDUtil.changeNullToEmpty(hashMap.get("AMOUNT"));
                String i_jyje = StringDUtil.changeNullToEmpty(hashMap.get("I_JYJE"));
                if (!StringUtils.isEmpty(i_jyje)) {
                    thirdMoney = thirdMoney.add(new BigDecimal(i_jyje));

                    if (new BigDecimal(i_jyje).compareTo(BigDecimal.ZERO) > 0) {
                        thirdReceiveMoney = thirdReceiveMoney.add(new BigDecimal(i_jyje));
                    } else {
                        thirdRefundMoney = thirdRefundMoney.add(new BigDecimal(i_jyje));
                    }

                    thirdNum++;
                }
                if (!StringUtils.isEmpty(amount)) {
                    HISMoney = HISMoney.add(new BigDecimal(amount));
                    if (new BigDecimal(amount).compareTo(BigDecimal.ZERO) > 0) {
                        HISReceiveMoney = HISReceiveMoney.add(new BigDecimal(amount));
                    } else {
                        HISRefundMoney = HISRefundMoney.add(new BigDecimal(amount));
                    }
                    HISNum++;
                }

            }

//            responseMap.put("thirdNum", thirdNum);
//            responseMap.put("thirdMoney", thirdMoney);
//            responseMap.put("thirdReceiveMoney", thirdReceiveMoney);
//            responseMap.put("thirdRefundMoney", thirdRefundMoney);
//            responseMap.put("HISNum", HISNum);
//            responseMap.put("HISMoney", HISMoney);
//            responseMap.put("HISReceiveMoney", HISReceiveMoney);
//            responseMap.put("HISRefundMoney", HISRefundMoney);


            //支付方式
            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> third_pay = dicinfoService.findDicinfoTreeNodeList("THIRD_PAY");
            HashMap<String, String> thirdPayMap = new HashMap<>();
            for (Dicinfo dicinfo : third_pay) {
                thirdPayMap.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());
            }

            //操作员选择
            HashMap<Object, Object> activeMap = new HashMap<>();
            activeMap.put("is_active", "1");
            List<HashMap<Object, Object>> allOperator = null;
            try {
                allOperator = operatorService.findAllOperator(activeMap);
            } catch (Exception e) {
                e.printStackTrace();
            }

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

                String i_jyqd = StringDUtil.changeNullToEmpty(hashMap.get("I_JYQD"));
                hashMap.put("I_JYQD", thirdPayMap.get(i_jyqd));


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

                String hisopernum = StringDUtil.changeNullToEmpty(hashMap.get("HISOPERNUM"));
                HashMap<Object, Object> hisOper = allOperator.stream().filter(h -> h.get("HISOPERCODE").equals(hisopernum)).findAny().orElse(null);
                if (hisOper != null) {
                    hashMap.put("HISOPERNUM", hisOper.get("USER_NAME"));
                }

//                String paymethod = StringDUtil.changeNullToEmpty(hashMap.get("PAYMETHOD"));
//                String paymethodStr="";
//                if ("1".equals(paymethod)){
//                    paymethodStr="门诊";
//                }else if ("2".equals(paymethod)){
//                    paymethodStr="住院";
//                }
//                hashMap.put("PAYMETHOD",paymethodStr);

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

            hm.put("PAYTYPE", "合计结果:");
            hm.put("TRANID", "第三方交易笔数共" + thirdNum + "笔,收款总计" + thirdReceiveMoney + "元，退款总计" + thirdRefundMoney + "元，汇总金额" + thirdMoney + "元；HIS交易共" + HISNum + "笔，收款总计" + HISReceiveMoney + "元，退款总计" + HISRefundMoney + "元，汇总金额" + HISMoney + "元；");
            list.add(hm);


            if (list.size() > 0) {
                //定义标题头和文件名
                String[] DISTANCE_HEADERNAME = {"业务类型", "交易状态", "支付方式", "HIS订单号", "金额", "交易时间", "操作员号", "患者姓名", "支付方式", "订单号", "金额", "交易时间"};
                String[] sqlKey = {"BIZTYPE", "H_JYLX", "PAYTYPE", "TRANID", "AMOUNT", "TRADETIME", "HISOPERNUM", "PATIENTNAME", "I_JYQD", "I_DDH", "I_JYJE", "JYSJ"};

                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("10000", 3);
                exportXLS.modifyWidthOfHeader("5000", 4);
                exportXLS.modifyWidthOfHeader("5000", 5);
                exportXLS.modifyWidthOfHeader("5000", 6);
                exportXLS.modifyWidthOfHeader("5000", 7);
                exportXLS.modifyWidthOfHeader("5000", 8);
                exportXLS.modifyWidthOfHeader("10000", 9);
                exportXLS.modifyWidthOfHeader("5000", 10);
                exportXLS.modifyWidthOfHeader("5000", 11);
//                exportXLS.modifyWidthOfHeader("5000", 11);

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

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

}
