<template>
  <div>
    <div v-if="isAddContact">
      <el-dialog :visible.sync="isAddContact" :close-on-press-escape="false" :close-on-click-modal="false"
        :modal-append-to-body="false" :show-close="false" custom-class="concact_dialog" center width="900px">
        <div slot="title" 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>
        <el-form @submit.native.prevent :model="userForm" inline :rules="userRule" ref="userForm" label-width="80px"
          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="medium">
              <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="
            this.ProductName == 'ficc' ||
            this.ProductName == 'admin' ||
            (this.regionType == '国内' && this.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="(this.ProductName == '权益' && this.regionType == '海外') || (this.ProductName == '权益' && this.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>
          <!-- <el-form-item label="手机号2" prop="tel2">
				<el-input
				v-model="userForm.tel2"
				placeholder="请输入手机号"
				style="width:280px"
				clearable>
				</el-input>
			</el-form-item> -->
          <!-- FICC填写邮箱 -->
          <el-form-item v-show="
            this.ProductName == 'ficc' ||
            this.ProductName == 'admin' ||
            (this.regionType == '国内' && this.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="(this.ProductName == '权益' && this.regionType == '海外') || (this.ProductName == '权益' && this.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-from-item>
          <span @click="handleShowMove" style="color:#4A83F1;marginLeft:40px;cursor: pointer;">移动联系人</span>
        </el-from-item> -->
          <!-- <el-form-item
          label="移动到"
          prop="companyName"
          style="width: 100%"
          v-if="title == '编辑联系人'"
        >
          <el-select
            v-model="userForm.companyName"
            filterable
            remote
            :remote-method="getCompany"
            @focus="focusGetCompany"
            placeholder="请选择公司"
            style="width: 280px"
          >
            <el-option
              v-for="item in typeArr"
              :key="item.CompanyId"
              :label="item.CompanyName"
              :value="item.CompanyId"
            >
            </el-option>
          </el-select>
          <span
            style="
              color: #409eff;
              marginleft: 20px;
              fontsize: 16px;
              cursor: pointer;
            "
            @click="$router.push({ path: '/addCustom' })"
            >创建客户</span
          >
        </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.native="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="this.ProductName == '权益' && this.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="提示" :visible.sync="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 slot-scope="scope">{{ scope.row.RealName }}</template>
        </el-table-column>
        <el-table-column align="center" label="手机号/邮箱" width="300">
          <template slot-scope="scope">
            {{ scope.row.Mobile }}
            {{ scope.row.Mobile && scope.row.Email ? "/" : "" }}
            {{ scope.row.Email }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="销售">
          <template slot-scope="scope">{{ scope.row.SellerRealName }}</template>
        </el-table-column>
        <el-table-column align="center" label="关联客户">
          <template slot-scope="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>


  </div>
</template>

<script>
import { validateTel, validatePwd } from "@/utils/validate.js";
import { customInterence, departInterence } from "@/api/api.js";
import { lang } from 'moment';
export default {
  name: "",
  props: {
    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:Object,
      default: '',
    }
  },
  data() {
    var validateMobile = (rule, value, callback) => {
      if (!/^\d+$/.test(value) && value) {
        callback(new Error("请输入正确的手机号格式"));
      } else {
        callback();
      }
    };
    return {
      telCodeArr: [],

      isHaveUser: false, //已存在联系人弹窗
      uploadloading: false,
      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: '  请输入正确的手机号码' }
        ],
        // tel2:[
        // 	//{ validator: validateMobile, trigger: 'blur'},
        // ],
        // mail: [
        // { required: true, message: '至少输入一个手机号或邮箱', trigger: 'blur' },
        // ],
        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: this.needCard, message: "名片不能为空", trigger: "change" },
        ],
      },
      userData: [], //已存在的联系人
      canMove: "", //是否显示移动按钮
      typeArr: [], //公司列表
      userFormIndeterminacy: '',
      btnLoading:false,
    };
  },
  methods: {
    getPhoneCode(){
        departInterence.getPhoneAreaCode().then(res=>{
            if(res.Ret!==200) return 
            this.telCodeArr = res.Data||[]
            this.telCodeArr = this.telCodeArr.map(i=>{
                return {
                    value:i.Value,
                    label:i.Name
                }
            })
        })
    },
    // 领取自己的流失客户点击下一步
    handleNext() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          // 海外电话邮箱必填
          if (this.regionType == '海外') {
            // 权益
            if (this.ProductName == '权益') {
              if (!this.userForm.telQY) {
                this.$message.warning("请填写手机号");
                return
              }
              if (!this.userForm.mailQY) {
                this.$message.warning("请填写邮箱");
                return
              }
            } else {
              if (!this.userForm.tel1) {
                this.$message.warning("请填写手机号");
                return
              }
              if (!this.userForm.mail) {
                this.$message.warning("请填写邮箱");
                return
              }
            }
          }

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

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


          // if(this.ProductName=='权益'&&!this.userForm.mail&&!this.userForm.tel1){
          //   this.$message.warning("至少输入一个手机号或邮箱");
          //   return;
          // }
          // if (this.ProductName == "ficc" &&this.userForm.mail == "" && this.userForm.tel1 == "") {
          //   this.$message.warning("至少输入一个手机号或邮箱");
          //   return;
          // }
          this.$emit('addContactNext', { formData: { ...this.userForm, RegionType: this.regionType, CompanyId: this.id } })
        }
      })

    },


    focusGetCompany() {
      customInterence
        .companySearch({
          KeyWord: "##",
        })
        .then((res) => {
          if (res.Ret === 200) {
            this.typeArr = res.Data.List || [];
          }
        });
    },
    /* 过滤公司 */
    getCompany(query) {
      if (query) {
        customInterence
          .companySearch({
            KeyWord: query,
          })
          .then((res) => {
            if (res.Ret === 200) {
              this.typeArr = res.Data.List || [];
            }
          });
      } else {
        this.typeArr = [];
      }
    },
    /* 保存 */
    saveUser() {
     
      this.$refs.userForm.validate((valid, key) => {
        if (valid) {
          this.btnLoading=true;
          if (this.title == "新增联系人") {
            customInterence
              .concactAdd({
                CompanyId:
                  this.name == this.userForm.companyName
                    ? Number(this.id)
                    : Number(this.userForm.companyName),
                Email: this.userForm.mail || this.userForm.mailQY,
                DepartmentName: this.userForm.depart,
                IsMaker: Number(this.userForm.desiger),
                CountryCode: this.userForm.telCode,
                MobileOne: this.userForm.tel1 || this.userForm.telQY,
                MobileTwo: this.userForm.tel2,
                Position: this.userForm.post,
                RealName: this.userForm.name,
                Sex: Number(this.userForm.sex),
                Source: this.userForm.Source,
                BusinessCardUrl: this.userForm.carte,
                RegionType: this.regionType,
                CompanyName:this.custom_name
              })
              .then((res) => {
                if (res.Ret === 200) {
                  !this.isPickOther &&
                    !this.isPickLoss &&
                    this.$message.success(res.Msg);
                  this.$emit("cancel", 1, res.Data);
                } else if (res.Ret === 600) {
                  this.canMove = res.Data.HasMove;
                  this.userData = [];
                  this.userData.push(res.Data);
                  this.isHaveUser = true;
                }
                this.btnLoading=false
              });
          } else {
            customInterence
              .concactEdit({
                UserId: this.userId,
                CompanyId:
                  this.name == this.userForm.companyName
                    ? Number(this.id)
                    : Number(this.userForm.companyName),
                Email: this.userForm.mailQY,
                DepartmentName: this.userForm.depart,
                IsMaker: Number(this.userForm.desiger),
                CountryCode: this.userForm.telCode,
                MobileOne: this.userForm.telQY,
                MobileTwo: this.userForm.tel2,
                Position: this.userForm.post,
                RealName: this.userForm.name,
                Sex: Number(this.userForm.sex),
                Source: this.userForm.Source,
                BusinessCardUrl: this.userForm.carte,
                RegionType: this.regionType,
              })
              .then((res) => {
                if (res.Ret === 200) {
                  this.$message.success(res.Msg);
                  this.$emit("cancel", 1);
                } else if (res.Ret === 600) {
                  this.canMove = res.Data.HasMove;
                  this.userData = [];
                  this.userData.push(res.Data);
                  this.isHaveUser = true;
                }
                this.btnLoading=false
              });
          }
        }
      });
     
    },
    saveUserFicc() {
     
      if (this.ProductName == '权益' && !this.userForm.mail && !this.userForm.tel1) {
        this.$message.warning("至少输入一个手机号或邮箱");
        return;
      }
      if (
        this.ProductName == "ficc" &&
        this.userForm.mail == "" &&
        this.userForm.tel1 == ""
      ) {
        this.$message.warning("至少输入一个手机号或邮箱");
        return;
      } else {
        var num = 0;
        this.$refs.userForm.validateField(
          ["name", "sex", "tel1", "desiger", "carte"],
          (emailError) => {
            if (!emailError) {
              num += 1;
            } else {
              return false;
            }
          }
        );

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

            customInterence
              .concactEdit({
                UserId: this.userId,
                CompanyId:
                  this.name == this.userForm.companyName
                    ? Number(this.id)
                    : Number(this.userForm.companyName),
                Email: this.userForm.mail,
                DepartmentName: this.userForm.depart,
                IsMaker: Number(this.userForm.desiger),
                CountryCode: this.userForm.telCode,
                MobileOne: this.userForm.tel1,
                MobileTwo: this.userForm.tel2,
                Position: this.userForm.post,
                RealName: this.userForm.name,
                Sex: Number(this.userForm.sex),
                Source: this.userForm.Source,
                BusinessCardUrl: this.userForm.carte,
                RegionType: this.regionType,
              })
              .then((res) => {
                if (res.Ret === 200) {
                  this.$message.success(res.Msg);
                  this.$emit("cancel", 1);
                } else if (res.Ret === 600) {
                  this.canMove = res.Data.HasMove;
                  this.userData = [];
                  this.userData.push(res.Data);
                  this.isHaveUser = true;
                }
                this.btnLoading=false
              });
          }
        }
      }
    },
    /* 移动 */
    moveSale() {
      let userId = this.userData[0].UserId;
      let SellerId = localStorage.getItem('AdminId')
      customInterence
        .moveUser({
          CompanyId: Number(this.id),
          BusinessCardUrl: this.userForm.carte,
          DepartmentName: this.userForm.depart,
          Email: this.userForm.mail || this.userForm.mailQY,
          IsMaker: Number(this.userForm.desiger),
          CountryCode: this.userForm.telCode,
          Mobile: this.userForm.tel1 || this.userForm.telQY,
          Position: this.userForm.post,
          RegionType: "",
          RealName: this.userForm.name,
          Remark: "",
          SellerId: Number(SellerId),
          Sex: Number(this.userForm.sex),
          UserId: Number(userId),
        })
        .then((res) => {
          if (res.Ret === 200) {
            !this.isPickOther &&
              !this.isPickLoss &&
              this.$message.success("移动成功！");
            this.isHaveUser = false;
            this.$emit("cancel", 1, userId);
          }
        });
    },
    /* 取消弹窗 */
    cancelHandle() {
      this.$refs.userForm.resetFields();
      this.$emit("cancel");
    },
    //  取消联系人重复弹窗
    cancelHandle2() {
      this.canMove = "";
      this.isHaveUser = false;
    },
    // 点击我知道了
    knowHandle() {
      // 已重复联系人所属公司id
      let re_id = this.userData[0].CompanyId;
      let userId = this.userData[0].UserId; //重复联系人的id

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

      /* 领取流失客户或其他类型且联系人重复且不存在当前客户下 */
      if (
        (this.isPickLoss && re_id != Number(this.id)) ||
        (this.isPickOther && re_id != Number(this.id))
      ) {
        this.$message.warning("领取失败");
      }
      this.canMove = "";
      this.isHaveUser = false;
    },
    /* 预览 */
    preview() {
      $("#img").click();
    },
    clickinput() {
      //上传模拟点击
      // debugger
      $("#fileCard").click();
    },
    // 选择文件上传
    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) {
          this.$message.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
          this.uploadloading = true;
          customInterence.upload(form).then((res) => {
            if (res.Ret === 200) {
              // that.$message.success( '上传成功' );
              this.userForm.carte = res.Data.ResourceUrl;
            }
            this.uploadloading = false;
            $("#fileCard").val("");
            hostfile = {};
          });
        } else {
          this.$message.error("上传文件格式不正确！");
        }
      }
    },
  },
  created() {

  },
  mounted() {
    console.log(this.userForm);
  },
  computed: {
    ProductName() {
      let type = localStorage.getItem("RoleType") || "";
      if (type == "ficc") {
        return "ficc";
      } else if (type == "权益") {
        return "权益";
      } else {
        return "ficc";
      }
    },
  },
  watch: {
    isAddContact() {
        this.getPhoneCode()
      if (this.userForm.Source) {
        this.userFormIndeterminacy = this.userForm.Source
      } else {
        this.userForm.Source = this.userFormIndeterminacy || 'add_user'
      }
    }
  }
};
</script>
<style lang='scss'>
.concact_dialog {
  .el-form-item__label {
    width: 90px !important;
  }

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