<template>
  <PageContainer title="审核流配置">
    <QueryToolbar>
      <el-button
        v-if="canManage"
        type="primary"
        @click="openCreateDrawer"
      >
        新增流程
      </el-button>
      <el-button @click="load">刷新</el-button>
    </QueryToolbar>
    <el-table :data="rows" class="mt-md" empty-text="暂无数据">
      <el-table-column prop="flowCode" label="流程编码" />
      <el-table-column prop="flowName" label="流程名称" />
      <el-table-column prop="status" label="状态" width="120" :formatter="statusFormatter" />
      <el-table-column label="默认" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.isDefault" type="success">默认</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="节点" min-width="260">
        <template #default="{ row }">
          <el-tag v-for="node in row.nodes || []" :key="node.id" class="mr-xs">
            {{ toZhAuditNode(node.nodeCode || node.nodeName) }}{{
              node.assigneeType ? `(${toZhAssigneeType(node.assigneeType)}:${node.assigneeRefId || "-"})` : ""
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="{ row }">
          <el-button v-if="canManage" size="small" @click="handleCopy(row.id)">复制</el-button>
          <el-button v-if="canManage" size="small" @click="handleEdit(row)">编辑节点</el-button>
          <el-button v-if="canManage" size="small" @click="handleSetDefault(row.id)">设为默认</el-button>
          <el-button v-if="canManage && row.status === 'ENABLED'" size="small" @click="handleDisable(row.id)">
            停用
          </el-button>
          <el-button v-else-if="canManage" size="small" @click="handleEnable(row.id)">启用</el-button>
          <el-button
            v-if="canManage && row.status === 'DISABLED' && !row.isDefault"
            size="small"
            type="danger"
            @click="handleDelete(row.id, row.flowName)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="mt-md"
      background
      layout="total, prev, pager, next, sizes"
      :total="totalCount"
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      @size-change="load"
      @current-change="load"
    />

    <el-drawer v-model="createVisible" title="新增审核流" :size="DRAWER_SIZE.lg" destroy-on-close>
      <el-form ref="formRef" :model="form" label-position="left" :label-width="LABEL_WIDTH.md" :rules="formRules">
        <el-form-item label="流程编码" prop="flowCode">
          <el-input v-model="form.flowCode" />
        </el-form-item>
        <el-form-item label="流程名称" prop="flowName">
          <el-input v-model="form.flowName" />
        </el-form-item>
      </el-form>
      <el-table :data="createNodes" class="mt-sm mb-md" empty-text="暂无数据">
        <el-table-column prop="nodeName" label="节点" width="120" />
        <el-table-column label="审核人来源" width="180">
          <template #default="{ row }">
            <el-select v-model="row.assigneeType" class="w-input-sm">
              <el-option label="不指定" value="" />
              <el-option label="按角色" value="ROLE" />
              <el-option label="按用户" value="USER" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="来源对象">
          <template #default="{ row }">
            <el-select
              v-if="row.assigneeType === 'ROLE'"
              v-model="row.assigneeRefId"
              placeholder="请选择角色"
              class="w-input-md"
              clearable
            >
              <el-option v-for="role in roles" :key="role.id" :label="role.roleName" :value="role.id" />
            </el-select>
            <el-select
              v-else-if="row.assigneeType === 'USER'"
              v-model="row.assigneeRefId"
              placeholder="请选择用户"
              class="w-input-md"
              clearable
            >
              <el-option v-for="user in users" :key="user.id" :label="`${user.userName}(${user.id})`" :value="user.id" />
            </el-select>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button v-if="canManage" type="primary" @click="handleCreate">创建</el-button>
      </template>
    </el-drawer>

    <el-dialog v-model="editVisible" title="编辑审核流节点来源" :width="DIALOG_WIDTH.lg">
      <el-table :data="editNodes" empty-text="暂无数据">
        <el-table-column prop="nodeName" label="节点" width="120" />
        <el-table-column label="审核人来源" width="180">
          <template #default="{ row }">
            <el-select v-model="row.assigneeType" class="w-input-sm">
              <el-option label="不指定" value="" />
              <el-option label="按角色" value="ROLE" />
              <el-option label="按用户" value="USER" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="来源对象">
          <template #default="{ row }">
            <el-select
              v-if="row.assigneeType === 'ROLE'"
              v-model="row.assigneeRefId"
              placeholder="请选择角色"
              class="w-input-md"
              clearable
            >
              <el-option v-for="role in roles" :key="role.id" :label="role.roleName" :value="role.id" />
            </el-select>
            <el-select
              v-else-if="row.assigneeType === 'USER'"
              v-model="row.assigneeRefId"
              placeholder="请选择用户"
              class="w-input-md"
              clearable
            >
              <el-option v-for="user in users" :key="user.id" :label="`${user.userName}(${user.id})`" :value="user.id" />
            </el-select>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">保存</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import PageContainer from "../../components/PageContainer.vue";
import QueryToolbar from "../../components/QueryToolbar.vue";
import { DRAWER_SIZE, DIALOG_WIDTH, LABEL_WIDTH } from "../../constants/ui";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  copyAuditFlow,
  createAuditFlow,
  deleteAuditFlow,
  disableAuditFlow,
  enableAuditFlow,
  fetchAuditFlows,
  fetchRoles,
  fetchUsers,
  setDefaultAuditFlow,
  updateAuditFlow,
} from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";
import { toZhAssigneeType, toZhAuditNode, toZhStatus } from "../../utils/status";

const authStore = useAuthStore();
const canRead = computed(() => authStore.hasPermission(PERMS.audit.flowRead));
const canManage = computed(() => authStore.hasPermission(PERMS.audit.flowManage));
const rows = ref<any[]>([]);
const pageNo = ref(1);
const pageSize = ref(20);
const totalCount = ref(0);
const roles = ref<any[]>([]);
const users = ref<any[]>([]);
const createVisible = ref(false);
const editVisible = ref(false);
const editingFlow = ref<any>(null);
const editNodes = ref<any[]>([]);
const form = ref({
  flowCode: "FLOW_" + Date.now(),
  flowName: "新流程",
});

const formRef = ref<FormInstance>();
const formRules = ref<FormRules>({
  flowCode: [{ required: true, message: "请输入流程编码", trigger: "blur" }],
  flowName: [{ required: true, message: "请输入流程名称", trigger: "blur" }],
});

const statusFormatter = (_row: any, _column: any, value: unknown) => toZhStatus(value);

const createNodes = ref([
  { nodeCode: "INIT_REVIEW", nodeName: "初审", sortNo: 1, assigneeType: "ROLE", assigneeRefId: 104 },
  { nodeCode: "RE_REVIEW", nodeName: "复审", sortNo: 2, assigneeType: "ROLE", assigneeRefId: 104 },
  { nodeCode: "FINAL_REVIEW", nodeName: "终审", sortNo: 3, assigneeType: "ROLE", assigneeRefId: 104 },
]);

const openCreateDrawer = () => {
  form.value = {
    flowCode: "FLOW_" + Date.now(),
    flowName: "新流程",
  };
  createNodes.value = [
    { nodeCode: "INIT_REVIEW", nodeName: "初审", sortNo: 1, assigneeType: "ROLE", assigneeRefId: 104 },
    { nodeCode: "RE_REVIEW", nodeName: "复审", sortNo: 2, assigneeType: "ROLE", assigneeRefId: 104 },
    { nodeCode: "FINAL_REVIEW", nodeName: "终审", sortNo: 3, assigneeType: "ROLE", assigneeRefId: 104 },
  ];
  createVisible.value = true;
};

const load = async () => {
  if (!canRead.value) {
    rows.value = [];
    return;
  }
  const resp = await fetchAuditFlows({ pageNo: pageNo.value, pageSize: pageSize.value });
  rows.value = resp?.data?.list || [];
  totalCount.value = Number(resp?.data?.total || 0);
};

const loadOptions = async () => {
  try {
    const [roleResp, userResp] = await Promise.all([fetchRoles(), fetchUsers()]);
    roles.value = roleResp?.data?.list || [];
    users.value = userResp?.data?.list || [];
  } catch (_e) {
    roles.value = [];
    users.value = [];
  }
};

const handleCreate = async () => {
  if (!formRef.value) return;
  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) return;

  await createAuditFlow({
    flowCode: form.value.flowCode,
    flowName: form.value.flowName,
    nodes: createNodes.value,
  });
  ElMessage.success("流程创建成功");
  createVisible.value = false;
  await load();
};

const handleEdit = (row: any) => {
  editingFlow.value = row;
  editNodes.value = (row.nodes || []).map((node: any) => ({
    nodeCode: node.nodeCode,
    nodeName: node.nodeName,
    sortNo: node.sortNo,
    assigneeType: node.assigneeType || "",
    assigneeRefId: node.assigneeRefId || undefined,
  }));
  editVisible.value = true;
};

const handleSaveEdit = async () => {
  if (!editingFlow.value) {
    return;
  }
  await updateAuditFlow(editingFlow.value.id, {
    flowCode: editingFlow.value.flowCode,
    flowName: editingFlow.value.flowName,
    effectiveStartAt: editingFlow.value.effectiveStartAt,
    effectiveEndAt: editingFlow.value.effectiveEndAt,
    nodes: editNodes.value,
  });
  ElMessage.success("流程节点已更新");
  editVisible.value = false;
  await load();
};

const handleCopy = async (id: number) => {
  await copyAuditFlow(id);
  ElMessage.success("流程复制成功");
  await load();
};

const handleSetDefault = async (id: number) => {
  await setDefaultAuditFlow(id);
  ElMessage.success("默认流程已更新");
  await load();
};

const handleEnable = async (id: number) => {
  await enableAuditFlow(id);
  ElMessage.success("流程已启用");
  await load();
};

const handleDisable = async (id: number) => {
  await disableAuditFlow(id);
  ElMessage.success("流程已停用");
  await load();
};

const handleDelete = async (id: number, name: string) => {
  await ElMessageBox.confirm(`确认删除审核流「${name}」？删除后不可恢复。`, "删除审核流", {
    type: "warning",
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
  });
  await deleteAuditFlow(id);
  ElMessage.success("审核流已删除");
  await load();
};

onMounted(async () => {
  await Promise.all([load(), loadOptions()]);
});
</script>
