<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue';

import {
  addTeamManager,
  updateTeamManager,
} from '#/api/legacy/team';
import AccountInput from '#/components/account-input.vue';
import SystemRegionSelect from '#/views/operate/components/system-region-select.vue';

import {
  Form,
  FormItem,
  Input,
  Modal,
  message,
} from 'antdv-next';

const props = defineProps<{
  open: boolean;
  row: null | Record<string, any>;
  sysOrigin: string;
}>();

const emit = defineEmits<{
  close: [];
  success: [];
}>();

const saving = ref(false);

const form = reactive({
  contact: '',
  id: '',
  regionId: '',
  sysOrigin: '',
  userId: '',
});

const isUpdate = computed(() => Boolean(props.row?.id));
const title = computed(() => (isUpdate.value ? '修改经理' : '添加经理'));

watch(
  () => props.open,
  (open) => {
    if (!open) {
      return;
    }
    form.id = String(props.row?.id || '');
    form.userId = String(props.row?.userId || props.row?.userProfile?.id || '');
    form.sysOrigin = props.row?.sysOrigin || props.sysOrigin || 'LIKEI';
    form.contact = props.row?.contact || '';
    form.regionId = String(props.row?.regionId || '');
  },
  { immediate: true },
);

async function handleSubmit() {
  if (!isUpdate.value && !String(form.userId || '').trim()) {
    message.warning('请输入经理用户ID');
    return;
  }
  if (!form.regionId) {
    message.warning('请选择区域');
    return;
  }
  saving.value = true;
  try {
    const payload = {
      contact: form.contact.trim(),
      id: form.id || undefined,
      regionId: form.regionId,
      sysOrigin: form.sysOrigin,
      userId: form.userId,
    };
    if (isUpdate.value) {
      await updateTeamManager(payload);
    } else {
      await addTeamManager(payload);
    }
    message.success('保存成功');
    emit('success');
    emit('close');
  } finally {
    saving.value = false;
  }
}
</script>

<template>
  <Modal
    :confirm-loading="saving"
    destroy-on-close
    :open="open"
    :title="title"
    @cancel="emit('close')"
    @ok="handleSubmit"
  >
    <Form layout="vertical">
      <FormItem v-if="!isUpdate" label="经理ID">
        <AccountInput
          v-model:value="form.userId"
          placeholder="经理用户ID"
          :sys-origin="form.sysOrigin"
        />
      </FormItem>
      <FormItem label="区域">
        <SystemRegionSelect
          v-model:value="form.regionId"
          placeholder="请选择区域"
          :sys-origin="form.sysOrigin"
        />
      </FormItem>
      <FormItem label="联系方式">
        <Input v-model:value="form.contact" placeholder="联系方式" />
      </FormItem>
    </Form>
  </Modal>
</template>
