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

import { useAccessStore } from '@vben/stores';

import { $t } from '@/locales';
import { Button, Input, message, Modal, Upload } from 'antdv-next';

import { addEnterpriseCustomerApi, updateEnterpriseCustomerApi } from '#/api';

interface Props {
  open: boolean;
  mode: 'add' | 'edit';
  customerData?: any;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (e: 'save', data: any): void;
  (e: 'update:open', value: boolean): void;
}>();

const accessStore = useAccessStore();

const token = accessStore.accessToken;

const formData = ref({
  code: '',
  id: '',
  fileId: '',
  imgLogoFileId: '',
  fileList: [] as any[],
  name: '',
  contact: '',
  cellPhone: '',
  email: '',
  address: '',
  website: '',
  remark: '',
});

watch(
  () => props.open,
  (val) => {
    if (val && props.mode === 'edit' && props.customerData) {
      Object.assign(formData.value, props.customerData);
      if (props.customerData.imgLogoFileId) {
        formData.value.fileList = [
          {
            uid: '-1',
            name: 'logo.png',
            status: 'done',
            url: `/File/Download?fileId=${props.customerData.imgLogoFileId}`,
            response: {
              result: [
                {
                  id: props.customerData.imgLogoFileId,
                },
              ],
            },
          },
        ];
      }
    }
    if (val && props.mode === 'add') {
      resetFormData();
    }
  },
);

const isOpen = computed({
  get: () => props.open,
  set: (val) => emit('update:open', val),
});

function handleLogoUpload(info: any) {
  if (info.file.status === 'done' && info.file.response?.result?.[0]?.id) {
    formData.value.fileId = info.file.response.result[0].id;
    formData.value.imgLogoFileId = info.file.response.result[0].id;
  }
}

async function handleSave() {
  const data = {
    id: formData.value.id,
    fileId: formData.value.fileId,
    imgLogoFileId: formData.value.imgLogoFileId,
    version: `v${formData.value.imgLogoFileId || '0'}`,
    code: formData.value.code,
    name: formData.value.name,
    contact: formData.value.contact,
    cellPhone: formData.value.cellPhone,
    email: formData.value.email,
    address: formData.value.address,
    website: formData.value.website,
    remark: formData.value.remark,
  };
  try {
    const result = formData.value.id
      ? await updateEnterpriseCustomerApi(data)
      : await addEnterpriseCustomerApi(data);
    if (result?.isSuccess) {
      emit('save', data);
      isOpen.value = false;
      message.success($t('enterpriseCustomers.saveSuccess'));
    }
  } catch {}
}

function handleCancel() {
  isOpen.value = false;
}

function resetFormData() {
  formData.value = {
    code: '',
    id: '',
    fileId: '',
    imgLogoFileId: '',
    fileList: [] as any[],
    name: '',
    contact: '',
    cellPhone: '',
    email: '',
    address: '',
    website: '',
    remark: '',
  };
}
</script>

<template>
  <Modal
    v-model:open="isOpen"
    :footer="null"
    :title="
      mode === 'add'
        ? $t('enterpriseCustomers.modal.addTitle')
        : $t('enterpriseCustomers.modal.editTitle')
    "
    width="800px"
  >
    <div class="overflow-y-auto p-6">
      <div class="space-y-6">
        <div class="flex items-center gap-4">
          <div class="flex flex-col gap-2">
            <label class="text-sm font-medium">{{
              $t('enterpriseCustomers.modal.enterpriseLogo')
            }}</label>
            <Upload
              v-model:file-list="formData.fileList"
              :action="`/fileApi/File/UploadFiles?Authorization=${token}`"
              :headers="{ Authorization: String(token) }"
              :max-count="1"
              list-type="picture-card"
              @change="handleLogoUpload"
            >
              <div
                class="flex h-[100px] w-[200px] items-center justify-center border-2 border-dashed"
              >
                <div class="text-center">
                  <div class="text-4xl">+</div>
                  <div class="text-sm text-gray-500">
                    {{ $t('enterpriseCustomers.modal.uploadLogo') }}
                  </div>
                </div>
              </div>
            </Upload>
          </div>
        </div>

        <div class="grid grid-cols-2 gap-6">
          <div class="flex flex-col gap-2">
            <label class="text-sm font-medium">{{
              $t('enterpriseCustomers.modal.customerCode')
            }}</label>
            <Input
              v-model:value="formData.code"
              :disabled="props.mode === 'edit'"
              :placeholder="$t('enterpriseCustomers.modal.enterCustomerCode')"
            />
          </div>
          <div class="flex flex-col gap-2">
            <label class="text-sm font-medium">{{
              $t('enterpriseCustomers.modal.customerName')
            }}</label>
            <Input
              v-model:value="formData.name"
              :placeholder="$t('enterpriseCustomers.modal.enterCustomerName')"
            />
          </div>
          <div class="flex flex-col gap-2">
            <label class="text-sm font-medium">{{
              $t('enterpriseCustomers.modal.contact')
            }}</label>
            <Input
              v-model:value="formData.contact"
              :placeholder="$t('enterpriseCustomers.modal.enterContact')"
            />
          </div>
          <div class="flex flex-col gap-2">
            <label class="text-sm font-medium">{{
              $t('enterpriseCustomers.modal.cellPhone')
            }}</label>
            <Input
              v-model:value="formData.cellPhone"
              :placeholder="$t('enterpriseCustomers.modal.enterCellPhone')"
            />
          </div>
          <div class="flex flex-col gap-2">
            <label class="text-sm font-medium">{{
              $t('enterpriseCustomers.modal.email')
            }}</label>
            <Input
              v-model:value="formData.email"
              :placeholder="$t('enterpriseCustomers.modal.enterEmail')"
            />
          </div>
          <div class="flex flex-col gap-2">
            <label class="text-sm font-medium">{{
              $t('enterpriseCustomers.modal.website')
            }}</label>
            <Input
              v-model:value="formData.website"
              :placeholder="$t('enterpriseCustomers.modal.enterWebsite')"
            />
          </div>
          <div class="flex flex-col gap-2">
            <label class="text-sm font-medium">{{
              $t('enterpriseCustomers.modal.address')
            }}</label>
            <Input
              v-model:value="formData.address"
              :placeholder="$t('enterpriseCustomers.modal.enterAddress')"
            />
          </div>
          <div class="flex flex-col gap-2">
            <label class="text-sm font-medium">{{
              $t('enterpriseCustomers.modal.remark')
            }}</label>
            <Input
              v-model:value="formData.remark"
              :placeholder="$t('enterpriseCustomers.modal.enterRemark')"
              :rows="3"
            />
          </div>
        </div>
      </div>
    </div>

    <div class="flex justify-end gap-2 border-t pt-4">
      <Button @click="handleCancel">
        {{ $t('enterpriseCustomers.modal.cancel') }}
      </Button>
      <Button type="primary" @click="handleSave">
        {{ $t('enterpriseCustomers.modal.save') }}
      </Button>
    </div>
  </Modal>
</template>

<style lang="scss">
.ant-menu-light .ant-menu-item-selected,
.ant-menu-light > .ant-menu .ant-menu-item-selected {
  background-color: #f4f2f2;

  .ant-menu-title-content {
    color: #462424;
  }
}

.ant-table-wrapper .ant-table-tbody > tr > th,
.ant-table-wrapper .ant-table-tbody > tr > td {
  padding: 8px 16px;
}

.ant-table-wrapper .ant-table-thead > tr > th,
.ant-table-wrapper .ant-table-thead > tr > td {
  padding: 8px 16px;
}
</style>
