<template>
  <Spin :spinning="loading">
    <BasicForm @register="registerForm" />
    <div class="j-box-bottom-button-new">
      <div class="j-box-bottom-button-float">
        <c-button v-if="syncFlag === 0" preIcon="ant-design:sync-outlined" type="primary" @click="baseAddDept"
          >部门下发</c-button
        >
        <c-button preIcon="ant-design:sync-outlined" @click="onReset">重置</c-button>
        <c-button
          v-show="hasPermission('system:depart:basicInfo')"
          type="primary"
          preIcon="ant-design:save-filled"
          @click="onSubmit"
          >保存</c-button
        >
      </div>
    </div>
  </Spin>
</template>

<script lang="ts" setup>
  import { watch, computed, ref, unref, onMounted } from 'vue';
  import { BasicForm, useForm } from '@jdlinker/ui';
  import { saveOrUpdateDepart, syncAddDept } from '../depart.api';
  import { useBasicFormSchema, orgCategoryOptions } from '../depart.data';
  import { usePermission } from '@jdlinker/func';
  import { Spin } from 'ant-design-vue';

  const { hasPermission } = usePermission();
  const emit = defineEmits(['success']);
  const props = defineProps({
    data: { type: Object, default: () => ({}) },
    rootTreeData: { type: Array, default: () => [] }
  });
  const loading = ref<boolean>(false);
  // 当前是否是更新模式
  const isUpdate = ref<boolean>(true);
  // 当前的弹窗数据
  const model = ref<object>({});
  const syncFlag = ref(0);

  //注册表单
  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: useBasicFormSchema().basicFormSchema,
    showActionButtonGroup: false
  });

  const categoryOptions = computed(() => {
    if (!!props?.data?.parentId) {
      return orgCategoryOptions.child;
    } else {
      return orgCategoryOptions.root;
    }
  });

  onMounted(() => {
    // 禁用字段
    updateSchema([
      { field: 'parentId', componentProps: { disabled: true } },
      { field: 'orgCode', componentProps: { disabled: true } }
    ]);
    // data 变化，重填表单
    watch(
      () => props.data,
      async () => {
        let record: any = unref(props.data);
        if (typeof record !== 'object') {
          record = {};
        }
        model.value = record;
        await resetFields();
        await setFieldsValue({ ...record });
        syncFlag.value = record.syncFlag;
      },
      { deep: true, immediate: true }
    );
    // 更新 父部门 选项
    watch(
      () => props.rootTreeData,
      async () => {
        updateSchema([
          {
            field: 'parentId',
            componentProps: { treeData: props.rootTreeData }
          }
        ]);
      },
      { deep: true, immediate: true }
    );
    // 监听并更改 orgCategory options
    watch(
      categoryOptions,
      async () => {
        updateSchema([
          {
            field: 'orgCategory',
            componentProps: { options: categoryOptions.value }
          }
        ]);
      },
      { immediate: true }
    );
  });

  // 重置表单
  async function onReset() {
    await resetFields();
    await setFieldsValue({ ...model.value });
  }

  // 提交事件
  async function onSubmit() {
    try {
      loading.value = true;
      let values = await validate();
      values = Object.assign({}, model.value, values);
      //提交表单
      await saveOrUpdateDepart(values, isUpdate.value);
      //刷新列表
      emit('success');
      Object.assign(model.value, values);
    } finally {
      loading.value = false;
    }
  }

  // 下发部门到捷顺
  function baseAddDept() {
    syncAddDept(props.data).then(() => {
      syncFlag.value = 1;
      setFieldsValue({ syncFlag: 1 });
      emit('success');
    });
  }
</script>
<style>
  .j-box-bottom-button-new {
    height: 55px;
  }
</style>
