package com.manage.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.manage.annotation.OptionalLog;
import com.manage.annotation.RequiresPermissions;
import com.manage.entity.Power_Dept;
import com.manage.entity.Power_User;
import com.manage.service.cache.CacheManager;
import com.manage.service.ImportExcel.ImportExcelUtil;
import com.manage.service.Power_DeptService;
import com.manage.util.Msg;
import com.manage.util.PageHelper;
import com.manage.vo.ImportExcelEntity;
import com.manage.vo.PowerTree;
import com.manage.vo.Power_DeptVo;
import com.manage.vo.Power_UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Author ly
 * Date 2019/4/20
 * Time 16:39
 * Description No Description
 */
@Controller
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private Power_DeptService powerDeptService;

    /**
     * @Date 2019-4-25
     * @Author ly
     *  @Description 分页
     * */
    @RequestMapping("/pageList")
    @ResponseBody
    public PageHelper<Power_DeptVo> list(Power_DeptVo powerDept, HttpServletRequest request){
        PageHelper<Power_DeptVo>pageHelper = new PageHelper<Power_DeptVo>();
        try {
            //统计总记录数
            int total = powerDeptService.getTotal(powerDept);
            pageHelper.setTotal(total);
            //查询当前页实体对象
            List<Power_DeptVo> list = powerDeptService.findSomeByMore(powerDept,request);
            pageHelper.setRows(list);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            e.printStackTrace();
            CacheManager.addExcCount("exc");
        }
        return pageHelper;
    }
    /**
     * @Date 2019-4-25
     * @Author ly
     *  @Description 返回页面
     * */
    @OptionalLog(module = "查看",methods = "科室管理页面")
    @RequiresPermissions(value="/dept/pageUI")
    @RequestMapping("/pageUI")
    public String pageUI(HttpServletRequest request, Model model){
        Power_User powerUser1 =(Power_User) request.getSession().getAttribute("CURRENT_USER");
        model.addAttribute("user",powerUser1);
        CacheManager.addExcCount("noExc");
        return "deptDir/dept";
    }

    /**
     * @Date 2020-01-02
     * @Author zwh
     *  @Description 查看部门返回页面
     * */
    @OptionalLog(module = "查看",methods = "部门管理页面")
    @RequiresPermissions(value="/dept/bloodUI")
    @RequestMapping("/bloodUI")
    public String bloodUI(HttpServletRequest request, Model model){
        Power_User powerUser1 =(Power_User) request.getSession().getAttribute("CURRENT_USER");
        model.addAttribute("user",powerUser1);
        CacheManager.addExcCount("noExc");
        return "deptDir/blood";
    }

     /**
     * @Date 2019-4-22
     * @Author ly
     *  @Description 查询科室列表
     * */
    @RequestMapping("/selectList")
    @ResponseBody
    public Msg selectList(HttpServletRequest request) {
        try {
            List<Power_DeptVo> deptList = powerDeptService.selectDeptByUserId(request);
            CacheManager.addExcCount("noExc");
            return Msg.success().add("list",deptList);
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail();
        }
    }
    /**
     * @Date 2019-4-30
     * @Author ly
     *  @Description 查询科室
     * */
    @RequestMapping("/selectDept")
    @ResponseBody
    public Power_Dept selectDept(Integer deptId) {
        try {
            Power_Dept power_dept = powerDeptService.selectByPrimaryKey(deptId);
            CacheManager.addExcCount("noExc");
            return power_dept;
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @Date 2019-08-02
     * @Author zengwenhe
     *  @Description 验证科室名不能重复
     * */
    @RequestMapping("/checkDeptName")
    @ResponseBody
    public Msg checkDeptName(String deptName,Integer dictId) {
        try {
            List<Power_Dept> power_dept = powerDeptService.checkDeptName(deptName,dictId);
            if(power_dept != null && !power_dept.isEmpty()){
                return Msg.fail("科室名已存在");
            }else{
                CacheManager.addExcCount("noExc");
                return Msg.success();
            }
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("验证失败，请联系系统管理员!");
        }
    }

    /**
     * @Date 2019-07-31
     * @Author zengwenhe
     *  @Description 查询科室树
     * */
    @RequestMapping(value = "/selectDeptTreeByUserId",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String selectDeptTreeByUserId(HttpServletRequest request) {
        try {
            List<Power_DeptVo> list = powerDeptService.selectDeptByUserId(request);
            List<PowerTree> treeList = new ArrayList<>();
            Map<Integer,String> hospitalMap = new HashMap<>();
            Integer id = 1;
            Integer parentId = null;
            if(null != list && !list.isEmpty()){
                for (int i = 0;i < list.size();i++){
                    hospitalMap.put(list.get(i).getDictId(),list.get(i).getHospitalName());
                }
                for (Map.Entry<Integer, String> entry : hospitalMap.entrySet()) {
                    //医院层
                    PowerTree tree1 = new PowerTree();
                    tree1.setId(id);
                    tree1.setSelfId(entry.getKey());
                    tree1.setName(entry.getValue());
                    tree1.setParentId(0);
                    treeList.add(tree1);
                    parentId = id;
                    id++;
                    //科室层
                    for (int i = 0;i < list.size();i++){
                        if(entry.getKey().equals(list.get(i).getDictId())){
                            PowerTree tree2 = new PowerTree();
                            tree2.setId(id);
                            tree2.setSelfId(list.get(i).getDeptId());
                            tree2.setName(list.get(i).getDeptName());
                            tree2.setParentId(parentId);
                            treeList.add(tree2);
                            id++;
                        }
                    }
                }
            }
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(treeList);
            CacheManager.addExcCount("noExc");
            return json;
        }catch(Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }
    /**
     * @Date 2019-4-25
     * @Author ly
     *  @Description 新增科室
     * */
    @OptionalLog(module = "新增",methods = "科室管理",fieldName = "deptName")
    @RequiresPermissions(value="/dept/add")
    @RequestMapping("/add")
    @ResponseBody
    public Msg add(Power_Dept powerDept){
        try {
            List<Power_Dept> power_dept = powerDeptService.checkDeptName(powerDept.getDeptName(),powerDept.getDictId());
            if(null == power_dept || power_dept.isEmpty()){
                powerDeptService.insertSelective(powerDept);
                CacheManager.addExcCount("noExc");
                return Msg.success();
            }else{
                return Msg.fail("科室名已存在!");
            }
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("添加出错了,请联系系统管理员!");
        }

    }
    /**
     * @Date 2019-4-25
     * @Author ly
     *  @Description 更新科室
     * */
    @OptionalLog(module = "修改",methods = "科室管理",fieldName = "deptName")
    @RequiresPermissions(value="/dept/update")
    @RequestMapping("/update")
    @ResponseBody
    public Msg update(Power_Dept powerDept,HttpServletRequest request){
        try {
            List<Power_Dept> power_dept = powerDeptService.checkDeptName(powerDept.getDeptName(),powerDept.getDictId());
            if(null != power_dept && !power_dept.isEmpty() && !power_dept.get(0).getDeptId().equals(powerDept.getDeptId())){
                return Msg.fail("科室名已存在!");
            }else{
                powerDeptService.updateByPrimaryKeySelective(powerDept,request);
                CacheManager.addExcCount("noExc");
                return Msg.success();
            }
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("修改出错了,请联系系统管理员!");
        }


    }
    /**
     * @Date 2019-4-25
     * @Author ly
     *  @Description 删除科室
     * */
    @OptionalLog(module = "删除",methods = "科室管理",fieldName = "deptName",tableName = "power_dept")
    @RequiresPermissions(value="/dept/delete")
    @RequestMapping("/delete")
    @ResponseBody
    public Msg delete(Integer deptId){
        try {
            CacheManager.addExcCount("noExc");
            powerDeptService.deleteByPrimaryKey(deptId);
            return Msg.success();
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail();
        }
    }
    /**
     * @Date 2019-4-29
     * @Author ly
     *  @Description 导出Excel
     * */
    @OptionalLog(module = "导出excel",methods = "科室管理")
    @RequiresPermissions(value="/dept/export")
    @RequestMapping("/export")
    public void export(Power_DeptVo powerDept,HttpServletRequest request,HttpServletResponse response){
        try {
            powerDeptService.export(powerDept,request,response);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
        }
    }
    /**
     * @Date 2019-4-22
     * @Author ly
     *  @Description 根据一组科室id查询科室
     * */
    @RequestMapping("/findById")
    @ResponseBody
    public List<Power_Dept>findById(String dept_ids){
        try {
            List<Power_Dept>deptList = powerDeptService.selectByPrimaryKeys(dept_ids);
            CacheManager.addExcCount("noExc");
            return deptList;
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }


    /**
     * @Date 2019-08-06
     * @Author zengwenhe
     *  @Description 根据医院查询科室
     * */
    @RequestMapping("/selectDeptByDictId")
    @ResponseBody
    public Msg selectDeptByDictId(Integer dictId){
        try {
            List<Power_DeptVo> depts = powerDeptService.selectDeptByDictId(dictId,null);
            CacheManager.addExcCount("noExc");
            return Msg.success().add("depts",depts);
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("查询失败,请联系系统管理员!");
        }
    }

    /**
     * @Date 2019-10-11
     * @Author zengwh
     *  @Description 导入excel
     * */
    @OptionalLog(module = "导入excel",methods = "科室管理")
    @RequiresPermissions(value="/dept/importExcel")
    @RequestMapping(value="/importExcel",method = {RequestMethod.POST})
    @ResponseBody
    public ResponseEntity<String> importExcel(HttpServletRequest request){
        OutputStream os = null;
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(new MediaType("text","html", Charset.forName("UTF-8")));
        try {
            //读取文件
            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            MultipartFile multipartFile = multipartRequest.getFile("upfile");
            //属性名
            String[] fieldNames = {"deptName","dictId","effective","remark",};
            //判断集中类中的方法名
            String[] judgeMethods = {"judgeDeptName","judgeDictId","convertEffective","judgeRemark"};
            Power_Dept power_dept = new Power_Dept();
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            Power_UserVo user = (Power_UserVo)request.getSession().getAttribute("CURRENT_USER");
            power_dept.setCreater(user.getUserName());
            power_dept.setUpdater(user.getUserName());
            power_dept.setCreateDate(fmt.format(new Date()));
            power_dept.setUpdateDate(fmt.format(new Date()));
            power_dept.setDeptCode("");
            //实例化
            ImportExcelUtil.newInstance("power_DeptMapper",power_dept, Power_Dept.class);
            //导入excel的操作
            ImportExcelEntity excelEntity = ImportExcelUtil.fileImport(multipartFile,fieldNames,judgeMethods);
            CacheManager.addExcCount("noExc");
            if(excelEntity.getSuccessCount() == 0 && excelEntity.getWrongCount() == 0){
                //无数据
                return new ResponseEntity<String>("无数据!", responseHeaders, HttpStatus.OK);
            }
            if(excelEntity.getWrongCount() == 0){
                //成功
                return new ResponseEntity<String>(null, responseHeaders, HttpStatus.OK);
            }else{
                //有出错数据
                String msgStr = excelEntity.getWorkBookKey()+"@已成功导入"+excelEntity.getSuccessCount()+"条,失败"+excelEntity.getWrongCount()+"条,随后将导出错误记录!";
                return new ResponseEntity<String>(msgStr, responseHeaders, HttpStatus.OK);
            }

        }catch (Exception e){
            CacheManager.addExcCount("exc");
            //抛异常
            return new ResponseEntity<String>(e.getMessage(), responseHeaders, HttpStatus.OK);
        }finally {
            if(os != null){
                try {
                    os.flush();
                    os.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
