<script setup>
import { reactive, ref,watch } from "vue";
import { ElMessage } from 'element-plus'
import { customInterence } from '@/api/api.js';

const props = defineProps({
  title:{
    type:String,
    default:'标题'
  },
  showAddDia:{
    type:Boolean,
    required:true
  },
  contactsSubmitForm:{
    type:Object,
    default:()=> {}
  },
  companyId:{
    type:Number,
    required:true
  }
})
const emit = defineEmits(['close','updateList'])

const telCodeArr = [
  { value: '86', label: '+86' },
  { value: '852', label: "+852" },
  { value: '886', label: '+886' },
  { value: '1', label: '+1' },
  { value: '65', label: '+65' },
  { value: '62', label: '+62' },
  { value:'081',label: '+081' },
  { value:'44',label: '+44' }
]

// 关闭弹窗
const submitForm = reactive({
  Id:0,
  Name:"",
  Email:"",
  TelCode:'',
  Tel:'',
  carte:'',
  Enabled:1
})
const addContactsForm = ref(null)
function closeAddDia(){
  submitForm.Id=0
  submitForm.Name=""
  submitForm.Email=""
  submitForm.TelCode=''
  submitForm.Tel=''
  submitForm.carte=''
  submitForm.Enabled=1
  
  emit('close')
  addContactsForm.value.clearValidate()
}

watch(
  () => props.showAddDia,
  (nval) => {
    if(!nval) return

    if(props.contactsSubmitForm.Id){

      submitForm.Id=props.contactsSubmitForm.Id,
      submitForm.Name=props.contactsSubmitForm.Name,
      submitForm.Email=props.contactsSubmitForm.Email,
      submitForm.TelCode=props.contactsSubmitForm.CountryCode,
      submitForm.Tel=props.contactsSubmitForm.Mobile,
      submitForm.carte=props.contactsSubmitForm.BusinessCardUrl,
      submitForm.Enabled=props.contactsSubmitForm.Enabled
    }
  }
)


 /* 预览 */
function preview() {
  $("#img").click();
}
function clickinput() {
  //上传模拟点击
  // debugger
  $("#fileCard").click();
}
// 选择文件上传
function fileSelected() {
  //选择文件上传
  if (document.getElementById("fileCard").files[0]) {
    let hostfile = document.getElementById("fileCard").files[0];
    let size = Math.floor(hostfile.size / 1024 / 1024);
    if (size > 200) {
      ElMessage.error("上传文件大小不能大于200M！");
      hostfile = {};
      return false;
    }
    if (
      hostfile.name.toLowerCase().includes(".png") ||
      hostfile.name.toLowerCase().includes(".jpg") ||
      hostfile.name.toLowerCase().includes(".jpeg")
    ) {
      let form = new FormData();
      form.append("file", hostfile); //hostfile.name

      customInterence.upload(form).then((res) => {
        if (res.Ret === 200) {
          submitForm.carte = res.Data.ResourceUrl;
        }

        $("#fileCard").val("");
        hostfile = {};
      });
    } else {
      ElMessage.error("上传文件格式不正确！");
    }
  }
}


// 提交表单
const showHintDia = ref(false);
const existContactList = ref([])
const contactSource = ref('')
function submit(){
  addContactsForm.value.validate(valid=>{
    if(valid){
      // 保存
      const params={
        Id:submitForm.Id,
        CompanyId:companyId,
        Name:submitForm.Name,
        Email:submitForm.Email,
        CountryCode:submitForm.TelCode,
        Mobile:submitForm.Tel,
        BusinessCardUrl:submitForm.carte,
        Enabled:submitForm.Enabled
      }
      customInterence.contactsSaveEn(params).then(res=>{
        if(res.Ret == 200){
          if(submitForm.Id==0){
            // 新增
            emit('updateList')
          }else{
            emit('updateList')
          }
          ElMessage.success(`${props.title}成功`)
          closeAddDia()
        }else if(res.Ret == 1001){
          existContactList.value = res.Data?[res.Data]:[]
          contactSource.value = res.Data.Status
          showHintDia.value=true
        }
      })
    }
  })
}

// 移动联系人 
function moveContact(){
  if(!(existContactList.value && existContactList.value.length>0)){
    return 
  }
  customInterence.contactsMoveEn({EmailId:existContactList.value[0].Id,CompanyId:props.companyId}).then(res=>{
    if(res.Ret == 200){
      ElMessage.success('移动成功')
      emit('updateList')

      showHintDia.value=false
      closeAddDia()
    }
  })
}

</script>
<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    :model-value="showAddDia"
    width="725px"
    @closed="closeAddDia"
  >
    <div style="padding: 10px 66px 35px 66px">
      <el-form
        :model="submitForm"
        ref="addContactsForm"
        label-position="right"
        label-width="92px"
      >
        <el-form-item
          label="联系人姓名"
          prop="Name"
          :rules="{
            required: true,
            message: '联系人姓名不能为空',
            trigger: 'blur',
          }"
        >
          <el-input
            v-model="submitForm.Name"
            style="width: 337px"
            placeholder="请输入联系人姓名"
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱地址"
          prop="Email"
          :rules="[
            { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
            { type: 'email', message: '邮箱地址格式不正确', trigger: 'blur' },
          ]"
        >
          <el-input
            v-model="submitForm.Email"
            style="width: 337px"
            placeholder="请输入邮箱地址"
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="Phone">
          <el-select
            v-model="submitForm.TelCode"
            placeholder="区号"
            style="width: 90px"
          >
            <el-option
              v-for="item in telCodeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input
            v-model="submitForm.Tel"
            placeholder="手机号"
            style="width: 245px"
            clearable
          />
        </el-form-item>
        <el-form-item label="个人名片" prop="carte" style="width: 100%">
          <input
            type="file"
            name="file"
            @change="fileSelected"
            id="fileCard"
            class="true-file"
            style="display: none"
          />
          <el-button
            type="primary"
            size="medium"
            @click="clickinput"
            v-if="!submitForm.carte"
            >点击上传</el-button
          >
          <div class="img_item" v-if="submitForm.carte">
            <el-image
              :src="submitForm.carte"
              alt=""
              style="background: #aaa; width: 280px; height: 180px"
              :preview-src-list="submitForm.carte.split(',')"
              id="img"
            />
            <i
              class="el-icon-zoom-in"
              style="position: absolute; right: 20px; top: 20px; color: #fff"
              @click="preview"
            ></i>
            <span
              style="
                position: absolute;
                right: 12px;
                bottom: 1px;
                color: #409eff;
                font-size: 16px;
                cursor: pointer;
              "
              @click.stop="clickinput"
              >重新上传</span
            >
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="Enabled">
          <el-radio-group v-model="submitForm.Enabled">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div style="text-align: center; margin-top: 60px">
        <el-button
          type="primary"
          size="medium"
          style="width: 120px; margin-right: 6px"
          @click="submit"
          >确定</el-button
        >
        <el-button size="medium" style="width: 120px" @click="closeAddDia"
          >取消</el-button
        >
      </div>
    </div>
  </el-dialog>



  <!-- 存在联系人的提示弹窗 -->
  <el-dialog
    title="提示"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    :model-value="showHintDia"
    width="920px"
  >
    <div style="padding: 0 40px">
      <p style="margin-bottom: 20px">检测到系统中已存在以下联系人</p>
      <p style="margin-bottom: 10px" v-if="contactSource">
        来源：{{
          contactSource == 1
            ? "正式客户列表"
            : contactSource == 2
            ? "临时权限列表"
            : "终止权限列表"
        }}
      </p>
      <el-table :data="existContactList" border>
        <el-table-column label="联系人姓名" align="center" prop="Name">
          <template #default="{ row }">
            <img
              :src="$icons.card"
              alt=""
              style="width: 17px; cursor: pointer; marginright: 5px"
              v-if="row.BusinessCardUrl"
              @click="reviewCard(row.BusinessCardUrl)"
            />
            <span>{{ row.Name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="注册公司" align="center" prop="CompanyName">
          <template #default="{ row }">
            {{
              row.CompanyName ? row.CompanyName : row.RegisterCompanyName || "-"
            }}
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="Mobile">
          <template #default="{ row }">
            {{ row.CountryCode }}-{{ row.Mobile }}
          </template>
        </el-table-column>
        <el-table-column label="注册时间" align="center" prop="CreateTime">
          <template #default="{ row }">
            {{ row.CreateTime || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="邮箱地址" align="center" prop="Email">
          <template #default="{ row }">
            {{ row.Email }}
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: center; margin: 60px 0 40px">
        <el-button
          @click="showHintDia = false"
          style="min-width: 120px; margin-right: 6px"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="moveContact"
          style="min-width: 120px; padding: 12px 10px"
          >移动至当前用户</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>
<style scoped lang="scss"></style>
