<template>
  <div class="app-container">
    <el-row :gutter="20">
    <el-col :span="4" :xs="24">
      <org-tree v-model="queryParams.orgId" @defaultKey="getDefaultKey"  @checkChange="checkChange"
                @click="clickTreeNode"></org-tree>
    </el-col>
    <el-col :span="20" :xs="24">

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="关键字" prop="title">
          <el-input v-model="queryParams.title" placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item label="发布时间" prop="planStartTime">
          <el-date-picker
            v-model="queryParams.dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="messagStatus">
          <el-select v-model="queryParams.messagStatus" placeholder="请选择状态" clearable>
            <el-option
              v-for="dict in dict.type.message_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['core:notification:add']"
          >新增</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="notificationList"border
                height="600"
                size="small">
        <el-table-column label="序号" type="index" align="center">
          <template slot-scope="scope">
            <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建机构" align="center" width="160" prop="orgName" />
        <el-table-column label="消息类型" align="center"  prop="messagType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.messag_type" :value="scope.row.messagType"/>
          </template>
        </el-table-column>
        <el-table-column label="机构类型" align="center" prop="execOrgType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_org_type" :value="scope.row.tagOrgType"/>
          </template>
        </el-table-column>
        <el-table-column prop="tagRoleIds" width="180" label="目标角色">
          <template slot-scope="r">
            <span>{{getRolename(r.row.tagRoleIds)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题" align="center" width="200" prop="title" >
          <template slot-scope="r"><p :title="r.row.title" class="line-style">{{r.row.title}}</p></template>
        </el-table-column>

        <el-table-column label="创建人" align="center" prop="createBy" />
        <el-table-column label="发布时间" align="center" prop="publishTime" width="180">
  <!--        <template slot-scope="scope">
            <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d}') }}</span>
          </template>-->
        </el-table-column>
        <el-table-column label="状态" align="center" prop="messagStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.message_status" :value="scope.row.messagStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="lookThisOne(scope.row)"
              v-hasPermi="['core:notification:query']"
            >详情</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['core:notification:edit']"
              v-if="scope.row.messagStatus=='0'"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              v-hasPermi="['core:notification:remove']"
              v-if="scope.row.messagStatus=='0'"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              @click="publish(scope.row)"
              v-hasPermi="['core:notification:publish']"
              v-if="scope.row.messagStatus=='0'"
            >发布</el-button>
            <el-button
              size="mini"
              type="text"
              @click="publish(scope.row)"
              v-hasPermi="['core:notification:cancelPublish']"
              v-if="scope.row.messagStatus=='1'"
            >取消发布</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-col>
    <!-- 添加或修改公告通知对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" :disabled="!isSubmit" :maxlength="100"/>
        </el-form-item>
        <el-form-item label="消息类型" prop="messagType">
          <el-select v-model="form.messagType" placeholder="请选择消息类型" :disabled="!isSubmit" @change="showOrHidden()">
            <el-option
              v-for="dict in dict.type.messag_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
          <el-form-item label="机构类型" prop="tagOrgType">
            <el-select v-model="form.tagOrgType" placeholder="请选择机构类型" :disabled="!isSubmit" @change="execOrgTypeChanged()">
              <el-option v-for="dict in dict.type.sys_org_type" :key="dict.value" :label="dict.label"
                         :value="dict.value"></el-option>
            </el-select>

          </el-form-item>

        <el-form-item label="目标机构" prop="tagOrgIds">
<!--          <org-tree-select :queryData="form.tagOrgType" ref="orgTreeSelect" @selectNode="queryNode"
                           :placeholder="'请选择目标机构'" :disable="true"></org-tree-select>-->
          <org-tree-select
            v-model="form.tagOrgIds"
            :queryData="parseInt(form.tagOrgType)"
            ref="orgTreeSelect"
            :enabledCheckOrgTypes="parseInt(form.tagOrgType)"
            :disable="true" :disabled="!isSubmit">
          </org-tree-select>
        </el-form-item>
        <!-- </el-form-item>-->
        <el-form-item label="目标角色" v-if="isShow" prop="tagRoleIds">
          <el-select v-model="form.tagRoleIds" placeholder="请选择" :disabled="!isSubmit" multiple>
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容" :disabled="!isSubmit" :autosize="{ minRows: 6, maxRows: 10}" :maxlength="2000" show-word-limit/>
        </el-form-item>
        <el-form-item label="附件" prop="fileList">
          <K-file-upload ref="upload" :defaultValue="formFileListDefualtValue" :disabled="!isSubmit" v-model="form.fileList"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="isSubmit" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    </el-row>
  </div>
</template>

<script>
import { listNotification, getNotification, delNotification, addNotification, updateNotification,roleList,publishNotification } from "@/api/core/notification";
import OrgTree from "@/components/orgTree";
import orgDropDown from "@/components/orgTree/orgDropDown.vue";
import KFileUpload from "@/components/K-FileUpload/index.vue";
import OrgTreeSelect from '@/components/orgTreeSelect'
export default {
  components: {OrgTree,orgDropDown,KFileUpload,OrgTreeSelect},
  name: "Notification",
  dicts: ['messag_type', 'message_status','sys_org_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公告通知表格数据
      notificationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      orgId:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        dateRange: [],
        messagStatus: null
      },
      isShow:false,
      isSubmit:true,
      roleList: [],
      formFileListDefualtValue: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [{ required: true, message: "请输入标题" }],
        messagType: [{ required: true, message: "请选择消息类型" }],
        tagOrgType: [{ required: true, message: "请选择机构类型" }],
        tagOrgIds: [{ required: true, message: "请选择目标机构" }],
        content: [{ required: true, message: "请输入内容" }],
      }
    };
  },
  created() {
    this.getList();
    this.initRoleList();
    this.orgId = this.$store.getters.orgId;
  },
  methods: {
    /** 查询公告通知列表 */
    getList() {
      this.loading = true;
      listNotification(this.queryParams).then(response => {
        this.notificationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getRolename(roleIds){
      if(roleIds!=null && roleIds.length>0){
        return roleIds.map(v => {
          if(this.roleList.find(item => item.id === v)){
            return this.roleList.find(item => item.id === v).name
          }else {
            return "";
          }
        }).join(',');
      }else {
        return "";
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.$refs.orgTreeSelect.clear();
      //this.roleList=[];
      this.reset();
      this.isSubmit=true;
    },
    handleClose(){
      this.cancel();
    },
    queryNode(nodes) {
      this.form.tagOrgIds = JSON.parse(nodes).map(v => {
        return v.id
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orgId: null,
        orgName: null,
        orgPath: null,
        title: null,
        content: null,
        messagType: null,
        tagOrgIds: null,
        tagRoleIds: null,
        createBy: null,
        createTime: null,
        publishTime: null,
        messagStatus: null,
        fileList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.dateRange=[];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.initRoleList();
      this.formFileListDefualtValue=[];
      this.open = true;
      this.isShow=false;
      this.title = "添加公告通知";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getNotification(id).then(response => {
        this.form = response.data;
        if(this.form.tagRoleIds!=null&&this.form.tagRoleIds.length>0){
          this.isShow=true;
        }
        roleList(this.form.tagOrgType).then(res => {
          this.roleList = res.data;
        });
        this.formFileListDefualtValue = this.form.fileList;
        this.open = true;
        this.title = "修改公告通知";
      });
    },
    lookThisOne(row) {
      this.reset();
      this.isSubmit = false;
      const id = row.id || this.ids
      getNotification(id).then(response => {
        this.form = response.data;
        if(this.form.tagRoleIds!=null&&this.form.tagRoleIds.length>0){
          this.isShow=true;
        }
        roleList(this.form.tagOrgType).then(res => {
          this.roleList = res.data;
        });
        this.formFileListDefualtValue = this.form.fileList;
        this.open = true;
        this.title = "公告通知详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.orgId = this.orgId;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateNotification(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$refs.orgTreeSelect.clear();
              this.reset();
              this.$refs["upload"].clearFiles();
              this.form.fileList=[];
              this.getList();
            });
          } else {
            addNotification(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.$refs.orgTreeSelect.clear();
              this.reset();
              this.form.fileList=[];
              this.$refs["upload"].clearFiles();
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除该公告通知？').then(function() {
        return delNotification(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    publish(row){
      const id = row.id;
      const messagStatus = row.messagStatus;
      let message = "";
      let returnMessage = "";
      if(messagStatus==0){
          message="你确定要发布该消息吗？";
          returnMessage = "发布成功";
      }else{
          message="你确定要取消发布该消息吗？";
          returnMessage = "取消发布成功";
      }
      this.$modal.confirm(message).then(function() {
        return publishNotification(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(returnMessage);
      }).catch(() => {});
    },

    getDefaultKey(key) {
      this.queryParams.orgId = key;
      this.getList();
    },
    checkChange(state) {
      this.queryParams.checkSub = state;
      this.handleQuery();
    },
    // 节点单击事件
    clickTreeNode(data) {
      this.queryParams.orgId = data.id;
      this.orgName = data.name;
      this.handleQuery();
    },
    execOrgTypeChanged(row) {
      this.form.tagRoleIds=[];
      this.$refs.orgTreeSelect.clear();
      this.initRoleList(this.form.tagOrgType);
    },
    initRoleList(query) {
      this.form.tagRoleIds = [];
      roleList(query).then(response => {
        this.roleList = response.data;
      });
    },

    showOrHidden(){
      if(this.form.messagType=='1'){
        this.isShow=true;
      }else {
        this.form.tagRoleIds = [];
        this.isShow=false;
      }
    },
    /** 下穿状态改变*/
    changeCheckBox() {
      this.getList();
    },
  }
};
</script>
<style lang="scss" scoped>
.line-style{
  display : -webkit-box;
  -webkit-line-clamp: 3 ; //限定显示行数
  -webkit-box-orient: vertical;
  overflow : hidden ;
  text-overflow: ellipsis;
}
</style>
