<template>
  <PageWrapper>
    <el-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <el-input v-model="model[field]" />
        </template>
      </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"
        scroll-x="1200"
        virtual-scroll
      >
        <template #tableTitle>
          <el-space>
            <el-button type="primary" @click="addTenant" v-perm="['sys:tenant:add']">
              <template #icon>
                <el-icon style="vertical-align: middle">
                  <plus />
                </el-icon>
              </template>
              新建
            </el-button>

            <el-button type="danger" @click="handleDelete()" :disabled="!selectionData.length" v-perm="['sys:tenant:batchDelete']">
              <template #icon>
                <el-icon class="el-input__icon">
                  <Delete />
                </el-icon>
              </template>
              删除
            </el-button>
          </el-space>
        </template>
      </BasicTable>
    </el-card>
    <editDialog
        v-if="editVisible"
        :tenantId="tenantId"
        v-model:visible="editVisible"
        @success="reloadTable('noRefresh')"
    >
    </editDialog>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { h, nextTick, reactive, ref ,defineAsyncComponent} from 'vue';
  import { ColProps } from 'element-plus';
  import { TableAction } from '@/components/Table';
  import { useForm } from '@/components/Form/index';
  import { getTenantList,tenantDelete,tenantBatchDelete,tenantAccount } from '@/api/system/tenant';
  import {message,confirm} from "@/utils/auth";
  import { columns } from './columns';
  import { schemas } from './querySchemas';
  const tenantId =  ref(0);
  const tableRef = ref();
  const editVisible = ref(false)
  const selectionData = ref([])
  const editDialog = defineAsyncComponent(() =>
    import('./edit.vue'))
  const formParams = reactive({
    name: '',
    status:'',
  });


  const actionColumn = reactive({
    width: 320,
    label: '操作',
    prop: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
      return h(TableAction as any, {
        style: 'text',
        actions: [
          {
            label: '编辑',
            icon:'Edit',
            type: 'warning',
            onClick: handleEdit.bind(null, record),
            auth:['sys:tenant:update']
          },
          {
            label: '删除',
            icon:'Delete',
            type: 'danger',
            onClick: handleDelete.bind(null, record),
            auth:['sys:tenant:delete']
          },
          {
            label: '创建账号',
            icon:'Plus',
            type: 'warning',
            onClick: handleAddAccount.bind(null, record),
            auth:['sys:tenant:account']
          },
        ],
      });
    },
  });

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

  function reloadTable(noRefresh='') {
    tableRef.value.reload(noRefresh?{}:{pageNo:1});
  }

  async function handleEdit(record: Recordable) {
    tenantId.value=record.row.id
    await nextTick();
    editVisible.value=true
  }
  const handleAddAccount=async (recored: Recordable)=>{
      await tenantAccount({tenantId:recored.row.id})
      message("创建成功");
  }

  async function handleDelete(record: Recordable) {
    let ids = []
    if(!record){
      ids = selectionData.value.map(({id}) => id);
    }
    await confirm('确定要删除？');
    record? await tenantDelete(record.row.id):await tenantBatchDelete(ids);
    message("删除成功");
    reloadTable()
  }
  
  function handleSubmit(values: Recordable) {
    handleReset()
    for (const key in values) {
      formParams[key] = values[key]
    }
    reloadTable();
  }

  function handleReset() {
    for (const key in formParams) {
        formParams[key] ='';
    }
  }
  function onSelectionChange(value){
    selectionData.value = value
  }
  const [register, {}] = useForm({
    labelWidth: 80,
    layout: 'horizontal',
    colProps: { span: 6 } as ColProps,
    submitOnReset:true,
    schemas
  });
  //添加
  function addTenant() {
    tenantId.value =0
    editVisible.value  = true
  }

</script>

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