<template>
  <div>
    <div class="head-container">
      <el-button size="mini" type="primary" plain icon="el-icon-plus" @click="handleAdd"
                 v-hasPermi="['task:project:add']">新增项目
      </el-button>

      <el-input
        v-model="projectName"
        placeholder="请输入名称"
        clearable
        size="mini"
        prefix-icon="el-icon-search"
        style="margin-left: 20px"/>
    </div>
    <div class="head-container">
      <el-tree
        :data="projectData"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        ref="projectTree"
        node-key="id"
        default-expand-all
        highlight-current
        @node-click="handleNodeClick">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <div>{{ node.label }}</div>
              <div v-if="data.type!='模块'" style="font-size: 12px;color: #1c84c6">({{ data.type }})</div>
              <el-popover
                placement="right"
                trigger="hover">
                <el-button size="mini" type="primary" @click="handleAdd(data)"
                           v-hasPermi="['task:project:add']">新增</el-button>
                <el-button size="mini" @click="handleUpdate(data)" v-hasPermi="['task:project:edit']">修改</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(data)"
                           v-hasPermi="['task:project:delete']">删除</el-button>
                <el-button size="mini" @click="handleDetail(data)" v-if="data.type==='项目'"
                           v-hasPermi="['task:project:query']">详情</el-button>
                <i class="el-icon-share" slot="reference"></i>
               </el-popover>
            </span>
      </el-tree>
    </div>

    <!-- 添加或修改项目配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" size="mini" label-width="100px">
        <el-form-item label="名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="上级结构" prop="parentId">
          <treeselect v-model="form.parentId" :options="projectOptions" :normalizer="normalizer"
                      @select="treeSelectChange" placeholder="请选择"/>
        </el-form-item>
        <!--        <el-form-item label="类型" prop="type">-->
        <!--          <el-radio-group v-model="form.type" :disabled="typeDisable">-->
        <!--            <el-radio label="1">分类</el-radio>-->
        <!--            <el-radio label="2">项目</el-radio>-->
        <!--            <el-radio label="3">模块</el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="可查看人员" prop="viewable">
          <dept-user-tree ref="dut" :userList="userList" :multiple="true" @selected="selectCoExecutor"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject, getProjectTree
} from "@/api/task/project";
import {getDeptUserTree} from "@/api/system/user";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import DeptUserTree from "@/components/DeptUserTree"

export default {
  name: "Project",
  components: {Treeselect, DeptUserTree},
  data() {
    return {
      projectName: '',
      projectData: [],

      // 项目树数据
      projectOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 表单参数
      form: {},
      typeDisable: false,
      // 表单校验
      rules: {
        projectName: [
          {required: true, message: "项目名称不能为空", trigger: "blur"}
        ],
        type: [
          {required: true, message: "类型不能为空", trigger: "change"}
        ],
        status: [
          {required: true, message: "状态不能为空", trigger: "change"}
        ]
      },
      userList: []
    };
  },
  watch: {
    projectName(val) {
      this.$refs.projectTree.filter(val)
    }
  },
  created() {
    this.getProjectTree();
  },
  methods: {
    /** 查询项目树数据 */
    getProjectTree() {
      getProjectTree().then(res => {
        this.projectData = res.data
      })

    },
    /** 筛选节点 */
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /** 节点单击事件 */
    handleNodeClick(data) {
      this.$emit('selectProject', data.id)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.$refs.dut.clearText()
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        projectName: undefined,
        categoryId: undefined,
        description: undefined,
        status: "0",
        viewable: undefined
      };
      this.typeDisable = false
      this.resetForm("form");
    },
    /** 转换项目数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.projectName,
        children: node.children
      };
    },
    treeSelectChange(val) {
      if (val.type === '1') {
        this.form.type = '2'
      } else {
        this.form.type = '3'
      }
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row.id != undefined) {
        this.form.parentId = row.id;
        if (row.type === '分类') {
          this.form.type = '2'
        } else {
          this.form.type = '3'
        }
      } else {
        this.form.type = '1'
      }
      this.typeDisable = true

      this.open = true;
      this.title = "添加项目";
      listProject().then(response => {
        this.projectOptions = this.handleTree(response.data, "id");
      });
      getDeptUserTree('').then(res => {
        this.userList = res.data
      })
    },
    selectCoExecutor(val) {
      this.form.viewable = val.join();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      listProject().then(response => {
        this.projectOptions = this.handleTree(response.data, "id");
      });
      getProject(row.id).then(res => {
        this.form = res.data;
        this.open = true;
        this.title = "修改项目";
        this.typeDisable = true
      });
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateProject(this.form).then(res => {
              this.$message.success("修改成功");
              this.open = false;
              this.getProjectTree();
            });
          } else {
            addProject(this.form).then(res => {
              this.$message.success("新增成功");
              this.open = false;
              this.getProjectTree();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.name + '"的数据项？').then(() => {
        return delProject(row.id);
      }).then(() => {
        this.getProjectTree();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.$router.push({path: '/task/projectTable', query: {projectId: row.id}});
    }

  }
};
</script>
<style scoped lang="scss">
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
  margin-bottom: 10px;
}

.head-container {
  display: flex;
  margin-bottom: 20px;
  justify-content: space-between;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
}
</style>
