<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined" />
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
            >批量操作
            <Icon icon="mdi:chevron-down" />
          </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
        <!-- 新增生成账号按钮 -->
        <a-button type="primary" @click="showAutoGenerateForm = true" preIcon="ant-design:plus-outlined"> 生成账号 </a-button>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template #bodyCell="{ column, record, index, text }">
        <span v-if="column.dataIndex === 'identity'">
          {{ record.identityDescription }}
        </span>
        <span v-if="column.dataIndex === 'majorId'">
          {{ record.majorIdDescription }}
        </span>
        <span v-if="column.dataIndex === 'workload'" @click="handleWordloadClick(record)">
          <a-input-number v-if="record.seen" v-model:value="record.workload" @blur="handleWordLoadBlur(record)" />
          <span v-else>{{ record.workload }}</span>
        </span>
      </template>
    </BasicTable>

    <!-- 表单区域 -->
    <CeesUserModal @register="registerModal" @success="handleSuccess" />

    <!-- 生成账号表单 -->
    <a-modal
      v-model:visible="showAutoGenerateForm"
      title="生成账号"
      @ok="handleAutoGenerate"
      @cancel="showAutoGenerateForm = false"
      :destroyOnClose="true"
      :width="600"
      :bodyStyle="{ padding: '24px' }"
    >
      <a-form ref="autoGenerateFormRef" :model="autoGenerateForm" layout="vertical">
        <a-form-item label="账号类型" class="form-item-custom">
          <a-select v-model="autoGenerateForm.group" placeholder="请选择账号类型" @change="handleGroupChange" class="select-custom">
            <a-select-option v-for="item in autoGeneratType" :key="item.id" :value="item.value">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item v-if="isDisplay" label="专业" class="form-item-custom">
          <a-select v-model="autoGenerateForm.majorId" placeholder="请选择专业" @change="handleMajorChange" class="select-custom">
            <a-select-option v-for="item in majors" :key="item.id" :value="item.value">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="账号数量" class="form-item-custom">
          <a-input-number
            v-model="autoGenerateForm.num"
            :min="1"
            placeholder="请输入账号数量"
            @change="handleNumChange"
            class="input-number-custom"
          />
        </a-form-item>
        <!-- 新增生成规律按钮 -->
        <a-form-item class="form-item-custom" style="text-align: right">
          <a-button type="primary" @click="showGenerateRuleModal = true">生成规律</a-button>
        </a-form-item>
      </a-form>

      <!-- 生成规律设置对话框 -->
      <a-modal
        v-model:visible="showGenerateRuleModal"
        title="设置生成规律"
        @ok="handleGenerateRuleOk"
        @cancel="showGenerateRuleModal = false"
        :width="400"
        :centered="true"
        :bodyStyle="{ padding: '24px', display: 'flex', flexDirection: 'column', alignItems: 'center' }"
      >
        <a-form ref="generateRuleFormRef" :rules="generateRuleRules" :model="generateRuleForm" layout="vertical" style="width: 100%">
          <a-form-item name="groupType" label="账号类型第几位" style="width: 100%">
            <a-input-number v-model:value="generateRuleForm.groupType" placeholder="请输入账号类型的位置" style="width: 100%" />
          </a-form-item>

          <a-form-item name="majorId" label="学科类型第几位" style="width: 100%">
            <a-input-number v-model:value="generateRuleForm.majorId" placeholder="请输入学科类型的位置" style="width: 100%" />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-modal>
  </div>
</template>

<script lang="ts" name="org.jeecg.modules-ceesUser" setup>
  import { ref, onMounted, reactive, watch, nextTick } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import CeesUserModal from './components/CeesUserModal.vue';
  import { columns, searchFormSchema, superQuerySchema, updateGroupOptions } from './CeesUser.data';
  import {
    list,
    deleteOne,
    batchDelete,
    getImportUrl,
    getExportUrl,
    saveOrUpdate,
    getGroup,
    generateAccount,
    getGenerativeRules,
    updateGenerateRule,
  } from './CeesUser.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';
  import { message } from 'ant-design-vue';

  // 表单相关状态
  const showAutoGenerateForm = ref(false); // 控制表单显示
  const isDisplay = ref(false);
  const autoGenerateFormRef = ref();
  // 定义模态框的显示状态
  const showGenerateRuleModal = ref(false);
  // 定义生成规律表单数据
  const generateRuleForm = ref({
    groupType: undefined,
    majorId: undefined,
    id: undefined,
  });
  // 1. 表单引用
  const generateRuleFormRef = ref(null);
  // 2. 校验规则
  const generateRuleRules = {
    groupType: [
      { required: true, message: '账号类型位置不能为空', trigger: 'blur' },
      { type: 'number', max: 8, message: '不能大于8', trigger: 'blur' },
      { type: 'number', min: 1, message: '不能小于1', trigger: 'blur' },
      { validator: validateDifferent, trigger: 'blur' },
    ],
    majorId: [
      { required: true, message: '学科ID位置不能为空', trigger: 'blur' },
      { type: 'number', max: 8, message: '不能大于8', trigger: 'blur' },
      { type: 'number', min: 1, message: '不能小于1', trigger: 'blur' },
      { validator: validateDifferent, trigger: 'blur' },
    ],
  };
  // 3. 自定义校验方法：两个值不能相同
  function validateDifferent(_, value) {
    if (value === generateRuleForm.value.groupType && value === generateRuleForm.value.majorId) {
      return Promise.reject(new Error('账号类型位置和学科ID位置不能相同'));
    }
    return Promise.resolve();
  }
  // 从数据库中获取默认值
  const fetchDefaultValues = async () => {
    try {
      const response = await getGenerativeRules();
      console.log('response', response);
      const data = response.GenerativeRules;
      console.log('data', data);

      generateRuleForm.value.groupType = data.groupType;
      generateRuleForm.value.majorId = data.majorId;
      generateRuleForm.value.id = data.id;
      //console.log('generateRuleForm', generateRuleForm.value);
      await nextTick(); // 确保数据更新后视图能够重新渲染
    } catch (error) {
      console.error('获取默认值失败', error);
    }
  };

  // 定义方法
  const handleGenerateRuleOk = async () => {
    await generateRuleFormRef.value.validate();
    showGenerateRuleModal.value = false;
    console.log('generateRuleForm', generateRuleForm.value);
    try {
      const res = await updateGenerateRule(generateRuleForm.value); // 等待异步操作完成
      console.log('data', res);
      if (res === '更新成功') {
        message.success('更改规则成功');
        console.log('data', res);
      } else {
        message.error('更改失败');
      }
    } catch (error) {
      // 处理失败逻辑
      message.error('更改失败, 请重试！');
      console.error('请求失败:', error); // 打印错误信息方便调试
    }
  };
  const handleGroupChange = (value) => {
    autoGenerateForm.group = value;
    if (value != 1) {
      isDisplay.value = true;
    } else {
      isDisplay.value = false;
      autoGenerateForm.majorId = undefined;
    }
  };
  const handleMajorChange = (value) => {
    autoGenerateForm.majorId = value;
  };
  const handleNumChange = (value) => {
    autoGenerateForm.num = value;
  };

  const workloadSeen = ref(true);
  const handleWordLoadBlur = (record) => {
    console.log(record);
    saveOrUpdate(record, true);
    record.seen = false;
    //workloadSeen.value = true;
  };
  const handleWordloadClick = (record) => {
    //workloadSeen.value = false;
    record.seen = true;
    console.log(111);
  };

  const autoGenerateForm = reactive({
    group: undefined, // 账号类型
    majorId: undefined, // 专业
    num: undefined, // 账号数量
  });

  // 账号类型选项
  const autoGeneratType = ref([
    { id: 1, name: '行政人员', value: 1 },
    { id: 2, name: '研究生', value: 2 },
    { id: 2, name: '本校老师', value: 3 },
    { id: 3, name: '外校老师', value: 4 },
  ]);

  // 专业选项
  const majors = ref([
    { id: 1, name: '语文', value: 1 },
    { id: 2, name: '地理', value: 4 },
    { id: 3, name: '历史', value: 7 },
    { id: 4, name: '政治', value: 8 },
  ]);

  // 生成账号逻辑
  const handleAutoGenerate = () => {
    console.log(autoGenerateForm);
    if (autoGenerateForm.group == undefined) {
      message.warning('请选择身份', 1.5);
      return;
    }
    if (autoGenerateForm.majorId == undefined && isDisplay.value == true) {
      message.warning('请选择专业', 1.5);
      return;
    }
    if (autoGenerateForm.num == undefined) {
      message.warning('请输入账号数量', 1.5);
      return;
    }
    //     账号数量小于500并且大于0
    if (autoGenerateForm.num <= 0) {
      message.warning('账号数量必须大于0', 1.5);
      return;
    }
    if (autoGenerateForm.num > 500) {
      message.warning('账号数量不能大于500', 1.5);
      return;
    }
    // 调用生成账号的 API 或逻辑
    try {
      generateAccount(autoGenerateForm).then((res) => {
        console.log(res);
        if (res.code == 200) {
          message.success(res.message, 1.5);
          resetFormState();
          // 刷新表格
          reload();
        } else {
          message.error(res.message, 1.5);
        }
      });
    } catch (error) {
      // 处理失败逻辑
      message.error('账号生成失败，请重试');
    } finally {
      showAutoGenerateForm.value = false;
    }
  };
  // 新增重置方法
  const resetFormState = () => {
    // 深度重置表单数据
    Object.assign(autoGenerateForm, {
      group: undefined,
      majorId: undefined,
      num: undefined,
    });
    // 强制重置UI组件状态
    nextTick(() => {
      autoGenerateFormRef.value?.resetFields();
    });
  };
  // 其他代码保持不变
  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  const userStore = useUserStore();
  const [registerModal, { openModal }] = useModal();
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: 'CEES用户表',
      api: list,
      columns,
      canResize: false,
      formConfig: {
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: 'CEES用户表',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const groupOptions = ref<{ label: string; value: number }[]>([]);
  onMounted(async () => {
    fetchDefaultValues();
    try {
      const res = await getGroup();
      groupOptions.value = res.map((group) => ({
        label: group.name,
        value: group.id,
      }));
      updateGroupOptions.updateGroupOptions(groupOptions.value);
    } catch (error) {
      console.error('获取分组数据失败:', error);
    }
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;
  const superQueryConfig = reactive(superQuerySchema);

  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }

  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }

  function handleDetail(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: false,
    });
  }

  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }

  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }

  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
      },
    ];
  }

  function getDropDownAction(record) {
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
      },
    ];
  }
</script>

<style scoped>
  .form-item-custom {
    margin-bottom: 16px;
  }

  .select-custom {
    width: 100%;
  }

  .input-number-custom {
    width: 100%;
  }
</style>
