package com.emr.controller.emrApprove;

import com.alibaba.fastjson.JSON;
import com.emr.annotation.OptionalLog;
import com.emr.controller.FormTokenFlagUtil;
import com.emr.dao.CommomMapper;
import com.emr.dao.emrCollect.Emr_CollectMapper;
import com.emr.entity.Emr_Fun_Group_Distribution;
import com.emr.entity.Power_User;
import com.emr.entity.ResultUtil;
import com.emr.entity.emrCollect.Emr_Collect;
import com.emr.service.emrCollect.EmrCollectService;
import com.emr.service.emrFunGroupDistribution.FunGroupDistributionService;
import com.emr.util.ExceptionPrintUtil;
import com.emr.util.ExportExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @ProjectName:CollectionController
 * @Description:个人收藏页面
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/6/25 15:37
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/6/25 15:37
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Controller
@RequestMapping("collect/")
public class CollectionController {
    @Autowired
    private EmrCollectService emrCollectService;
    @Autowired
    private Emr_CollectMapper emrCollectMapper;
    @Autowired
    private CommomMapper commomMapper;
    @Autowired
    private FunGroupDistributionService funGroupDistributionService;
    /**
     * @ProjectName:collectManage
     * @Description:跳转到收藏管理页面
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019/6/25 15:37
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019/6/25 15:37
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    //174
    @RequiresPermissions("/collect/collectManage174")
    @OptionalLog(module = "查看",methods = "个人收藏")
    @RequestMapping("collectManage174")
    public String collectManage174(Model model,HttpServletRequest request){
        //加载收藏分类
        List<Emr_Collect> collectTypes = null;
        try {
            collectTypes = emrCollectService.selectAllCollectTypeByCreater( 1,request);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        model.addAttribute("collectTypes",collectTypes);
        return "approveManage/collection/collectManage174";
    }


    @RequiresPermissions("/collect/collectManage")
    @OptionalLog(module = "查看",methods = "个人收藏")
    @RequestMapping("collectManage")
    public String collectManage(Model model,HttpServletRequest request){
        //加载收藏分类
        List<Emr_Collect> collectTypes = null;
        try {
            collectTypes = emrCollectService.selectAllCollectTypeByCreater( 1,request);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        model.addAttribute("collectTypes",collectTypes);
        return "approveManage/collection/collectManage174";
    }

    /**
     * @ProjectName:getEmrCollectTypeNameTree
     * @Description:组织收藏类别树
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019/6/26 15:37
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019/6/26 15:37
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value="getEmrCollectTypeNameTree",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getEmrCollectTypeNameTree(HttpServletRequest request){
        try {
            List<Emr_Collect> collects = emrCollectService.selectAllCollectTypeByCreater( 1,request);
            Emr_Collect collect = new Emr_Collect();
            collect.setId(0);
            collect.setCollectTypeName("收藏列表");
            collects.add(collect);
            return JSON.toJSONString(collects);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @ProjectName:checkTypeFlagOrTypeName
     * @Description:验证类别标志或名称不能重复
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019/09/0615:37
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019/6/26 15:37
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("checkTypeFlagOrTypeName")
    @ResponseBody
    public ResultUtil checkTypeFlagOrTypeName(Emr_Collect emrCollect,HttpServletRequest request) throws Exception{
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        Emr_Collect emr_collect = emrCollectMapper.checkTypeFlagOrTypeName(user.getUserId(), emrCollect.getCollectTypeFlag(), emrCollect.getCollectTypeName());
        if(null != emr_collect){
            return ResultUtil.error();
        }
        return ResultUtil.ok();
    }

    /**
     * @ProjectName:addCollectType
     * @Description:保存收藏类别
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019/6/26 15:37
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019/6/26 15:37
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "保存",methods = "收藏类别",fieldName = "collectTypeName")
    @RequestMapping("addCollectType")
    @ResponseBody
    public ResultUtil addCollectType(Emr_Collect emrCollect,HttpServletRequest request) throws Exception{
        //验证类别名称是否重复
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        Integer userId = user.getUserId();
        Emr_Collect collect = emrCollectMapper.checkCollectTypeNameByCreaterAndTypeName(userId, emrCollect.getCollectTypeName());
        Emr_Collect collect1 = emrCollectMapper.checkTypeFlagOrTypeName(userId, emrCollect.getCollectTypeFlag(),null);
        //判断id是否有值，为null添加，否则更新
        if(null == emrCollect.getId()){
            if(collect != null){
                return ResultUtil.error("类别名称不能重复!");
            }
            if(collect1 != null){
                return ResultUtil.error("类别标志不能重复!");
            }
            boolean flag = FormTokenFlagUtil.isFlag(request);
            if(flag){
                emrCollectService.addCollect(emrCollect,request);
            }else{
                return ResultUtil.error("请不要重复提交!");
            }
        }else{
            if(null != collect && !collect.getId().equals(emrCollect.getId())){
                return ResultUtil.error("类别名称不能重复!");
            }
            if(null != collect1 && !collect1.getId().equals(emrCollect.getId())){
                return ResultUtil.error("类别标志不能重复!");
            }
            emrCollectService.updateCollect(emrCollect,request);

        }
        return ResultUtil.ok();
    }

    /**
     * @ProjectName:deleteCollectType
     * @Description:删除收藏类别
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019/6/26 15:37
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019/6/26 15:37
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/collect/deleteCollectType")
    @OptionalLog(module = "删除",methods = "收藏类别",fieldName = "collectTypeName",tableName = "emr_collect")
    @RequestMapping("deleteCollectType")
    @ResponseBody
    public ResultUtil deleteCollectType(Integer id) throws Exception{
        emrCollectService.deleteByPrimaryKey(id);
        return ResultUtil.ok();
    }

    //加载收藏类别
    @RequestMapping("getCollectType")
    @ResponseBody
    public String getCollectType(HttpServletRequest request){
        try {
            //加载收藏分类
            List<Emr_Collect> collectTypes = emrCollectService.selectAllCollectTypeByCreater( 1,request);
            return JSON.toJSONString(collectTypes);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }
    /**
     * @MethodName: addCollect
     * @Description: 收藏
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-10
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-26
     * @UpdateRemark: 从收藏模块添加收藏时，根据病案号和住院次数查询，并设置admissId,patientId
     * @Version: 1.0
     */
    @OptionalLog(module = "保存",methods = "个人收藏",fieldName = "name")
    @RequestMapping("addCollect")
    @ResponseBody
    public ResultUtil addCollect(Emr_Collect emrCollect,String name,String startTime2,String endTime2,HttpServletRequest request) throws Exception{
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        Integer userId = user.getUserId();
        String patientId = emrCollect.getPatientId();
        //根据同一病案查询标题是否存在
        Emr_Collect isPatientId = emrCollectMapper.selectCollectByUserIdAndPatientId(userId,patientId);
        if(emrCollect.getId() == null) {
            if(isPatientId != null){
                return ResultUtil.error("该病案已收藏!");
            }else{
                if(StringUtils.isBlank(emrCollect.getPatientId())){
                    //patientId为空，为未指定病案添加收藏，根据病案号和住院次数查询，并设置admissId,patientId
                    List<String> patientIdList = commomMapper.selectPatientIdByAdmissTimesAndInpatientNoAndName(emrCollect.getAdmissTimes(), emrCollect.getInpatientNo(), name,startTime2,endTime2);
                    if(null != patientIdList && !patientIdList.isEmpty()){
                        if(patientIdList.size() == 1){
                            patientId = patientIdList.get(0);
                            Emr_Collect isPatientId1 = emrCollectMapper.selectCollectByUserIdAndPatientId(userId,patientId);
                            if (isPatientId1 != null) {
                                return ResultUtil.error("该病案已收藏!");
                            }
                            emrCollect.setPatientId(patientId);
                            emrCollect.setAdmissId(emrCollect.getAdmissId());
                        }else{
                            return ResultUtil.error("查询结果不唯一,符合条件共计"+patientIdList.size()+"条");
                        }
                    }else{
                        return ResultUtil.error("查无该病案，请重新填写病案号和患者姓名和次数!");
                    }
                }
                boolean flag = FormTokenFlagUtil.isFlag(request);
                if(flag){
                    emrCollectService.addCollect(emrCollect,request);
                    return ResultUtil.ok();
                }else{
                    return ResultUtil.error("请不要重复提交!");
                }
            }
        }else{
            if(null != isPatientId && !isPatientId.getId().equals(emrCollect.getId())){
                return ResultUtil.error("该病案已收藏!");
            }else{
                //修改
                emrCollectService.updateCollect(emrCollect,request);
                return ResultUtil.ok();
            }
        }
    }

    /**
     * @MethodName: getCollectById
     * @Description: 通过id查询收藏对象
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-26
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-26
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getCollectById")
    @ResponseBody
    public String getCollectById(Integer id,String patientId,HttpServletRequest request){
        Power_User powerUser = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        try {
            Emr_Collect collect = new Emr_Collect();
            if(null  == id && StringUtils.isNotBlank(patientId)){
                collect = emrCollectService.selectCollectByUserIdAndPatientId(powerUser.getUserId(), patientId);
            }else{
                collect = emrCollectMapper.getCollectAndShowAndLockById(id,powerUser.getUserName());
                Date disDate = collect.getDisDate();
                if(null != disDate){
                    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                    collect.setDisTime(fmt.format(collect.getDisDate()));
                }
                if(null != collect.getIsShowDetail() && collect.getIsShowDetail() != 1){
                    //查询是否有免申请查看病案权限
                    List<Emr_Fun_Group_Distribution> approve = funGroupDistributionService.selectUserIdsByTypeFlag("approve", powerUser.getUserId());
                    if(null != approve && !approve.isEmpty()){
                        collect.setIsShowDetail(1);
                    }
                }
            }
            return JSON.toJSONString(collect);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: getCollectByUserIdAndPatientIdAndAdmissTimes
     * @Description: 根据用户id,patientId,admissTimes获取收藏对象
     * @Param  patientId,admissTimes:住院次数
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-10
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-10
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getCollectByUserIdAndPatientIdAndAdmissTimes")
    @ResponseBody
    public String getCollectByUserIdAndPatientIdAndAdmissTimes(String patientId,HttpServletRequest request){
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        Integer userId = user.getUserId();
        try{
            //根据用户id和patientId查询收藏对象
            Emr_Collect collect = emrCollectService.selectCollectByUserIdAndPatientId(userId, patientId);
            return JSON.toJSONString(collect);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: getCollectList
     * @Description: 获取收藏列表
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-26
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-26
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getCollectList")
    @ResponseBody
    public String getCollectList(Integer page,Integer limit,Emr_Collect collect,String startTime,String endTime,HttpServletRequest request){
        if(null != page && null != limit){
            PageHelper.startPage(page, limit);
        }
        try{
            //根据用户id和patientId查询收藏对象
            List<Emr_Collect> collects = emrCollectService.selectAllCollectByCreater(collect,startTime,endTime,request);
            //匹配权限
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            Set<String> menus = user.getMenus();
            if(null != collects && !collects.isEmpty()){
                if(null != menus && !menus.isEmpty()){
                    int updateOper = 0;
                    int deleteOper = 0;
                    for(String menu : menus){
                        if(StringUtils.isNotBlank(menu)){
                            if("/collect/updateCollect".equals(menu)){
                                updateOper = 1;
                            }
                            if("/collect/deleteCollect".equals(menu)){
                                deleteOper = 1;
                            }
                            if(updateOper == 1 && deleteOper == 1){
                                break;
                            }
                        }
                    }
                    for (Emr_Collect obj : collects){
                        obj.setUpdateOper(updateOper);
                        obj.setDeleteOper(deleteOper);
                    }
                }
            }
            PageInfo pageInfo = new PageInfo<>(collects);
            return JSON.toJSONString(pageInfo);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: exportExcel
     * @Description: 根据搜索条件导出excel
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-27
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-27
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/collect/exportExcel")
    @OptionalLog(module = "导出excel",methods = "个人收藏")
    @RequestMapping(value="exportExcel",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public void exportExcel(HttpServletResponse response,Emr_Collect collect,String startTime,String endTime,HttpServletRequest request,String checks) throws Exception {
        String tableThNames = "收藏类别,收藏人,收藏日期,标题,内容,病案号,患者姓名,住院次数";
        String fieldCns = "collectTypeName,creater,collectTime,title,content,inpatientNo,name,admissTimes";
        //构造excel的数据
        try{
            List<Emr_Collect> collects = new ArrayList<>();
            if(StringUtils.isNotBlank(checks)){
                collects = emrCollectMapper.selectAllByIds(checks);
            }else{
                collects = emrCollectService.selectAllCollectByCreater(collect,startTime,endTime,request);
            }
            //文件名
            String fileName = "个人收藏导出数据(" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ").xls";
            //ExportExcelUtil
            ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
            //导出excel的操作
            exportExcelUtil.expordExcel(tableThNames,fieldCns,collects,fileName,response);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
    }

    /**
     * @MethodName: deleteCollect
     * @Description: 根据收藏id删除
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-28
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-28
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/collect/deleteCollect")
    @OptionalLog(module = "删除",methods = "个人收藏",fieldName = "inpatientNo",tableName = "emr_collect")
    @RequestMapping("deleteCollect/{id}")
    @ResponseBody
    public ResultUtil deleteCollect(@PathVariable("id")Integer id) throws Exception{
        emrCollectService.deleteByPrimaryKey(id);
        return ResultUtil.ok();
    }
}
