<template>
  <basic-container>
    <!-- 页面标题和发起按钮 -->
    <div class="workflow-header">
      <h3 class="workflow-title">我的申请</h3>
      <el-button type="primary" icon="el-icon-plus" @click="handleStart">
        发起新流程
      </el-button>
    </div>

    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page="page"
      ref="crud"
      v-model="form"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!-- 状态列自定义 -->
      <template #status="{ row }">
        <el-tag
          :type="
            row.status === '已完成'
              ? 'success'
              : row.status === '已驳回'
                ? 'danger'
                : row.status === '待提交'
                  ? 'info'
                  : 'warning'
          "
          :effect="row.status === '待提交' ? 'plain' : 'light'"
        >
          {{ row.status }}
        </el-tag>
      </template>

      <!-- 自定义操作列 -->
      <template #menu="scope">
        <el-button
          type="primary"
          link
          size="small"
          @click.stop="handleView(scope.row)"
        >查看</el-button>
        <el-button
          v-if="scope.row.status === '待提交'"
          type="primary"
          link
          size="small"
          @click.stop="handleEdit(scope.row)"
        >编辑</el-button>
        <el-button
          v-if="scope.row.status === '待提交'"
          type="danger"
          link
          size="small"
          @click.stop="handleDelete(scope.row)"
        >删除</el-button>
      </template>
    </avue-crud>

    <!-- 发起流程弹窗 -->
    <el-dialog
      title="选择流程类型"
      v-model="startDialogVisible"
      width="600px"
      append-to-body
    >
      <el-row :gutter="20">
        <el-col
          :span="8"
          v-for="item in processTypes"
          :key="item.value"
          style="margin-bottom: 15px"
        >
          <el-card
            shadow="hover"
            :body-style="{ padding: '20px', textAlign: 'center', cursor: 'pointer' }"
            @click="selectProcessType(item)"
          >
            <el-icon size="32" style="margin-bottom: 10px">
              <Document />
            </el-icon>
            <div>{{ item.label }}</div>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getMyList, getProcessTypes } from '@/api/workflow';
import { Document } from '@element-plus/icons-vue';

export default {
  components: {
    Document,
  },
  data() {
    return {
      form: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      query: {},
      data: [],
      // 发起流程弹窗
      startDialogVisible: false,
      processTypes: [],
      // Avue 表格配置
      option: {
        height: 'auto',
        calcHeight: 32,
        tip: false,
        searchShow: false,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: false,
        editBtn: false,
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        menuWidth: 200,
        dialogClickModal: false,
        column: [
          {
            label: '流程名称',
            prop: 'processName',
            search: true,
            overHidden: true,
          },
          {
            label: '状态',
            prop: 'status',
            slot: true,
            width: 100,
            search: true,
            type: 'select',
            dicData: [
              { label: '待提交', value: '待提交' },
              { label: '审批中', value: '审批中' },
              { label: '已完成', value: '已完成' },
              { label: '已驳回', value: '已驳回' },
            ],
          },
          {
            label: '申请人',
            prop: 'tCreateUser',
            width: 100,
          },
          {
            label: '申请时间',
            prop: 'tArrivalTime',
            width: 180,
          },
          {
            label: '当前节点',
            prop: 'currentApprovalNode',
            width: 140,
          },
        ],
      },
    };
  },
  mounted() {
    this.loadProcessTypes();
  },
  methods: {
    loadProcessTypes() {
      getProcessTypes().then(res => {
        const data = res.data.data;
        this.processTypes = data.map(item => ({
          label: item.processName,
          value: item.processId,
        }));
      });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      const query = {
        ...this.query,
        ...params,
      };
      getMyList(page.currentPage, page.pageSize, query).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },
    // 发起新流程
    handleStart() {
      this.startDialogVisible = true;
    },
    // 选择流程类型
    selectProcessType(item) {
      this.startDialogVisible = false;
      this.$message.success(`选择了流程类型: ${item.label}`);
      // TODO: 后续接入流程发起表单页面
    },
    // 查看详情
    handleView(row) {
      this.$message.info(`查看流程详情: ${row.processName}`);
      // TODO: 后续接入流程详情页面
    },
    // 编辑（仅待提交状态）
    handleEdit(row) {
      this.$message.info(`编辑流程: ${row.processName}`);
      // TODO: 后续接入编辑表单页面
    },
    // 删除（仅待提交状态）
    handleDelete(row) {
      this.$confirm(`确认删除流程 "${row.processName}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        // 从列表中移除
        const index = this.data.findIndex(item => item.id === row.id);
        if (index !== -1) {
          this.data.splice(index, 1);
          this.page.total -= 1;
        }
        this.$message.success('删除成功');
      }).catch(() => {});
    },
  },
};
</script>

<style scoped>
.workflow-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}
.workflow-title {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}
</style>