<script setup>
import { computed, ref,watch } from "vue";
import { validateTel, validatePwd } from "@/utils/validate.js";
import { ElMessage } from 'element-plus'
import $ from 'jquery'
import { customInterence, departInterence } from "@/api/api.js";

const props = defineProps({
  isShowclose: {
    type: Boolean,
    default: true,
  },
  userId: {
    type: Number,
  },
  id: {
    type: String,
  },
  name: {
    type: String,
  },
  isAddContact: {
    type: Boolean,
  },
  userForm: {
    type: Object,
  },
  title: {
    type: String,
  },
  needCard: {
    type: Boolean,
    default: false,
    required: false,
  },
  regionType: {
    type: String,
    required: false,
  },
  // 是否是领取流失
  isPickLoss: {
    type: Boolean,
    default: false,
  },
  // 是否是领取权益/ficc
  isPickOther: {
    type: Boolean,
    default: false,
  },
  /* 是否是新增客户入口 */
  isAddUser: {
    type: Boolean,
    default: false,
  },
  /* 是否是编辑客户入口 */
  isEditUser: {
    type: Boolean,
    default: false,
  },
  // 是否为领取自己的流失客户
  isPickSelf: {
    type: Boolean,
    default: false
  },
  custom_name:{
    type:String,
    default: '',
  }
})
const emit = defineEmits(['addContactNext','cancel'])


const ProductName = computed(() => {
  let type = localStorage.getItem("RoleType") || "";
  if (type == "ficc") {
    return "ficc";
  } else if (type == "权益") {
    return "权益";
  } else {
    return "ficc";
  }
})


function validateMobile (rule, value, callback) {
  if (!/^\d+$/.test(value) && value) {
    callback(new Error("请输入正确的手机号格式"));
  } else {
    callback();
  }
}
const userRule = {
  name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  sex: [{ required: true, message: "性别不能为空", trigger: "change" }],
  tel1: [
    // { required: true, message: '至少输入一个手机号或邮箱', trigger: 'blur' },
    { validator: validateMobile, trigger: "blur" },
    // { pattern: /^\d|^\+/, message: '  请输入正确的手机号码' }
  ],

  mailQY: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  telQY: [{ required: true, message: "请输入手机号", trigger: "blur" },
    //  { pattern: /^\d|^\+/, message: '  请输入正确的手机号码' }
  ],
  desiger: [
    { required: true, message: "请选择是否为决策人", trigger: "change" },
  ],
  carte: [
    { required: props.needCard, message: "名片不能为空", trigger: "change" },
  ],
}

const userFormIndeterminacy = ref('')

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

    getPhoneCode()
    if (props.userForm.Source) {
      userFormIndeterminacy.value = props.userForm.Source
    } else {
      props.userForm.Source = userFormIndeterminacy.value || 'add_user'
    }
  }
)


const telCodeArr = ref([])
function getPhoneCode(){
    departInterence.getPhoneAreaCode().then(res=>{
        if(res.Ret!==200) return 
        telCodeArr.value = res.Data&&res.Data.map(i=>{
            return {
                value:i.Value,
                label:i.Name
            }
        })
    })
}

// 领取自己的流失客户点击下一步
const userFormRef = ref(null)
function handleNext() {
  userFormRef.value.validate((valid) => {
    if (valid) {
      // 海外电话邮箱必填
      if (props.regionType == '海外') {
        // 权益
        if (ProductName.value == '权益') {
          if (!props.userForm.telQY) {
            ElMessage.warning("请填写手机号");
            return
          }
          if (!props.userForm.mailQY) {
            ElMessage.warning("请填写邮箱");
            return
          }
        } else {
          if (!props.userForm.tel1) {
            ElMessage.warning("请填写手机号");
            return
          }
          if (!props.userForm.mail) {
            ElMessage.warning("请填写邮箱");
            return
          }
        }
      }

      if (ProductName.value == 'ficc' || ProductName.value == 'admin' || (props.regionType == '国内' && ProductName.value == '权益')) {
        if (!props.userForm.tel1 && !props.userForm.mail) {
          ElMessage.warning("至少输入一个手机号或邮箱");
          return
        }
      }

      if (ProductName.value == '权益' && props.regionType !== '国内') {
        if (!props.userForm.telQY && !props.userForm.mailQY) {
          ElMessage.warning("至少输入一个手机号或邮箱");
          return
        }
      }

      emit('addContactNext', { formData: { ...props.userForm, RegionType: props.regionType, CompanyId: props.id } })
    }
  })

}


const typeArr = ref([]) //公司列表
function focusGetCompany() {
  customInterence
    .companySearch({
      KeyWord: "##",
    })
    .then((res) => {
      if (res.Ret === 200) {
        typeArr.value = res.Data.List || [];
      }
    });
}

/* 过滤公司 */
function getCompany(query) {
  if (query) {
    customInterence
      .companySearch({
        KeyWord: query,
      })
      .then((res) => {
        if (res.Ret === 200) {
          typeArr.value = res.Data.List || [];
        }
      });
  } else {
    typeArr.value = [];
  }
}


const btnLoading = ref(false)
/* 保存 */
function saveUser() {
  userFormRef.value.validate((valid, key) => {
    if (valid) {
      btnLoading.value=true;
      if (props.title == "新增联系人") {
        customInterence
          .concactAdd({
            CompanyId:
              props.name == props.userForm.companyName
                ? Number(props.id)
                : Number(props.userForm.companyName),
            Email: props.userForm.mail || props.userForm.mailQY,
            DepartmentName: props.userForm.depart,
            IsMaker: Number(props.userForm.desiger),
            CountryCode: props.userForm.telCode,
            MobileOne: props.userForm.tel1 || props.userForm.telQY,
            MobileTwo: props.userForm.tel2,
            Position: props.userForm.post,
            RealName: props.userForm.name,
            Sex: Number(props.userForm.sex),
            Source: props.userForm.Source,
            BusinessCardUrl: props.userForm.carte,
            RegionType: props.regionType,
            CompanyName:props.custom_name
          })
          .then((res) => {
            if (res.Ret === 200) {
              !props.isPickOther &&
                !props.isPickLoss &&
                ElMessage.success(res.Msg);
              emit("cancel", 1, res.Data);
            } else if (res.Ret === 600) {
              canMove.value = res.Data.HasMove;
              userData.value = [];
              userData.value.push(res.Data);
              isHaveUser.value = true;
            }
            btnLoading.value=false
          });
      } else {
        customInterence
          .concactEdit({
            UserId: props.userId,
            CompanyId:
              props.name == props.userForm.companyName
                ? Number(props.id)
                : Number(props.userForm.companyName),
            Email: props.userForm.mailQY,
            DepartmentName: props.userForm.depart,
            IsMaker: Number(props.userForm.desiger),
            CountryCode: props.userForm.telCode,
            MobileOne: props.userForm.telQY,
            MobileTwo: props.userForm.tel2,
            Position: props.userForm.post,
            RealName: props.userForm.name,
            Sex: Number(props.userForm.sex),
            Source: props.userForm.Source,
            BusinessCardUrl: props.userForm.carte,
            RegionType: props.regionType,
          })
          .then((res) => {
            if (res.Ret === 200) {
              ElMessage.success(res.Msg);
              emit("cancel", 1);
            } else if (res.Ret === 600) {
              canMove.value = res.Data.HasMove;
              userData.value = [];
              userData.value.push(res.Data);
              isHaveUser.value = true;
            }
            btnLoading.value=false
          });
      }
    }
  });
  
}

function saveUserFicc() {
  if (ProductName.value == '权益' && !props.userForm.mail && !props.userForm.tel1) {
    ElMessage.warning("至少输入一个手机号或邮箱");
    return;
  }
  if (
    ProductName.value == "ficc" &&
    props.userForm.mail == "" &&
    props.userForm.tel1 == ""
  ) {
    ElMessage.warning("至少输入一个手机号或邮箱");
    return;
  } else {

    userFormRef.value.validate(valid => {
      if(!valid) return 
      btnLoading.value=true;
      if (props.title == "新增联系人") {
        customInterence
          .concactAdd({
            CompanyId:
              props.name == props.userForm.companyName
                ? Number(props.id)
                : Number(props.userForm.companyName),
            Email: props.userForm.mail || props.userForm.mailQY,
            DepartmentName: props.userForm.depart,
            IsMaker: Number(props.userForm.desiger),
            CountryCode: props.userForm.telCode,
            MobileOne: props.userForm.tel1 || props.userForm.telQY,
            MobileTwo: props.userForm.tel2,
            Position: props.userForm.post,
            RealName: props.userForm.name,
            Sex: Number(props.userForm.sex),
            Source: props.userForm.Source,
            BusinessCardUrl: props.userForm.carte,
            RegionType: props.regionType,
            CompanyName:props.custom_name
          })
          .then((res) => {
            if (res.Ret === 200) {
              !props.isPickOther &&
                !props.isPickLoss &&
                ElMessage.success(res.Msg);
              emit("cancel", 1, res.Data);
            } else if (res.Ret === 600) {
              canMove.value = res.Data.HasMove;
              userData.value = [];
              userData.value.push(res.Data);
              isHaveUser.value = true;
            }
            btnLoading.value=false
          });
      } else {

        customInterence
          .concactEdit({
            UserId: props.userId,
            CompanyId:
              props.name == props.userForm.companyName
                ? Number(props.id)
                : Number(props.userForm.companyName),
            Email: props.userForm.mail,
            DepartmentName: props.userForm.depart,
            IsMaker: Number(props.userForm.desiger),
            CountryCode: props.userForm.telCode,
            MobileOne: props.userForm.tel1,
            MobileTwo: props.userForm.tel2,
            Position: props.userForm.post,
            RealName: props.userForm.name,
            Sex: Number(props.userForm.sex),
            Source: props.userForm.Source,
            BusinessCardUrl: props.userForm.carte,
            RegionType: props.regionType,
          })
          .then((res) => {
            if (res.Ret === 200) {
              ElMessage.success(res.Msg);
              emit("cancel", 1);
            } else if (res.Ret === 600) {
              canMove.value = res.Data.HasMove;
              userData.value = [];
              userData.value.push(res.Data);
              isHaveUser.value = true;
            }
            btnLoading.value=false
          });
      }
    })

  }
}

/* 取消弹窗 */
function cancelHandle() {
  userFormRef.value.resetFields();
  emit("cancel");
}


/* 移动 */
const userData = ref([]) //已存在的联系人
const canMove = ref("") //是否显示移动按钮
const isHaveUser = ref(false) //已存在联系人弹窗
function moveSale() {
  let userId = userData.value[0].UserId;
  let SellerId = localStorage.getItem('AdminId')
  customInterence
    .moveUser({
      CompanyId: Number(props.id),
      BusinessCardUrl: props.userForm.carte,
      DepartmentName: props.userForm.depart,
      Email: props.userForm.mail || props.userForm.mailQY,
      IsMaker: Number(props.userForm.desiger),
      CountryCode: props.userForm.telCode,
      Mobile: props.userForm.tel1 || props.userForm.telQY,
      Position: props.userForm.post,
      RegionType: "",
      RealName: props.userForm.name,
      Remark: "",
      SellerId: Number(SellerId),
      Sex: Number(props.userForm.sex),
      UserId: Number(userId),
    })
    .then((res) => {
      if (res.Ret === 200) {
        !props.isPickOther &&
          !props.isPickLoss &&
          ElMessage.success("移动成功！");
        isHaveUser.value = false;
        emit("cancel", 1, userId);
      }
    });
}
//  取消联系人重复弹窗
function cancelHandle2() {
  canMove.value = "";
  isHaveUser.value = false;
}


// 点击我知道了
function knowHandle() {
  // 已重复联系人所属公司id
  let re_id = userData.value[0].CompanyId;
  let userId = userData.value[0].UserId; //重复联系人的id

  if (props.isPickLoss && re_id === Number(props.id)) {
    // 领取流失客户且重复联系人在当前客户下继续领取
    emit("cancel", 1, userId);
  } else if (props.isPickOther && re_id === Number(props.id)) {
    // 领取其他类型客户且重复联系人在当前客户下继续领取
    emit("cancel", 1, userId);
  } else if (props.isAddUser && re_id !== Number(props.id)) {
    // 新增客户入口且重复联系人不在当前客户下
    ElMessage.warning("新增失败");
  } else if (props.isEditUser && re_id !== Number(props.id)) {
    // 编辑客户入口且重复联系人不在当前客户下
    ElMessage.warning("添加失败");
  }

  /* 领取流失客户或其他类型且联系人重复且不存在当前客户下 */
  if (
    (props.isPickLoss && re_id != Number(props.id)) ||
    (props.isPickOther && re_id != Number(props.id))
  ) {
    ElMessage.warning("领取失败");
  }
  canMove.value = "";
  isHaveUser.value = false;
}

/* 预览 */
function preview() {
  $("#img").click();
}

function clickinput() {
  //上传模拟点击
  // debugger
  $("#fileCard").click();
}


const uploadloading = ref(false)
// 选择文件上传
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
      uploadloading.value = true;
      customInterence.upload(form).then((res) => {
        if (res.Ret === 200) {
          // that.$message.success( '上传成功' );
          props.userForm.carte = res.Data.ResourceUrl;
        }
        uploadloading.value = false;
        $("#fileCard").val("");
        hostfile = {};
      });
    } else {
      ElMessage.error("上传文件格式不正确！");
    }
  }
}



</script>
<template>
  <div v-if="isAddContact">
    <el-dialog
      :model-value="isAddContact"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :show-close="false"
      class="concact_dialog"
      center
      width="900px"
      draggable
    >
      <template #header>
        <div
          style="display: flex; align-items: center; position: relative"
        >
          <img
            :src="title == '新增联系人' ? $icons.add : $icons.edit"
            style="color: #fff; width: 16px; height: 16px; margin-right: 5px"
          />
          <span style="font-size: 16px">{{ title }}</span>
          <i
            class="el-icon-close"
            style="
              font-size: 24px;
              cursor: pointer;
              position: absolute;
              right: 20px;
              top: 50%;
              transform: translateY(-50%);
            "
            @click="cancelHandle"
          ></i>
        </div>
      </template>
      <el-form
        @submit.prevent
        :model="userForm"
        inline
        :rules="userRule"
        ref="userFormRef"
        label-width="90px"
        class="demo-ruleForm"
        style="margin-top: 15px"
      >
        <el-form-item label="姓名" prop="name" style="margin-right: 30px">
          <el-input
            v-model="userForm.name"
            placeholder="请输入姓名"
            style="width: 315px"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex" style="width: 370px">
          <el-radio-group v-model="userForm.sex" size="default">
            <el-radio :label="1" style="width: 50px">男</el-radio>
            <el-radio :label="2" style="width: 50px; margin-left: 0"
              >女</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- FICC填写手机号 -->
        <el-form-item
          v-show="
            ProductName == 'ficc' ||
            ProductName == 'admin' ||
            (props.regionType == '国内' && ProductName == '权益')
          "
          label="手机号"
          prop="tel1"
          style=""
        >
          <el-select
            v-model="userForm.telCode"
            placeholder="区号"
            style="width: 90px"
          >
            <el-option
              v-for="item in telCodeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            v-model="userForm.tel1"
            placeholder="手机号和邮箱至少填写一个"
            style="width: 220px"
            clearable
          >
          </el-input>
        </el-form-item>
        <!-- 权益填写手机号 -->
        <el-form-item
          v-if="
            (ProductName == '权益' && props.regionType == '海外') ||
            (ProductName == '权益' && props.regionType !== '国内')
          "
          label="手机号"
          prop="telQY"
          style=""
        >
          <el-select
            v-model="userForm.telCode"
            placeholder="区号"
            style="width: 90px"
          >
            <el-option
              v-for="item in telCodeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            v-model="userForm.telQY"
            placeholder="请输入手机号"
            style="width: 220px"
            clearable
          >
          </el-input>
        </el-form-item>

        <!-- FICC填写邮箱 -->
        <el-form-item
          v-show="
            ProductName == 'ficc' ||
            ProductName == 'admin' ||
            (props.regionType == '国内' && ProductName == '权益')
          "
          label="邮箱"
          prop="mail"
          style="marginright: 30px"
        >
          <el-input
            v-model="userForm.mail"
            placeholder="请输入邮箱"
            style="width: 280px"
            clearable
          >
          </el-input>
        </el-form-item>
        <!-- 权益填写邮箱 -->
        <el-form-item
          v-if="
            (ProductName == '权益' && props.regionType == '海外') ||
            (ProductName == '权益' && props.regionType !== '国内')
          "
          label="邮箱"
          prop="mailQY"
          style="margin-right: 30px"
        >
          <el-input
            v-model="userForm.mailQY"
            placeholder="请输入邮箱"
            style="width: 280px"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="职位" prop="post">
          <el-input
            v-model="userForm.post"
            placeholder="请输入职位"
            style="width: 315px"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="是否KP" prop="desiger" style="margin-right: 30px">
          <el-select
            v-model="userForm.desiger"
            placeholder="请选择是否是KP"
            style="width: 280px"
          >
            <el-option
              v-for="(item, index) in ['否', '是']"
              :key="item"
              :label="item"
              :value="index"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="depart">
          <el-input
            v-model="userForm.depart"
            placeholder="请输入部门"
            style="width: 315px"
            clearable
          >
          </el-input>
        </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="default"
            @click="clickinput"
            v-if="!userForm.carte"
            >点击上传</el-button
          >
          <div class="img_item" v-if="userForm.carte">
            <el-image
              :src="userForm.carte"
              alt=""
              style="background: #aaa; width: 280px; height: 180px"
              :preview-src-list="userForm.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>
      <div
        style="display: flex; justify-content: center; margin: 30px 0 55px"
        v-if="!isPickSelf"
      >
        <el-button
          v-if="ProductName == '权益' && props.regionType == '海外'"
          type="primary"
          :loading="btnLoading"
          style="width: 80px; margin-right: 24px"
          @click="saveUser"
          :style="!isShowclose ? 'width:120px' : ''"
          >确定
        </el-button>
        <el-button
          v-else
          type="primary"
          style="width: 80px; margin-right: 24px"
          @click="saveUserFicc"
          :loading="btnLoading"
          :style="!isShowclose ? 'width:120px' : ''"
          >确定</el-button
        >
        <el-button
          type="primary"
          plain
          style="width: 80px"
          @click="cancelHandle"
          v-if="isShowclose"
          >取消</el-button
        >
      </div>
      <div
        style="display: flex; justify-content: center; margin: 30px 0 55px"
        v-else
      >
        <el-button
          type="primary"
          style="width: 80px; margin-right: 24px"
          @click="handleNext"
          >下一步</el-button
        >
        <el-button
          type="primary"
          plain
          style="width: 80px"
          @click="cancelHandle"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
  <!-- 用户已存在弹窗 -->
  <el-dialog
    title="提示"
    :model-value="isHaveUser"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    @close="cancelHandle2"
    center
    top="25vh"
    width="700px"
  >
    <div style="font-size: 15px; color: #606266; margin-bottom: 10px">
      检测系统中已存在以下联系人
      <span v-if="!canMove">（请联系对应销售处理）</span>
    </div>
    <el-table :data="userData" border>
      <el-table-column align="center" label="联系人">
        <template #default="scope">{{ scope.row.RealName }}</template>
      </el-table-column>
      <el-table-column align="center" label="手机号/邮箱" width="300">
        <template #default="scope">
          {{ scope.row.Mobile }}
          {{ scope.row.Mobile && scope.row.Email ? "/" : "" }}
          {{ scope.row.Email }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="销售">
        <template #default="scope">{{ scope.row.SellerRealName }}</template>
      </el-table-column>
      <el-table-column align="center" label="关联客户">
        <template #default="scope">{{ scope.row.CompanyName }}</template>
      </el-table-column>
    </el-table>
    <div style="display: flex; justify-content: center; margin: 30px 0">
      <template v-if="canMove">
        <el-button type="primary" style="margin-right: 24px" @click="moveSale"
          >移动至当前客户</el-button
        >
        <el-button
          type="primary"
          plain
          style="width: 80px"
          @click="cancelHandle2"
          >取消</el-button
        >
      </template>
      <el-button
        type="primary"
        style="width: 100px"
        v-else
        @click="knowHandle()"
        >知道了</el-button
      >
    </div>
  </el-dialog>
</template>
<style scoped lang="scss">
.concact_dialog {
  .el-form-item__label {
    width: 90px !important;
  }

  .img_item {
    position: relative;
    width: 280px;
    height: 180px;
    border-radius: 4px;
  }
}
</style>
