<template>
  <a-card title="" :bordered="false">
    <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam"
            :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row>
        <a-col :span="4">
          <a-form-item label="手机号">
            <a-input v-model:value="queryParam.phone" placeholder="请输入手机号" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
          <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
<!--          <a-button type="primary" preIcon="ant-design:export-outlined" @click="exportXls" style="margin: 8px">导出</a-button>-->
<!--          <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls" style="margin-left: 8px">导入</j-upload-button>-->
        </a-col>
      </a-row>
    </a-form>
    <JVxeTable
      toolbar
      :toolbarConfig="toolbarConfig"
      rowNumber
      rowSelection
      keepSource
      asyncRemove
      :height="500"
      :loading="loading"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="pagination"
      @save="handleTableSave"
      @removed="handleTableRemove"
      @edit-closed="handleEditClosed"
      @pageChange="handlePageChange"
      @valueChange="handleValueChange"
      @selectRowChange="handleSelectRowChange"
    />
  </a-card>
</template>

<script lang="ts" setup>
// 即时保存示例
import {reactive, ref} from 'vue';
import { message } from 'ant-design-vue';
import {defHttp} from '/@/utils/http/axios';
import {JVxeColumn, JVxeTypes} from '/@/components/jeecg/JVxeTable/types';
import {useMessage} from '/@/hooks/web/useMessage';
import {useListPage} from "@/hooks/system/useListPage";
import {getExportUrl, getImportUrl, list} from "@/views/yx/yxHistoryMajorEnroll/YxHistoryMajorEnroll.api";
import {XLSX_FILE_SUFFIX, XLSX_MIME_TYPE} from "@/hooks/system/useMethods";
import { render } from "@/utils/common/renderUtils";
const { createMessage, createConfirm, createSuccessModal, createInfoModal, createErrorModal, createWarningModal, notification } = useMessage();
const labelCol = reactive({
  xs: {span: 24},
  sm: {span: 7},
});
const wrapperCol = reactive({
  xs: {span: 24},
  sm: {span: 16},
});
// 工具栏的按钮配置
const toolbarConfig = reactive({
  // add 新增按钮；remove 删除按钮；clearSelection 清空选择按钮
  // btn: ['add', 'save', 'remove', 'clearSelection'],
  btn: [],
});
// 是否正在加载
const loading = ref(false);
// 查询参数
const queryParam = reactive({
  phone: '',
})
// 分页器参数
const pagination = reactive({
  // 当前页码
  current: 1,
  // 每页的条数
  pageSize: 10,
  // 可切换的条数
  pageSizeOptions: ['10', '20', '30', '100', '200'],
  // 数据总数（目前并不知道真实的总数，所以先填写0，在后台查出来后再赋值）
  total: 0,
});
// 选择的行
const selectedRows = ref<Recordable[]>([]);
// 数据源，控制表格的数据
const dataSource = ref<Recordable[]>([]);
// 列配置，控制表格显示的列
const columns = ref<JVxeColumn[]>([
  /*{ key: 'num', title: '序号', width: 80, type: JVxeTypes.normal },*/
  {
    title: '用户账号',
    key: 'username',
    type: JVxeTypes.input,
  },
  {
    title: '用户姓名',
    key: 'realname',
    type: JVxeTypes.input,
  },
  {
    title: '性别',
    key: 'sex',
  },
  {
    title: '手机号',
    key: 'phone',
    type: JVxeTypes.input,
  },
  {
    title: '显示历年线差',
    key: 'showLinediff',
    type: JVxeTypes.checkbox,
    width: 100,
    customValue: ['1', '0'], // true ,false
  },
  {
    title: '状态',
    key: 'status_dictText',
    width: 150,
  },
]);
const [messageApi, contextHolder] = message.useMessage();
const { prefixCls,tableContext,onImportXls } = useListPage({
  tableProps:{
    title: '历年录取数据表',
    canResize:false,
  },
  importConfig:{
    url: getImportUrl,
    success: handleSuccess
  }
})

// 查询url地址
enum Api {
  getData = '/sys/user/list',
  // 模拟保存单行数据（即时保存）
  saveRow = '/sys/user/edit',
  // 模拟保存整个表格的数据
  saveAll = '/yx/yxHistoryMajorEnroll/saveBatch',
  deleteBatch = '/yx/yxHistoryMajorEnroll/deleteBatch',
  importExcel = '/yx/yxHistoryMajorEnroll/importExcel',
  exportXls = '/yx/yxHistoryMajorEnroll/exportXlsBySchoolMajor',
  renewControlLine = '/yx/yxHistoryMajorEnroll/renewControlLine'
}

loadData();

async function searchQuery() {
  pagination.current = 1
  loadData()
}


async function searchReset() {
  pagination.current = 1
  queryParam.phone = ''
  loadData()
}

// 加载数据
async function loadData() {
  loading.value = true;
  // 调用查询数据接口
  await defHttp
    .get({
      // 请求地址
      url: Api.getData,
      // 封装查询条件
      params: {
        phone: queryParam.phone ? '*' + queryParam.phone + '*' : '',
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
      },
    })
    .then((result) => {
      // 后台查询回来的 total，数据总数量
      pagination.total = result.total;
      // 将查询的数据赋值给 dataSource
      dataSource.value = result.records;
      // 重置选择
      selectedRows.value = [];
    })
    .finally(() => {
      // 这里是无论成功或失败都会执行的方法，在这里关闭loading
      loading.value = false;
    });
}


// 【整体保存】点击保存按钮时触发的事件
function handleTableSave({$table, target}) {
  // 校验整个表格
  $table.validate().then((errMap) => {
    // 校验通过
    if (!errMap) {
      // 获取所有数据
      let tableData = target.getTableData();
      console.log('当前保存的数据是：', tableData);
      // 获取新增的数据
      let newData = target.getNewData();
      console.log('-- 新增的数据：', newData);
      // 获取删除的数据
      let deleteData = target.getDeleteData();
      console.log('-- 删除的数据：', deleteData);
      // 【模拟保存】
      loading.value = true;
      defHttp
        .post({
          url: Api.saveAll,
          params: tableData,
        })
        .then(() => {
          createMessage.success(`保存成功！`);
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

// 触发单元格删除事件
function handleTableRemove(event) {
  // 把 event.deleteRows 传给后台进行删除（注意：这里不会传递前端逻辑新增的数据，因为不需要请求后台删除）
  console.log('待删除的数据: ', event.deleteRows);
  // 也可以只传ID，因为可以根据ID删除
  let deleteIds = event.deleteRows.map((row) => row.id);
  console.log('待删除的数据ids: ', deleteIds);
  // 模拟请求后台删除
  loading.value = true;
  window.setTimeout(() => {
    defHttp
      .delete({
        url: Api.deleteBatch, data: {ids: deleteIds.join(',')}
      }, {joinParamsToUrl: true})
      .then((res) => {
        createMessage.success('删除成功');
        //// 假设后台返回删除成功，必须要调用 confirmRemove() 方法，才会真正在表格里移除（会同时删除选中的逻辑新增的数据）
        event.confirmRemove();
      })
      .finally(() => {
        loading.value = false;
      });
  }, 1000);
}


function handleValueChange(event) {
  console.log('handleValueChange.event: ', event);
  let {$table, row, column} = event;
  let field = column.property;
  console.log(row)
  handleEditClosed(event)
}

// 单元格编辑完成之后触发的事件
function handleEditClosed(event) {
  let {$table, row, column} = event;
  let field = column.property;
  // 判断单元格值是否被修改
  if ($table.isUpdateByRow(row, field)) {
    // 校验当前行
    $table.validate(row).then((errMap) => {
      // 校验通过
      if (!errMap) {
        // 【模拟保存】
        let hideLoading = createMessage.loading(`正在保存"${column.title}"`, 0);
        console.log('即时保存数据：', row);
        defHttp
          .put({
            url: Api.saveRow,
            params: row,
          })
          .then((res) => {
            createMessage.success(`"${column.title}"保存成功！`);
            // 局部更新单元格为已保存状态
            $table.reloadRow(row, null, field);
          })
          .finally(() => {
            hideLoading();
          });
      }
    });
  }
}

// 当分页参数变化时触发的事件
function handlePageChange(event) {
  // 重新赋值
  pagination.current = event.current;
  pagination.pageSize = event.pageSize;
  // 查询数据
  loadData();
}
/**
 * 成功回调
 */
function handleSuccess() {
  loadData();
}

// 当选择的行变化时触发的事件
function handleSelectRowChange(event) {
  selectedRows.value = event.selectedRows;
}


/**
 * 导出xls
 * @param name
 * @param url
 */
async function exportXls(isXlsx = false) {
  let name = ''
  let selections = ''
  if (selectedRows.value) {
    selectedRows.value.forEach(i=>{
      selections+=i.id+","
    })
    console.log(selectedRows.value)
  }
  const data = await defHttp.get({ url: Api.exportXls, params: {selections:selections}, responseType: 'blob', timeout: 60000 }, { isTransformResponse: false });
  if (!data) {
    createMessage.warning('文件下载失败');
    return;
  }
  if (!name || typeof name != 'string') {
    name = '导出文件';
  }
  let blobOptions = { type: 'application/vnd.ms-excel' };
  let fileSuffix = '.xls';
  if (isXlsx === true) {
    blobOptions['type'] = XLSX_MIME_TYPE;
    fileSuffix = XLSX_FILE_SUFFIX;
  }
  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    window.navigator.msSaveBlob(new Blob([data], blobOptions), name + fileSuffix);
  } else {
    let url = window.URL.createObjectURL(new Blob([data], blobOptions));
    let link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    link.setAttribute('download', name + fileSuffix);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link); //下载完成移除元素
    window.URL.revokeObjectURL(url); //释放掉blob对象
  }
}

</script>

<style scoped></style>
