<template>
  <div class="gl-page-content-full" v-if="!showFlowDetailVisible">
    <div class="content">
      <div class="tabs">
        <el-tabs v-model="flowType" type="card">
          <el-tab-pane label="公共模板" :name="REPORT_TEMPLATE_PUBLIC_STATUS.PUBLIC" />
          <el-tab-pane label="个人模板" :name="REPORT_TEMPLATE_PUBLIC_STATUS.PRIVATE" />
        </el-tabs>
      </div>
      <div class="flow-table-list">
        <BaseTable
          listTitle="仿真报告模板"
          v-model:viewType="viewType"
          showIndex
          ref="tableRef"
          tableName="SIMULATION_REPORT_LIB_LIST"
          :params="searchParams"
          :hideSearchKeys="
            flowType === REPORT_TEMPLATE_PUBLIC_STATUS.PRIVATE ? ['creatorName'] : ['approveType']
          "
          :api="queryReportTemplateApi"
          :searchLimitNum="3"
          :actionList="actionList"
          fullHeight
        >
          <template #cardTemplate="{ tableData }">
            <div class="flow-card-box">
              <div class="flow-grid">
                <div v-for="report in tableData" :key="report.id" class="flow-card">
                  <div class="flow-background">
                    <span
                      :class="
                        report.approveType === FLOW_APPROVE_STATUS_ENUM.NOT_APPROVED
                          ? 'approve-box no-approve'
                          : report.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVING
                            ? 'approve-box approving'
                            : report.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVED
                              ? 'approve-box approve-success'
                              : 'approve-box approve-refuse'
                      "
                    >
                      {{ FLOW_APPROVE_STATUS.O[report.approveType] }}
                    </span>
                    <el-dropdown class="flow-card-el-dropdown" :teleported="false">
                      <div class="btn-box">...</div>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="viewFlowFun(report)">预览</el-dropdown-item>
                          <el-dropdown-item
                            v-if="
                              !(
                                report.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVING ||
                                report.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVED
                              )
                            "
                            @click="openDiaFun(REPORT_OPERATION_TYPE.EDIT, report)"
                            >编辑</el-dropdown-item
                          >
                          <el-dropdown-item
                            @click="upgradeFlowFun(report)"
                            v-if="report.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVED"
                            >升版</el-dropdown-item
                          >
                          <el-dropdown-item @click="copyFlowFun(report)">
                            <span class="flow-primary-btn">复制</span>
                          </el-dropdown-item>

                          <!-- <el-dropdown-item
                            v-if="
                              flow.templateStatus === FLOW_USE_STATUS.USED &&
                              flow.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVED
                            "
                            @click="changeFlowStatusMessageBox(flow.uuid, FLOW_USE_STATUS.STOP)"
                          >
                            <span class="flow-delete-btn">弃用</span>
                          </el-dropdown-item>
                          <el-dropdown-item
                            v-if="
                              flow.templateStatus === FLOW_USE_STATUS.STOP &&
                              flow.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVED
                            "
                            @click="changeFlowStatusMessageBox(flow.uuid, FLOW_USE_STATUS.USED)"
                            >启用</el-dropdown-item
                          > -->
                          <el-dropdown-item
                            v-if="report.approveType !== FLOW_APPROVE_STATUS_ENUM.APPROVING"
                            @click="deleteFlowMessageBox(report.templateCode)"
                          >
                            <span class="flow-delete-btn">删除</span>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    <div class="use-btn">
                      <div class="btn">
                        <el-button type="primary" @click="copyFlowFun(report)">复制模板</el-button>
                      </div>
                      <el-button @click="viewFlowFun(report)">
                        &nbsp;&nbsp;&nbsp;&nbsp;预览&nbsp;&nbsp;&nbsp;
                      </el-button>
                    </div>
                  </div>
                  <div class="flow-info-box">
                    <div class="name-version">
                      <span class="version">{{ report.templateVersion }}</span>
                      <span class="name">{{ report.templateName }}</span>
                    </div>
                    <div class="user-time">
                      <span class="user">{{ report.creatorName }}</span>
                      <span class="line">|</span>
                      <span class="time">更新于{{ report.updateTime.slice(0, 10) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <template #leftOptions>
            <el-button
              v-if="flowType !== REPORT_TEMPLATE_PUBLIC_STATUS.PUBLIC"
              icon="plus"
              @click="openDiaFun(REPORT_OPERATION_TYPE.CREATE)"
              type="primary"
            >
              {{ $t('项目列表.新增') }}
            </el-button>
          </template>
          <template #templateVersion="{ row }">
            <span class="template-version">
              {{ row.templateVersion }}
            </span>
          </template>
          <template #templateStatus="{ row }">
            <StatusDot
              :status="
                row.templateStatus === FLOW_USE_STATUS.USED
                  ? 'success'
                  : row.templateStatus === FLOW_USE_STATUS.STOP
                    ? 'error'
                    : 'info'
              "
              :title="FLOW_USE_TYPE.O[row.templateStatus]"
            />
          </template>
          <template #templateType="{ row }">
            {{ DISCIPLINE_TYPE.O[row.templateType] }}
          </template>
          <template #approveType="{ row }">
            <StatusDot :status="statusMapFun4(row.approveType)">
              <template #default>
                <span
                  :class="
                    row.approveType !== FLOW_APPROVE_STATUS_ENUM.NOT_APPROVED
                      ? 'approving-span'
                      : ''
                  "
                  @click="seeApproveDetailFun(row)"
                  >{{ FLOW_APPROVE_STATUS.O[row.approveType] }}</span
                >
              </template>
            </StatusDot>
          </template>
          <template #simulationPoolInfoList="{ row }">
            <PoolTaskSelect :modelValue="row.simulationPoolInfoList" :editable="false" />
          </template>
        </BaseTable>
      </div>
    </div>
  </div>
  <addDialog
    ref="addDiaRef"
    v-model:showDialog="showDialog"
    :dialogType="dialogType"
    @confirm="addOrEditFun"
    :flowContent="copyFlowContent"
    :templateVersion="templateVersion"
  ></addDialog>
  <ReportCreate
    v-if="showFlowDetailVisible"
    :reportUuid="reportUuid"
    @goBack="showFlowDetailVisible = false"
    :operationType="dialogType"
    :upgradeReportInfo="upgradeReportInfo"
  ></ReportCreate>
  <ReportViewDialog
    v-if="showFlowViewVisible"
    v-model:showDialog="showFlowViewVisible"
    :reportFileId="reportFileId"
    :reportUuid="reportUuid"
  ></ReportViewDialog>
  <ApprovalProcess v-model="approveDetailVisible" :flowId="approveId" />
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import { useDict } from '@/utils/useDict';
import addDialog from './components/addDialog.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { FLOW_APPROVE_STATUS_ENUM, FLOW_USE_STATUS } from '@/utils/enum/flow';
import ReportViewDialog from '@/components/common/report/reportViewDialog.vue';
import ApprovalProcess from '@/components/common/approvalProcess/index.vue';
import StatusDot from '@/components/common/statusDot/index.vue';
import { statusMapFun4 } from '@/components/common/statusDot/statusMap';
import PoolTaskSelect from '@/components/pool/poolTaskSelect.vue';
import { deleteReportTemplateApi, queryReportTemplateApi } from '@/api/capability/report';
import { REPORT_OPERATION_TYPE, REPORT_TEMPLATE_PUBLIC_STATUS } from '@/utils/enum/report';
import ReportCreate from './components/reportCreate.vue';

defineProps({
  apiParams: {
    type: Object,
    default: () => ({}),
  },
});
const showFlowDetailVisible = ref(false);
const showFlowViewVisible = ref(false);
const approveDetailVisible = ref(false);
const approveId = ref('');
const { FLOW_APPROVE_STATUS, FLOW_USE_TYPE, DISCIPLINE_TYPE } = useDict(
  'FLOW_APPROVE_STATUS',
  'FLOW_USE_TYPE',
  'DISCIPLINE_TYPE'
);
const showDialog = ref(false);
const dialogType = ref<REPORT_OPERATION_TYPE>(REPORT_OPERATION_TYPE.CREATE); // create 编辑 edit
const viewType = ref('list');
const addDiaRef = ref();
const templateVersion = ref('');
const flowType = ref<string>(REPORT_TEMPLATE_PUBLIC_STATUS.PUBLIC);

const actionList = ref<any>([
  {
    title: '预览',
    type: 'primary',
    click: (row: any) => {
      viewFlowFun(row);
    },
  },
  // {
  //   title: '重命名',
  //   type: 'primary',
  //   click: (row: any) => {
  //     openDiaFun('edit', row);
  //   },
  // },
  {
    title: '编辑',
    type: 'primary',
    click: (row: any) => {
      openDiaFun(REPORT_OPERATION_TYPE.EDIT, row);
    },
    hide: (row: any) => {
      return (
        row.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVING ||
        row.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVED
      );
    },
  },
  {
    title: '升版',
    type: 'primary',
    click: (row: any) => {
      upgradeFlowFun(row);
    },
    hide: (row: any) => {
      return (
        row.approveType !== FLOW_APPROVE_STATUS_ENUM.APPROVED ||
        row.templateStatus === FLOW_USE_STATUS.STOP
      );
    },
  },
  {
    title: '复制',
    type: 'primary',
    click: (row: any) => {
      copyFlowFun(row);
    },
  },
  // {
  //   title: '弃用',
  //   type: 'danger',
  //   needConfirm: true,
  //   confirmTip: '确认弃用？',
  //   click: (row: any) => {
  //     changeFlowStatus(row.uuid, FLOW_USE_STATUS.STOP);
  //   },
  //   hide: (row: any) => {
  //     return !(
  //       row.templateStatus === FLOW_USE_STATUS.USED &&
  //       row.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVED
  //     );
  //   },
  // },
  // {
  //   title: '启用',
  //   type: 'primary',
  //   needConfirm: true,
  //   confirmTip: '确认启用？',
  //   click: (row: any) => {
  //     changeFlowStatus(row.uuid, FLOW_USE_STATUS.USED);
  //   },
  //   hide: (row: any) => {
  //     return !(
  //       row.templateStatus === FLOW_USE_STATUS.STOP &&
  //       row.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVED
  //     );
  //   },
  // },
  {
    title: '删除',
    type: 'danger',
    needConfirm: true,
    confirmTip: '确认删除吗？',
    click: (row: any) => {
      deleteReportFun(row.templateCode);
    },
    hide: (row: any) => {
      return row.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVING;
    },
  },
]);

const searchParams = computed(() => {
  // const params = tableRef.value?.getSearchParamsFun();
  // if (params && params.templateStatus === FLOW_USE_STATUS.USED) {
  //   params.approveType = FLOW_APPROVE_STATUS_ENUM.APPROVED;
  // }
  return {
    // personal: true,
    type: flowType.value,
  };
});

const openDiaFun = (tag: REPORT_OPERATION_TYPE, row?: any) => {
  dialogType.value = tag;
  showDialog.value = true;
  if (tag === REPORT_OPERATION_TYPE.CREATE) {
    // nextTick(() => {
    addDiaRef.value.resetForm();
    // });
  } else {
    if (row) {
      templateVersion.value = row.templateVersion;
      // 待优化
      // setTimeout(() => {
      // nextTick(() => {
      addDiaRef.value.setEditForm({ ...row });
      // });
      // }, 1000);
    }
  }
};

const seeApproveDetailFun = (row: any) => {
  if (row.approveType !== FLOW_APPROVE_STATUS_ENUM.NOT_APPROVED) {
    approveDetailVisible.value = true;
    approveId.value = row.approveFlowId;
  }
};

const upgradeReportInfo = ref();

const addOrEditFun = ({ type, uuid, comment, file, fileId }: any) => {
  tableRef.value.resetFun();
  if (type && type === 'next') {
    goFlowDetailFun(uuid);
    upgradeReportInfo.value = {
      comment,
      file,
      fileId,
    };
    showDialog.value = false;
  }
};

const deleteReportFun = async (templateCode: string) => {
  const res: any = await deleteReportTemplateApi({ templateCode });
  if (res.code === 200) {
    tableRef.value.resetFun();
  } else {
    ElMessage.error(res.message);
  }
};

const deleteFlowMessageBox = (templateCode: string) => {
  ElMessageBox.confirm('确认删除流程?', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteReportFun(templateCode);
    })
    .catch(() => {});
};

// const changeFlowStatus = async (uuid: string, type: number) => {
//   const res: any = await updateFlowTemplateUseStatusApi({ uuid, status: type });
//   if (res.code === 200) {
//     if (type === FLOW_USE_STATUS.USED) {
//       ElMessage.success('启用流程成功！');
//     } else {
//       ElMessage.success('弃用流程成功！');
//     }
//     tableRef.value.resetFun();
//   } else {
//     ElMessage.error(res.message);
//   }
// };

// const changeFlowStatusMessageBox = (uuid: string, type: number) => {
//   ElMessageBox.confirm(`确认${type === FLOW_USE_STATUS.STOP ? '弃用' : '启用'}流程?`, {
//     confirmButtonText: '确认',
//     cancelButtonText: '取消',
//     type: 'warning',
//   })
//     .then(() => {
//       changeFlowStatus(uuid, type);
//     })
//     .catch(() => {});
// };

const reportUuid = ref();
const reportFileId = ref();

const viewFlowFun = (row: any) => {
  showFlowViewVisible.value = true;
  reportUuid.value = row.uuid;
  reportFileId.value = row.fileId;
};

const goFlowDetailFun = (uuid: string) => {
  showFlowDetailVisible.value = true;
  reportUuid.value = uuid;
};

const tableRef = ref();

const copyFlowContent = reactive({
  viewContent: '',
  templateContent: '',
});
const copyFlowFun = (flow: any) => {
  showDialog.value = true;
  dialogType.value = REPORT_OPERATION_TYPE.COPY;
  copyFlowContent.viewContent = flow.viewContent;
  copyFlowContent.templateContent = flow.templateContent;
  addDiaRef.value.setEditForm({
    templateName: flow.templateName,
    templateType: flow.templateType,
    comment: flow.comment,
    fileId: flow.fileId,
    // simulationPoolInfoList: flow.simulationPoolInfoList,
  });
};

const upgradeFlowFun = (flow: any) => {
  showDialog.value = true;
  dialogType.value = REPORT_OPERATION_TYPE.UPGRADE;
  addDiaRef.value.setEditForm({ ...flow });
  templateVersion.value = flow.templateVersion;
};
</script>

<style lang="scss">
.flow-card-el-dropdown {
  position: absolute;
  top: var(--margin-tiny);
  right: var(--margin-tiny);
}
.el-dropdown-menu:hover ~ .btn-box {
  visibility: visible;
  transition: all 0.3s ease-in-out;
  opacity: 1;
}
</style>

<style lang="scss" scoped>
.gl-page-content-full {
  .content {
    height: 100%;
    .tabs {
      height: 55px;
    }
  }
  .flow-table-list {
    height: calc(100% - 55px);
  }
  .approving-span {
    cursor: pointer;
  }
  .flow-car-list {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
    .filter-btn {
      text-align: right;
      margin: 10px 0;
    }
    .project {
      height: 156px;
      display: flex;
      justify-content: space-between;
      padding: 12px;
      border-radius: 6px;
      position: relative;
      overflow: hidden;
      border: 1px solid red;
      .progress {
        width: 40px;
        display: flex;
        flex-direction: column;
        align-items: center;
      }
    }
    .activeProject {
      border: 2px solid red;
      box-shadow: 0 0 5px 2px #d3d0f0;
      .projectCenter {
        .projectName {
          font-size: 14px;
        }
      }
      .name {
        font-weight: 700;
      }
    }
    .circle {
      display: inline-block;
      width: 10px;
      height: 10px;
      position: absolute;
      top: 6px;
      right: 6px;
      margin-right: 0;
    }
  }
  .flow-delete-btn {
    color: var(--el-color-danger);
  }
}
.flow-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}
.flow-card {
  background: var(--el-bg-color);
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease-in-out;
  border: 1px solid var(--el-border-color);
  overflow: hidden;
  .flow-background {
    width: 100%;
    height: 200px;
    background-color: var(--el-bg-color-page);
    background-image: url(@/assets/imgs/dragFlow/default-img.svg);
    background-size: 100px;
    background-repeat: no-repeat;
    background-position: center;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    &:hover {
      background-color: var(--el-bg-color-page);
      background-image: none;
      .approve-box {
        visibility: hidden;
        opacity: 0;
        transition: all 0.3s ease-in-out;
      }
      .use-btn {
        visibility: visible;
        transition: all 0.3s ease-in-out;
        opacity: 1;
      }
      .btn-box {
        visibility: visible;
        transition: all 0.3s ease-in-out;
        opacity: 1;
      }
    }
    .approve-box {
      position: absolute;
      top: 0;
      left: 0;
      display: inline-block;
      width: 60px;
      text-align: center;
      padding: var(--padding-tiny) var(--padding-small);
      font-size: var(--font-size-text-small);
      background-color: var(--el-bg-color);
      border-radius: 4px 0px 16px 0px;
    }
    .btn-box {
      width: 32px;
      height: 32px;
      background-color: var(--el-bg-color);
      position: absolute;
      top: var(--margin-tiny);
      right: var(--margin-tiny);
      font-weight: 600;
      font-size: 18px;
      text-align: center;
      line-height: 23px;
      cursor: pointer;
      visibility: hidden;
      transition: all 0.3s ease;
      opacity: 0;
      border-radius: var(--border-radius-normal);
    }
    .use-btn {
      visibility: hidden;
      opacity: 0;
      transition: all 0.3s ease;
      width: 100px;
      .btn {
        margin-bottom: var(--margin-small);
      }
    }
  }
  .flow-info-box {
    padding: var(--padding-medium);
    .name-version {
      margin-bottom: var(--margin-medium);
      span {
        display: inline-block;
        font-size: var(--font-size-text-normal);
      }
      .version {
        background-color: var(--el-color-primary-light-9);
        padding: 0 var(--padding-tiny);
        border-radius: var(--border-radius-small);
        margin-right: var(--margin-tiny);
        color: var(--el-color-primary);
      }
      .name {
        font-weight: 600;
      }
    }
    .user-time {
      span {
        font-size: var(--font-size-text-small);
        color: #595959;
      }
      .line {
        margin: 0 var(--margin-tiny);
      }
    }
  }
}
.progress-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
  font-size: 13px;
}
.progress-label {
  color: #64748b;
}
.progress-value {
  color: #3b82f6;
  font-weight: 600;
}
.progress-bar {
  height: 6px;
  background-color: #e2e8f0;
  border-radius: 3px;
  overflow: hidden;
}
.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #3b82f6, #60a5fa);
  border-radius: 3px;
  transition: width 0.5s ease-in-out;
}
.date-row {
  display: flex;
  justify-content: space-between;
  margin-top: 4px;
  font-size: 12px;
  color: #64748b;
}
.no-approve {
  color: #0366ff;
}
.approving {
  color: #ed7b2f;
}
.approve-success {
  color: #00a870;
}
.approve-refuse {
  color: #e34d59;
}
.template-version {
  color: #0366ff;
}
</style>
