<script setup lang="tsx">
import { nextTick, ref } from 'vue';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import type { InternalRowData } from 'naive-ui/es/data-table/src/interface';
import { enableStatusRecord } from '@/constants/business';
import {
  fetchAddDepartment,
  fetchDeleteDepartment,
  fetchEditDepartment,
  fetchGetDepartmentList
} from '@/service/api/system-department';
import { useAppStore } from '@/store/modules/app';
import { $t } from '@/locales';
import { useForm } from '@/components/zt/Form/hooks/useForm';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
import { formSchems, searchSchems } from './department.data';
const appStore = useAppStore();
const checkedRowKeys = ref([]);

const wrapperRef = ref<HTMLElement | null>(null);
const deptData = ref<Api.SystemManage.DepartmentModel[]>([]);
const loading = ref(false);

const [registerForm, { setFieldsValue, validate, getFieldsValue, updateSchema }] = useForm({
  schemas: formSchems,
  showSubmitButton: false,
  showAdvancedButton: false,
  showResetButton: false,
  labelWidth: 120,
  showActionButtonGroup: false,
  layout: 'horizontal',
  gridProps: {
    cols: 1,
    itemResponsive: true
  },
  collapsedRows: 1
});
const [registerSearchForm, { getFieldsValue: getSeachForm }] = useForm({
  labelWidth: 120,
  layout: 'horizontal',
  gridProps: {
    cols: '1 xl:4 s:1 l:3',
    itemResponsive: true
  },
  collapsedRows: 1,
  schemas: searchSchems
});

const colums: NaiveUI.TableColumn<InternalRowData>[] = [
  {
    key: 'deptId',
    title: '部门ID',
    align: 'center'
  },
  {
    key: 'deptName',
    title: '部门名称',
    align: 'center',
    minWidth: 120
  },
  {
    key: 'leaderUserName',
    title: '部门负责人',
    align: 'center'
  },
  {
    key: 'phone',
    title: '负责人电话',
    align: 'center'
  },
  {
    key: 'seq',
    title: '排序',
    align: 'center'
  },
  {
    key: 'status',
    title: '状态',
    align: 'center',
    width: 60,
    render: (row: InternalRowData) => {
      const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
        1: 'success',
        0: 'warning'
      };
      const status = row.status as Api.Common.EnableStatus;
      const label = $t(enableStatusRecord[status]);
      return <NTag type={tagMap[status]}>{label}</NTag>;
    }
  },
  {
    key: 'createTime',
    title: '创建时间',
    align: 'center',
    width: 160
  },
  {
    key: 'operate',
    title: $t('common.operate'),
    align: 'center',
    width: 130,
    fixed: 'right',
    render: (row: any) => (
      <div class="flex-center justify-end gap-8px">
        <NButton type="primary" ghost size="small" onClick={() => handleEdit(row)}>
          {$t('common.edit')}
        </NButton>
        {row.deptId != 1 && (
          <NPopconfirm onPositiveClick={() => handleDelete(row)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        )}
      </div>
    )
  }
];
const [registerModal, { openModal, setModalProps, setSubLoading, closeModal }] = useModal({
  title: '部门',
  width: 800,
  isShowHeaderText: false
});
// const { checkedRowKeys, onBatchDeleted, onDeleted } = useTableOperate(data, 'id', getData);
function handleAdd() {
  setModalProps({
    title: '新增部门'
  });
  openModal();
}

async function handleBatchDelete() {
  // request
  console.log(checkedRowKeys.value);
}

async function handleDelete(row: Recordable) {
  // request
  loading.value = true;
  await fetchDeleteDepartment(row.deptId);
  getDepartment({});
  loading.value = false;
}

function handleEdit(item: Api.SystemManage.DepartmentModel) {
  setModalProps({
    title: '编辑部门'
  });
  openModal(item);
  nextTick(async () => {
    await setFieldsValue(item);
    if (item.level == 1 && item.deptId == 1) {
      updateSchema([{ field: 'parentId', componentProps: { disabled: true } }]);
    }
  });
}
async function getDepartment(seachForm: Recordable) {
  console.log(seachForm);

  loading.value = true;
  const { data } = await fetchGetDepartmentList(seachForm as Recordable);
  deptData.value = data as Api.SystemManage.DepartmentModel[];
  loading.value = false;
}

// init
getDepartment({});

async function handleSubmit() {
  setSubLoading(false);
  await validate();
  setSubLoading(true);
  const form = getFieldsValue();
  const { error } = form.deptId ? await fetchEditDepartment(form) : await fetchAddDepartment(form);
  if (!error) {
    closeModal();
    getDepartment({});
  }
}
</script>

<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard :bordered="false" size="small">
      <NCollapse display-directive="show" :default-expanded-names="['dept-search']">
        <NCollapseItem title="搜索" name="dept-search">
          <BasicForm
            @register-form="registerSearchForm"
            @submit="getDepartment(getSeachForm())"
            @reset="getDepartment({})"
          />
        </NCollapseItem>
      </NCollapse>
    </NCard>
    <NCard title="部门列表" :bordered="false" size="small" class="card-wrapper sm:flex-1-hidden">
      <template #header-extra>
        <TableHeaderOperation
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          is-add
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getDepartment({})"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="colums"
        :data="deptData"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1088"
        :loading="loading"
        :row-key="row => row.deptId"
        remote
        class="sm:h-full"
      />
      <BasicModal @register="registerModal" @ok="handleSubmit">
        <BasicForm @register-form="registerForm">
          <template #parentId="{ model, field }">
            <NTreeSelect
              v-model:value="model[field]"
              :options="deptData"
              label-field="deptName"
              key-field="deptId"
            ></NTreeSelect>
          </template>
        </BasicForm>
      </BasicModal>
    </NCard>
  </div>
</template>

<style scoped></style>
