<template>
  <el-dialog :model-value="visible" :width="width" title="新用户建档" :close-on-press-escape="false"
    :close-on-click-modal="canClose" @close="close()">
    <el-form class="pr-30px pt-15px" :label-width="100">
      <!-- <div class="pl-15px  pb-15px text-16px  text-gray-500">用户未建档，请先填写信息建档</div> -->
      <el-form-item class="is-required" label="地址">
        <el-input v-model="form.address" placeholder="请输入地址" />
      </el-form-item>
      <el-form-item class="is-required" label="联系方式">
        <el-input v-model="form.mobile" placeholder="请输入联系方式" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div text-center>
        <el-button plain class="w-100px" type="primary" :icon="Close" @click="close()">取消</el-button>
        <el-button class="w-100px" :loading="loading" :icon="Select" type="primary" @click="confirm()">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { addHisCustomer } from '@/api/hlw'
import validate from "@/utils/validate";

import { Close, Select } from "@element-plus/icons-vue";

const emits = defineEmits(['close', 'confirm'])
const props = defineProps({
  width: {
    type: Number,
    default: 600
  },
  visible: {
    type: Boolean,
    default: false,
  },
  cardInfo: {
    type: Object,
    default: () => ({})
  }
})

const form = ref({ mobile: '', address: '' })
const loading = ref(false);

function close() {
  if (loading.value) return;
  emits('close')
}

async function confirm() {
  if (loading.value) return;
  if (form.value.address.trim() === '') {
    return ElMessage.info('请输入地址')
  }
  if (form.value.address.trim().length > 100) {
    return ElMessage.info('地址最多输入100个字')
  }
  if (form.value.mobile.trim() === '') {
    return ElMessage.info('请输入联系方式')
  }
  if (form.value.mobile.trim() !== '' && !validate.isMobile(form.value.mobile.trim())) {
    return ElMessage.info('请输入正确的联系方式')
  }
  loading.value = true;
  const payload = {
    idCard: props.cardInfo.IDNum,
    name: props.cardInfo.Name,
    address: form.value.address.trim(),
    mobile: form.value.mobile.trim(),
    mdtrt_cert_type: '03',
    mdtrt_cert_no: props.cardInfo.CardNum,
    card_sn: props.cardInfo.CardIDCode
  }
  const { success, message, data } = await addHisCustomer(payload);
  const card = data && Array.isArray(data.list) && data.list[0] ? data.list[0] : null;
  loading.value = false;
  if (success && card) {
    close()
    emits('confirm', card)
  } else {
    ElMessage.error(message || '建档失败')
  }
}

watch(() => props.visible, (val) => {
  if (val) {
    form.value = { mobile: '', address: '' }
  }
})

</script>