<script lang="ts" setup>
/**
 * @Name: EditDrawer.vue
 * @Description: 公司编辑
 * @Author: Cheney
 */

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


const loading = ref(false);
const isOpen = defineModel({ default: false });
const { companyOverview, company } = defineProps<{
  companyOverview: any;
  company: any;
}>();

const emit = defineEmits([ 'refresh' ]);

onBeforeMount(() => {
  replaceCol();
});

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

interface RuleForm {
  company: string;
  companyEnglishName: string;
  address: string;
  juridicalPerson: string;
  vatNumber: string;
  vatCompany: string;
  contacts: ContactItem[];
}

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

const rules = reactive<FormRules<RuleForm>>({
  company: [
    { required: true, message: 'Please input platform name', trigger: 'blur' }
  ],
  companyEnglishName: [
    { required: true, message: 'Please input platform name', trigger: 'blur' }
  ],
  address: [
    { required: true, message: 'Please input country name', trigger: 'blur' }
  ],
  juridicalPerson: [
    { required: true, message: 'Please input platform name', trigger: 'blur' }
  ],
  vatNumber: [
    { required: true, message: 'Please select line', trigger: 'change' }
  ],
  vatCompany: [
    { required: true, message: 'Please select line', trigger: 'change' }
  ],
  contacts: {
    phone: [ { required: true, message: '请输入电话号码', trigger: 'blur' } ],
    email: [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
    ]
  }
});

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

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

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const formData = {
        ...ruleForm,
        companyPhoneEmail: ruleForm.contacts.map(contact => ({
          email: contact.email,
          phone: contact.phone
        }))
      };
      await useResponse({ id: companyOverview.id, partial: 1, formData }, api.updateShopDetail, loading);
      isOpen.value = false;
      ElMessage.success('编辑成功');
      emit('refresh');
    } else {
      console.log('error submit!', fields);
    }
  });
};

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

function replaceCol() {
  const result = Object.keys(ruleForm).reduce((acc, key) => {
    if (key in companyOverview) {
      acc[key] = companyOverview[key];
    }
    return acc;
  }, {} as { [key: string]: any });

  // 处理 contacts 字段
  if (companyOverview.companyPhoneEmail) {
    result.contacts = cloneDeep(companyOverview.companyPhoneEmail);  // 深拷贝
  }

  Object.assign(ruleForm, result);
}
</script>

<template>
  <el-drawer v-model="isOpen" :title="`公司编辑 - ${company}`" size="30%">
    <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        class="mx-2.5 mt-2.5"
        label-width="auto"
        status-icon>
      <el-form-item label="公司名称" prop="platformNumber">
        <el-input v-model="ruleForm.company"/>
      </el-form-item>
      <el-form-item label="公司英文名" prop="platformName">
        <el-input v-model="ruleForm.companyEnglishName"/>
      </el-form-item>
      <el-form-item label="公司地址" prop="country">
        <el-input v-model="ruleForm.address"/>
      </el-form-item>
      <el-form-item label="公司法人" prop="brandName">
        <el-input v-model="ruleForm.juridicalPerson"/>
      </el-form-item>
      <el-form-item label="VAT税号" prop="status">
        <el-input v-model="ruleForm.vatNumber"/>
      </el-form-item>
      <el-form-item label="VAT税号公司" prop="platform">
        <el-input v-model="ruleForm.vatCompany"/>
      </el-form-item>

      <el-form-item
          v-for="(contact, index) in ruleForm.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-center">
          <el-button :icon="Plus" type="warning" @click="addContact">新增联系方式</el-button>
          <el-button :loading="loading" type="primary" @click="submitForm(ruleFormRef)">确 定</el-button>
          <el-button @click="resetForm(ruleFormRef)">重 置</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped>

</style>
