<template>
  <div class="p-2">
    <!-- 代理后台登录地址 -->
    <el-alert type="warning" :closable="false" class="mb-[10px]" v-if="loginAddress">
      <template #default>
        <span class="login-url-text">代理登录地址：</span>
        <a :href="loginAddress" target="_blank" class="login-url-link">{{ loginAddress }}</a>
      </template>
    </el-alert>

    <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" :inline="true" class="search-form">
            <!-- 第一行：授权到期和是否到期 -->
            <el-row :gutter="10" class="first-row">
              <el-col :span="6">
                <el-form-item label="授权到期：" prop="expireDateRange" class="form-item-compact">
                  <el-date-picker
                    v-model="queryParams.expireDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    style="width: 280px"
                    size="default"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="是否到期：" prop="isExpired" class="form-item-compact">
                  <el-select v-model="queryParams.isExpired" placeholder="请选择" clearable style="width: 280px">
                    <el-option label="全部" value="" />
                    <el-option label="已到期" value="1" />
                    <el-option label="未到期" value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-show="showSecondRow">
                <el-form-item label="选择状态：" prop="status" class="form-item-compact">
                  <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 280px">
                    <el-option label="全部" value="" />
                    <el-option label="正常" value="0" />
                    <el-option label="停用" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-show="showSecondRow">
                <el-form-item label="创建时间：" prop="createTimeRange" class="form-item-compact">
                  <el-date-picker
                    v-model="queryParams.createTimeRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    style="width: 280px"
                    size="default"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item class="search-buttons">
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="6" class="collapse-btn-col">
                <el-button type="text" @click="toggleSecondRow" class="collapse-btn"> 收起 {{ showSecondRow ? '▲' : '▼' }} </el-button>
              </el-col>
            </el-row>

            <!-- 第二行：选择状态和创建时间（可收起） -->
            <!-- <el-row v-show="showSecondRow" :gutter="10" class="second-row"> </el-row> -->
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 搜索和操作按钮区域 -->
    <el-card shadow="never" class="mb-2">
      <el-row :gutter="16" class="search-and-action-row">
        <!-- 左侧搜索区域 -->
        <el-col :span="12" class="search-section">
          <!-- <el-input v-model="searchKeyword" placeholder="输入搜索" style="width: 200px" clearable>
            <template #suffix>
              <el-icon class="el-input__icon"><Search /></el-icon>
            </template>
          </el-input> -->
        </el-col>

        <!-- 右侧操作按钮区域 -->
        <el-col :span="12" class="action-section">
          <div class="action-buttons">
            <el-button icon="Refresh" @click="resetQuery">刷新</el-button>
            <el-button type="success" plain icon="Plus" @click="handleAdd">新增</el-button>
            <el-button type="warning" plain @click="handleRenewal">手动续期</el-button>
            <el-dropdown @command="handleBatchCommand">
              <el-button type="info" plain>
                批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="enable" :disabled="!multipleSelection.length">
                    <el-icon><unlock /></el-icon>启用
                  </el-dropdown-item>
                  <el-dropdown-item command="disable" :disabled="!multipleSelection.length">
                    <el-icon><lock /></el-icon>禁用
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" :disabled="!multipleSelection.length" divided>
                    <el-icon><delete /></el-icon>删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="primary" plain @click="handleExport">导出</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card shadow="never">
      <el-table v-loading="loading" border :data="sysAgentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="代理人账号" align="center" width="200">
          <template #default="scope">
            <span>{{ scope.row.userInfo?.userName || scope.row.userName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="代理人信息" align="center" width="300">
          <template #default="scope">
            <span>{{ scope.row.userInfo?.nickName || scope.row.nickName }}{{ (scope.row.userInfo?.phonenumber || scope.row.phonenumber) ? '-' + (scope.row.userInfo?.phonenumber || scope.row.phonenumber) : '' }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="省份" align="center" width="100">
          <template #default="scope">
            <span>{{ scope.row.userInfo?.province || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="市" align="center" width="100">
          <template #default="scope">
            <span>{{ scope.row.userInfo?.city || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="区" align="center" width="100">
          <template #default="scope">
            <span>{{ scope.row.userInfo?.district || '-' }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="授权到期" align="center" width="180">
          <template #default="scope">
            <span>{{ scope.row.expireDate ? parseTime(scope.row.expireDate, '{y}-{m}-{d}') : '-' }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注" align="center" width="120">
          <template #default="scope">
            <span>{{ scope.row.remark || '-' }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="来源渠道" align="center" width="200">
          <template #default="scope">
            <dict-tag :options="sys_source_channel" :value="scope.row.sourceChannel" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="280" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['system:sysAgent:edit']">编辑</el-button>
            <el-button link type="primary" @click="handleStatusChange(scope.row)" v-hasPermi="['system:sysAgent:edit']">
              {{ scope.row.status === '0' ? '禁用' : '启用' }}
            </el-button>
            <el-button link type="primary" @click="handleResetPwd(scope.row)" v-hasPermi="['system:sysAgent:edit']">重置密码</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['system:sysAgent:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改代理信息拓展对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="sysAgentFormRef" :model="form" :rules="rules" label-width="110px">
        <!-- 用户基本信息 -->
        <el-divider content-position="left">用户基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="代理人账号" prop="user.userName">
              <el-input v-model="form.user.userName" placeholder="请输入代理人账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代理人姓名" prop="user.nickName">
              <el-input v-model="form.user.nickName" placeholder="代理人姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="user.phonenumber">
              <el-input v-model="form.user.phonenumber" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="user.email">
              <el-input v-model="form.user.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" v-if="!form.agent?.userId">
            <el-form-item label="代理登录密码" prop="user.password">
              <el-input v-model="form.user.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="user.sex">
              <el-select v-model="form.user.sex" placeholder="请选择性别">
                <el-option label="男" value="0" />
                <el-option label="女" value="1" />
                <el-option label="未知" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 代理信息 -->
        <el-divider content-position="left">代理信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属区域" prop="user.codeArr">
              <el-cascader
                v-model="form.user.codeArr"
                :options="regionData as any"
                placeholder="请选择"
                @change="handleChange"
                style="width: 100%"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="授权到期" prop="agent.expireDate">
              <el-date-picker
                clearable
                v-model="form.agent.expireDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择授权到期时间"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="来源渠道" prop="agent.sourceChannel">
              <el-select v-model="form.agent.sourceChannel" placeholder="请选择来源渠道" style="width: 100%">
                <el-option v-for="dict in sys_source_channel" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代理分组" prop="user.groupId">
              <el-select v-model="form.user.groupId" placeholder="请选择代理分组" clearable filterable style="width: 100%">
                <el-option v-for="group in agentGroupList" :key="group.id" :label="group.groupName" :value="group.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="agent.status">
              <el-radio-group v-model="form.agent.status">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }} </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="agent.remark">
          <el-input v-model="form.agent.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SysAgent" lang="ts">
import { computed } from 'vue';
import {
  listSysAgent,
  getSysAgent,
  delSysAgent,
  addSysAgent,
  updateSysAgent,
  updateBatchUserStatus,
  resetAgentPwd
} from '@/api/system/sysAgent/index';
import { SysAgentVO, SysAgentQuery, SysAgentForm, SysUserAgentForm, SysUserForm } from '@/api/system/sysAgent/types';
import { listGroup } from '@/api/system/agentGroup';
import { GroupVO } from '@/api/system/agentGroup/types';
import { regionData } from 'element-china-area-data';
import { ArrowDown, Unlock, Lock, Delete } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';

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

const sysAgentList = ref<SysAgentVO[]>([]);
const agentGroupList = ref<GroupVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const showSecondRow = ref(true);
const searchKeyword = ref('');
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const multipleSelection = ref<SysAgentVO[]>([]);
const total = ref(0);
const selectedOptions = ref([]);
const loginAddress = ref<string>('');

// 代理后台登录地址 - 从字典获取
const agentLoginUrl = computed(() => {
  if (!background_url.value || background_url.value.length === 0) {
    return '';
  }
  const urlDict = background_url.value.find((item: any) => item.value === 'agent_bg');
  return urlDict?.label || '';
});

const queryFormRef = ref<ElFormInstance>();
const sysAgentFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SysUserAgentForm = {
  user: {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    userType: undefined,
    identity: undefined,
    email: undefined,
    phonenumber: undefined,
    sex: undefined,
    password: undefined,
    status: '0',
    remark: undefined,
    roleIds: [],
    postIds: [],
    groupId: undefined,
    areaCode: undefined,
    province: undefined,
    city: undefined,
    district: undefined,
    codeArr: []
  },
  agent: {
    userId: undefined,
    expireDate: undefined,
    sourceChannel: undefined,
    status: '0',
    remark: undefined
  }
};
const data = reactive<PageData<SysUserAgentForm, SysAgentQuery>>({
  form: JSON.parse(JSON.stringify(initFormData)),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    tenantId: undefined,
    areaCode: undefined,
    province: undefined,
    city: undefined,
    district: undefined,
    expireDate: undefined,
    status: undefined,
    expireDateRange: undefined,
    isExpired: undefined,
    createTimeRange: undefined,
    params: {}
  },
  rules: {
    'user.userName': [
      { required: true, message: '代理人账号不能为空', trigger: 'blur' },
      { min: 2, max: 30, message: '代理人账号长度必须介于 2 和 30 之间', trigger: 'blur' }
    ],
    'user.nickName': [
      { required: true, message: '代理人姓名不能为空', trigger: 'blur' },
      { min: 2, max: 30, message: '代理人姓名长度必须介于 2 和 30 之间', trigger: 'blur' }
    ],
    'user.password': [{ min: 6, max: 20, message: '密码长度必须介于 6 和 20 之间', required: true, trigger: 'blur' }],
    'user.email': [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
    'user.phonenumber': [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
    'agent.expireDate': [{ required: true, message: '授权到期不能为空', trigger: 'blur' }],
    'agent.status': [{ required: true, message: '状态不能为空', trigger: 'change' }],
    'user.groupId': [{ required: true, message: '代理分组不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询代理信息拓展列表 */
const getList = async () => {
  loading.value = true;

  // 转换查询参数为嵌套结构，匹配后端SysUserExtendBo
  const queryParamsConverted: any = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };

  // 处理授权到期日期范围
  if (queryParams.value.expireDateRange && queryParams.value.expireDateRange.length === 2) {
    queryParamsConverted.expireDateStart = queryParams.value.expireDateRange[0];
    queryParamsConverted.expireDateEnd = queryParams.value.expireDateRange[1];
  }

  // 处理创建时间日期范围
  if (queryParams.value.createTimeRange && queryParams.value.createTimeRange.length === 2) {
    queryParamsConverted.createTimeStart = queryParams.value.createTimeRange[0];
    queryParamsConverted.createTimeEnd = queryParams.value.createTimeRange[1];
  }

  // 添加搜索关键词
  if (searchKeyword.value) {
    queryParamsConverted.searchKeyword = searchKeyword.value;
  }

  // 代理相关查询条件嵌套到agent对象
  if (queryParams.value.status) {
    queryParamsConverted['agent.status'] = queryParams.value.status;
  }
  if (queryParams.value.expireDate) {
    queryParamsConverted['agent.expireDate'] = queryParams.value.expireDate;
  }
  if (queryParams.value.isExpired) {
    queryParamsConverted.isExpired = queryParams.value.isExpired;
  }

  // 用户相关查询条件嵌套到user对象（区域信息等）
  if (queryParams.value.areaCode) {
    queryParamsConverted['user.areaCode'] = queryParams.value.areaCode;
  }
  if (queryParams.value.province) {
    queryParamsConverted['user.province'] = queryParams.value.province;
  }
  if (queryParams.value.city) {
    queryParamsConverted['user.city'] = queryParams.value.city;
  }
  if (queryParams.value.district) {
    queryParamsConverted['user.district'] = queryParams.value.district;
  }

  const res = await listSysAgent(queryParamsConverted);
  sysAgentList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
// 构建映射表：code => name
const areaCodeToName: Record<string, string> = {};

function buildAreaMap(data: any[]) {
  data.forEach((node) => {
    areaCodeToName[node.value] = node.label;
    if (node.children) buildAreaMap(node.children);
  });
}

// 初始化时构建一次
buildAreaMap(regionData);

// 然后 handleChange 改为：
const handleChange = (val: string[]) => {
  if (form.value.user) {
    form.value.user.areaCode = val.join(',');
    form.value.user.province = areaCodeToName[val[0]] || '';
    form.value.user.city = areaCodeToName[val[1]] || '';
    form.value.user.district = areaCodeToName[val[2]] || '';
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = JSON.parse(JSON.stringify(initFormData));
  sysAgentFormRef.value?.resetFields();
};

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

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

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

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  await getAgentGroupList();
  dialog.visible = true;
  dialog.title = '添加代理信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SysAgentVO) => {
  reset();
  await getAgentGroupList();

  if (row) {
    try {
      // 调用单个查询接口获取完整的代理信息
      const response = await getSysAgent(row.userId);
      const agentData = response.data as any;

      // 将用户基本信息赋值给 user
      if (form.value.user && agentData.userInfo) {
        const userInfo = agentData.userInfo;
        form.value.user.userId = userInfo.userId;
        form.value.user.userName = userInfo.userName;
        form.value.user.nickName = userInfo.nickName;
        form.value.user.email = userInfo.email;
        form.value.user.phonenumber = userInfo.phonenumber;
        form.value.user.sex = userInfo.sex;
        form.value.user.status = userInfo.status;
        form.value.user.remark = userInfo.remark;
        form.value.user.deptId = userInfo.deptId;

        // 设置代理分组 - 从接口返回的groupId中获取
        if (userInfo.groupId) {
          form.value.user.groupId = userInfo.groupId;
        }

        // 设置区域信息到用户基本信息中
        if (userInfo.areaCode) {
          form.value.user.areaCode = userInfo.areaCode;
          form.value.user.province = userInfo.province;
          form.value.user.city = userInfo.city;
          form.value.user.district = userInfo.district;

          // 设置级联选择器的值
          form.value.user.codeArr = userInfo.areaCode.split(',');
        }
      }

      // 将代理信息赋值给 agent
      if (form.value.agent) {
        form.value.agent.userId = agentData.userId;
        form.value.agent.expireDate = agentData.expireDate;
        form.value.agent.sourceChannel = agentData.sourceChannel;
        form.value.agent.status = agentData.status;
        form.value.agent.remark = agentData.remark;
      }
    } catch (error) {
      console.error('获取代理信息失败:', error);
      proxy?.$modal.msgError('获取代理信息失败');
      return;
    }
  }

  dialog.visible = true;
  dialog.title = '修改代理信息';
};

/** 提交按钮 */
const submitForm = () => {
  // 动态设置密码验证规则
  const isEdit = !!form.value.agent?.userId;
  if (!isEdit) {
    // 新增模式下密码必填
    if (!form.value.user?.password) {
      proxy?.$modal.msgError('密码不能为空');
      return;
    }
  }

  sysAgentFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      // 处理代理分组：将groupId设置到用户信息中
      if (form.value.user?.groupId) {
        // groupId 已经在表单中，无需额外处理
      }

      if (isEdit) {
        await updateSysAgent(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addSysAgent(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 状态修改 */
const handleStatusChange = async (row: SysAgentVO) => {
  const currentStatus = row.status;
  const newStatus = currentStatus === '0' ? '1' : '0';
  const statusText = newStatus === '0' ? '启用' : '停用';

  try {
    await proxy?.$modal.confirm(`确认要${statusText}代理用户"${row.userInfo?.nickName || row.nickName}"吗？`);

    // 构建更新数据，只更新状态
    const updateData: SysUserAgentForm = {
      user: {
        userId: row.userId,
        status: newStatus
      },
      agent: {
        userId: row.userId,
        status: newStatus
      }
    };

    await updateSysAgent(updateData);
    proxy?.$modal.msgSuccess(`${statusText}成功`);
    await getList();
  } catch (error) {
    console.error('状态修改失败:', error);
  }
};

/** 重置密码按钮操作 */
const handleResetPwd = async (row: SysAgentVO) => {
  try {
    const nickName = row.userInfo?.nickName || row.nickName;
    const userName = row.userInfo?.userName || row.userName;
    const res = await ElMessageBox.prompt('请输入"' + (nickName || userName) + '"的新密码', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
      inputValidator: (value) => {
        if (/<|>|"|'|\||\\/.test(value)) {
          return '不能包含非法字符：< > " \' \\ |';
        }
      }
    });

    if (res) {
      await resetAgentPwd(row.userId, res.value);
      proxy?.$modal.msgSuccess('修改成功，新密码是：' + res.value);
    }
  } catch (error) {
    // 用户取消操作，不需要处理
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: SysAgentVO) => {
  const _userIds = row?.userId || ids.value;
  await proxy?.$modal.confirm('是否确认删除代理信息编号为"' + _userIds + '"的数据项？').finally(() => (loading.value = false));
  await delSysAgent(_userIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 切换第二行显示/隐藏 */
const toggleSecondRow = () => {
  showSecondRow.value = !showSecondRow.value;
};

/** 手动续期按钮操作 */
const handleRenewal = () => {
  proxy?.$modal.msgSuccess('手动续期功能开发中...');
};

/** 批量操作命令处理 */
const handleBatchCommand = (command: string) => {
  if (multipleSelection.value.length === 0) {
    proxy?.$modal.msgError('请选择要操作的数据');
    return;
  }

  const userIds = multipleSelection.value.map((item) => item.userId);
  const userNames = multipleSelection.value.map((item) => item.userInfo?.userName || item.userName).join('、');

  switch (command) {
    case 'enable':
      handleBatchStatus('0', userIds, userNames, '启用');
      break;
    case 'disable':
      handleBatchStatus('1', userIds, userNames, '禁用');
      break;
    case 'delete':
      handleBatchDelete(userIds, userNames);
      break;
  }
};

/** 批量状态操作 */
const handleBatchStatus = (status: string, userIds: (string | number)[], userNames: string, operation: string) => {
  const statusText = status === '0' ? '启用' : '禁用';
  proxy?.$modal.confirm(`是否确认${statusText}用户"${userNames}"？`).then(async () => {
    try {
      await updateBatchUserStatus(userIds, status);
      await getList();
      proxy?.$modal.msgSuccess(`${statusText}成功`);
      multipleSelection.value = [];
    } catch (error) {
      proxy?.$modal.msgError(`${statusText}失败`);
    }
  });
};

/** 批量删除操作 */
const handleBatchDelete = (userIds: (string | number)[], userNames: string) => {
  proxy?.$modal.confirm(`是否确认删除用户"${userNames}"？`).then(async () => {
    try {
      await delSysAgent(userIds);
      await getList();
      proxy?.$modal.msgSuccess('删除成功');
      multipleSelection.value = [];
    } catch (error) {
      proxy?.$modal.msgError('删除失败');
    }
  });
};

/** 导出按钮操作 */
const handleExport = () => {
  // 处理日期范围参数
  const params = { ...queryParams.value };

  // 处理授权到期日期范围
  if (params.expireDateRange && params.expireDateRange.length === 2) {
    params.expireDateStart = params.expireDateRange[0];
    params.expireDateEnd = params.expireDateRange[1];
  }
  delete params.expireDateRange;

  // 处理创建时间日期范围
  if (params.createTimeRange && params.createTimeRange.length === 2) {
    params.createTimeStart = params.createTimeRange[0];
    params.createTimeEnd = params.createTimeRange[1];
  }
  delete params.createTimeRange;

  // 添加搜索关键词
  if (searchKeyword.value) {
    params.searchKeyword = searchKeyword.value;
  }

  // 构造user对象来传递状态参数
  if (params.status) {
    params['user.status'] = params.status;
    delete params.status;
  }

  // 使用系统标准的下载方法
  proxy?.download('system/agent/export', params, `代理用户数据_${new Date().getTime()}.xlsx`);
};

/** 获取代理分组列表 */
const getAgentGroupList = async () => {
  try {
    const res = await listGroup({
      pageNum: 1,
      pageSize: 100,
      groupName: '',
      status: '0'
    });
    agentGroupList.value = res.rows || [];
  } catch (error) {
    console.error('获取代理分组列表失败:', error);
    agentGroupList.value = [];
  }
};

onMounted(() => {
  getList();
  getAgentGroupList();
  proxy?.getConfigKey('agent.login.address').then((response) => {
    loginAddress.value = response.data;
  });
});
</script>

<style scoped>
/* 登录地址样式 */
.login-url-text {
  font-size: 14px;
  color: #606266;
}

.login-url-link {
  font-size: 14px;
  color: #409eff;
  text-decoration: none;
}

.login-url-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.search-form {
  padding: 8px 0;
}

.form-item-compact {
  margin-bottom: 8px;
}

.form-item-compact :deep(.el-form-item__label) {
  font-size: 14px;
  color: #606266;
  font-weight: normal;
  padding-right: 8px;
  width: 80px !important;
  min-width: 80px;
  flex-shrink: 0;
}

.form-item-compact :deep(.el-form-item__content) {
  margin-left: 0 !important;
  flex: 1;
  max-width: calc(100% - 88px);
}

/* 第一行和第二行样式 */
.first-row {
  margin-bottom: 5px;
}

.second-row {
  margin-bottom: 0px;
  padding-top: 5px;
  border-top: 1px solid #f0f0f0;
}

/* 收起按钮样式 */
.collapse-btn-col {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.collapse-btn {
  color: #409eff;
  font-size: 14px;
  padding: 0;
  height: auto;
  border: none;
}

.collapse-btn:hover {
  color: #66b1ff;
}

/* 搜索和操作按钮区域样式 */
.search-and-action-row {
  display: flex;
  align-items: center;
  padding: 12px 0;
}

.search-section {
  display: flex;
  align-items: center;
}

.action-section {
  display: flex;
  justify-content: flex-end;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons .el-button {
  margin: 0;
}

/* 调整日期选择器样式 */
.form-item-compact :deep(.el-date-editor) {
  width: 220px !important;
  max-width: 220px !important;
  min-width: 220px !important;
}

.form-item-compact :deep(.el-date-editor .el-input) {
  width: 220px !important;
  max-width: 220px !important;
}

.form-item-compact :deep(.el-date-editor .el-input__inner) {
  width: 220px !important;
  max-width: 220px !important;
  padding-left: 8px;
  padding-right: 8px;
}

/* 调整选择器样式 */
.form-item-compact :deep(.el-select) {
  width: 220px !important;
  max-width: 220px !important;
  min-width: 220px !important;
}

.form-item-compact :deep(.el-select .el-input) {
  width: 220px !important;
  max-width: 220px !important;
}

.form-item-compact :deep(.el-select .el-input__inner) {
  width: 220px !important;
  max-width: 220px !important;
  min-width: 220px !important;
}

.form-item-compact :deep(.el-select .el-input__wrapper) {
  width: 220px !important;
  max-width: 220px !important;
}

/* 搜索按钮样式 */
.search-buttons {
  margin-bottom: 0;
}

.search-buttons :deep(.el-form-item__content) {
  margin-left: 0 !important;
}

.search-buttons .el-button {
  margin-right: 8px;
}

.search-buttons .el-button:last-child {
  margin-right: 0;
}

/* 表格下方的按钮区域 */
.mb8 {
  margin-bottom: 8px;
}

/* 响应式布局调整 */
@media (max-width: 1200px) {
  .search-form .el-col {
    margin-bottom: 8px;
  }

  .search-and-action-row {
    flex-direction: column;
    gap: 12px;
  }

  .search-section,
  .action-section {
    width: 100%;
    justify-content: center;
  }
}
</style>
