<template>
  <a-drawer
    :title="modalTitle"
    :maskClosable="true"
    width="850"
    placement="right"
    :closable="true"
    @close="handleCancel"
    v-model:open="modalVisible"
    :ok-button-props="okBtnStatus"
    destroy-on-close
    style="overflow: auto; padding-bottom: 53px"
  >
    <a-form ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="企业名称" name="companyName">
        <a-input :auto-size="{ minRows: 0, maxRows: 255 }" placeholder="请输入企业名称" v-model:value="companyName" />
      </a-form-item>
      <div v-for="(item, index) in setEnquiryForm.emailList" :key="index">
        <a-form-item
          label="询盘接收邮箱："
          :name="'emailList.' + index + '.email'"
          :rules="[{ required: false, message: '邮箱不能为空', trigger: 'change' }]"
        >
          <a-input style="width: 250px; margin-right: 20px" v-model:value="item.email" />
          <a-button
            v-show="index === setEnquiryForm.emailList.length - 1"
            style="margin-right: 10px"
            type="primary"
            @click="handleSetEnquiryFormInput(item, index, true)"
            >+
          </a-button>
          <a-button v-show="setEnquiryForm.emailList.length !== 1" @click="handleSetEnquiryFormInput(item, index, false)">-</a-button>
        </a-form-item>
      </div>
      <a-button style="margin-left: 25px" @click="clearSetEnquiryEmailList()">清空全部邮箱</a-button>
      <p style="color: red; margin-left: 25px">Tips:设置该邮箱用于接收通过Adweb发送询盘~~</p>
    </a-form>

    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }"
    >
      <a-button type="primary" @click="submitSetEnquiry" v-if="okBtnStatus" :loading="spinning"> 提交 </a-button>
    </div>
  </a-drawer>
</template>
<script setup lang="ts">
  import { reactive, ref } from 'vue';
  import { getAction, postAction, postActionForm } from '/@/api/manage/manage';
  import { useMessage } from '@/hooks/web/useMessage';
  import { Modal } from 'ant-design-vue';
  const { createMessage } = useMessage();

  const modalTitle = ref('询盘设置');

  const labelCol = reactive({ span: 3 });
  const wrapperCol = reactive({ span: 21 });
  let siteInfo = reactive({ id: '', code: '', domain: '', name: '' });
  const spinning = ref(false);
  const tipTitle = ref('');

  const okBtnStatus = ref(true);
  const modalVisible = ref(false);

  let setEnquiryForm = ref({
    isSendEmailByAdweb: false,
    emailList: [{ email: '' }],
  });
  let setEnquiryUrl = '/adweb/adwebSiteManage/setEnquiryEmailListBySiteCode';
  const emit = defineEmits(['success']);
  const companyName = ref('');

  function init(record) {
    modalVisible.value = true;
    companyName.value = record.companyName;
    siteInfo = record;
    setEnquiryForm.value.emailList = [];

    if (record.enquiryEmailList) {
      //r.enquiryEmailList 转数组并去除[]""
      let split = record.enquiryEmailList.replace(/[\[\]"]/g, '').split(',');

      split.forEach(function (item) {
        setEnquiryForm.value.emailList.push({
          email: item,
        });
      });
    } else {
      setEnquiryForm.value.emailList = [
        {
          email: '',
        },
      ];
    }
  }

  function handleCancel() {
    cleanAllFormData();
  }

  function cleanAllFormData() {
    okBtnStatus.value = true;

    spinning.value = false;
    tipTitle.value = '';

    modalVisible.value = false;
    modalTitle.value = '';
  }

  function handleSetEnquiryFormInput(item, index, flag) {
    if (setEnquiryForm.value.emailList.length === 1 && !flag) {
      createMessage.warning('无法再减少输入框！');
      return;
    } else if (setEnquiryForm.value.emailList.length === 10 && flag) {
      createMessage.warning('无法再增加输入框！');
      return;
    }
    flag ? setEnquiryForm.value.emailList.push({ email: '' }) : setEnquiryForm.value.emailList.splice(index, 1);
  }

  function clearSetEnquiryEmailList() {
    Modal.confirm({
      title: '提示',
      content: `是否清空询盘邮箱列表？`,
      centered: true,
      closable: true,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setEnquiryForm.value.emailList = [{ email: '' }];
      },
    });
  }

  function submitSetEnquiry() {
    spinning.value = true;
    let emailList = [];

    setEnquiryForm.value.emailList.forEach((item) => {
      emailList.push(item.email.trim());
    });
    let params = new FormData();
    params.append('siteCode', siteInfo.code);
    if (companyName.value) {
      params.append('companyName', companyName.value);
    }

    params.append('emailList', emailList);
    postActionForm(setEnquiryUrl, params, 120000)
      .then(function (res) {
        if (res.code == 200) {
          createMessage.success(res.message);
          setEnquiryForm.value.emailList = [];
          companyName.value = '';

          modalVisible.value = false;
          cleanAllFormData();
          emit('success');
        } else {
          spinning.value = false;
          createMessage.error(res.message);
        }
      })
      .catch(function () {
        spinning.value = false;
        createMessage.error('网络超时，请重试!');
      });
  }

  defineExpose({ init });
</script>
