<template>
  <div class="ele-body">
    <el-card shadow="never">
      <index-search @search="reload" />
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        height="calc(100vh - 400px)"
        full-height="calc(100vh - 116px)"
        cache-key="task-manage-1"
        :selection.sync="selection"
        :tree-props="{ children: 'children' }"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="openEdit({}, 'add')"
          >
            新建
          </el-button>
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            class="ele-btn-icon"
            @click="allDelBtn"
          >
            删除
          </el-button>

          <!--          <el-button class="el-icon-sort" size="small" @click="expandAll">-->
          <!--            展开/折叠-->
          <!--          </el-button>-->
          <!-- <div class="el-button--primary">122222</div> -->
        </template>
        <template v-slot:code="{ row }">
          <el-button type="text" @click="openDetail(row)">{{
            row.code
          }}</el-button>
        </template>
        <template v-slot:isOverTime="{ row }">
          <el-tag v-if="row.isOverTime == 0" type="success">正常</el-tag>
          <el-tag v-else type="danger">超时</el-tag>
        </template>
        <template v-slot:projectName="{ row }">
          <el-tag v-if="row.relationType == 0" type="success">{{
            row.projectName
          }}</el-tag>
          <span v-else>{{ row.projectName }}</span>
        </template>
        <template v-slot:projectStageName="{ row }">
          <el-tag v-if="row.relationType == 1" type="success">{{
            row.projectStageName
          }}</el-tag>
          <span v-else>{{ row.projectStageName }}</span>
        </template>
        <template v-slot:targetPlanName="{ row }">
          <el-tag v-if="row.relationType == 2" type="success">{{
            row.targetPlanName
          }}</el-tag>
          <span v-else>{{ row.targetPlanName }}</span>
        </template>
        <template v-slot:planStageName="{ row }">
          <el-tag v-if="row.relationType == 3" type="success">{{
            row.planStageName
          }}</el-tag>
          <span v-else>{{ row.planStageName }}</span>
        </template>
        <template v-slot:taskName="{ row }">
          <el-tag v-if="row.relationType == 4" type="success">{{
            row.taskName
          }}</el-tag>
          <span v-else>{{ row.taskName }}</span>
        </template>

        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            v-if="[0].includes(row.status)"
            @click="openEdit(row, 'edit')"
          >
            修改
          </el-link>
          <el-popconfirm
            class="ele-action"
            title="确定要删除吗？"
            v-if="[0].includes(row.status)"
            @confirm="remove([row.id])"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              操作菜单<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-link
                  type="primary"
                  :underline="false"
                  icon="el-icon-video-play"
                  @click="handleStart(row, 1)"
                  v-if="
                    [0, 2].includes(row.status) && row.ortherProcessStatus == 1
                  "
                >
                  执行
                </el-link>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-link
                  type="primary"
                  :underline="false"
                  icon="el-icon-position"
                  @click="handleTransfer(row)"
                  v-if="[0, 1].includes(row.status)"
                >
                  转派
                </el-link>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-link
                  icon="el-icon-video-pause"
                  type="warning"
                  :underline="false"
                  @click="handleStart(row, 2)"
                  v-if="[1].includes(row.status)"
                >
                  暂停
                </el-link>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-link
                  icon="el-icon-error"
                  type="danger"
                  :underline="false"
                  @click="handleStart(row, 4)"
                  v-if="[0, 1, 2].includes(row.status)"
                >
                  终止
                </el-link>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-link
                  type="primary"
                  :underline="false"
                  icon="el-icon-finished"
                  @click="handleStart(row, 3)"
                  v-if="[1].includes(row.status) && row.ifFilesAllFinish == 1"
                >
                  报工
                </el-link>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-link
                  icon="el-icon-info"
                  type="primary"
                  :underline="false"
                  @click="handelBOMConstructDetail(row)"
                >
                  任务信息
                </el-link>
              </el-dropdown-item>
              <el-dropdown-item
                divided
                v-if="[1].includes(row.status) && row.ifFilesAllFinish == 0"
              >
                <el-link
                  type="primary"
                  :underline="false"
                  icon="el-icon-plus"
                  @click="handleSubmitDeliverables(row)"
                >
                  交付物提交
                </el-link>
              </el-dropdown-item>
              <el-dropdown-item
                divided
                v-if="[0, 1].includes(row.status) && row.projectId"
              >
                <el-link
                  type="primary"
                  :underline="false"
                  icon="el-icon-plus"
                  @click="openEdit(row, 'add')"
                >
                  新增子任务
                </el-link>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
        <template v-slot:type="{ row }">
          {{ getDictV('task_type', row.type) }}
        </template>
      </ele-pro-table>
    </el-card>
    <!-- 编辑弹窗 -->
    <add-or-edit-dialog
      v-if="addOrEditDialogFlag"
      @reload="reload"
      :addOrEditDialogFlag.sync="addOrEditDialogFlag"
      ref="addOrEditDialogRef"
    ></add-or-edit-dialog>
    <detail-dialog
      v-if="detailDialogFlag"
      :detailDialogFlag.sync="detailDialogFlag"
      ref="detailDialogRef"
    ></detail-dialog>

    <submit-deliverables-dialog
      ref="submitDeliverablesDialogRef"
      v-if="submitDeliverablesDialogFlag"
      :submitDeliverablesDialogFlag.sync="submitDeliverablesDialogFlag"
    ></submit-deliverables-dialog>
    <transfer-dialog
      ref="transferDialogRef"
      v-if="transferDialogFlag"
      @reload="reload"
      :transferDialogFlag.sync="transferDialogFlag"
    ></transfer-dialog>
    <!-- 多选删除弹窗 -->
    <pop-modal
      :visible.sync="delVisible"
      content="是否确定删除？"
      @done="commitBtn"
    />
  </div>
</template>

<script>
  import indexSearch from './components/index-search.vue';
  import addOrEditDialog from './components/addOrEditDialog.vue';
  import submitDeliverablesDialog from './components/submitDeliverablesDialog.vue';
  import detailDialog from './components/detailDialog.vue';
  import popModal from '@/components/pop-modal';
  import {
    projectsTaskDeleteAPI,
    projectsTaskOpRation,
    projectsTaskPageAPI,
    myProjectsTaskPageAPI
  } from '@/api/project-manage/task';
  import { proStatusEnum, reviewStatusEnum } from '@/enum/dict';
  import { mapGetters } from 'vuex';
  import { getByCode } from '@/api/system/dictionary-data';
  import transferDialog from './components/transferDialog.vue';

  export default {
    name: 'index',
    components: {
      addOrEditDialog,
      detailDialog,
      indexSearch,
      popModal,
      transferDialog,
      submitDeliverablesDialog
    },

    props: {
      projectType: {
        type: Number,
        default: 0
      },
      ids: {
        type: String,
        default: ''
      },
      tableHeight: {
        default: ''
      }
    },

    computed: {
      ...mapGetters(['getDictValue']),

      columns() {
        return [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center'
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true
          },
          // {
          //   prop: 'type',
          //   label: '任务类型',
          //   align: 'center',
          //   showOverflowTooltip: true,
          //   minWidth: 100,
          //   slot: 'type',
          // },
          {
            prop: 'code',
            label: '任务编码',
            align: 'center',
            showOverflowTooltip: true,
            slot: 'code',
            minWidth: 180
          },
          {
            prop: 'name',
            label: '任务名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'type',
            label: '任务类型',
            align: 'center',
            showOverflowTooltip: true,
            slot: 'type',
            minWidth: 150
          },
          // {
          //   prop: 'projectName',
          //   label: '关联项目',
          //   align: 'center',
          //   slot: 'projectName',
          //   showOverflowTooltip: true,
          //   minWidth: 150
          // },
          // {
          //   prop: 'projectStageName',
          //   label: '关联项目阶段',
          //   align: 'center',
          //   slot: 'projectStageName',
          //   showOverflowTooltip: true,
          //   minWidth: 150
          // },
          // {
          //   prop: 'targetPlanName',
          //   label: '关联计划',
          //   align: 'center',
          //   slot: 'targetPlanName',
          //   showOverflowTooltip: true,
          //   minWidth: 150
          // },
          // {
          //   prop: 'planStageName',
          //   label: '关联计划节点',
          //   align: 'center',
          //   slot: 'planStageName',
          //   showOverflowTooltip: true,
          //   minWidth: 150
          // },
          // {
          //   prop: 'taskName',
          //   label: '关联任务',
          //   align: 'center',
          //   showOverflowTooltip: true,
          //   slot: 'taskName',
          //   minWidth: 150
          // },
          // {
          //   prop: 'responsibleDeptName',
          //   label: '负责部门',
          //   align: 'center',
          //   showOverflowTooltip: true,
          //   minWidth: 120
          // },
          {
            prop: 'responsibleUserName',
            label: '执行人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120,
            formatter: (_row, _column, cellValue) => {
              return !_row.responsibleUserList.length
                ? ''
                : _row.responsibleUserList.map((i) => i.userName).join(',');
            }
          },
          {
            prop: 'cost',
            label: '费用(元)',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },
          {
            prop: 'planStartDate',
            label: '计划开始日期',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'planEndDate',
            label: '计划完成日期',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'realStartTime',
            label: '实际开始日期',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'realEndTime',
            label: '实际完成日期',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'status',
            label: '状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100,
            formatter: (_row, _column, cellValue) => {
              return proStatusEnum[_row.status]?.label;
            }
          },
          {
            prop: 'isOverTime',
            label: '是否超时',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100,
            slot: 'isOverTime'
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 220,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true
          }
        ];
      }
    },
    data() {
      return {
        selection: [],
        dictList: [],
        treeTypeEnum: {
          0: '项目',
          1: '项目阶段',
          2: '计划',
          3: '计划节点',
          4: '任务'
        },
        // 是否显示编辑弹窗
        addOrEditDialogFlag: false,
        transferDialogFlag: false,
        submitDeliverablesDialogFlag: false,
        delVisible: false,
        detailDialogFlag: false
      };
    },
    async created() {},
    watch: {
      $route() {
        this.reload && this.reload();
      }
    },
    methods: {
      getDictV(code, val) {
        if (!this.dictList[code]) return '';
        return this.dictList[code].find((item) => item.value == val)?.label;
      },
      async getDictList(code) {
        let { data: res } = await getByCode(code);
        this.dictList[code] = res.map((item) => {
          let values = Object.keys(item);
          return {
            value: values[0],
            label: item[values[0]]
          };
        });
      },
      /* 表格数据源 */
      async datasource({ page, limit, where, parent }) {
        await this.getDictList('task_type');
        const api =
          this.$route.path == '/task/myTaskList'
            ? myProjectsTaskPageAPI
            : projectsTaskPageAPI;
        return api({
          pageNum: page,
          size: limit,
          ...where
        });
      },
      /* 刷新表格 */
      reload(where) {
        this.$refs.table.reload({ where, size: 1, pageNum: 10 });
      },
      /* 显示编辑 */
      openEdit(row = {}, type) {
        this.addOrEditDialogFlag = true;
        row.taskId = row.id;
        this.$nextTick(() => {
          this.$refs.addOrEditDialogRef.init(row, type);
        });
      },
      handelBOMConstructDetail(row) {
        this.$router.push({
          path: '/project-manage/task-manage/components/details',
          query: {
            row: JSON.stringify(row)
          }
        });
      },
      openDetail(row = {}) {
        this.detailDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.detailDialogRef.init(row);
        });
      },
      //转派
      handleTransfer(row) {
        this.transferDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.transferDialogRef.init(row);
        });
      },
      //报工
      async handleStart(row, afterStatus) {
        let params = {
          id: row.id,
          afterStatus: afterStatus,
          status: row.status
        };
        await projectsTaskOpRation(params);
        this.$message.success('操作成功');
        this.reload();
      },
      /* 显示编辑 */
      handleSubmitDeliverables(row = {}, type) {
        this.submitDeliverablesDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.submitDeliverablesDialogRef.init(row, type);
        });
      },
      //流程提交
      // processSubmit(row) {
      //   submit({
      //     planId: row.id
      //   }).then((res) => {
      //     this.$message.success('提交成功');
      //     this.reload();
      //   });
      // },
      //批量删除
      allDelBtn() {
        if (this.selection.length === 0) return;
        let flag = this.selection.some((item) =>
          [1, 2, 3].includes(item.status)
        );
        if (flag)
          return this.$message.warning(
            '抱歉执行中、暂停中、已完成的数据不能删除,请检查'
          );
        this.delVisible = true;
      },
      //删除弹框确定
      commitBtn() {
        const dataId = this.selection.map((v) => v.id);
        this.remove(dataId);
      },
      /* 删除 */
      remove(ids) {
        const loading = this.$loading({ lock: true });
        projectsTaskDeleteAPI(ids)
          .then((res) => {
            loading.close();
            this.$message.success('删除成功');
            this.reload();
          })
          .catch((e) => {
            loading.close();
            // this.$message.error(e.message);
          });
      }
    }
  };
</script>
<style lang="scss" scoped>
  .el-dropdown-link {
    cursor: pointer;
    color: #188ffd;
  }
  ::v-deep .el-dropdown-link {
    cursor: pointer;
    color: #188ffd;
  }
  ::v-deep .el-dropdown-menu__item {
    .el-link {
      width: 100%;
      display: flex;
      flex: 1;
      justify-content: flex-start;
    }
  }
</style>
