<template>
  <PageWrapper>
    <el-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset"></BasicForm>
    </el-card>
    <el-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="tableRef"
        :actionColumn="actionColumn"
         @selection-change="onSelectionChange"
      >
        <template #tableTitle>
          <el-space>
          <el-button type="primary" @click="handleAdd" v-perm="['sys:level:add']">
            <template #icon>
              <el-icon class="el-input__icon">
                <PlusOutlined />
              </el-icon>
            </template>
            添加职级
          </el-button>
          <el-button type="danger" @click="handleDelete()" :disabled="!selectionData.length"  v-perm="['sys:level:batchDelete']">
              <template #icon>
                <el-icon class="el-input__icon">
                  <Delete />
                </el-icon>
              </template>
              删除
            </el-button>
            <el-upload
            ref="upload"
            action="/api/level/import"
            :headers="uploadHeaders"
            :on-error="onError"
            :on-success="onSuccess"
            :before-upload="beforeUpload"
            :show-file-list="false"
            :limit="1"
            v-perm="['sys:level:import']"
          >
            <el-button type="primary">
              <template #icon>
                <el-icon class="el-input__icon">
                  <Upload />
                </el-icon>
              </template>
              导入
            </el-button>
          </el-upload>
            <el-button type="primary" @click="handleExport" :loading="exportLoading" :disabled="exportLoading" v-perm="['sys:level:export']">
              <template #icon>
                <el-icon class="el-input__icon">
                  <Download />
                </el-icon>
              </template>
              导出
            </el-button>
          </el-space>
        </template>
      </BasicTable>
    </el-card>

    <editDialog
        v-if="editVisible"
        :levelId="levelId"
        v-model:visible="editVisible"
        @success="reloadTable('noRefresh')"
    >
    </editDialog>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref, h,nextTick,defineAsyncComponent } from 'vue';
  import { ColProps,UploadInstance } from 'element-plus';
  import { schemas } from './querySchemas';
  import { useForm } from '@/components/Form/index';
  import { TableAction } from '@/components/Table';
  import { getLevelList,levelDelete,levelBatchDelete,levelExport } from '@/api/system/level';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import {message,confirm,loading, closeLoading} from "@/utils/auth";
  import { useUserStore } from '@/store/modules/user';
  const editDialog = defineAsyncComponent(() =>
    import('./edit.vue')
)
  const levelId =ref(0)
  const upload = ref<UploadInstance>();
  const exportLoading=ref(false)
  const editVisible=ref(false)
  const selectionData = ref([])
  const tableRef = ref();
  const formParams = reactive({
    name:'',
    status:''
  });
  const uploadHeaders = reactive({
    authorization:useUserStore().getToken
  });
  const actionColumn = reactive({
    width: 250,
    label: '操作',
    prop: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            icon:'Edit',
            type: 'warning',
            onClick: handleEdit.bind(null, record),
            auth: ['sys:level:update'],
          },
          {
            label: '删除',
            icon:'Delete',
            type: 'danger',
            onClick: handleDelete.bind(null, record),
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            auth: ['sys:level:delete'],
          },
        ],
      });
    },
  });

  const loadDataTable = async (res: any) => {
    const result = await getLevelList({ ...formParams, ...res });
    return result;
  };

  function reloadTable(noRefresh='') {
    tableRef.value.reload(noRefresh?{}:{pageNo:1});
  }
  const [register, {}] = useForm({
    labelWidth: 80,
    layout: 'horizontal',
    colProps: { span: 6 } as ColProps,
    submitOnReset:true,
    schemas
  });
  function handleSubmit(values: Recordable) {
    handleReset()
    for (const key in values) {
      formParams[key] = values[key]
    }
    reloadTable();
  }

  function handleReset() {
    for (const key in formParams) {
        formParams[key] ='';
    }
  }
  const handleAdd = async () => {
  levelId.value=0
  await nextTick();
  editVisible.value=true
};

const handleEdit = async (record: Recordable) => {
  levelId.value=record.row.id
  await nextTick();
  editVisible.value=true
};

async function handleDelete(record: Recordable) {
    let ids = []
    if(!record){
      ids = selectionData.value.map(({id}) => id);
    }
    await confirm('确定要删除？');
    record? await levelDelete(record.row.id):await levelBatchDelete(ids);
    message("删除成功");
    reloadTable()
  }
function onSelectionChange(value){
    selectionData.value = value
  }
  const beforeUpload = (file: UploadFile) => {
  const isLt2M = file.size / 1024 / 1024 < 200;
  if (!isLt2M) {
    message("大小不能超过200MB!", "error");
    return false;
  }
  if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
    message("请上传.xlsx .xls", "error");
    return false;
  }
  loading("上传中");
  return true;
};
const onSuccess = (file: UploadFile) => {
  upload.value!.clearFiles();
  closeLoading();
  if (file.code == 0) {
    message("导入成功,"+file.msg);
    reloadTable()
  } else {
    message(file.msg ? file.msg : "导入失败", "error");
  }
};
const onError = () => {
  upload.value!.clearFiles();
  closeLoading();
  message("导入失败", "error");
};
//导出
const handleExport = async()=>{
  exportLoading.value=true
  const data=await levelExport()
  window.open(data)
  exportLoading.value=false
  message("导出成功");
}
</script>

<style lang="scss" scoped></style>
