<template>
  <div class="gl-page-content" v-if="!showFlowDetailVisible">
    <!-- <div class="display-mode">
      <el-radio-group v-model="viewType">
        <el-radio-button label="卡片" value="card" />
        <el-radio-button label="列表" value="list" />
      </el-radio-group>
    </div> -->
    <div class="flow-table-list">
      <!-- :params="{...apiParams}" -->
      <BaseTable
        listTitle="仿真流程数据"
        v-model:viewType="viewType"
        showIndex
        ref="tableRef"
        tableName="SIMULATION_FLOW_LIB_LIST"
        :api="queryFlowTemplateApi"
        :searchLimitNum="3"
        :actionList="actionList"
        @search="searchFun"
      >
        <!-- :searchParams="{type:FLOW_TEMPLATE_PUBLIC_STATUS.PUBLIC}" -->
        <!-- :actionsWidth="tableActionsLength['2-2-2-2']" -->
        <template #cardTemplate="{ tableData }">
          <div class="flow-card-box">
            <div class="flow-grid">
              <div v-for="flow in tableData" :key="flow.id" class="flow-card">
                <div class="flow-background">
                  <span
                    :class="flow.approveType === FLOW_APPROVE_STATUS_ENUM.NOT_APPROVED?
                      'approve-box no-approve':
                      flow.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVING?
                        'approve-box approving':
                        flow.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVED?
                          'approve-box approve-success':'approve-refuse'"
                  >
                    {{ FLOW_APPROVE_STATUS.O[flow.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="openDiaFun(FLOW_OPERATION_TYPE.EDIT, flow)">重命名</el-dropdown-item>
                        <el-dropdown-item @click="goFlowDetailFun(flow.uuid)">编辑</el-dropdown-item>
                        <el-dropdown-item v-if="flow.templateStatus === FLOW_USE_STATUS.USED" @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" @click="changeFlowStatusMessageBox(flow.uuid,FLOW_USE_STATUS.USED)">启用</el-dropdown-item>
                        <el-dropdown-item @click="deleteFlowMessageBox(flow.uuid)">
                          <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(flow)">复制模板</el-button>
                    </div>
                    <el-button @click="viewFlowFun(flow)"> &nbsp;&nbsp;&nbsp;&nbsp;预览&nbsp;&nbsp;&nbsp; </el-button>
                  </div>
                </div>
                <div class="flow-info-box">
                  <div class="name-version">
                    <span class="version">{{ flow.templateVersion }}</span>
                    <span class="name">{{ flow.templateName }}</span>
                  </div>
                  <div class="user-time">
                    <span class="user">{{ flow.createName }}</span>
                    <span class="line">|</span>
                    <span class="time">更新与{{ flow.updateTime.slice(0,10) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
        <template #leftOptions>
          <el-button v-if="flowType !== FLOW_TEMPLATE_PUBLIC_STATUS.PUBLIC" icon="plus" @click="openDiaFun(FLOW_OPERATION_TYPE.CREATE)" type="primary">
            {{ $t('项目列表.新增') }}
          </el-button>
        </template>
        <template #templateStatus="{ row }">
          <span
            :class="row.templateStatus === FLOW_USE_STATUS.USED?
              'dot dot-success':'dot dot-refuse'"
          >.</span>{{ FLOW_USE_TYPE.O[row.templateStatus] }}
        </template>
        <template #approveType="{ row }">
          <span
            :class="row.approveType === FLOW_APPROVE_STATUS_ENUM.NOT_APPROVED?
              'dot dot-in-precess':
              row.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVING?
                'dot dot-approving approving':
                row.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVED?
                  'dot dot-success':'dot dot-refuse'"
          >.</span>
          <span
            :class="row.approveType !== FLOW_APPROVE_STATUS_ENUM.NOT_APPROVED?'approving-span':''"
            @click="seeApproveDetailFun(row)"
          >{{ FLOW_APPROVE_STATUS.O[row.approveType] }}</span>
        </template>
        <!-- <template #tableActions="{ row }">
          <div class="gl-table-actions">
            <el-link type="primary" @click="viewFlowFun(row)">预览</el-link>
            <el-link type="primary" @click="openDiaFun('edit', row)">重命名</el-link>
            <el-link type="primary" @click="copyFlowFun( row)">复制</el-link>
            <el-link type="primary" @click="goFlowDetailFun(row)">编辑</el-link>
            <el-popconfirm v-if="row.templateStatus === FLOW_USE_STATUS.USED && row.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVED" title="确认弃用？" @confirm="changeFlowStatus(row.uuid,FLOW_USE_STATUS.STOP)">
              <template #reference>
                <el-link type="primary">弃用</el-link>
              </template>
            </el-popconfirm>
            <el-popconfirm v-if="row.templateStatus === FLOW_USE_STATUS.STOP && row.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVED" title="确认启用？" @confirm="changeFlowStatus(row.uuid,FLOW_USE_STATUS.USED)">
              <template #reference>
                <el-link type="primary">启用</el-link>
              </template>
            </el-popconfirm>
            <el-popconfirm title="确认删除吗？" @confirm="deleteFlowFun(row.uuid)">
              <template #reference>
                <el-link type="danger">删除</el-link>
              </template>
            </el-popconfirm>
          </div>
        </template> -->
      </BaseTable>
    </div>
  </div>
  <addDialog
    ref="addDiaRef"
    v-model:showDialog="showDialog"
    :dialogType="dialogType"
    @confirm="addOrEditFun"
    :flowContent="copyFlowContent"
    :templateVersion="templateVersion"
  ></addDialog>
  <flowCreate
    v-if="showFlowDetailVisible"
    :flowUuid="flowUuid"
    @goBack="showFlowDetailVisible = false"
    :operationType="dialogType"
    :templateVersion="templateVersion"
  ></flowCreate>
  <flowViewDialog
    v-if="showFlowViewVisible"
    v-model:showDialog="showFlowViewVisible"
    :flowUuid="flowUuid"
  ></flowViewDialog>
  <ApprovalProcess v-model="approveDetailVisible" :flowId="approveId" />
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import { useDict } from '@/utils/useDict';
import addDialog from './components/addDialog.vue';
import flowCreate from '@/views/simulation/creation/index.vue';
import { deleteFlowTemplateDraftApi, queryFlowTemplateApi, updateFlowTemplateUseStatusApi } from '@/api/capability/flow';
import { ElMessage, ElMessageBox } from 'element-plus';
import { FLOW_APPROVE_STATUS_ENUM, FLOW_OPERATION_TYPE, FLOW_TEMPLATE_PUBLIC_STATUS, FLOW_USE_STATUS } from '@/utils/enum/flow';
import flowViewDialog from '@/components/common/flow/flowViewDialog.vue';
import ApprovalProcess from '@/components/common/approvalProcess/index.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 } = useDict('FLOW_APPROVE_STATUS', 'FLOW_USE_TYPE');

const showDialog = ref(false);

const dialogType = ref<FLOW_OPERATION_TYPE>(FLOW_OPERATION_TYPE.CREATE); // create 编辑 edit

const viewType = ref('list');

const addDiaRef = ref();

const templateVersion = ref('');

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) => {
      // goFlowDetailFun(row.uuid);
      openDiaFun(FLOW_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;
    },
  },
  {
    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) => {
      deleteFlowFun(row.uuid);
    },
    hide: (row: any) => {
      return row.approveType === FLOW_APPROVE_STATUS_ENUM.APPROVING;
    },
  },
]);

const openDiaFun = (tag: FLOW_OPERATION_TYPE, row?: any) => {
  dialogType.value = tag;
  showDialog.value = true;
  console.log('addDiaRef.value', addDiaRef.value);
  if (tag === FLOW_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 addOrEditFun = ({ type, uuid }:any) => {
  tableRef.value.resetFun();
  flowUuid.value = uuid;
  if (type === 'next') {
    goFlowDetailFun(uuid);
    showDialog.value = false;
  }
};

const deleteFlowFun = async (uuid:string) => {
  const res:any = await deleteFlowTemplateDraftApi({ uuid });
  if (res.code === 200) {
    tableRef.value.resetFun();
  } else {
    ElMessage.error(res.msg);
  }
};

const deleteFlowMessageBox = (uuid:string) => {
  ElMessageBox.confirm(
    '确认删除流程?',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      deleteFlowFun(uuid);
    })
    .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.msg);
  }
};

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

const flowUuid = ref();

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

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

// NODE_LIST_LEVEL1
// const headData = ref<any[]>( [
//   { title: '项目名称', key: 'nodeName', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 200 },
//   { title: '项目代号', key: 'nodeCode', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 120 },
//   { title: '项目类型', key: 'nodeSubType', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 120 },
//   { title: '进度状态', key: 'progressStatusValue', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 120 },
//   { title: '计划开始时间', key: 'beginTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 180 },
//   { title: '计划结束时间', key: 'endTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 180 },
//   { title: '实际完成时间', key: 'finishTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 180 },
//   { title: '项目经理', key: 'memberList', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 120 },
//   { title: '创建人', key: 'creator', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 120 },
//   { title: '创建时间', key: 'createTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 180 },
//   { title: '描述', key: 'description', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 200 },
//   { title: '操作', key: 'tableActions', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 150, fixed: 'right' },
// ]);

const tableRef = ref();

const copyFlowContent = reactive({
  viewContent: '',
  templateContent: '',
});
const copyFlowFun = (flow:any) => {
  showDialog.value = true;
  dialogType.value = FLOW_OPERATION_TYPE.COPY;
  copyFlowContent.viewContent = flow.viewContent;
  copyFlowContent.templateContent = flow.templateContent;
  addDiaRef.value.setEditForm({ });

};

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

};

const flowType = ref<string>(FLOW_TEMPLATE_PUBLIC_STATUS.PRIVATE);

const searchFun = () => {
  const searchParams = tableRef.value.getSearchParamsFun();
  console.log('searchFun', searchParams);
  flowType.value = searchParams.type;
};

</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 {
  .display-mode {
    text-align: right;
  }
  .approving-span {
    cursor: pointer;
  }

  .flow-car-list {
    width: 100%;
    // // overflow-y: auto;
    // // height: calc(100% - 16px);
    // // margin-top: 16px;
    // display: flex;
    // flex-wrap: wrap;
    // gap: @DEFAULT_PADDING;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;

    // padding-right: 5px;
    .filter-btn {
      text-align: right;
      margin: 10px 0;
    }

    .project {
      // width: calc(25% - 9px);
      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 {
      // background-color: @DEFAULT_THEME_BACKGROUND_COLOR;
      border: 2px solid red;
      // color: #fff;
      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: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  // padding: 18px;
  transition: all 0.3s ease-in-out;
  border: 1px solid #e2e8f0;
  overflow: hidden;
  .flow-background {
    width: 100%;
    height: 200px;
    background-color: #F7F9FA;
    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: #F2F2F2;
      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 {
    // height: 50px;
    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;
      }
      .user {
      }
      .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 ;
}

</style>
