<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :width="800"
    :body-style="{
      height: '400px !important',
    }"
    :title="getTitle"
    @ok="handleSubmit"
    wrapClassName="custom-modal-box"
  >
    <div class="config-title">
      <span class="font-semibold">联系人</span>
      <span class="add-span" @click="addConfig" v-if="!isUpdate">+ 增加</span>
    </div>
    <a-radio-group v-model:value="defaultIndex" style="width: 100%">
      <a-form
        ref="formRef"
        :model="personList"
        name="personList"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
        layout="vertical"
        autocomplete="off"
      >
        <template v-for="(item, index) in personList.list" :key="index">
          <a-row style="margin: 0 0 20px 10px">
            <a-col :span="20" style="color: #999">联系人{{ index + 1 }}</a-col>
            <a-col :span="4" align="right">
              <a-radio :value="index">默认</a-radio>
              <span @click="deleteConfig(index)" class="delete-span" v-if="index !== 0">删除</span>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item
                label="姓名"
                :name="['list', index, 'name']"
                :rules="{ required: true, message: '请输入姓名', trigger: 'change' }"
              >
                <a-input v-model:value="item.name" placeholder="请输入姓名" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="电话" :name="['list', index, 'phone']">
                <a-input v-model:value="item.phone" placeholder="请输入电话" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="职位" :name="['list', index, 'post']">
                <a-input v-model:value="item.post" placeholder="请输入职位" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="部门" :name="['list', index, 'dept']">
                <a-input v-model:value="item.dept" placeholder="请输入部门" />
              </a-form-item>
            </a-col>
          </a-row>
        </template>
      </a-form>
    </a-radio-group>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { addContacts, updateContacts, getContactsInfo } from '/@/api/erp/customer/list';
  const { t } = useI18n();

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');
  const customerId = ref('');
  const defaultIndex = ref<any>();
  const formRef = ref();
  const personList = ref<any>({
    list: [
      {
        isDefault: false,
        dept: '',
        name: '',
        phone: '',
        post: '',
      },
    ],
  });

  const emit = defineEmits(['success', 'register']);

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false, destroyOnClose: true });

    isUpdate.value = !!data?.isUpdate;
    customerId.value = data.customerId;
    defaultIndex.value = null;

    if (unref(isUpdate)) {
      rowId.value = data.id;
      const info = await getContactsInfo(data.id);
      personList.value.list[0] = info;
      defaultIndex.value = info.isDefault ? 0 : null;
    } else {
      personList.value = {
        list: [
          {
            isDefault: false,
            dept: '',
            name: '',
            phone: '',
            post: '',
          },
        ],
      };
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增联系人' : '编辑联系人'));

  const addConfig = () => {
    personList.value.list.push({ isDefault: false, dept: '', name: '', phone: '', post: '' });
  };

  const deleteConfig = (index) => {
    personList.value.list.splice(index, 1);
  };

  async function handleSubmit() {
    try {
      await formRef.value.validate();
      personList.value.list.map((x, idx) => {
        x.isDefault = idx === defaultIndex.value ? 1 : 0;
      });

      setModalProps({ confirmLoading: true });

      if (!unref(isUpdate)) {
        const params = {
          customerId: customerId.value,
          caseErpCustomerContactsDtoList: [...personList.value.list],
        };
        await addContacts(params);
        notification.success({
          message: '新增联系人',
          description: t('成功'),
        });
      } else {
        const params = {
          id: rowId.value,
          customerId: customerId.value,
          ...personList.value.list[0],
        };
        await updateContacts(params);
        notification.success({
          message: '编辑联系人',
          description: t('成功'),
        });
      }
      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  .config-title {
    display: flex;
    justify-content: space-between;
    margin: 18px;
    font-weight: 700;

    .add-span {
      color: #5e95ff;
      cursor: pointer;
    }
  }

  .delete-span {
    color: #ff8080;
    cursor: pointer;
  }
</style>
