package com.emr.controller.printing;

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.recordType.Emr_Type;
import com.emr.service.recordType.EmrTypeRelatedService;
import com.emr.service.recordType.EmrTypeService;
import com.emr.util.ExceptionPrintUtil;
import com.emr.vo.emrType.EmrTypeVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
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 java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @ProjectName:PrintingController
 * @Description:打印用途管理
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/6/20 13:53
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/6/20 13:53
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Controller
@RequestMapping("printing/")
public class PrintingController {
    @Autowired
    private EmrTypeService emrTypeService;
    @Autowired
    private EmrTypeRelatedService typeRelatedService;
    @Autowired
    private Zd_AssortMapper assortMapper;
    /**
     * 封装加载选中类别对象
     * */
    private void loatSelectFlagEmrType(Model model, HttpServletRequest request){
        try {
            Emr_Type emrType = emrTypeService.selectFlagExist(request);
            model.addAttribute("emrType",emrType);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
    }
    /**
     * @MethodName: printManage
     * @Description: 跳转到打印用途管理页面
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-20
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-20
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/printing/printManage")
    @OptionalLog(module = "查看",methods = "打印用途管理页面")
    @RequestMapping("printManage")
    public String printManage(Model model,HttpServletRequest request){
        try {
            loatSelectFlagEmrType(model,request);
            String formToken = UUID.randomUUID().toString();
            request.getSession().setAttribute("formToken",formToken);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        return "recordManage/printing/printManage";
    }

    /**
     * @MethodName: printManageIframe
     * @Description: 跳转到打印用途管理嵌套iframe页面
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-20
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-20
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("printManageIframe")
    public String printManageIframe(Model model,Integer id,HttpServletRequest request){
        if(null != id){
            try {
                List<Zd_Assort> assortss = new ArrayList<>();
                //查询该用户有的权限
                Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
                if(user.getRoleId() != 0 && user.getRoleId() != -100){
                    //权限分类
                    List<Zd_Assort> assorts = assortMapper.selectAllAndUserReaderByUserIdAndRoleId(user.getUserId(),user.getRoleId());
                    //分配后的分类
                    List<Zd_Assort> assorts1 = assortMapper.selectAllAndRelatedByTypeId(id);
                    //printFlag 不为空才不为空
                    if(null != assorts && !assorts.isEmpty() && null != assorts1 && !assorts1.isEmpty()){
                        for (Zd_Assort assort : assorts){
                            if(StringUtils.isNotBlank(assort.getPrintFlag())){
                                assort.setPrintFlag(null);
                                for (Zd_Assort assort1 : assorts1){
                                    if(assort.getAssortId().equals(assort1.getAssortId()) && StringUtils.isNotBlank(assort1.getPrintFlag())){
                                        assort.setPrintFlag("1");
                                        break;
                                    }
                                }
                                assortss.add(assort);
                            }
                        }
                    }
                }else{
                    //查询所有分类
                    assortss = assortMapper.selectAllAndRelatedByTypeId(id);
                }
                model.addAttribute("id",id);
                model.addAttribute("assorts",assortss);
                Emr_Type emrType = emrTypeService.selectByPrimaryKey(id);
                model.addAttribute("emrType",emrType);
                Emr_Type selectFlag = emrTypeService.selectFlagExist(request);
                if(null != selectFlag){
                    model.addAttribute("selectFlagId",selectFlag.getId());
                }
            }catch (Exception e){
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
            }
        }
        return "recordManage/printing/printManageIframe";
    }
    /**
     * @MethodName: checkTypeFlagByCreater
     * @Description: 添加打印类别验证类别标识是否重复
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-09-06
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-09-06
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("checkTypeFlagByCreater")
    @ResponseBody
    public ResultUtil checkTypeFlagByCreater(String typeFlag,HttpServletRequest request) throws Exception{
        Emr_Type type = emrTypeService.checkTypeFlagByCreater(typeFlag,request);
        if(null == type){
            return ResultUtil.ok();
        }else{
            return ResultUtil.error("该类别标识已存在！");
        }
    }

    /**
     * @MethodName: checkTypeNameByCreater
     * @Description: 添加打印类别验证类别名称是否重复
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-20
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-20
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("checkTypeNameByCreater")
    @ResponseBody
    public ResultUtil checkTypeNameByCreater(String typeName,HttpServletRequest request) throws Exception{
        Emr_Type type = emrTypeService.checkTypeNameByCreater(typeName,request);
        if(null == type){
            return ResultUtil.ok();
        }else{
            return ResultUtil.error("该类别名称已存在！");
        }
    }

    /**
     * @MethodName: addEmrType
     * @Description: 添加打印类别
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-20
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-20
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/printing/addEmrType")
    @OptionalLog(module = "新增",methods = "打印类别",fieldName = "typeName")
    @RequestMapping("addEmrType")
    @ResponseBody
    public ResultUtil addEmrType(Emr_Type emrType,HttpServletRequest request) throws Exception{
        boolean flag = FormTokenFlagUtil.isFlag(request);
        if(!flag){
            return ResultUtil.error("请不要重复提交!");
        }
        Emr_Type type = emrTypeService.checkTypeNameByCreater(emrType.getTypeName(), request);
        Emr_Type type1 = emrTypeService.checkTypeFlagByCreater(emrType.getTypeFlag(), request);
        if (null != type && !type.getId().equals(emrType.getId())) {
            return ResultUtil.error("该类别名称已存在！");
        }
        if (null != type1 && !type1.getId().equals(emrType.getId())) {
            return ResultUtil.error("该类别标志已存在！");
        }
        if(StringUtils.isNoneBlank(emrType.getTypeFlag()) && StringUtils.isNotBlank(emrType.getTypeName())){
            emrTypeService.addEmrType(emrType,request);
            return ResultUtil.ok(emrType.getId());
        }else{
            return ResultUtil.error("类别标志或类别名称不能为空!");
        }
    }

    /**
     * @MethodName: updateEmrType
     * @Description: 更新打印类别
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-20
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-20
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/printing/updateEmrType")
    @OptionalLog(module = "修改",methods = "打印类别",fieldName = "typeName")
    @RequestMapping("updateEmrType")
    @ResponseBody
    public ResultUtil updateEmrType(Emr_Type emrType,Integer selectFlagId,HttpServletRequest request) throws Exception{
        if(StringUtils.isNoneBlank(emrType.getTypeFlag()) && StringUtils.isNotBlank(emrType.getTypeName())) {
            Emr_Type type = emrTypeService.checkTypeNameByCreater(emrType.getTypeName(), request);
            Emr_Type type1 = emrTypeService.checkTypeFlagByCreater(emrType.getTypeFlag(), request);
            if (null != type && !type.getId().equals(emrType.getId())) {
                return ResultUtil.error("该类别名称已存在！");
            }
            if (null != type1 && !type1.getId().equals(emrType.getId())) {
                return ResultUtil.error("该类别标志已存在！");
            }
            emrTypeService.updateEmrType(emrType, selectFlagId, request);
            return ResultUtil.ok();
        }else{
            return ResultUtil.error("类别标志或类别名称不能为空!");
        }
    }

    /**
     * @MethodName: deleteEmrType
     * @Description: 删除打印类别
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-20
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-20
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/printing/deleteEmrType")
    @OptionalLog(module = "删除",methods = "打印类别",fieldName = "typeName",tableName = "emr_type")
    @RequestMapping("deleteEmrType")
    @ResponseBody
    public ResultUtil deleteEmrType(Integer id) throws Exception{
        emrTypeService.deleteEmrType(id);
        return ResultUtil.ok();
    }

    /**
     * @MethodName: getEmrTypeTree
     * @Description: 组织打印管理类别树
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-20
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-20
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value="getEmrTypeTree")
    @ResponseBody
    public String getEmrTypeTree(HttpServletRequest request){
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        try {
            List<Emr_Type> typeList = emrTypeService.selectAllByCreater(null,request);
            List<EmrTypeVo> typeVoList = new ArrayList<>();
            //设置默认选中
            if (null != typeList && !typeList.isEmpty()) {
                for (Emr_Type emr_type : typeList) {
                    EmrTypeVo emrTypeVo = new EmrTypeVo();
                    BeanUtils.copyProperties(emr_type, emrTypeVo);
                    if (emr_type.getSelectFlag() == 1 && user.getUserName().equals(emr_type.getCreater())) {
                        emrTypeVo.setChecked("true");
                    }
                    emrTypeVo.setNewName(emr_type.getTypeName());
                    typeVoList.add(emrTypeVo);
                }
            }
            List<EmrTypeVo> types = new ArrayList<>();
            EmrTypeVo emrTypeVo = new EmrTypeVo();
            //添加父节点
            emrTypeVo.setId(0);
            emrTypeVo.setTypeName("类别列表");
            types.add(emrTypeVo);
            types.addAll(typeVoList);
            return JSON.toJSONString(types);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: addTypeRelated
     * @Description: 添加类别关联
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-21
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-21
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/printing/addTypeRelated")
    @OptionalLog(module = "保存",methods = "打印用途管理分配")
    @RequestMapping(value="addTypeRelated")
    @ResponseBody
    public ResultUtil addTypeRelated(Integer typeId,String selects,HttpServletRequest request) throws Exception{
        //先删除后添加
        typeRelatedService.deleteByTypeId(typeId);
        if(StringUtils.isNotBlank(selects)){
            String[] selectList = selects.split(",");
            typeRelatedService.SimpleInsert(selectList,typeId,request);
            return ResultUtil.ok();
        }else{
            return ResultUtil.error("至少选中一个!");
        }
    }

    /**
     * @MethodName: udpateCheckByEmrType
     * @Description: 变更打印类别选中
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-24
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-24
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value="udpateCheckByEmrType/{id}")
    @ResponseBody
    public ResultUtil udpateCheckByEmrType(@PathVariable("id") Integer id,HttpServletRequest request) throws Exception{
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        Emr_Type type = emrTypeService.selectByPrimaryKey(id);
        //判断是系统管理员，不建议乱修改客户选中的
        if(user.getRoleId() == 0 && !type.getCreater().equals(user.getUserName())){
            return ResultUtil.error("修改失败,该类别为客户创建,不建议修改!");
        }
        Emr_Type oldFlagType = emrTypeService.selectFlagExist(request);
        if(null == oldFlagType || (!type.getId().equals(oldFlagType.getId()))){
            //原来的更新为不选中，现在的改为选中
            type.setSelectFlag(1);
            if(null == oldFlagType){
                emrTypeService.updateEmrType(type,null,request);
            }else{
                emrTypeService.updateEmrType(type,oldFlagType.getId(),request);
            }
        }
        return ResultUtil.ok();
    }
}
