<template>
  <div class="p-2">
    <!-- 搜索区域 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" label-width="80" :inline="true">
            <el-form-item label="互斥组" prop="groupName">
              <el-input v-model="queryParams.groupName" placeholder="请输入互斥组名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="编码" prop="groupCode">
              <el-input v-model="queryParams.groupCode" placeholder="请输入互斥组编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="状态" clearable>
                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              ></el-date-picker>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 主表格区域 -->
    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:menu:add']" type="primary" plain icon="Plus" @click="handleAdd()">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:menu:edit']" type="success" plain :disabled="single" icon="Edit" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:menu:remove']" type="danger" plain :disabled="ids.length === 0" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:menu:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table ref="mutexGroupTableRef" v-loading="loading" :data="mutexGroupList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="互斥组名称" prop="groupName" :show-overflow-tooltip="true" width="200">
          <template #default="scope">
            <div class="group-name-cell">
              <div class="group-name">{{ scope.row.groupName }}</div>
              <div class="group-code">{{ scope.row.groupCode }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="显示顺序" prop="groupSort" width="100" align="center" />
        <el-table-column label="包含菜单" prop="menuNames" :show-overflow-tooltip="true" min-width="200">
          <template #default="scope">
            <div class="menu-info">
              <el-tag v-if="scope.row.menuCount > 0" type="primary" size="small" class="menu-count-tag">
                {{ scope.row.menuCount }} 个菜单
              </el-tag>
              <span v-else class="no-menu">暂无菜单</span>
              <div v-if="scope.row.menuNames" class="menu-names">{{ scope.row.menuNames }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" min-width="150" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['system:menu:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['system:menu:remove']" link type="danger" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 引入互斥组表单组件 -->
    <mutex-group-form v-model:visible="formVisible" :edit-type="editType" :row-data="currentRow" @save="handleSave" />
  </div>
</template>

<script setup name="MenuMutexGroup" lang="ts">
import { changeGroupStatus, deleteMutexGroup, listMutexGroup } from '@/api/system/menuMutexGroup';
import { MutexGroupQuery, MutexGroupVO } from '@/api/system/menuMutexGroup/types';
import MutexGroupForm from './mutexGroupForm.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

// 表单控制状态
const formVisible = ref(false);
const editType = ref('');
const currentRow = ref<MutexGroupVO | null>(null);

const mutexGroupList = ref<MutexGroupVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();

// 查询参数
const queryParams = reactive<MutexGroupQuery>({
  pageNum: 1,
  pageSize: 10,
  groupName: '',
  groupCode: '',
  status: ''
});

/**
 * 查询互斥组列表
 */
const getList = () => {
  loading.value = true;
  listMutexGroup(proxy?.addDateRange(queryParams, dateRange.value)).then((res) => {
    mutexGroupList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
};

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/**删除按钮操作 */
const handleDelete = async (row?: MutexGroupVO) => {
  const groupIds = row?.groupId || ids.value;
  try {
    await proxy?.$modal.confirm('是否确认删除所选的互斥组数据？删除后相关的互斥检查将失效！');
    await deleteMutexGroup(groupIds);
    getList();
    proxy?.$modal.msgSuccess('删除成功');
  } catch (error) {
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/menuMutexGroup/export',
    {
      ...queryParams
    },
    `mutex_group_${new Date().getTime()}.xlsx`
  );
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: MutexGroupVO[]) => {
  ids.value = selection.map((item: MutexGroupVO) => item.groupId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 互斥组状态修改 */
const handleStatusChange = async (row: MutexGroupVO) => {
  const text = row.status === '0' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.groupName + '"互斥组吗?');
    await changeGroupStatus(row.groupId, row.status);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch {
    row.status = row.status === '0' ? '1' : '0';
  }
};

/** 新增按钮操作 */
const handleAdd = () => {
  currentRow.value = null;
  editType.value = 'add';
  formVisible.value = true;
};

/** 修改按钮操作 */
const handleUpdate = (row?: MutexGroupVO) => {
  if (row) {
    currentRow.value = row;
  } else {
    const selectedGroup = mutexGroupList.value?.find((item) => item.groupId === ids.value[0]);
    currentRow.value = selectedGroup || null;
  }
  editType.value = 'edit';
  formVisible.value = true;
};

/** 保存成功后的处理 */
const handleSave = () => {
  getList();
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.el-card {
  margin-bottom: 10px;
}

.group-name-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.group-name {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.group-code {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #666;
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
}

.menu-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.menu-count-tag {
  align-self: flex-start;
}

.no-menu {
  color: #999;
  font-size: 12px;
  font-style: italic;
}

.menu-names {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}
</style>
