<template>
  <div class="gl-page-content-full">
    <div class="content">
      <FileTree
        ref="FileTreeRef"
        :api="getSimulationNodeTreeApi"
        :templateId="currentDimension"
        :params="{
          dimensionTemplateId: currentDimension
        }"
        @choseNode="choseNodeFun"
        @search="searchShow = true"
      >
        <template #options>
          <div class="top-options">
            <div class="text">显示维度：</div>
            <div class="select">
              <el-select placeholder="请选择" v-model="currentDimension">
                <el-option
                  v-for="item in templateList"
                  :key="item.id"
                  :label="item.templateName"
                  :value="item.id"
                />
              </el-select>
            </div>
            <div class="text">
              <el-link type="primary" @click="configurationShow = true">维度管理</el-link>
            </div>
          </div>
        </template>
        <template #table>
          <div class="table-content">
            <div class="table">
              <BaseTable
                ref="BaseTableRef"
                tableName="DATA_OVERVIEW"
                :api="dataOverViewListSimulationNodeFilesApi"
                :params="{
                  dimensionTemplateId: currentDimension,
                  fileId: currentData.id,
                }"
                showCheckbox
                @checkbox-all="checkboxChangeFun"
                @checkbox-change="checkboxChangeFun"
                @cell-click="cellClickFun"
              >
                <template #leftOptions>
                  <div>
                    <el-dropdown trigger="click">
                      <el-button :icon="CirclePlus" type="primary" class="option-btn">
                        新增<el-icon class="el-icon--right"><arrow-down /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="addDiaFun(NODE_TYPE.PROJECT)">新增项目</el-dropdown-item>
                          <el-dropdown-item @click="addDiaFun(NODE_TYPE.PHASE)">新增阶段</el-dropdown-item>
                          <el-dropdown-item @click="addDiaFun(NODE_TYPE.CATEGORY)">新增分类</el-dropdown-item>
                          <el-dropdown-item @click="addDiaFun(NODE_TYPE.TASK)">新增任务</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    <el-dropdown trigger="click">
                      <el-button :icon="Upload" type="primary" class="option-btn">
                        上传<el-icon class="el-icon--right"><arrow-down /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="openAddDirFun">新建文件夹</el-dropdown-item>
                          <el-dropdown-item>
                            <el-upload :show-file-list="false" :before-upload="beforeUploadFun">
                              上传文件
                            </el-upload>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    <el-button :icon="Edit" type="primary" @click="editFun">编辑</el-button>
                    <el-button :icon="Delete" type="danger" :disabled="chosenData.length === 0" @click="delFun">删除</el-button>
                    <el-button :icon="Refresh" @click="reloadFun">刷新</el-button>
                    <span class="info-switch">
                      <el-switch
                        v-model="infoShow"
                        inline-prompt
                        active-text="详细信息"
                        inactive-text="详细信息"
                      />
                    </span>
                  </div>
                </template>
                <template #originalName="{ row }">
                  <div class="file-name">
                    <template v-if="row.dataType === 1">
                      <el-icon :size="16">
                        <MessageBox v-if="row.relatedResourceUuidOwnType === NODE_TYPE.PROJECT" />
                        <Share v-else-if="row.relatedResourceUuidOwnType === NODE_TYPE.PHASE" />
                        <Document v-else-if="row.relatedResourceUuidOwnType === NODE_TYPE.TASK"/>
                        <Folder v-else />
                      </el-icon>
                      <el-link type="primary" class="name" @dblclick="goDetailFun(row)">{{ row.originalName }}</el-link>
                    </template>
                    <template v-else>
                      <el-icon :size="16">
                        <Document />
                      </el-icon>
                      <span>{{ row.originalName }}</span>
                    </template>
                  </div>
                </template>
                <template #dataType="{ row }">
                  {{ DATA_TYPE.O[row.dataType] }}
                </template>
                <template #fileSize="{ row }">
                  {{ formatFileSize(row.fileSize) }}
                </template>
              </BaseTable>
            </div>
            <div v-if="infoShow" class="info">
              <FileInfo
                :data="fileData"
              />
            </div>
          </div>
        </template>
      </FileTree>
    </div>
    <Configuration
      v-model="configurationShow"
      :dimensionId="currentDimension"
      @confirm="reloadFun"
    />
    <FileSearch
      v-model="searchShow"
      :dirId="currentData.id"
      @search="searchFileFun"
    />
    <AddDir
      v-model="addDirShow"
      :data="currentData"
      @submit="reloadFun"
    />
    <PhaseInfoDia
      v-if="showNodeInfoDialog"
      v-model:showNodeInfoDialog="showNodeInfoDialog"
      :nodeLevel1Uuid="editId"
      dialogType="edit"
      @completeFun="reloadFun"
    />
    <ProjectInfoDialog
      v-model="showProjectInfoDialog"
      :projectId="editId"
      :nodeLevel1List="[]"
      @completeFun="reloadFun"
    />
    <NodeDetailDialog
      v-model="modalVisible"
      :operationType="editId ? 'edit': 'add'"
      :nodeType="nodeType"
      :detail="editId ? editData: null"
      @confirm="addNodeFun"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import FileTree from '@/components/common/dataFileTree/index.vue';
import { getSimulationNodeTreeApi, getAllTemplateApi } from '@/api/data/dimensionTemplate';
import { addNodeForDataApi, addTaskForDataApi, getNodeDetailForDataApi } from '@/api/project/node';
import { getTaskDetailApi } from '@/api/project/task';
import { dataOverViewListSimulationNodeFilesApi, dataOverViewDeleteSimulationNodeFilesApi, dataOverViewUploadSimulationNodeFilesApi } from '@/api/data/dataOverView';
import BaseTable from '@/components/common/table/baseTable.vue';
import Configuration from './components/configuration.vue';
import FileSearch from './components/search.vue';
import FileInfo from './components/info.vue';
import AddDir from './components/addDir.vue';
import PhaseInfoDia from '@/components/project/phaseInfoDialog.vue';
import NodeDetailDialog from '@/components/common/treeCaseTable/nodeDetailDialog.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import ProjectInfoDialog from '@/components/project/projectInfoDialog.vue';
import { CirclePlus, Upload, Edit, Refresh, Delete, Folder, Document, Share, MessageBox } from '@element-plus/icons-vue';
import { getTagMapList } from '@/utils/task';
import { NODE_TYPE } from '@/utils/enum/node';
import { useDict } from '@/utils/useDict';
import { formatFileSize } from '@/utils/file';

const { DATA_TYPE } = useDict('DATA_TYPE');
const currentDimension = ref(1);
const templateList = ref<any>([]);
const configurationShow = ref(false);
const searchShow = ref(false);
const infoShow = ref(false);
const showProjectInfoDialog = ref(false);
const showNodeInfoDialog = ref(false);
const addDirShow = ref(false);
const modalVisible = ref(false);
const currentData = ref<any>('');
const FileTreeRef = ref();
const editId = ref('');
const editData = ref<any>({});
const chosenData = ref<any>([]);
const BaseTableRef = ref();
const fileData = ref<any>({});
const nodeType = ref<any>('');

onMounted(() => {
  getAllTemplateFun();
});

const getAllTemplateFun = () => {
  getAllTemplateApi({}).then((res: any) => {
    if (res.code === 200) {
      templateList.value = res.data.allDimensionTemplates;
      currentDimension.value = res.data.allDimensionTemplates[0].id || '';
    }
  });
};

const addDiaFun = (type: string) => {
  nodeType.value = type;
  editId.value = '';
  if (type === NODE_TYPE.PROJECT) {
    showProjectInfoDialog.value = true;
  }
  if (type === NODE_TYPE.PHASE) {
    if (!currentData.value || currentData.value.relatedResourceUuidOwnType !== NODE_TYPE.PROJECT) {
      ElMessage.warning('请在项目下创建阶段');
      return;
    }
    editId.value = currentData.value.relatedResourceUuid;
    showNodeInfoDialog.value = true;
  }
  if (type === NODE_TYPE.CATEGORY) {
    if (!currentData.value || ![NODE_TYPE.PHASE, NODE_TYPE.WORKSPACE, NODE_TYPE.MACHINE].includes(currentData.value.relatedResourceUuidOwnType)) {
      ElMessage.warning('请在节点或分类下创建分类');
      return;
    }
    modalVisible.value = true;
  }
  if (type === NODE_TYPE.TASK) {
    modalVisible.value = true;
  }
};

const editFun = () => {
  if (!currentData.value) {
    ElMessage.warning('请选择一个目录');
    return;
  }
  nodeType.value = currentData.value.relatedResourceUuidOwnType;
  if (currentData.value.relatedResourceUuidOwnType === NODE_TYPE.PROJECT) {
    editId.value = currentData.value.relatedResourceUuid;
    showProjectInfoDialog.value = true;
  }
  if (currentData.value.relatedResourceUuidOwnType === NODE_TYPE.PHASE) {
    editId.value = currentData.value.relatedParentUuid;
    showNodeInfoDialog.value = true;
  }
  if ([NODE_TYPE.WORKSPACE, NODE_TYPE.MACHINE].includes(currentData.value.relatedResourceUuidOwnType)) {
    editId.value = currentData.value.relatedParentUuid;
    const params = {
      relatedResourceUuid: currentData.value.relatedResourceUuid,
    };
    getNodeDetailForDataApi(params).then((res: any) => {
      if (res.code === 200) {
        editData.value = res.data;
      }
      modalVisible.value = true;
    });
  }
  if ([NODE_TYPE.TASK].includes(currentData.value.relatedResourceUuidOwnType)) {
    editId.value = currentData.value.relatedParentUuid;
    const params = {
      relatedResourceUuid: currentData.value.relatedResourceUuid,
    };
    getTaskDetailApi(params).then((res: any) => {
      if (res.code === 200) {
        editData.value = res.data;
      }
      modalVisible.value = true;
    });
  }
};

const delFun = () => {
  ElMessageBox.confirm('删除后不可恢复，确认删除吗？', '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const proList: any[] = [];
    chosenData.value.forEach((item: any) => {
      proList.push(dataOverViewDeleteSimulationNodeFilesApi({ deleteId: item.id, dataType: item.dataType }));
    });
    Promise.all(proList).then(() => {
      ElMessage.success('操作成功');
      reloadFun();
    });
  }).catch(() => {});
};

const cellClickFun = (data: any) => {
  const { row } = data;
  fileData.value = row;
};

const beforeUploadFun = (file: any) => {
  if (!currentData.value) {
    ElMessage.warning('请选择一个目录');
    return;
  }
  const { name } = file;
  const params = {
    fileName: name,
    dirId: currentData.value.id,
    file: file,
  };
  dataOverViewUploadSimulationNodeFilesApi(params).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('上传成功');
      reloadFun();
    }
  });
  return false;
};

const searchFileFun = (data: any) => {
  BaseTableRef.value?.setDataFun(data.data);
};

const addNodeFun = (data: any) => {
  if ([NODE_TYPE.CATEGORY, NODE_TYPE.WORKSPACE].includes(nodeType.value)) {
    addClassFun(data);
  }
  if (nodeType.value === NODE_TYPE.TASK) {
    addTaskFun(data);
  }
};

const addClassFun = (data: any) => {
  const params = {
    addNodeList: [{
      ...data,
      pid: currentData.value.relatedResourceUuid,
    }],
    tagMap: getTagMapList(),
  };
  addNodeForDataApi(params).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('操作成功');
      modalVisible.value = false;
      reloadFun();
    }
  });
};

const addTaskFun = (data: any) => {
  const params = {
    addTaskList: [{
      ...data,
      pid: currentData.value.relatedResourceUuid,
    }],
    tagMap: getTagMapList(),
  };
  addTaskForDataApi(params).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('操作成功');
      modalVisible.value = false;
      reloadFun();
    }
  });
};

const openAddDirFun = () => {
  if (!currentData.value) {
    ElMessage.warning('请选择一个目录');
    return;
  }
  addDirShow.value = true;
};

const goDetailFun = (data: any) => {
  if (FileTreeRef.value) {
    FileTreeRef.value.openDirFun(data.id);
  }
};

const choseNodeFun = (data: any) => {
  currentData.value = data;
};

const checkboxChangeFun = (data: any) => {
  chosenData.value = data.records;
};

const reloadFun = () => {
  chosenData.value = [];
  currentData.value = '';
  if (FileTreeRef.value) {
    FileTreeRef.value.reloadFun();
  }
};
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  height: 100%;
  .top-options {
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    .text {
      font-size: 14px;
      width: 70px;
      text-align: center;
    }
    .select {
      flex: 1;
      padding: 0 10px;
    }
  }
  .option-btn {
    margin-right: 12px;
  }
  .file-name {
    display: flex;
    align-items: center;
    color: var(--el-color-primary);
    .name {
      padding-left: 4px;
    }
  }
  .info-switch {
    margin-left: 12px;
  }
  .table-content {
    display: flex;
    .table {
      flex: 1;
      width: 0;
    }
    .info {
      width: 250px;
    }
  }
}
</style>
