package com.emr.controller.otherManage;

import com.alibaba.fastjson.JSON;
import com.emr.annotation.OptionalLog;
import com.emr.entity.Emr_Dictionary;
import com.emr.entity.Emr_Fun_Group_Distribution;
import com.emr.entity.Power_User;
import com.emr.service.CommomService;
import com.emr.service.emrDictionary.EmrDictionaryService;
import com.emr.service.emrFunGroupDistribution.FunGroupDistributionService;
import com.emr.util.ExceptionPrintUtil;
import com.emr.util.ExportExcelUtil;
import com.emr.vo.Emr_Fun_Group_DistributionVo;
import com.emr.vo.Msg;
import com.emr.vo.PowerTree;
import com.emr.vo.User;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/11/14 10:39
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/11/14 10:39
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Controller
@RequestMapping("funGroupDistribution/")
public class FunGroupDistributionController {
    @Autowired
    private EmrDictionaryService dictionaryService;
    @Autowired
    private CommomService commomService;
    @Autowired
    private FunGroupDistributionService funGroupDistributionService;
    /**
     * @MethodName funGroupDistributionList
     * @Description: 跳转到功能组别分配页面
     * @Param 无
     * @Returnt otherManage/funGroupDistribution
     * @Author: 曾文和
     * @CreateDate: 2019-11-14
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-11-14
     * @UpdateRemark: 更新说明
     * @Version: 1.2.4
     */
    @OptionalLog(module = "查看",methods="功能组别分配页面")
    @RequiresPermissions("/funGroupDistribution/funGroupDistributionList")
    @RequestMapping("funGroupDistributionList")
    public String funGroupDistribution(){
        return "otherManage/funGroupDistribution";
    }

    /**
     * @MethodName getFunGroup
     * @Description: 从字典中获取功能组别
     * @Param 无
     * @Returnt Map
     * @Author: 曾文和
     * @CreateDate: 2019-11-14
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-11-14
     * @UpdateRemark: 更新说明
     * @Version: 1.2.4
     */
    @RequestMapping("getFunGroup")
    @ResponseBody
    public String getFunGroup(){
        try {
            List<Emr_Dictionary> groupList = dictionaryService.selectDictionaryByTypeCode("fun_group");
            return JSON.toJSONString(groupList);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return "";
        }
    }

    /**
     * @MethodName getUsetTree
     * @Description: 获取用户树
     * @Param 无
     * @Returnt Map
     * @Author: 曾文和
     * @CreateDate: 2019-11-14
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-11-14
     * @UpdateRemark: 更新说明
     * @Version: 1.2.4
     */
    @RequestMapping("getUsetTree")
    @ResponseBody
    public String getUsetTree(String typeFlag,HttpServletRequest request){
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        try {
            List<PowerTree> treeList = new ArrayList<>();
            List<User> list = commomService.getUserList(user.getUserName(), request);
            List<User> userList = new ArrayList<>(list);
            List<Emr_Fun_Group_Distribution> userIds = new ArrayList<>();
            if(StringUtils.isNoneBlank(typeFlag)){
                //查询该typeFlag有效期内的用户id集合
                userIds = funGroupDistributionService.selectUserIdsByTypeFlag(typeFlag,null);
            }
            if(!userList.isEmpty()){
                Map<Integer,String> roleMap = new HashMap<>();
                for (int i = 0; i < userList.size(); i++) {
                    //去除有效期已添加了的用户
                    int flag = 0;
                    if(null != userIds && !userIds.isEmpty()){
                        for (Emr_Fun_Group_Distribution userId : userIds) {
                            if (userId.getUserId().equals(userList.get(i).getUserId())) {
                                //存在
                                //删除
                                userList.remove(i);
                                //flag置为1
                                flag = 1;
                            }
                        }
                    }
                    if(flag == 0){
                        roleMap.put(userList.get(i).getRoleId(),userList.get(i).getRoleName());
                    }
                }
                int id = 0;
                int parentId = 0;
                for(Map.Entry<Integer,String> entry : roleMap.entrySet()){
                    //第一层，角色层
                    PowerTree tree1 = new PowerTree();
                    id++;
                    parentId = id;
                    tree1.setId(id);
                    tree1.setName(entry.getValue());
                    treeList.add(tree1);
                    for (User user1 : userList) {
                        //第二层，用户层
                        if (entry.getKey().equals(user1.getRoleId())) {
                            id++;
                            PowerTree tree2 = new PowerTree();
                            tree2.setId(id);
                            if (StringUtils.isNotBlank(user1.getName())) {
                                tree2.setName(user1.getUserName() + "(" + user1.getName() + ")");
                            } else {
                                tree2.setName(user1.getUserName());
                            }
                            tree2.setParentId(parentId);
                            tree2.setSelfId(user1.getUserId());
                            treeList.add(tree2);
                        }
                    }
                }
            }
            return JSON.toJSONString(treeList);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName addFunGroupDistribution
     * @Description: 保存分配
     * @Param 无
     * @Returnt Map
     * @Author: 曾文和
     * @CreateDate: 2019-11-14
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-11-14
     * @UpdateRemark: 更新说明
     * @Version: 1.2.4
     */
    @OptionalLog(module = "新增",methods = "功能组别分配",fieldName = "userNames")
    @RequiresPermissions("/funGroupDistribution/addFunGroupDistribution")
    @RequestMapping(value="addFunGroupDistribution",method = RequestMethod.POST)
    @ResponseBody
    public Msg addFunGroupDistribution(Emr_Fun_Group_DistributionVo distributionVo, HttpServletRequest request) {
        try {
            funGroupDistributionService.SimpleInsert(distributionVo, request);
            return Msg.success();
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return Msg.fail("添加失败,请联系系统管理员");
        }
    }

    /**
     * @MethodName getFunGroupDistributionList
     * @Description: 分配列表
     * @Param 无
     * @Returnt Map
     * @Author: 曾文和
     * @CreateDate: 2019-11-14
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-11-14
     * @UpdateRemark: 更新说明
     * @Version: 1.2.4
     */
    @RequestMapping("getFunGroupDistributionList")
    @ResponseBody
    public PageInfo getFunGroupDistributionList(Emr_Fun_Group_Distribution distribution, Integer page, Integer limit, String startTime, String endTime, HttpServletRequest request) {
        if(null != page && null != limit){
            PageHelper.startPage(page, limit);
        }
        try {
            List<Emr_Fun_Group_DistributionVo> list = funGroupDistributionService.selectAll(distribution,startTime,endTime);
            if(null != list && !list.isEmpty()){
                //赋值修改和删除权限
                Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
                Set<String> menus = user.getMenus();
                int updateOper = 0;
                int deleteOper = 0;
                for(String menu : menus){
                    if(StringUtils.isNotBlank(menu)){
                        if("/funGroupDistribution/updateFunGroupDistribution".equals(menu)){
                            updateOper = 1;
                        }
                        if("/funGroupDistribution/deleteById".equals(menu)){
                            deleteOper = 1;
                        }
                        if(updateOper == 1 && deleteOper == 1){
                            break;
                        }
                    }
                }
                for (Emr_Fun_Group_DistributionVo obj : list){
                    obj.setUpdateOper(updateOper);
                    obj.setDeleteOper(deleteOper);
                }
            }
            return new PageInfo<>(list);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName getDistributionById
     * @Description: 编辑回显根据id查询
     * @Param 无
     * @Returnt Map
     * @Author: 曾文和
     * @CreateDate: 2019-11-14
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-11-14
     * @UpdateRemark: 更新说明
     * @Version: 1.2.4
     */
    @RequestMapping("getDistributionById")
    @ResponseBody
    public String getDistributionById(Integer id) {
        try {
            Emr_Fun_Group_Distribution distribution = funGroupDistributionService.selectByPrimaryKey(id);
            return JSON.toJSONString(distribution);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return "";
        }
    }

    /**
     * @MethodName updateFunGroupDistribution
     * @Description: 修改
     * @Param 无
     * @Returnt Map
     * @Author: 曾文和
     * @CreateDate: 2019-11-14
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-11-14
     * @UpdateRemark: 更新说明
     * @Version: 1.2.4
     */
    @OptionalLog(module = "修改",methods = "功能组别分配",fieldName = "userName")
    @RequiresPermissions("/funGroupDistribution/updateFunGroupDistribution")
    @RequestMapping("updateFunGroupDistribution")
    @ResponseBody
    public Msg updateFunGroupDistribution(Emr_Fun_Group_Distribution distribution, HttpServletRequest request) {
        String typeFlag = distribution.getTypeFlag();
        String userName = distribution.getUserName();
        try {
            if(StringUtils.isNotBlank(typeFlag) && StringUtils.isNotBlank(userName)){
                Emr_Fun_Group_Distribution distribution1 = funGroupDistributionService.checkTypeFlagAndUserName(typeFlag, userName);
                if(null != distribution1 && !distribution1.getId().equals(distribution.getId())){
                    return Msg.fail("该分配已存在");
                }else{
                    funGroupDistributionService.updateByPrimaryKeySelective(distribution,request);
                    return Msg.success();
                }
            }else{
                return Msg.fail("组别和分配用户不能为空");
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return Msg.fail("保存出错了,请联系系统管理员");
        }
    }

    /**
     * @MethodName deleteById
     * @Description: 单个删除
     * @Param 无
     * @Returnt Map
     * @Author: 曾文和
     * @CreateDate: 2019-11-14
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-11-14
     * @UpdateRemark: 更新说明
     * @Version: 1.2.4
     */
    @OptionalLog(module = "删除",methods = "功能组别分配",fieldName = "userName",tableName = "emr_fun_group_distribution")
    @RequiresPermissions("/funGroupDistribution/deleteById")
    @RequestMapping(value="deleteById/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Msg deleteById(@PathVariable("id")Integer id) {
        try {
            funGroupDistributionService.deleteByPrimaryKey(id);
            return Msg.success();
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return Msg.fail("出错了,请联系系统管理员");
        }
    }
    /**
     * @MethodName deleteByIds
     * @Description: 批量删除
     * @Param 无
     * @Returnt Map
     * @Author: 曾文和
     * @CreateDate: 2019-11-14
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-11-14
     * @UpdateRemark: 更新说明
     * @Version: 1.2.4
     */
    @OptionalLog(module = "批量删除",methods = "功能组别分配")
    @RequiresPermissions("/funGroupDistribution/deleteById")
    @RequestMapping("deleteByIds/{ids}")
    @ResponseBody
    public Msg deleteByIds(@PathVariable("ids")String ids) {
        try {
            if(StringUtils.isNotBlank(ids)){
                ids = ids.substring(0,ids.length()-1);
                funGroupDistributionService.deleteByIds(ids);
                return Msg.success();
            }else{
                return Msg.fail("至少选中一个");
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return Msg.fail("出错了,请联系系统管理员");
        }
    }

    /**
     * @MethodName: exportExcel
     * @Description: 根据搜索条件导出excel
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-11-14
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-11-14
     * @UpdateRemark: 更新说明
     * @Version: 1.2.4
     */
    @OptionalLog(module = "导出excel",methods = "功能组别分配")
    @RequiresPermissions("/funGroupDistribution/exportExcel")
    @RequestMapping(value="exportExcel",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public void exportExcel(HttpServletResponse response,Emr_Fun_Group_Distribution distribution, String startTime, String endTime, String checks){
        String tableThNames = "功能组别,已分配,备注,有效日期,创建人,创建时间,修改人,修改时间";
        String fieldCns = "typeFlag,userName,remark,effectiveTime,creater,createDate,updater,updateDate";
        List<Emr_Fun_Group_DistributionVo> list = new ArrayList<>();
        try {
            //构造excel的数据
            if(StringUtils.isNotBlank(checks)){
                list = funGroupDistributionService.selectAllByIds(checks);
            }else{
                //构造excel的数据
                list = funGroupDistributionService.selectAll(distribution, startTime, endTime);
            }
            //文件名
            String fileName = "功能组别分配导出数据(" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ").xls";
            //ExportExcelUtil
            ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
            //导出excel的操作
            exportExcelUtil.expordExcel(tableThNames,fieldCns,list,fileName,response);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
    }
}
