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.BankbillHistoryService;
import com.saye.hospitalgd.service.system.DicinfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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 2021/9/13 15:52
 */
@Controller
@RequestMapping("/thirdDetail")
@Api(tags = "三方账单明细")
public class ThirdDetailController {

    @Autowired
    private BankbillHistoryService bankbillHistoryService;

    @Autowired
    private DicinfoService dicinfoService;

    /**
     * @description: 到三方对账页面
     * @author thuang
     * @date 2021/9/22 14:59
     * @version 1.0
     */
    @RequestMapping("/toThirdDetail")
    public String toThirdDetail(ModelMap modelMap) {

        try {
            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<HashMap<Object,Object>> list = bankbillHistoryService.findCzffs();
            modelMap.addAttribute("zffsList",list);*/

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


        } catch (Exception e) {
            e.printStackTrace();
        }
        return "financialReconciliation/thirdDetail";
    }

    /**
     * @description: 查询三方对账记录
     * @author thuang
     * @date 2021/9/17 8:55
     * @version 1.0
     */
    @RequestMapping("/findThirdDetail")
    @ResponseBody
    @ApiOperation("查询三方对账记录")
    public HashMap<Object, Object> findThirdDetail(String c_zffs, 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("c_zffs", c_zffs);
            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>>(bankbillHistoryService.findBankbillHistoryList(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 2021/9/17 8:55
//     * @version 1.0
//     */
//    @RequestMapping("/findThirdDetailCount")
//    @ResponseBody
//    public HashMap<Object, Object> findThirdDetailCount(String c_zffs, 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("c_zffs", c_zffs);
//            map.put("startTime", startTime);
//            map.put("endTime", endTime);
//            map.put("likeFiled", likeFiled);
//
//
//            List<HashMap<Object, Object>> bankbillHistoryList = bankbillHistoryService.findBankbillHistoryList(map);
//
//            int thirdNum = 0;
//            BigDecimal thirdMoney = new BigDecimal(0);
//
//            for (HashMap<Object, Object> hashMap : bankbillHistoryList) {
//                String i_jyje = StringDUtil.changeNullToEmpty(hashMap.get("I_JYJE"));
//                if (!StringUtils.isEmpty(i_jyje)) {
//                    thirdMoney = thirdMoney.add(new BigDecimal(i_jyje));
//                    thirdNum++;
//                }
//            }
//            responseMap.put("code", 0);
//            responseMap.put("msg", "OK");
//            responseMap.put("thirdNum", thirdNum);
//            responseMap.put("thirdMoney", thirdMoney);
//        } catch (Exception e) {
//            e.printStackTrace();
//            String msg = e.getMessage();
//            responseMap.put("code", 1);
//            responseMap.put("msg", "查询失败,原因：" + msg);
//        }
//
//
//        return responseMap;
//    }


    /**
     * @description: 统计第三方数据
     * @author thuang
     * @date 2022/1/7 9:46
     * @version 1.0
     */
    @RequestMapping("/findThirdCountData")
    @ResponseBody
    @ApiOperation("统计第三方数据")
    public HashMap<Object, Object> findThirdCountData(@RequestBody HashMap<Object, Object> map) {
        HashMap<Object, Object> responseMap = new HashMap<Object, Object>();

        String errCode = "0";
        String errMsg = "";
        try {
            List<HashMap<Object, Object>> thirdDetailCount = bankbillHistoryService.findBankbillCountData(map);

            responseMap.put("money", thirdDetailCount.get(0).get("MONEY"));
            responseMap.put("num", thirdDetailCount.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: 导出三方账单明细
     * @author thuang
     * @date 2021/10/22 15:38
     * @version 1.0
     */
    @RequestMapping("/exportThirdDetail")
    @ResponseBody
    @ApiOperation("导出三方账单明细")
    public HashMap<Object, Object> exportThirdDetail(@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>> thirdDetailCount = bankbillHistoryService.findBankbillCountData(map);

            List<HashMap<Object, Object>> list = bankbillHistoryService.findBankbillHistoryList(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));
            }
            HashMap<Object, Object> tjMap = new HashMap<>();
            tjMap.put("C_QSRQ", "合计：");
            tjMap.put("C_LSH", "交易笔数共" + thirdDetailCount.get(0).get("NUM") + "笔,汇总金额" + thirdDetailCount.get(0).get("MONEY") + "元");
            list.add(tjMap);
            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", "C_JYLX", "C_FQQS"};

                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("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);
                exportXLS.modifyWidthOfHeader("6000", 16);
                exportXLS.modifyWidthOfHeader("5000", 17);

                // 文件名称
                //产生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;
    }


}
