<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="500"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '编辑代报餐人员' : '添加代报餐人员'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    :maskClosable="false"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 24 }, sm: { span: 24 } }"
      layout="vertical"
    >
      <a-form-item label="代报餐人员" name="parentId">
        <SelectUser
          :placeholder="`请选择帮代报餐的人员`"
          v-model:value="parentName"
          @done="chooseParentId"
        />
      </a-form-item>
      <a-form-item label="报餐人姓名" name="userId">
        <SelectUser
          :placeholder="`请选择需要代报的人员`"
          v-model:value="nickName"
          @done="chooseUserId"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import type { BCAgent } from '@/api/apps/bc/agent/model';
  import { addBCAgent, updateBCAgent } from '@/api/apps/bc/agent';
  import { FormInstance, Rule } from 'ant-design-vue/es/form';
  import useFormData from '@/utils/use-form-data';
  import { User } from '@/api/user/model';

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: BCAgent | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  const formRef = ref<FormInstance | null>(null);
  // 是否是修改
  const isUpdate = ref(false);
  const parentName = ref();
  const nickName = ref();

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<BCAgent>({
    userId: undefined,
    parentId: undefined,
    sortNumber: 100
  });

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    parentId: [
      {
        required: true,
        message: '请选择代报餐的人员',
        type: 'number',
        trigger: 'blur'
      }
    ],
    userId: [
      {
        required: true,
        type: 'number',
        message: '请选择报餐的人员姓名',
        trigger: 'blur'
      }
    ]
  });

  const chooseUserId = (data: User) => {
    form.userId = data.userId;
    nickName.value = data.nickname;
  };

  const chooseParentId = (data: User) => {
    form.parentId = data.userId;
    parentName.value = data.nickname;
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const merchantForm = {
          ...form
        };
        const saveOrUpdate = isUpdate.value ? updateBCAgent : addBCAgent;
        saveOrUpdate(merchantForm)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            resetFields();
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          loading.value = false;
          assignFields({
            ...props.data
          });
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
  .ml-10 {
    margin-left: 5px;
  }
  .flex-sb {
    display: flex;
    justify-content: space-between;
  }
</style>
