<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="所属分类" prop="categoryId">
        <el-select
          v-model="queryParams.categoryId"
          clearable
          style="width: 200px">
          <el-option v-for="item in categoryList" :key="item.id" :label="item.categoryName" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="所属项目" prop="projectId">
        <el-select
          v-model="queryParams.projectId"
          clearable
          style="width: 200px">
          <el-option v-for="item in projectList" :key="item.id" :label="item.projectName" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="月份选择">
        <el-date-picker
          v-model="queryParams.month"
          type="month"
          value-format="yyyy-MM"
          placeholder="选择月份"
          clearable
          style="width: 200px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="项目状态"
          style="width: 200px">
          <el-option :key="0" label="全部" value="0"/>
          <el-option :key="1" label="未开始" value="1"/>
          <el-option :key="2" label="进行中" value="1"/>
          <el-option :key="3" label="延期" value="1"/>
          <el-option :key="4" label="完成" value="1"/>
          <el-option :key="5" label="终止" value="1"/>
        </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" style="margin-bottom:8px">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['task:task:add']"
        >新增
        </el-button>
      </el-col>
    </el-row>

    <el-table :data="TaskList"
              @row-click="rowClick"
              border
              stripe
              size="mini">
      <el-table-column label="任务编号" prop="id" width="100"/>
      <el-table-column label="任务名称" prop="taskName"/>
      <el-table-column label="所属项目" prop="projectName"/>
      <el-table-column label="执行人" prop="executorName" width="100"/>
      <el-table-column label="进度" prop="progressValue" width="80">
        <template slot-scope="scope">
          <span>{{ (scope.row.progressValue ? scope.row.progressValue : 0) + '%' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template slot-scope="scope">
          <el-tag size="mini" :color="statusMap[scope.row.status].color">{{ statusMap[scope.row.status].name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="任务起止时间" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.beginDate + ' 至 ' + scope.row.endDate }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAudit(scope.row)"
            v-hasPermi="['task:task:audit']"
          >审核
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSplit(scope.row)"
            v-hasPermi="['task:task:split']"
          >分解
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['task:task:edit']"
          >终止
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['task:task:delete']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 10px;text-align: center">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加或修改任务配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称"/>
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-radio-group v-model="form.taskType">
            <el-radio label="1">软件开发</el-radio>
            <el-radio label="2">硬件开发</el-radio>
            <el-radio label="3">测试</el-radio>
            <el-radio label="4">实施</el-radio>
            <el-radio label="5">日常事务</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属项目" prop="projectId">
          <el-select
            v-model="form.projectId"
            clearable
            style="width: 240px">
            <el-option v-for="item in projectList" :key="item.id" :label="item.projectName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="起止时间">
          <el-date-picker
            v-model="form.rangeDate"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="执行人" prop="executor">
          <el-cascader
            v-model="form.executor"
            :options="userList"
            @change="(val)=>selectExecutor(val,'form')"
            :props="{ expandTrigger: 'hover',value:'id',label:'label' }"
            :show-all-levels="false"></el-cascader>
        </el-form-item>
        <el-form-item label="共同执行人" prop="coExecutor">
          <dept-user-tree :userList="userList" @selected="selectCoExecutor"/>
        </el-form-item>
        <el-form-item label="任务附件">
          <!--          <el-upload-->
          <!--            class="upload-demo"-->
          <!--            action="https://jsonplaceholder.typicode.com/posts/"-->
          <!--            :on-preview="handlePreview"-->
          <!--            :on-remove="handleRemove"-->
          <!--            :before-remove="beforeRemove"-->
          <!--            multiple-->
          <!--            :limit="3"-->
          <!--            :on-exceed="handleExceed"-->
          <!--            :file-list="fileList">-->
          <!--            <el-button size="small" type="primary">点击上传</el-button>-->
          <!--          </el-upload>-->
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitForm">确 定</el-button>
        <el-button size="small" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情/审核任务对话框 -->
    <el-dialog :title="detailTitle" :visible.sync="detailOpen" width="500px" append-to-body>
      <task-detail :detail-form="detailForm"></task-detail>
      <div v-if="detailTitle=='审核任务'" style="margin-top: 10px">
        <el-form ref="auditForm" :model="auditForm" label-width="100px">
          <el-form-item label="审核意见">
            <el-radio-group v-model="auditForm.auditResult">
              <el-radio label="1">确认完成</el-radio>
              <el-radio label="0">驳回</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核备注">
            <el-input v-model="auditForm.auditOpinion" type="textarea"/>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitAudit">确 定</el-button>
        <el-button size="small" @click="detailCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分解任务对话框 -->
    <el-dialog title="分解任务" :visible.sync="splitOpen" width="500px" append-to-body>
      <el-form ref="splitForm" class="split-form">
        <el-form-item label="任务名称：">
          <div>{{ splitForm.taskName }}</div>
        </el-form-item>
        <el-form-item label="所属项目：">
          <span>{{ splitForm.projectName }}</span>
          <el-button type="text" size="medium" icon="el-icon-circle-plus-outline"
                     style="float: right; padding: -1px 3px" @click="addChild"></el-button>
        </el-form-item>
        <el-card shadow="always" v-for="(c,index) in splitForm.children" :key="index">
          <div slot="header" class="clearfix">
            <span>子任务{{ index + 1 }}</span>
            <el-button type="text" icon="el-icon-close" @click="delChild(index)"
                       style="float: right; padding: 3px 0"></el-button>
          </div>
          <el-form label-width="80px">
            <el-form-item label="任务名称">
              <el-input v-model="c.taskName" size="small" style="width: 350px"/>
            </el-form-item>
            <el-form-item label="执行人" prop="executor">
              <el-cascader
                ref="dut"
                v-model="c.executor"
                :options="userList"
                @change="(val)=>selectExecutor(val,'splitForm',index)"
                :props="{ expandTrigger: 'hover',value:'id',label:'label' }"
                :show-all-levels="false"></el-cascader>
            </el-form-item>
            <el-form-item label="起止时间">
              <el-date-picker
                v-model="c.rangeDate"
                type="daterange"
                size="small"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-form>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitSplit">确 定</el-button>
        <el-button size="small" @click="splitCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listTask,
  getTask,
  delTask,
  addTask,
  updateTask,
  auditTask,
  splitTask
} from "@/api/task/task";
import {getCategoryList} from "@/api/task/category";
import {getProjectList} from "@/api/task/project";
import {getDeptUserTree} from "@/api/system/user";
import DateUtil from "@/utils/date"
import TaskDetail from "./components/taskDetail"
import DeptUserTree from "@/components/DeptUserTree"

const statusMap = {
  '0': {name: '待查看', color: '#E8EBEE'},
  '1': {name: '未开始', color: '#f4f4f5'},
  '2': {name: '进行中', color: '#ecf5ff'},
  '3': {name: '延期', color: '#ECD994'},
  '4': {name: '完成', color: '#f0f9eb'},
  '5': {name: '终止', color: '#F97C07'}
}
export default {
  name: "Task",
  components: {TaskDetail, DeptUserTree},
  data() {
    return {
      categoryList: [],
      projectList: [],
      userList: [],
      // 总条数
      total: 0,
      // 项目表格数据
      TaskList: [],
      statusMap: statusMap,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: undefined,
        projectId: undefined,
        month: DateUtil.month(),
        status: '0'
      },
      // 表单参数
      form: {},
      detailTitle: "",
      detailOpen: false,
      detailForm: {},
      auditForm: {},
      splitOpen: false,
      splitForm: {},
      // 表单校验
      rules: {
        taskName: [
          {required: true, message: "项目名称不能为空", trigger: "blur"}
        ],
        taskType: [
          {required: true, message: "任务类型不能为空", trigger: "change"}
        ],
        projectId: [
          {required: true, message: "所属项目不能为空", trigger: "change"}
        ],
        rangeDate: [
          {required: true, message: "起止时间不能为空", trigger: "change"}
        ],
        executor: [
          {required: true, message: "执行人不能为空", trigger: "change"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询项目列表 */
    getList() {
      getCategoryList("").then(res => {
        this.categoryList = res.data;
      })
      getProjectList("").then(res => {
        this.projectList = res.data;
      })
      listTask(this.queryParams).then(res => {
          this.TaskList = res.data.records;
          this.total = res.data.total;
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset()
    },
    reset() {
      this.form = {
        id: undefined,
        taskName: undefined,
        categoryId: undefined,
        description: undefined,
        status: "0",
      };
      this.resetForm("form");
    },
    // 取消按钮（详情/审核）
    detailCancel() {
      this.detailOpen = false;
      this.detailForm = {};
      this.auditForm = {}
      this.resetForm("auditForm");
    },
    // 取消按钮（分解任务）
    splitCancel() {
      this.splitOpen = false;
      this.splitForm = {}
      this.resetForm("splitForm");
    },

    /** 查看任务详情*/
    rowClick(row, column, event) {
      if (!column.property) {
        return
      }
      getTask(row.id).then(res => {
        this.detailForm = res.data;
        this.detailOpen = true;
        this.detailTitle = "任务详情";
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      getDeptUserTree().then(res => {
        this.userList = res.data
      })
      this.reset();
      this.open = true;
      this.title = "添加项目";
    },

    selectExecutor(val, form, index) {
      if (form === 'splitForm') {
        let child = this.splitForm.children[index];
        child.executor = val[val.length - 1]
      }
      if (form === 'form') {
        this.form.executor = val[val.length - 1]
      }
    },
    selectCoExecutor(val) {
      this.form.coExecutor = val.join();
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      getTask(row.id).then(res => {
        this.detailForm = res.data;
        this.detailOpen = true;
        this.detailTitle = "审核任务";
      })
    },
    /** 分解按钮操作 */
    handleSplit(row) {
      getDeptUserTree().then(res => {
        this.userList = res.data
        this.splitForm = {
          parentId: row.id,
          taskName: row.taskName,
          projectName: row.projectName,
          children: []
        }
        this.splitOpen = true
      })
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.beginDate = this.form.rangeDate[0]
          this.form.endDate = this.form.rangeDate[1]
          addTask(this.form).then(res => {
            this.$message.success("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },

    /** 审核提交按钮 */
    submitAudit() {

    },
    /** 分解任务提交按钮 */
    submitSplit() {
      splitTask(this.splitForm).then(res => {
        this.getList()
        this.splitOpen = false
        this.$message.success("操作成功");
      })
    },

    /** 终止按钮操作 */
    handleUpdate(row) {
      this.$confirm('是否确认终止任务编号为"' + row.id + '"的任务？').then(() => {
        return updateTask({id: row.id, status: '5'});
      }).then(() => {
        this.getList();
        this.$message.success("终止成功");
      }).catch(() => {
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除任务编号为"' + row.id + '"的数据项？').then(() => {
        return delTask(row.id);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },

    addChild() {
      let child = {
        taskName: undefined,
        executor: undefined,
        rangeDate: []
      }
      this.splitForm.children.push(child)
    },
    delChild(index) {
      this.splitForm.children.splice(index, 1)
    },
  }
};
</script>
<style scoped lang="scss">
.split-form {

  ::v-deep .el-form-item__label {
    font-size: 13px;
  }

  ::v-deep.el-form-item {
    margin-bottom: 0;
  }

  ::v-deep.el-card__header {
    padding: 5px 10px;
  }

  ::v-deep.el-card__body {
    padding: 5px;
  }
}
</style>
