package com.emr.controller.distributionManage;

import com.alibaba.fastjson.JSON;
import com.emr.annotation.OptionalLog;
import com.emr.controller.FormTokenFlagUtil;
import com.emr.dao.Zd_AssortMapper;
import com.emr.entity.Power_User;
import com.emr.entity.ResultUtil;
import com.emr.entity.Zd_Assort;
import com.emr.entity.emrRoleReader.Emr_Role_Reader;
import com.emr.entity.emrUserReader.Emr_User_Reader;
import com.emr.service.Zd_AssortServiceImpl;
import com.emr.service.emrRoleReader.EmrRoleRearderService;
import com.emr.service.emrUserReader.EmrUserRearderService;
import com.emr.util.ExceptionPrintUtil;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
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 java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/7/8 9:51
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/7/8 9:51
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Controller
@RequestMapping("distribution/")
public class DistributionController {
    @Value("${POWER_JSP}")
    private String POWER_JSP;
    @Autowired
    private Zd_AssortMapper assortMapper;
    @Autowired
    private Zd_AssortServiceImpl assortService;
    @Autowired
    private EmrRoleRearderService roleRearderService;
    @Autowired
    private EmrUserRearderService userRearderService;
    /**
     * @MethodName userDistributionManage
     * @Description: 跳转到用户调阅分配页面
     * @Param 无
     * @Returnt distributionManage/userDistributionManage
     * @Author: 曾文和
     * @CreateDate: 2019-07-08
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-08
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/distribution/userDistributionManage")
    @OptionalLog(module = "查看",methods = "用户调阅分配页面")
    @RequestMapping("userDistributionManage")
    public String userDistributionManage(Model model){
        Zd_Assort zd_assort = new Zd_Assort();
        zd_assort.setPrintFlag("0");
        List<Zd_Assort> assorts = null;
        try{
            assorts = assortMapper.selectAll(zd_assort);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        model.addAttribute("assorts",assorts);
        model.addAttribute("POWER_URLHEAD",POWER_JSP);
        return "distributionManage/userDistributionManage";
    }
/**********************************************角色分配***********************************************/
    /**
     * @MethodName roleDistributionManage
     * @Description: 跳转到角色调阅分配页面
     * @Param 无
     * @Returnt distributionManage/roleDistributionManage
     * @Author: 曾文和
     * @CreateDate: 2019-07-08
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-08
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/distribution/roleDistributionManage")
    @OptionalLog(module = "查看",methods = "角色调阅分配页面")
    @RequestMapping("roleDistributionManage")
    public String roleDistributionManage(Model model){
        Zd_Assort zd_assort = new Zd_Assort();
        zd_assort.setPrintFlag("0");
        List<Zd_Assort> assorts = null;
        try{
            assorts = assortMapper.selectAll(zd_assort);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        model.addAttribute("assorts",assorts);
        model.addAttribute("POWER_URLHEAD",POWER_JSP);
        return "distributionManage/roleDistributionManage";
    }
    /**
     * @MethodName getAssortList
     * @Description: 获取分段集合
     * @Param 无
     * @Returnt distributionManage/roleDistributionManage
     * @Author: 曾文和
     * @CreateDate: 2019-07-08
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-08
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getAssortList")
    @ResponseBody
    public String getAssortList(Integer page, Integer limit, Zd_Assort assort,HttpServletRequest request){
        if(null != page && null != limit){
            PageHelper.startPage(page, limit);
        }
        //匹配权限
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        try{
            List<Zd_Assort> assorts = assortMapper.selectAll(assort);
            if(null != assorts && !assorts.isEmpty()){
                Set<String> menus = user.getMenus();
                if(null != menus && !menus.isEmpty()){
                    int updateOper = 0;
                    int deleteOper = 0;
                    for(String menu : menus){
                        if(StringUtils.isNotBlank(menu)){
                            if("/distribution/saveDistribution".equals(menu)){
                                updateOper = 1;
                            }
                            if("/distribution/deleteAssortByAssortId".equals(menu)){
                                deleteOper = 1;
                            }
                        }
                    }
                    for (Zd_Assort obj : assorts){
                        obj.setUpdateOper(updateOper);
                        obj.setDeleteOper(deleteOper);
                    }
                }
            }
            PageInfo pageInfo = new PageInfo<>(assorts);
            return JSON.toJSONString(pageInfo);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }
    /*************************************用户和角色公用方法***************************************************/
    /**
     * @MethodName checkAssortName
     * @Description: 验证名称是否重复
     * @Param 无
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-07-08
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-08
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("checkAssortName")
    @ResponseBody
    public ResultUtil checkAssortName(String assortName) throws Exception{
        Zd_Assort assort = assortMapper.checkAssortName(assortName);
        if(assort == null){
            return ResultUtil.ok();
        }else{
            return ResultUtil.error();
        }
    }

    /**
     * @MethodName saveDistribution
     * @Description: 保存分段信息
     * @Param 无
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-07-08
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-08
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "保存",methods = "调阅分段信息",fieldName = "assortName")
    @RequestMapping("saveDistribution")
    @ResponseBody
    public ResultUtil saveDistribution(Zd_Assort assort,HttpServletRequest request) throws Exception{
        if(StringUtils.isBlank(assort.getAssortId())){
            Zd_Assort assorts = assortMapper.checkAssortName(assort.getAssortName());
            if(assorts != null){
                return ResultUtil.error("名称已存在!");
            }
            boolean flag = FormTokenFlagUtil.isFlag(request);
            if(flag){
                //添加
                assortService.insert(assort);
            }else{
                return ResultUtil.error("请不要重复提交!");
            }
        }else{
            //修改
            Zd_Assort existAssort = assortMapper.checkAssortName(assort.getAssortName());
            if(null != existAssort && !existAssort.getAssortId().equals(assort.getAssortId())){
                return ResultUtil.error("名称已存在!");
            }else{
                assortService.updateByPrimaryKeySelective(assort);
            }
        }
        return ResultUtil.ok();
    }

    /**
     * @MethodName getAssortByAssortId
     * @Description: 根据assortId查询assort对象
     * @Param 无
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-07-08
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-08
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getAssortByAssortId/{assortId}")
    @ResponseBody
    public String getAssortByAssortId(@PathVariable("assortId") String assortId){
        try{
            Zd_Assort assort = assortMapper.getAssortByAssortId(assortId);
            return JSON.toJSONString(assort);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName deleteAssortByAssortId
     * @Description: 根据assortId删除assort对象
     * @Param 无
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-07-08
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-08
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/distribution/deleteAssortByAssortId")
    @OptionalLog(module = "删除",methods = "调阅分段信息",fieldName = "assortName",tableName = "zd_assort")
    @RequestMapping("deleteAssortByAssortId/{assortId}")
    @ResponseBody
    public ResultUtil deleteAssortByAssortId(@PathVariable("assortId") String assortId) throws Exception{
        assortService.deleteAssortByAssortId(assortId);
        return ResultUtil.ok();
    }

    /**
     * @MethodName distributionManageIframe
     * @Description: 刷新分配页面
     * @Param 无
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-07-08
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-08
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("distributionManageIframe")
    public String distributionManageIframe(Integer roleId,Integer userId,Integer roleIdByUser,Model model){
        List<Zd_Assort> assorts = new ArrayList<>();
        try {
            if(null != roleId){
                assorts = assortMapper.selectAllAndRoleReaderByRoleId(roleId);
            }else if(null != userId){
                assorts = assortMapper.selectAllAndUserReaderByUserIdAndRoleId(userId,roleIdByUser);
            }
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        model.addAttribute("assorts",assorts);
        model.addAttribute("roleId",roleId);
        model.addAttribute("userId",userId);
        model.addAttribute("roleIdByUser",roleIdByUser);
        return "distributionManage/distributionManageIframe";
    }

    /**
     * @MethodName saveUserOrRoleReader
     * @Description: 保存用户调阅分配表或角色调阅分配表
     * @Param 无
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-07-08
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-08
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "保存",methods = "调阅分配")
    @RequestMapping("saveUserOrRoleReader")
    @ResponseBody
    public ResultUtil saveUserOrRoleReader(Integer userId, Integer roleId, Integer roleIdByUser, String selects, HttpServletRequest request) throws Exception{
        //先删除后添加
        if(null != roleId){
            roleRearderService.deleteReaderByRoleId(roleId);
        }else if(null != userId){
            userRearderService.deleteReaderByUserId(userId);
        }
        String[] selectList = selects.split(",");
        if(null != roleId) {
            List<Emr_Role_Reader> list = new ArrayList<>();
            Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (String s : selectList) {
                if (StringUtils.isNoneBlank(s)) {
                    Emr_Role_Reader roleReader = new Emr_Role_Reader();
                    roleReader.setRoleId(roleId);
                    roleReader.setRecordId(s);
                    roleReader.setCreater(user.getUserName());
                    roleReader.setUpater(user.getUserName());
                    roleReader.setCreateTime(fmt.format(new Date()));
                    roleReader.setUpdateTime(fmt.format(new Date()));
                    list.add(roleReader);
                }
            }
            roleRearderService.SimpleInsert(list);
        }
        if(null != userId) {
            //与角色分配表对比，多出部分，flag设为1，减少部分flag设为0
            //角色权限
            List<Emr_Role_Reader> roleReaders = roleRearderService.selectAllByRoleId(roleIdByUser);
            List<Emr_User_Reader> list = new ArrayList<>();
            if (null != roleReaders && !roleReaders.isEmpty()) {
                //计算新增和删除
                List<String> roles = new ArrayList<>();
                for (Emr_Role_Reader roleReader : roleReaders) {
                    if (StringUtils.isNotBlank(selects)) {
                        roles.add(roleReader.getRecordId().toString());
                    } else {
                        //全取消
                        list.add(addUserReaderFunction(userId, roleIdByUser, roleReader.getRecordId().toString(), 0, request));
                    }
                }
                if (StringUtils.isNotBlank(selects)) {
                    String[] readers = selects.split(",");
                    List<String> users = Arrays.asList(readers);
                    //新增部分
                    Collection<String> inserts = new ArrayList<String>(users);
                    inserts.removeAll(roles);
                    if (!inserts.isEmpty()) {
                        //新增flag为1
                        for (String insertReader : inserts) {
                            if (StringUtils.isNotBlank(insertReader)) {
                                list.add(addUserReaderFunction(userId, roleIdByUser, insertReader, 1,request));
                            }
                        }
                    }
                    //删除部分
                    Collection<String> deletes = new ArrayList<String>(roles);
                    deletes.removeAll(users);
                    if (!deletes.isEmpty()) {
                        for (String deleteReader : deletes) {
                            if (StringUtils.isNotBlank(deleteReader)) {
                                list.add(addUserReaderFunction(userId, roleIdByUser, deleteReader, 0,request));
                            }
                        }
                    }
                }
            }else{
                //全部新增
                if (StringUtils.isNotBlank(selects)) {
                    String[] readers = selects.split(",");
                    for (String insertReader : readers) {
                        if (StringUtils.isNotBlank(insertReader)) {
                            list.add(addUserReaderFunction(userId, roleIdByUser, insertReader, 1,request));
                        }
                    }
                }
            }
            userRearderService.SimpleInsert(list);
        }
        return ResultUtil.ok();
    }

    //封装新增用户权限表公共部分
    private Emr_User_Reader addUserReaderFunction(Integer userId,Integer roleIdByUser,String readerId,Integer flag,HttpServletRequest request){
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Emr_User_Reader userReader = new Emr_User_Reader();
        userReader.setUserId(userId);
        userReader.setRoleId(roleIdByUser);
        userReader.setRecordId(readerId);
        userReader.setFlag(flag);
        userReader.setCreater(user.getUserName());
        userReader.setUpdater(user.getUserName());
        userReader.setCreateTime(fmt.format(new Date()));
        userReader.setUpdateTime(fmt.format(new Date()));
        return userReader;
    }
}
