<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 style="height:calc(100vh - 148px);overflow: auto">
      <el-tree
        :data="projectData"
        :props="defaultProps"
        :expand-on-click-node="false"
        :check-on-click-node="true"
        :filter-node-method="filterNode"
        :indent="10"
        accordion
        ref="projectTree"
        class="custom-tree"
        node-key="id"
        :highlight-current="true"
        :default-expanded-keys="expandedKeys"
        @node-expand="nodeExpand"
        @node-click="handleNodeClick">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <el-tooltip class="item" effect="dark" :content="node.label" :disabled="node.label&&node.label.length<11"
                          placement="top-end">
                  <div :class="data.type==='分类'?'c-project-name':''">{{ node.label | ellipsis }}</div>
              </el-tooltip>

              <div v-if="data.type!='模块'" style="font-size: 12px;color: #1c84c6">({{ data.type }})</div>
              <el-dropdown size="mini" placement="bottom-start" @command="(command) => handleCommand(command, data)">
                <i class="el-icon-share"/>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="handleAdd" icon="el-icon-plus" v-if="data.type==='分类'"
                                    v-hasPermi="['task:project:add']">新增</el-dropdown-item>
                  <el-dropdown-item command="handleUpdate" icon="el-icon-edit"
                                    v-hasPermi="['task:project:edit']">修改</el-dropdown-item>
                  <el-dropdown-item command="handleUpdate" icon="el-icon-delete"
                                    v-hasPermi="['task:project:delete']">删除</el-dropdown-item>
                  <el-dropdown-item command="handleTable" icon="el-icon-document" v-if="data.type==='项目'"
                                    v-hasPermi="['task:project:table']">统计</el-dropdown-item>
                  <el-dropdown-item command="handleDetail" icon="el-icon-view">详情</el-dropdown-item>
                  <el-dropdown-item command="handleArchive" icon="el-icon-folder" v-if="data.type==='项目'"
                                    v-hasPermi="['task:project:archive']">归档</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </span>
      </el-tree>
    </div>

    <!-- 添加或修改项目配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" @close="cancel" width="700px" class="add-dialog" append-to-body>
      <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" class="mini-treeselect">
          <treeselect v-model="form.parentId" :options="projectOptions" :normalizer="normalizer"
                      @select="treeSelectChange" :disabled="!form.parentId&&title==='修改项目'"
                      :placeholder="title==='修改项目'?'无':'请选择'"/>
        </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="viewable" v-if="form.type==='2'&&form.parentId">
          <dept-user-tree ref="dut" :userList="userList" :multiple="true" @selected="selectCoExecutor"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <rich-text-editor ref="rtEditor" v-model="form.description"></rich-text-editor>
        </el-form-item>
        <el-form-item label="审核流程" v-if="form.type==='2'&&form.parentId">
          <audit-module ref="auditModule" :audit-users="auditUsers"
                        :project-audit-configs="projectAuditConfigs"></audit-module>
        </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>

    <!-- 查看项目配置详情对话框 -->
    <el-dialog title="详情" :visible.sync="detailOpen" width="700px" class="add-dialog" append-to-body>
      <el-form ref="form" :model="form" size="mini" label-width="100px">
        <el-form-item label="名称" prop="projectName">
          <div>{{ form.projectName }}</div>
        </el-form-item>
        <el-form-item label="上级结构" prop="parentId">
          <div>{{ form.parentName || '无' }}</div>
        </el-form-item>
        <!--        <el-form-item label="状态" prop="status">-->
        <!--          <el-radio-group v-model="form.status" :disabled="true">-->
        <!--            <el-radio label="0">正常</el-radio>-->
        <!--            <el-radio label="1">停用</el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <el-form-item label="可查看人员" prop="viewable" v-if="form.type==='2'">
          <div>{{ form.viewUserNames }}</div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <div v-html="form.description"></div>
        </el-form-item>
        <el-form-item label="审核流程" v-if="form.type==='2'">
          <template v-for="(config,index) in form.auditConfigs">
            <el-tag>{{ config.configCode }}</el-tag>
            <i class="el-icon-right" v-if="index!=form.auditConfigs.length-1"></i>
          </template>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

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

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import DeptUserTree from "@/components/DeptUserTree"
import RichTextEditor from '@/components/RichTextEditor'
import AuditModule from '@/views/task/components/auditModule';
import {projectAuditConfigs} from "@/api/task/task";

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

      // 项目树数据
      projectOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        projectName: [
          {required: true, message: "项目名称不能为空", trigger: "blur"}
        ],
        type: [
          {required: true, message: "类型不能为空", trigger: "change"}
        ],
        status: [
          {required: true, message: "状态不能为空", trigger: "change"}
        ]
      },
      userList: [],
      expandedKeys: [],
      detailOpen: false,
      auditUsers: [],
      projectAuditConfigs: []
    };
  },
  watch: {
    projectName(val) {
      this.$refs.projectTree.filter(val)
    }
  },
  filters: {
    ellipsis(val) {
      if (!val) {
        return ''
      }
      if (val.length > 10) {
        return val.slice(0, 10) + '...'
      }
      return val
    }
  },
  created() {
    this.getProjectTree();
  },
  methods: {
    /** 查询项目树数据 */
    getProjectTree() {
      getProjectTree({status: '0'}).then(res => {
        this.projectData = res.data
      })

    },
    /** 筛选节点 */
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    nodeExpand(data, node, self) {
      this.expandedKeys = [data.id]
    },
    /** 节点单击事件 */
    handleNodeClick(data) {
      this.$emit('selectProject', data.id)
    },
    // 取消按钮
    cancel() {
      this.$refs.dut && this.$refs.dut.clearText()
      this.projectAuditConfigs = []
      this.auditUsers = []
      this.reset();
      this.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: undefined,
        projectName: undefined,
        categoryId: undefined,
        description: undefined,
        status: "0",
        viewable: undefined
      };

      this.resetForm("form");
    },
    /** 转换项目数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name || node.projectName,
        children: node.children,
        isDisabled: node.type != '1' && node.type != '分类'
      };
    },
    treeSelectChange(val) {
      if (val.type === '项目') {
        this.$message.error("上级结构不能选择项目")
        return
      }
      if (val.type === '1') {
        this.form.type = '2'
      } else {
        // this.form.type = '3'
        this.form.type = '2'
      }
    },
    /** 更多操作触发 */
    handleCommand(command, data) {
      switch (command) {
        case 'handleAdd':
          this.handleAdd(data)
          break
        case 'handleUpdate':
          this.handleUpdate(data)
          break
        case 'handleEdit':
          this.handleEdit(data)
          break
        case 'handleDelete':
          this.handleDelete(data)
          break
        case 'handleDetail':
          this.handleDetail(data)
          break
        case 'handleArchive':
          this.handleArchive(data)
          break
        default:
          break
      }
    },

    /** 新增按钮操作 */
    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.open = true;
      this.title = "添加项目";
      listProject({type: '1'}).then(response => {
        this.projectOptions = this.handleTree(response.data, "id");
      });
      getDeptUserTree('1').then(res => {
        this.userList = res.data
      })
      getAuditUsers().then(res => {
        this.auditUsers = res.data
      })
    },
    selectCoExecutor(val) {
      this.form.viewable = val.join();
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      let arr = []
      if (row.parentId != '0') {
        arr.push(getProjectTree({status: '0'}).then(response => {
          this.projectOptions = response.data
        }))
        getAuditUsers().then(res => {
          this.auditUsers = res.data
        })
        projectAuditConfigs({projectId: row.id}).then(res => {
          this.projectAuditConfigs = res.data
        })
      }
      arr.push(getDeptUserTree('1').then(res => {
        this.userList = res.data
      }))
      arr.push(getProject(row.id).then(res => {
        this.form = res.data;
        this.open = true;
        this.title = "修改项目";
      }))
      await Promise.all(arr)
      if (row.type === '项目') {
        this.$refs.dut.setCheckedNode(this.form.viewable)
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.$refs.auditModule) {
            this.form['auditConfigs'] = this.$refs.auditModule.getAuditConfigs()
          }

          if (this.form.id != undefined) {
            if (this.form.id === this.form.parentId) {
              this.$message.error("上级结构不能自身节点")
              return
            }
            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(() => {
      });
    },
    /** 统计按钮操作 */
    handleTable(row) {
      this.$router.push({path: '/task/projectTable', query: {projectId: row.id}});
    },
    /** 详情按钮操作 */
    async handleDetail(row) {
      let arr = []
      arr.push(getProject(row.id).then(res => {
        this.form = res.data;
      }))

      arr.push(getProjectTree({status: '0'}).then(res => {
        this.projectData = res.data
      }))
      await Promise.all(arr)
      this.projectData.forEach(item => {
        if (item.id === this.form.parentId) {
          this.form.parentName = item.name
        }
      })
      this.detailOpen = true;
    },
    handleArchive(row) {
      this.$confirm('是否将' + row.type + '【' + row.name + '】归档?', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {id: row.id, status: '1'}
        archiveProject(data).then(res => {
          this.$message.success('归档成功!');
          this.getProjectTree();
          this.$emit("selectProject", null)
        })
      }).catch(() => {
      });
    },

    clear() {
      this.$refs.projectTree.setCurrentKey(null)
      this.$emit('selectProject', null)
    }

  }
};
</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;

  .c-project-name {
    font-weight: bold
  }
}

.add-dialog ::v-deep .el-dialog__body {
  padding: 0 20px 10px 20px;
}

.mini-treeselect {
  ::v-deep.vue-treeselect__control {
    height: 28px;
  }

  ::v-deep.vue-treeselect__placeholder, .vue-treeselect__single-value {
    padding-left: 10px;
    line-height: 28px;
  }
}

.el-icon-right {
  font-weight: bold;
  margin-right: 5px;
}
</style>
