package com.saye.hrs.controller;

import javax.annotation.Resource;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.saye.hrs.commons.date.DateDUtil;
import com.saye.hrs.commons.excel.ExportXLSX;
import com.saye.hrs.commons.excel.HashMapConversionImpl;
import com.saye.hrs.commons.excel.IConversionByExport;
import com.saye.hrs.commons.log.ExceptionDUtil;
import com.saye.hrs.commons.log.LogUtil;
import com.saye.hrs.commons.page.PageUtil;
import com.saye.hrs.commons.page.TemplatePage;
import com.saye.hrs.commons.string.StringDUtil;
import com.saye.hrs.model.StatusDefine;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.saye.hrs.service.OrderService;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.ui.ModelMap;

/**
 * 
 *
 * @author dqzhang
 * @since 2021-09-16 16:26:19
 */
@RequestMapping("order")
@Controller
public class OrderController {
   
    @Resource
    private OrderService orderService;

    /**
     * 跳转页面
     * @param  modelMap
     * @param 
     * @return 
     */
    @RequestMapping("/toOrder")
	public String toUserManager(ModelMap modelMap){
            //查询科室
        List<HashMap<Object, Object>> distinctOrderOffice = this.orderService.findDistinctOrderOffice();
        modelMap.addAttribute("list", distinctOrderOffice);
		//查询所有角色
		return "order/order";
	}
    /**
     * 分页查询列表
     * @param  page limit
     * @param 
     * @return 查询结果
     */
    @RequestMapping("/findOrderPageList")
    @ResponseBody
    public TemplatePage findOrderPageList(Integer page,Integer limit,String name,String startTime,String endTime,String ksdm) {
        HashMap<Object,Object> map=new HashMap<Object,Object>();
        map.put("name",name);
        map.put("startTime",startTime.replace("-",""));
        map.put("endTime",endTime.replace("-",""));
        map.put("ksdm",ksdm);

        PageHelper.startPage(page, limit);
		PageInfo<HashMap<Object,Object>> appsPageInfo = new PageInfo<HashMap<Object,Object>>(this.orderService.findOrderList(map));
		return PageUtil.loadJsonPage(appsPageInfo);
    }



    /**
     * 通过主键查询单条数据
     * @param map
     * @return 单条数据
     */
    @RequestMapping("/findOrderById")
    @ResponseBody
    public HashMap<Object,Object> findOrderById(@RequestBody HashMap<Object,Object> map) {
        return this.orderService.findOrderById(map);
    }

    /**
     * 新增数据
     * @param map
     * @return map
     */
    @RequestMapping("/insertOrder")
    @ResponseBody
    public HashMap<Object,Object> insertOrder(@RequestBody HashMap<Object,Object> map) {
        String errCode = "0";
        String errMsg = "";
        try{  
            this.orderService.insertOrder(map);
        } catch (Exception e) {
            errCode = "999";
            errMsg = "新增失败";
			LogUtil.error(this.getClass(), "新增失败，原因:"+ExceptionDUtil.getDetailExceptionMsg(e));
		}
		HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
		resultMap.put("errCode",errCode);
		resultMap.put("errMsg",errMsg);
		return resultMap;
    }

    /**
     * 编辑数据
     * @param map
     * @return map
     */
    @RequestMapping("/updateOrder")
    @ResponseBody
    public HashMap<Object,Object> updateOrder(@RequestBody HashMap<Object,Object> map) {
        String errCode = "0";
        String errMsg = "";
        try{  
            this.orderService.updateOrder(map);
        } catch (Exception e) {
            errCode = "999";
            errMsg = "修改失败";
			LogUtil.error(this.getClass(), "修改失败，原因:"+ExceptionDUtil.getDetailExceptionMsg(e));
		}
		HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
		resultMap.put("errCode",errCode);
		resultMap.put("errMsg",errMsg);
		return resultMap;
    }

    /**
     * 删除数据
     * @param map
     * @return map
     */
    @RequestMapping("/deleteOrderById")
    @ResponseBody
    public HashMap<Object,Object> deleteOrderById(@RequestBody HashMap<Object,Object> map) {
        String errCode = "0";
        String errMsg = "";
        try{  
            this.orderService.deleteOrderById(map);
        } catch (Exception e) {
            errCode = "999";
            errMsg = "删除失败";
			LogUtil.error(this.getClass(), "删除失败，原因:"+ExceptionDUtil.getDetailExceptionMsg(e));
		}
		HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
		resultMap.put("errCode",errCode);
		resultMap.put("errMsg",errMsg);
        return resultMap;
    }
    
    /**
     * 	去预约须知页面
     */
    @RequestMapping("/toOrderNotice")
	public String toOrderNotice(ModelMap modelMap){

		return "order/orderNotice";
	}
    
    /**
     * @description 查询预约须知
     * @author dqzhang       
     * @created 2022年4月26日 下午1:54:59 
     * @return
     */
    @RequestMapping("/findOrderNotice")
    @ResponseBody
    public HashMap<Object, Object> findOrderNotice() {
    	
		return this.orderService.findOrderNotice();
    }
    
    /**
     * @description 更新预约须知
     * @author dqzhang       
     * @created 2022年4月26日 下午5:00:08 
     * @param map
     * @return
     */
    @RequestMapping("/updateOrderNotice")
    @ResponseBody
    public HashMap<Object,Object> updateOrderNotice(@RequestBody HashMap<Object,Object> map) {
        String errCode = "0";
        String errMsg = "";
        try{  
            this.orderService.updateOrderNotice(map);
        } catch (Exception e) {
            errCode = "999";
            errMsg = "修改失败";
			LogUtil.error(this.getClass(), "修改失败，原因:"+ExceptionDUtil.getDetailExceptionMsg(e));
		}
		HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
		resultMap.put("errCode",errCode);
		resultMap.put("errMsg",errMsg);
		return resultMap;
    }


    /**
     * @description: 导出预约挂号明细
     * @author thuang
     * @date 2023/04/07 15:12
     * @version 1.0
     */
    @RequestMapping("/exportOrderDetail")
    @ResponseBody
    public HashMap<Object, Object> exportOrderDetail(@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{
            String startTime = StringDUtil.changeNullToEmpty(map.get("startTime"));
            String endTime = StringDUtil.changeNullToEmpty(map.get("endTime"));
            map.put("startTime",startTime.replace("-",""));
            map.put("endTime",endTime.replace("-",""));

            List<HashMap<Object, Object>> list = this.orderService.findOrderList(map);


            if (list.size()>0) {
                //定义标题头和文件名
                String[] DISTANCE_HEADERNAME = {"科室名称","预约日期","预约序号","时间段","患者姓名","就诊卡","身份证"};
                String[] sqlKey = {"KSMC","YYRQ","YYHX","SJD","TRUE_NAME","MEDICAL_CARD","ID_CARD"};

                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("5000", 6);

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

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

