<template>
  <div class="comp-content">
    <!-- <el-button @click="openTaskDetailDialogFun()">
      测试打开任务详情
    </el-button> -->
    <loadCaseTable
      ref="treeTableRef"
      tableName="PROJECT_TASK_TREE_LIST"
      :data="tableList"
      @checkboxChange="checkboxChangeFun"
      readonly
      :loading="tableLoading"
      :specialActionList="[
        {
          title: '推报告',
          type: 'primary',
          click: (row: any) => {
            pushReportFun(row);
          },
          hide: (row: any) => {
            return (
              row.nodeType !== NODE_TYPE.WORKSPACE || !enableConfigByTenant([TENANT_ENUM.LYRIC])
            );
          },
        },
        ...skipApprovePageBtns(projectCode),
        {
          title: '详情',
          type: 'primary',
          click: (row: any) => {
            openTaskDetailDialogFun(row);
          },
          hide: (row: any) => {
            return row.nodeType !== NODE_TYPE.TASK;
          },
        },
      ]"
      :exportApi="exportTaskTreeApi"
      exportFileName="任务列表"
      :exportParams="exportParams"
      showNodeCompleteNum
    >
      <template #otherLeftOptions>
        <el-button v-if="enableConfigByTenant([TENANT_ENUM.LYRIC])" @click="skipDesignLyric"
          >设计审核跳转</el-button
        >
        <el-form label-width="60">
          <el-form-item label="阶段：" class="phase-content">
            <el-select
              class="phase-select"
              @change="updatePhaseUuid"
              v-model="phaseUuid"
              placeholder="阶段"
              :options="phaseListOptions"
            >
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <!-- <template #exportBtn>
        <el-button class="export-btn" @click="exportTaskFun">导出</el-button>
      </template> -->
    </loadCaseTable>

    <!-- <loadcase-pro-table
      :loading="tableLoading"
      ref="tableRef"
      :columns="tableColumns"
      :dataSource="tableList"
      :checkStrictly="true"
      :leftVisible="true"
      :leftButtonVisible="false"
      :readonly="true"
      :excludeOperation="[]"
      :projectUuid="projectUuid"
      :phaseUuid="phaseUuid"
      :toolbarConfig="{
        enabled: true,
        custom: true,
        slots: {
          tools: 'toolbar_tools',
          buttons: 'toolbar_buttons',
        },
      }"
      :showHeader="false"
    >
      <template #toolbar_tools_left_extra>
        <el-form label-width="60px">
          <el-form-item label="阶段：" class="phase-content">
            <el-select
              class="phase-select"
              @change="updatePhaseUuid"
              v-model="phaseUuid"
              placeholder="阶段"
              :options="phaseListOptions"
            >
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template #exportBtn>
        <el-button class="export-btn" @click="exportTaskFun">导出</el-button>
      </template>
      <template #detail_default="{ row }">
        <el-button
          type="primary"
          v-if="row.nodeType === NODE_TYPE.TASK"
          link
          @click="openTaskDetailDialogFun(row)"
        >详情</el-button>
      </template>
    </loadcase-pro-table> -->

    <taskDetail
      v-if="showTaskDetailDialog"
      :taskId="currentTaskInfo.id"
      :current-task-info="currentTaskInfo"
      @closeFn="showTaskDetailDialog = false"
      @updateFn="updateTaskInfoFun"
    >
    </taskDetail>
  </div>
  <PushReportDialog
    :projectUuid="projectUuid"
    :workspaceUuid="workspaceUuid"
    :workspaceCode="workspaceCode"
    v-model:show-dialog="showPushReportVisible"
    :projectCode="projectCode"
    @updateWorkspaceApproveStatus="updateWorkspaceApproveStatus"
  ></PushReportDialog>
</template>
<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue';
import { getTaskTreeFun } from './projectApi';
import { NODE_TYPE } from '@/utils/enum/node';
import { getChildrenNodeListApi } from '@/api/project/node';
import taskDetail from './taskDetail.vue';
import loadCaseTable from '@/components/common/treeCaseTable/loadCaseTable.vue';
import { getTagMapList } from '@/utils/task';
import { exportTaskTreeApi } from '@/api/project/project';
import { getIdMap } from './project';
import PushReportDialog from './pushReportDialog.vue';
import { enableConfigByTenant, TENANT_ENUM } from '@/tenants/tenant';
import { skipApprovePageBtns, skipDesignLyric } from '@/tenants/lyric/utils/projectTask';
import { TASK_APPROVE_STATUS_ENUM, TASK_PROCESS_STATUS } from '@/utils/enum/task';
import { updateTaskStatusApi } from '@/api/project/task';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';

const props = defineProps<{
  projectUuid: string;
  projectCode: string;
  currentPhase: string;
}>();

const emits = defineEmits(['getPhaseList']);

const exportParams = computed(() => {
  return {
    idMap: getIdMap(props.projectUuid, phaseUuid.value),
    tagMap: getTagMapList(),
    taskIdList: selectTaskList.value,
  };
});

const tableList = ref<any[]>([]);
const tableLoading = ref(false);
const phaseUuid = ref<any>('');

// const getTaskTreeFun = async() => {
//   const res:any = await getTaskTreeApi({
//     phaseNodeId: props.projectUuid,
//   });
//   if(res.code === 200) {
//     tableList.value = res.data;
//   }
// };
const updatePhaseUuid = async (value: string) => {
  tableLoading.value = true;
  phaseUuid.value = value;
  await getTaskTreeList();
  tableLoading.value = false;
};

const treeTableRef = ref();

const getTaskTreeList = async () => {
  tableList.value = await getTaskTreeFun(props.projectUuid, phaseUuid.value);
  setTimeout(() => {
    treeTableRef.value.loadcaseTableRef.TreeTableRef.treeTableRef.setAllTreeExpand(true);
  }, 200);
};

const phaseListOptions = ref<any[]>([]);
const getPhaseListApi = async () => {
  const res: any = await getChildrenNodeListApi({
    current: 1,
    size: 999,
    nodeType: NODE_TYPE.PHASE,
    nodeId: props.projectUuid,
  });
  if (res && res.code === 200) {
    phaseListOptions.value = res.data.map((item: { nodeName: string; uuid: string }) => {
      return { label: item.nodeName, value: item.uuid, info: item };
    });
    if (phaseListOptions.value.length) {
      // 没选中阶段 或者 选中了阶段但是不在阶段列表中
      if (
        !phaseListOptions.value.some((item) => {
          return phaseUuid.value === item.value;
        })
      ) {
        const phase = phaseListOptions.value.find(
          (item) => item.label === props.currentPhase
        )?.value;
        if (phase && phaseUuid.value !== phase) {
          // phaseUuid.value = phase;
          updatePhaseUuid(phase);
        } else {
          updatePhaseUuid(phaseListOptions.value[0].value);
        }
      }
    }
  } else {
    phaseListOptions.value = [];
  }
  emits('getPhaseList', phaseListOptions.value);
};

const showTaskDetailDialog = ref(false);

// 测试打开任务详情窗口
const currentTaskInfo = ref<any>({});
const openTaskDetailDialogFun = (row?: any) => {
  if (row) {
    currentTaskInfo.value = row;
  }
  currentTaskInfo.value.achieveStatus = currentTaskInfo.value.achieveStatus + '';
  showTaskDetailDialog.value = true;
};

const updateTaskInfoFun = async (info: any) => {
  const { flag, data }: any = info;

  if (flag === 'info') {
    const params: any = {
      taskIds: [data.uuid],
      req: {
        ...data,
      },
    };

    if (data.exeStatus === TASK_PROCESS_STATUS.COMPLETED) {
      params.req.finishTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    }
    const res: any = await updateTaskStatusApi(params);
    if (res && res.code === 200) {
      ElMessage.success('更新成功');
      await getTaskTreeList();
    }
  }

  showTaskDetailDialog.value = false;
};

const refreshPhaseList = () => {
  getPhaseListApi();
};

const selectTaskList = ref<any[]>([]);
const checkboxChangeFun = (rows: any[]) => {
  selectTaskList.value = rows.map((item) => item.uuid);
};

const showPushReportVisible = ref(false);

const workspaceUuid = ref('');
const workspaceCode = ref('');

const currentWorkspaceInfo = ref<any>({});
const pushReportFun = (row: any) => {
  showPushReportVisible.value = true;
  workspaceUuid.value = row.uuid;
  workspaceCode.value = row.nodeCode;
  currentWorkspaceInfo.value = row;
};

const updateWorkspaceApproveStatus = () => {
  currentWorkspaceInfo.value.approvalStatus = TASK_APPROVE_STATUS_ENUM.APPROVING;
  // treeTableRef.value.loadcaseTableRef.TreeTableRef.treeTableRef.setRow(currentWorkspaceInfo.value, {
  //   ...currentWorkspaceInfo.value,
  //   approvalStatus: TASK_APPROVE_STATUS_ENUM.APPROVING,
  // });
};

// watch(
//   () => props.currentPhase,
//   (val: string) => {
//     if (val) {
//       const phase = phaseListOptions.value.find((item) => item.label === val)?.value;
//       if (phase && phaseUuid.value !== phase) {
//         // phaseUuid.value = phase;
//         updatePhaseUuid(phase);
//       }
//     }
//   }
// );

onMounted(async () => {
  getPhaseListApi();
  // setTimeout(async() => {
  //   const tableData: any =
  //   await tableRef.value?.loadcaseTableRef.proTreeRef.getTableData();
  // }, 2000);
});

// watch(
//   () => props.projectUuid,
//   async (newVal) => {
//     if (newVal) {
//       tableList.value = await getTaskTreeFun(phaseUuid.value);
//       nextTick(() => {
//         tableRef.value.changeLevel('全部展开');
//       });
//     }
//   });

defineExpose({
  refreshPhaseList,
  getTaskTreeList,
});
</script>
<style lang="scss" scoped>
.export-btn {
  margin-right: var(--margin-small);
}
.comp-content {
  height: 100%;
  width: 100%;
}

.gl-page-content {
  height: 0;
}

// :deep(.vxe-toolbar .vxe-buttons--wrapper) {
//   justify-content: flex-start;
// }

.phase-content {
  margin-bottom: 0;
}

.phase-select {
  width: 120px;
}
</style>
