<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :width="800"
    :body-style="{
      height: '400px !important',
    }"
    wrapClassName="custom-modal-box"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <div class="custom-modal-padding-box">
      <NodeHead nodeName="基本信息" class="title" />
      <BasicForm @register="registerForm">
        <template #imgUpload="{ model }">
          <Upload v-model:value="model.filePath" listType="picture" />
        </template>
      </BasicForm>

      <div class="row-title-box">
        <NodeHead nodeName="联系人" class="row-title-title" />
        <a-button type="primary" @click="addConfig" class="custom-btn"> +增加 </a-button>
      </div>
      <a-radio-group v-model:value="defaultIndex" style="width: 100%">
        <a-form
          ref="formRef"
          :model="personList"
          name="personList"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 22 }"
          autocomplete="off"
          layout="vertical"
          class="custom-form-box"
        >
          <template v-for="(item, index) in personList.list" :key="index">
            <a-row style="border-bottom: 1px solid #ddd; padding: 12px 16px; margin-bottom: 16px">
              <a-col :span="18" style="color: #1c8dff">联系人{{ index + 1 }}</a-col>
              <a-col :span="6" align="right">
                <a-radio :value="index">默认</a-radio>
                <span @click="deleteConfig(index)" class="delete-span">删除</span>
              </a-col>
            </a-row>
            <a-row style="padding-left: 16px">
              <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 style="padding-left: 16px">
              <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>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import Upload from '/@/components/Form/src/components/Upload.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { addCustomer, updateCustomer, getCustomerInfo } from '/@/api/erp/customer/list';
  const { t } = useI18n();

  const FormSchema: FormSchema[] = [
    {
      field: 'name',
      label: '客户名称',
      component: 'Input',
      required: true,
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请输入客户名称',
      },
    },
    {
      field: 'typeId',
      label: '客户类型',
      component: 'DicSelect',
      required: true,
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请选择客户类型',
        itemId: '1679007059387240450',
        isShowAdd: false,
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'industry',
      label: '所在行业',
      component: 'Input',
      required: true,
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请输入所在行业',
      },
    },
    {
      field: 'sourceId',
      label: '来源',
      component: 'DicSelect',
      required: true,
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请选择来源',
        itemId: '1679008505423876097',
        isShowAdd: false,
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'scaleId',
      label: '规模',
      component: 'DicSelect',
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请选择规模',
        itemId: '1679009315172012034',
        isShowAdd: false,
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'natureId',
      label: '公司性质',
      component: 'DicSelect',
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请选择公司性质',
        itemId: '1679010661178691585',
        isShowAdd: false,
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'address',
      label: '地址',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入地址',
      },
    },
    {
      field: 'filePath',
      label: '图片上传',
      component: 'Upload',
      slot: 'imgUpload',
      colProps: { span: 24 },
    },
  ];

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

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

  const [registerForm, { setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    schemas: FormSchema,
    layout: 'vertical',
    showActionButtonGroup: false,
    rowProps: { gutter: 32 },
    actionColOptions: {
      span: 23,
    },
  });

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

    isUpdate.value = !!data?.isUpdate;
    state.value = data?.state;
    defaultIndex.value = 0;
    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getCustomerInfo(data.id);
      setFieldsValue({ ...record });
      personList.value.list = [...record.caseErpCustomerContacts];
      personList.value.list.some((x, idx) => {
        if (x.isDefault) {
          defaultIndex.value = idx;
          return true;
        }
        return false;
      });
    } 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 {
      const values = await validate();
      await formRef.value.validate();

      if (personList.value.list.length) {
        personList.value.list.map((x, idx) => (x.isDefault = idx === defaultIndex.value ? 1 : 0));
      }

      const info = {
        ...values,
        state: state.value,
        addCaseErpCustomerContactsDtoList: personList.value.list,
      };
      setModalProps({ confirmLoading: true });

      if (!unref(isUpdate)) {
        await addCustomer(info);
        notification.success({
          message: '新增客户',
          description: t('成功'),
        });
      } else {
        info.id = rowId.value;
        await updateCustomer(info);
        notification.success({
          message: '编辑客户',
          description: t('成功'),
        });
      }

      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  .sub-title {
    font-weight: 700;
    margin: 0 18px 18px;
  }

  .config-title {
    display: flex;
    justify-content: space-between;
    margin: 18px;
    font-weight: 700;

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

  .delete-span {
    width: 52px;
    height: 24px;
    background: rgb(255 84 97 / 8%);
    border-radius: 4px;
    border: 1px solid #ff5461;
    padding: 4px 12px;
    color: #ff8080;
    cursor: pointer;
  }

  .custom-modal-padding-box {
    height: 100%;
    padding: 16px 0;

    .title {
      padding: 0 16px 16px;
    }

    .row-title-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      padding-left: 16px;
    }

    .row-title-title {
      padding: 0 !important;
    }

    .custom-btn {
      width: 82px;
      height: 32px;
      background: #1c8dff;
      border-radius: 4px;
      margin-right: 16px;
      font-weight: 400;
      font-size: 14px;
      color: #fff;
    }
  }

  .custom-form-box {
    background: #f3f3f3;
    border-radius: 4px;
    margin: 0 16px;
  }
</style>
