<script lang="ts" setup>
/**
 * @Name: CompanyCreate.vue
 * @Description: 新增公司
 * @Author: Cheney
 */

import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { useResponse } from '/@/utils/useResponse';
import * as api from '../api';
import { Delete, Finished, Plus, RefreshLeft } from '@element-plus/icons-vue';


const isOpen = defineModel({ default: false });
const emit = defineEmits([ 'refresh' ]);

const createLoading = ref(false);

interface ContactItem {
  phone: string;
  email: string;
}

interface RuleForm {
  name: string;
  address: string;
  enName: string;
  juridicalPerson: string;
  vatNumber: string;
  vatCompany: string;
  contacts: ContactItem[];
}

const ruleFormRef = ref<FormInstance>();
const form = reactive<RuleForm>({
  name: '',
  address: '',
  enName: '',
  juridicalPerson: '',
  vatNumber: '',
  vatCompany: '',
  contacts: [
    {
      phone: '',
      email: ''
    }
  ]
});

const rules = reactive<FormRules<RuleForm>>({
  name: [ { required: true, message: '请输入公司名称', trigger: 'blur' } ],
  enName: [ { required: true, message: '请输入公司英文名称', trigger: 'blur' } ],
  address: [ { required: true, message: '请输入公司地址', trigger: 'blur' } ],
  juridicalPerson: [ { required: true, message: '请输入公司法人', trigger: 'blur' } ],
  vatNumber: [ { required: true, message: '请输入VAT税号', trigger: 'blur' } ],
  vatCompany: [ { required: true, message: '请输入VAT税号公司', trigger: 'blur' } ],
  contacts: {
    phone: [ { required: true, message: '请输入电话号码', trigger: 'blur' } ],
    email: [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
    ]
  }
});

const addContact = () => {
  form.contacts.push({
    phone: '',
    email: ''
  });
};

const removeContact = (item: ContactItem) => {
  const index = form.contacts.indexOf(item);
  if (index !== -1) {
    form.contacts.splice(index, 1);
  }
};

async function create() {
  const body = {
    company: form.name,
    companyEnglishName: form.enName,
    address: form.address,
    juridicalPerson: form.juridicalPerson,
    vatNumber: form.vatNumber,
    vatCompany: form.vatCompany,
    companyPhoneEmail: form.contacts
  };
  await useResponse(body, api.createCompany, createLoading);
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await create();
      isOpen.value = false;
      emit('refresh');
    } else {
      console.log('error submit!', fields);
      ElMessage.error('请检查表单');
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<template>
  <el-dialog v-model="isOpen" :close-on-click-modal="false" title="新增公司" width="35%">
    <el-form
        ref="ruleFormRef"
        :model="form"
        :rules="rules"
        label-width="auto"
        status-icon
    >
      <el-form-item label="公司名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入公司名称"></el-input>
      </el-form-item>
      <el-form-item label="英文名称" prop="enName">
        <el-input v-model="form.enName" placeholder="请输入公司英文名称"></el-input>
      </el-form-item>
      <el-form-item label="公司地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入公司地址"></el-input>
      </el-form-item>
      <el-form-item label="公司法人" prop="juridicalPerson">
        <el-input v-model="form.juridicalPerson" placeholder="请输入公司法人"></el-input>
      </el-form-item>
      <el-form-item label="VAT税号" prop="vatNumber">
        <el-input v-model="form.vatNumber" placeholder="请输入VAT税号"></el-input>
      </el-form-item>
      <el-form-item label="VAT税号公司" prop="vatCompany">
        <el-input v-model="form.vatCompany" placeholder="请输入VAT税号公司"></el-input>
      </el-form-item>

      <el-form-item
          v-for="(contact, index) in form.contacts"
          :key="index"
          :label="'联系方式' + (index + 1)"
      >
        <div class="flex gap-2.5 items-start">
          <el-form-item
              :prop="'contacts.' + index + '.phone'"
          >
            <el-input
                v-model="contact.phone"
                placeholder="请输入电话"
            />
          </el-form-item>
          <el-form-item
              :prop="'contacts.' + index + '.email'"
              :rules="rules.contacts.email"
          >
            <el-input
                v-model="contact.email"
                placeholder="请输入邮箱"
            />
          </el-form-item>
          <el-button :icon="Delete" type="danger" @click.prevent="removeContact(contact)">
            删 除
          </el-button>
        </div>
      </el-form-item>

      <el-form-item>
        <div class="flex flex-1 justify-end">
          <el-button :icon="Plus" type="warning" @click="addContact">新增联系方式</el-button>
          <el-button :icon="Finished" :loading="createLoading" type="primary" @click="submitForm(ruleFormRef)">创 建
          </el-button>
          <el-button :icon="RefreshLeft" @click="resetForm(ruleFormRef)">重 置</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped>

</style>
