package com.manage.controller;

import com.manage.annotation.RequiresPermissions;
import com.manage.dao.Power_Sys_DictMapper;
import com.manage.entity.Power_Sys_Dict;
import com.manage.entity.Power_User;
import com.manage.service.cache.CacheManager;
import com.manage.service.Power_DeptService;
import com.manage.service.Power_Sys_DictService;
import com.manage.util.Msg;
import com.manage.util.PageHelper;
import com.manage.vo.Power_DeptVo;
import com.manage.vo.Power_Sys_DictVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
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.util.ArrayList;
import java.util.List;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/8/29 13:45
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/8/29 13:45
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Controller
@RequestMapping("/dict")
public class Power_Sys_DictController {
    @Autowired
    Power_Sys_DictService powerSysDictService;
    @Autowired
    Power_DeptService deptService;
    @Autowired
    Power_Sys_DictMapper sysDictMapper;
    /**
     * @Date 2019-5-5
     * @Author ly
     *  @Description 返回页面
     * */
    @RequiresPermissions(value="/dict/pageUI")
    @RequestMapping("/pageUI")
    public String pageUI(){
        CacheManager.addExcCount("noExc");
        return "dictDir/dict";
    }


    @RequestMapping("/selectHosList")
    @ResponseBody
    public List<Power_Sys_Dict> selectHosList(HttpServletRequest request){
        try {
            List<Power_Sys_Dict> power_sys_dicts = powerSysDictService.selectHosList(request);
            CacheManager.addExcCount("noExc");
            return  power_sys_dicts;
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/selectList")
    @ResponseBody
    public List<Power_Sys_Dict> selectList(){
        try {
            List<Power_Sys_Dict> power_sys_dicts = powerSysDictService.selectList();
            CacheManager.addExcCount("noExc");
            return power_sys_dicts;
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/selectDict")
    @ResponseBody
    public Power_Sys_Dict selectDict(Integer dictId){
        try {
            Power_Sys_Dict power_sys_dict = powerSysDictService.selectByPrimaryKey(dictId);
            CacheManager.addExcCount("noExc");
            return  power_sys_dict;
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }
    @RequestMapping("/checkHospitalName")
    @ResponseBody
    public Msg checkHospitalName(String hospitalName){
        try {
            Power_Sys_DictVo dictVo = powerSysDictService.checkHospitalName(hospitalName);
            CacheManager.addExcCount("noExc");
            if(dictVo != null){
                return Msg.fail("医院名称已存在");
            }else{
                return Msg.success();
            }
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("验证失败,请联系系统管理员");
        }
    }

    @RequiresPermissions(value="/dict/add")
    @RequestMapping("/add")
    @ResponseBody
    public Msg add(Power_Sys_DictVo powerSysDict, HttpServletRequest request){
        try {
            if(powerSysDict.getDictId()  == null){
                //添加医院
                if(StringUtils.isNoneBlank(powerSysDict.getHospitalName())){
                    Power_Sys_DictVo dictVo = powerSysDictService.checkHospitalName(powerSysDict.getHospitalName());
                    if(dictVo != null){
                        return Msg.fail("医院名称不能重复!");
                    }
                    powerSysDictService.insertSelective(powerSysDict,request);
                    Integer dictId = powerSysDict.getDictId();
                    CacheManager.addExcCount("noExc");
                    return Msg.success().add("dictId",dictId);
                }else{
                    //添加系统
                    String deptIds = powerSysDict.getDeptIds();
                    if(StringUtils.isBlank(deptIds)){
                        deptIds = "-999";
                    }
                    if(!deptIds.contains(",")){
                        List<Power_Sys_Dict> deptBySysFlagList = sysDictMapper.selectDeptIdByParentIdAndSysFlag(powerSysDict.getParentId(), powerSysDict.getSysFlag(),deptIds);
                        if(null != deptBySysFlagList && !deptBySysFlagList.isEmpty()){
                            return Msg.fail("系统标识已存在!");
                        }
                    }
                    /*List<Power_Sys_Dict> dicts = powerSysDictService.checkSysFlagOrSysNameByDeptIds(powerSysDict.getSysFlag(), powerSysDict.getSysName(), deptIds);
                    if(null != dicts && !dicts.isEmpty()) {
                        if (StringUtils.isNoneBlank(powerSysDict.getSysFlag())) {
                            return Msg.fail("系统标识已存在!");
                        } else {
                            return Msg.fail("系统名称已存在!");
                        }
                    }*/
                    if(StringUtils.isNoneBlank(deptIds) && deptIds.contains(",")){
                        int count = powerSysDictService.simpleInsertDict(powerSysDict, deptIds, request);
                        if(count == 0){
                            return Msg.fail("系统已存在!");
                        }else{
                            int dictLastId = sysDictMapper.selectLastDict();
                            powerSysDict.setDictId(dictLastId);
                        }
                    }else{
                        powerSysDict.setDeptId(Integer.valueOf(deptIds));
                        powerSysDictService.insertSelective(powerSysDict,request);
                    }
                    CacheManager.addExcCount("noExc");
                    return Msg.success().add("dictId",powerSysDict.getDictId());
                }
            }else{
                //修改
                if(StringUtils.isNoneBlank(powerSysDict.getHospitalName())){
                    //修改医院信息
                    Power_Sys_DictVo dictVo = powerSysDictService.checkHospitalName(powerSysDict.getHospitalName());
                    if(dictVo != null && dictVo.getDictId() != powerSysDict.getDictId()){
                        return Msg.fail("医院名称已存在!");
                    }else{
                        powerSysDictService.updateByPrimaryKeySelective(powerSysDict,request);
                        CacheManager.addExcCount("noExc");
                        return Msg.success().add("dictId",powerSysDict.getDictId());
                    }
                }else{
                    //修改系统信息
                    Integer deptId = powerSysDict.getDeptId();
                    if(null == deptId){
                        deptId = -999;
                    }
                    List<Power_Sys_Dict> flagExists = powerSysDictService.checkSysFlagOrSysNameByDeptId(powerSysDict.getSysFlag(), null, deptId.toString());
                    if(null != flagExists && !flagExists.isEmpty()) {
                        //判断是否包含在这个集合里
                        Boolean flagExist = false;
                        for (int i = 0; i < flagExists.size(); i++) {
                            if(!flagExists.get(i).getDictId().equals(powerSysDict.getDictId())){
                                flagExist = true;
                            }
                        }
                        if(flagExist){
                            return Msg.fail("系统标识已存在!");
                        }
                    }
                    //修改系统信息
                    List<Power_Sys_Dict> sysNameExists = powerSysDictService.checkSysFlagOrSysNameByDeptId(null, powerSysDict.getSysName(), deptId.toString());
                    if(null != sysNameExists && !sysNameExists.isEmpty()) {
                        //判断是否包含在这个集合里
                        Boolean sysNameExist = false;
                        for (int i = 0; i < sysNameExists.size(); i++) {
                            if(!sysNameExists.get(i).getDictId().equals(powerSysDict.getDictId())){
                                sysNameExist = true;
                            }
                        }
                        if(sysNameExist){
                            return Msg.fail("系统名称已存在!");
                        }
                    }
                    if(StringUtils.isNoneBlank(powerSysDict.getSysType()) && "权限系统".equals(powerSysDict.getSysType())){
                        powerSysDict.setDeptId(null);

                    }else{
                        //计算出科室减少部分批量删除，增加部分批量增加，重叠部分批量修改
                    }
                    powerSysDictService.updateByPrimaryKeySelective(powerSysDict,request);
                }
                CacheManager.addExcCount("noExc");
                return Msg.success().add("dictId",powerSysDict.getDictId());
            }
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("添加失败,请联系系统管理员!");
        }
    }
    @RequiresPermissions(value="/dict/update")
    @RequestMapping("/update")
    @ResponseBody
    public Msg update(@RequestBody Power_Sys_Dict powerSysDict, HttpServletRequest request){
        try {
            powerSysDictService.updateByPrimaryKeySelective(powerSysDict,request);
            CacheManager.addExcCount("noExc");
            return  Msg.success();
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("更新失败,请联系系统管理员!");
        }
    }
    @RequiresPermissions(value="/dict/delete")
    @RequestMapping("/delete")
    @ResponseBody
    public Msg delete(Integer dictId){
        try {
            powerSysDictService.deleteByPrimaryKey(dictId);
            CacheManager.addExcCount("noExc");
            return  Msg.success();
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("更新失败,请联系系统管理员!");
        }
    }
    @RequestMapping("/selectType")
    @ResponseBody
    public List<Power_Sys_DictVo> selectType(){
        try {
            List<Power_Sys_DictVo> power_sys_dictVos = powerSysDictService.selectSysType();
            CacheManager.addExcCount("noExc");
            return power_sys_dictVos;
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }
    @RequestMapping("/export")
    public void download(HttpServletResponse response){
        try {
            powerSysDictService.export(response);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
        }
    }

    @RequestMapping("/getHospitalByParentId")
    @ResponseBody
    public Msg getHospitalByParentId(Integer dictId){
        try {
            Power_Sys_DictVo powerSysExsit = powerSysDictService.getHospitalByParentId(dictId, "权限系统");
            CacheManager.addExcCount("noExc");
            if(null != powerSysExsit){
                return Msg.fail();
            }else{
                return Msg.success();
            }
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("查询失败,请联系系统管理员!");
        }
    }

    @RequestMapping("/dictManagePage")
    public String dictManagePage(Integer level, String operFlag, Integer selfId, Integer deptId, Model model, HttpServletRequest request){
        try {
            Power_Sys_DictVo hospital = new Power_Sys_DictVo();
            if(null != selfId && level != 0){
                hospital = powerSysDictService.selectByPrimaryKey(selfId);
                //加载节点信息
            }
            //按医院查询科室集合
            if(StringUtils.isNoneBlank(operFlag) && "edit".equals(operFlag)){
                if(level != null && level > 0){
                    level -= 1;
                }
            }
            model.addAttribute("hospital",hospital);
            if(selfId != null && level != 0){
                //加载系统分类
                List<String> sysTypes = new ArrayList();

                Power_Sys_DictVo dict = new Power_Sys_DictVo();
                if(!hospital.getDictId().equals(hospital.getParentId()) && StringUtils.isNoneBlank(operFlag) && "edit".equals(operFlag)){
                    dict = hospital;
                    model.addAttribute("dict",dict);
                }
                if(level != 0 && selfId >= 0 || selfId == -100){
                    //权限系统是否存在，不存在才加载
                    Power_Sys_DictVo powerSysExsit = powerSysDictService.getHospitalByParentId(selfId, "权限系统");
                    if(null == powerSysExsit && level != 2 || "权限系统".equals(hospital.getSysType())){
                        sysTypes.add("权限系统");
                    }
                }
                //权限系统、病案管理系统、病案归档系统、复印预约系统、科研系统、其它
                sysTypes.add("档案管理系统");
                sysTypes.add("档案归档系统");
                sysTypes.add("复印预约系统");
                sysTypes.add("科研系统");
                sysTypes.add("其它");
                model.addAttribute("sysTypes",sysTypes);
                if(hospital != null){
                    selfId = hospital.getHospitalId();
                }
                List<Power_DeptVo> depts = deptService.selectDeptByDictId(selfId,dict.getSysFlag());
                model.addAttribute("depts",depts);
            }
            //加载医院列表
            List<Power_Sys_Dict> hospitals = powerSysDictService.selectHosList(request);
            model.addAttribute("hospitals",hospitals);
            //节点层级
            model.addAttribute("level",level);
            //加载角色id,系统管理员可编辑
            Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
            model.addAttribute("user",user);
            model.addAttribute("operFlag",operFlag);
            if(null != deptId){
                deptId -= deptId*2;
            }
            model.addAttribute("deptId",deptId);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
        }
        return "dictDir/dictManageIframe";
    }

    @RequestMapping("/checkSysFlagOrSysNameByDeptId")
    @ResponseBody
    public Msg checkSysFlagOrSysNameByDeptId(String sysFlag,String sysName,String deptIds){
        try {
            if(StringUtils.isBlank(deptIds)){
                deptIds = "-999";
            }
            List<Power_Sys_Dict> dicts = powerSysDictService.checkSysFlagOrSysNameByDeptId(sysFlag, sysName, deptIds);
            CacheManager.addExcCount("noExc");
            if(null != dicts && !dicts.isEmpty()){
                if(StringUtils.isNoneBlank(sysFlag)){
                    return Msg.fail("系统标识已存在!");
                }else{
                    return Msg.fail("系统名称已存在!");
                }
            }else{
                return Msg.success();
            }
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("验证失败，请联系系统管理员!");
        }
    }
}
