package com.saye.hospitalgd.controller.historyLog;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.saye.hospitalgd.commons.date.DateDUtil;
import com.saye.hospitalgd.commons.log.ExceptionDUtil;
import com.saye.hospitalgd.commons.log.LogUtil;
import com.saye.hospitalgd.service.historyLog.CashDetailService;
import io.swagger.annotations.Api;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author thuang
 * @version 1.0
 * @description: 现金记录
 * @date 2021/11/5 13:07
 */
@Controller
@Api(tags = "")
@RequestMapping("/cashLog")
public class CashLogController {

    @Autowired
    private CashDetailService cashDetailService;

    /**
     * @description: 查询现金记录
     * @author thuang
     * @date 2021/11/5 13:10
     * @version 1.0
     */
    @RequestMapping("/toCashLog")
    public String toHisBillLog(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);

        return "historyLog/cashLog";
    }

    /**
     * @description: 查询现金记录
     * @author thuang
     * @date 2021/11/5 17:02
     * @version 1.0
     */
    @RequestMapping("/findCashList")
    @ResponseBody
    public HashMap<Object,Object> findCashList(String startTime,String endTime,int page,int limit){
        HashMap<Object,Object> responseMap=new HashMap<Object,Object>();

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

            PageHelper.startPage(page, limit);
            PageInfo<HashMap<Object, Object>> pageInfo = new PageInfo<HashMap<Object, Object>>(cashDetailService.findCashDetailPageList(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/11/5 17:03
     * @version 1.0
     */
    @RequestMapping("/uploadCash")
    @ResponseBody
    public HashMap<Object, Object> uploadSpecialEvent(@RequestParam("spareFile") MultipartFile file, HttpServletRequest request, HttpServletResponse response)throws Exception{
        HashMap<Object, Object> responseMap=new HashMap<Object, Object>();
        String errCode="0";
        String errMsg="";

        String input_trade_date="";

        //添加人员

        if (!file.isEmpty()) {
            XSSFWorkbook workbook =null;

            //创建Excel，读取文件内容
            workbook = new XSSFWorkbook(file.getInputStream());

            //获取第一个工作表
            XSSFSheet sheet =  workbook.getSheetAt(0);
            //获取sheet中第一行行号
            int firstRowNum = sheet.getFirstRowNum();
            //获取sheet中最后一行行号
            int lastRowNum = sheet.getLastRowNum();

            try {
                //时间
                String create_time = DateDUtil.getCurrentDate(DateDUtil.yyyy_MM_dd_HH_mm_ss);


                //循环数据
                boolean isOK=true;
                List<HashMap<Object,Object>> addList =new ArrayList<>();
                for(int i=firstRowNum+2;i<=lastRowNum;i++) {//因为表格中第一行为说明，第二行为列标题
                    XSSFRow row = sheet.getRow(i);

                    HashMap<Object,Object> addMap=new HashMap<>();

                    //操作员号
                    XSSFCell czyh = row.getCell(0);
                    if (czyh != null) {
                        czyh.setCellType(Cell.CELL_TYPE_STRING);
                        String czyhStr = czyh.getStringCellValue();
                        czyhStr = czyhStr.trim();

                        addMap.put("czyh",czyhStr);
                    } else {
                        isOK = false;
                        break;
                    }

                    //交易日期
                    XSSFCell trade_date = row.getCell(1);
                    if (trade_date != null) {
                        trade_date.setCellType(Cell.CELL_TYPE_STRING);
                        String trade_dateStr = trade_date.getStringCellValue();
                        trade_dateStr = trade_dateStr.trim();
                        addMap.put("trade_date",trade_dateStr);

                        if (i==2){
                            input_trade_date=trade_dateStr;
                        }
                    } else {
                        isOK = false;
                        break;
                    }


                    //交易金额
                    XSSFCell jyje = row.getCell(2);
                    if (jyje != null) {
                        jyje.setCellType(Cell.CELL_TYPE_STRING);
                        String jyjeStr = jyje.getStringCellValue();
                        addMap.put("jyje",jyjeStr);

                    }else{
                        isOK = false;
                        break;
                    }

                    //添加日期
                    addMap.put("create_time",create_time);

                    addList.add(addMap);
                }

                if(isOK){
                    errCode="999";
                    errMsg="导入失败，请检查数据内容";
                }else{
                    cashDetailService.insertCash(addList);
                    LogUtil.info(this.getClass(),"导入"+input_trade_date+"金额记录成功");
                }
            } catch (Exception e) {
                errCode="999";
                errMsg="导入金额记录失败！原因："+e.getMessage();
                e.printStackTrace();
                LogUtil.error(this.getClass(), "导入"+input_trade_date+"金额记录失败，原因:"+ ExceptionDUtil.getDetailExceptionMsg(e));
            } finally {
                workbook.close();
            }
        }

        responseMap.put("errCode", errCode);
        responseMap.put("errMsg", errMsg);
        return responseMap;
    }

    /**
     * @description: 修改修改现金金额
     * @author thuang
     * @date 2021/11/8 9:21
     * @version 1.0
     */
    @PostMapping("/editCash")
    @ResponseBody
    public HashMap<Object,Object> editCash(@RequestBody HashMap<Object,Object> map){
        HashMap<Object, Object> responseMap=new HashMap<Object, Object>();
        String errCode="0";
        String errMsg="";

        try{
            cashDetailService.editCash(map);

        } catch (Exception e) {
            errCode="999";
            errMsg="修改金额记录失败！原因："+e.getMessage();
            e.printStackTrace();
            LogUtil.error(this.getClass(), "修改金额记录失败，原因:"+ ExceptionDUtil.getDetailExceptionMsg(e));
        }

        responseMap.put("errCode", errCode);
        responseMap.put("errMsg", errMsg);
        return responseMap;
    }

    /**
     * @description: 删除现金金额
     * @author thuang
     * @date 2021/11/8 9:22
     * @version 1.0
     */
    @PostMapping("/deleteCash")
    @ResponseBody
    public HashMap<Object,Object> deleteCash(@RequestBody HashMap<Object,Object> map){
        HashMap<Object, Object> responseMap=new HashMap<Object, Object>();
        String errCode="0";
        String errMsg="";

        try{
            cashDetailService.deleteCash(map);

        } catch (Exception e) {
            errCode="999";
            errMsg="删除金额记录失败！原因："+e.getMessage();
            e.printStackTrace();
            LogUtil.error(this.getClass(), "删除金额记录失败，原因:"+ ExceptionDUtil.getDetailExceptionMsg(e));
        }

        responseMap.put("errCode", errCode);
        responseMap.put("errMsg", errMsg);
        return responseMap;
    }
}
