<script setup>
import { ref, watch, onMounted, computed } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { raiInterface, raiSpecial } from "@/api/api.js";

const props = defineProps({
  addDialogVisible: {
    type: Boolean,
    default: false,
  },
  selectList: {
    type: String,
  },
  signUpAdd: {
    type: String,
  },
  minimumSummation: {
    type: Number,
  },

  selectionArr: {
    type: Array,
    required: true,
    default: [],
  },
  addDialogType: {
    type: String,
    required: true,
  },
});

const dynamicItem = ref([{ name: "", isShow: false, radio: "1", checked: false }]);
const companyList = ref([]); //客户名称的数组
const userTyepa = ref([]); //客户名称的数组
const timeout = ref(null);
const warningIsShow = ref(false);
const isShow = ref("");
const userId = ref("");

const isType = computed(() => {
  if (props.selectionArr.length > 0) {
    return props.selectionArr.some(
      (item) => item.ActivityTypeName == "公司调研电话会" || item.ActivityTypeName == "专家电话会" || item.ActivityTypeName == "分析师电话会" || item.IsYidongConduct == 1
    );
  }
});

const isShowSummary = computed(() => {
  if (props.selectionArr.length > 0) {
    return (props.addDialogType == "新增外呼人员" || props.addDialogType == "新增报名") && !props.selectionArr.some((item) => item.ActivityTypeName == "公司调研电话会" && item.LimitPeopleNum !== 0);
  }
});

const $emit = defineEmits(["getsDataList"]);

async function confirmPerson() {
  let addSignuUser = addSignuUser();
  measurement();
  const is = dynamicItem.value.some((item) => item.isShow == true);
  if (is) return ElMessage.error("姓名有误");
  if (!userId.value) return ElMessage.error("请输入姓名！");
  const res =
    (isType.value && props.addDialogType != "新增预约纪要") || props.signUpAdd == "报名" || props.signUpAdd == "易董" || props.signUpAdd == "c类"
      ? await raiInterface.activitySignupAddSignuUser({
          ActivityIds: props.selectList,
          List: addSignuUser,
        })
      : props.signUpAdd == "专项"
      ? await raiSpecial.addUserSpecial({
          ActivityIds: props.selectList,
          List: addSignuUser,
        })
      : props.addDialogType == "新增预约纪要"
      ? await raiInterface.activityAddSummaryUser({
          ActivityIds: props.selectList,
          UserIds: userId.value,
        })
      : await raiInterface.activitySignupAddUser({
          ActivityIds: props.selectList,
          List: addSignuUser,
        });

  if (res.Ret === 200) {
    ElMessage.success("添加成功");
    $emit.getsDataList();
  }
  userId.value = "";
  userTyep.value = [];
  (dynamicItem.value = [{ name: "", isShow: false, radio: "1", checked: false }]), $emit("update:addDialogVisible", false);
}
function addSignuUser() {
  let arr = [];
  dynamicItem.value.forEach((item) => {
    if (item.name) {
      arr.push({
        IsAppointment: item.checked ? 1 : 0,
        UserId: item.id,
        SignupType: isType.value ? +item.radio : 0,
      });
    }
  });
  return arr;
}
// 添加数组
function addItem() {
  if (props.signUpAdd == "报名" && props.minimumSummation == dynamicItem.value.length) return ElMessage.warning(`所选活动最多还能添加${props.minimumSummation}人`);
  dynamicItem.value.push({
    name: "",
    isShow: false,
    radio: "1",
    checked: false,
  });
}
// 删除数组的某一项
function deleteItem(item, index) {
  dynamicItem.value.splice(index, 1);
}
/* 获取客户名称 */
function getCompany(query) {
  if (query.includes(",")) return;
  if (query) {
    raiInterface
      .activitySignupUserList({
        KeyWord: query,
      })
      .then((res) => {
        if (res.Ret === 200) {
          let arr = [];
          res.Data.List &&
            res.Data.List.forEach((item) => {
              let obj = {
                ...item,
                value: item.RealName + " , " + item.Mobile + " , " + item.CompanyName,
              };
              arr.push(obj);
            });
          companyList.value = arr;
        }
      });
  } else {
    companyList.value = [];
  }
}
function callbackHandle(data, cb) {
  let results = data
    ? companyList.value.filter((item) => {
        return item.value.includes(data);
      })
    : companyList.value;
  clearTimeout(timeout.value);
  timeout.value = setTimeout(() => {
    cb(results);
  }, 300);
  if (results.length == 0) {
    warningIsShow.value = true;
  } else {
    warningIsShow.value = false;
  }
}
//退出弹框
function handleClose() {
  userId.value = "";
  userTyep.value = [];
  dynamicItem.value = [{ name: "", isShow: false, radio: "1", checked: false }];
  $emit("update:addDialogVisible", false);
}
//失去焦点
function focusCompany(name) {
  if ((name.length && companyList.value.length == 0) || warningIsShow.value) {
    dynamicItem.value.forEach((item) => {
      if (item.name == name) {
        item.isShow = true;
      }
    });
  } else {
    dynamicItem.value.forEach((item) => {
      if (item.name == name) {
        item.isShow = false;
      }
    });
  }
}
//联想选择后

function selectCompany(val, index) {
  companyList.value.forEach((item) => {
    if (item.value == val.name) {
      dynamicItem.value.splice(index, 1, { name: val.name, isShow: false, radio: val.radio, id: item.UserId, checked: dynamicItem.value[index].checked });
    }
  });
}
//最后的确定 遍历
function measurement() {
  const arr = [];
  const userIds = [];
  dynamicItem.value.forEach((item) => {
    if (item.name) {
      let obj = {
        Uid: item.id,
        Type: item.radio,
      };
      userIds.push(item.id);
      arr.push(obj);
    }
  });
  userId.value = userIds.length ? userIds.join(",") : "";
  userTyep.value = JSON.stringify(arr);
}
</script>

<template>
  <div class="container-applydialog">
    <el-dialog
      draggable
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      center
      v-model="props.addDialogVisible"
      :customClass="[isType && props.addDialogType !== '新增预约纪要' ? 'container-applydial' : 'container-custom']"
      :before-close="handleClose"
    >
      <template #header>
        <div style="display: flex; align-items: center">
          <img :src="$icons.add" style="color: #fff; width: 16px; height: 16px; margin-right: 5px" />
          <span style="font-size: 16px">{{ props.addDialogType }}</span>
        </div>
      </template>
      <div class="inline" v-for="(item, index) in dynamicItem" :key="index">
        <div class="inline-content">
          <el-autocomplete
            class="inline-input"
            v-model="item.name"
            :fetch-suggestions="callbackHandle"
            placeholder="请输入姓名"
            @input="getCompany(item.name)"
            @select="selectCompany(item, index)"
            @blur="focusCompany(item.name)"
            :trigger-on-focus="false"
            clearable
          ></el-autocomplete>
          <template v-if="props.selectionArr && props.selectionArr.length && props.selectionArr[0].ActivityTypeName == '公司调研电话会'">
            <div class="radio-content" v-if="props.selectionArr[0].IsResearchPoints != 1">
              <el-radio v-model="item.radio" label="1">预约外呼</el-radio>
              <el-radio v-model="item.radio" label="2" v-if="props.selectionArr[0].LimitPeopleNum > 0">自主拨入</el-radio>
            </div>
            <div style="margin: 0 20px" v-if="props.selectionArr[0].IsCanAppointmentMinutes > 0">
              <el-checkbox v-model="item.checked">同时预约纪要</el-checkbox>
            </div>
          </template>
          <template v-else>
            <div v-if="isType && props.addDialogType !== '新增预约纪要'" class="radio-content">
              <el-radio v-model="item.radio" label="1">预约外呼</el-radio>
              <el-radio v-model="item.radio" label="2">自主拨入</el-radio>
            </div>
            <div style="margin: 0 20px" v-if="isShowSummary && props.signUpAdd !== '易董' && props.signUpAdd !== '专项'">
              <el-checkbox v-model="item.checked">同时预约纪要</el-checkbox>
            </div>
          </template>
          <div style="width: 20px"><img @click="deleteItem(item, index)" src="~@/assets/img/icons/delete-Item.png" :class="index == 0 ? 'defaultyi' : ''" alt="" /></div>
        </div>
        <p v-if="item.isShow">系统中无此人，请先将其添加到对应公司的联系人列表下</p>
      </div>
      <div class="add-box">
        <img @click="addItem" :src="$icons.addblue" alt="" />
        <span @click="addItem">添加</span>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="confirmPerson">确定</el-button>
          <el-button @click="handleClose">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.container-applydialog {
  .container-custom {
    width: 700px;
  }
  .container-applydial {
    width: 900px;
  }
  .inline {
    margin-bottom: 20px;
    width: 100%;
    .inline-input {
      width: 392px !important;
    }
    p {
      padding-top: 5px;
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 500;
      line-height: 20px;
      color: #ef5858;
      opacity: 1;
    }
  }
  .inline-content {
    padding-right: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    img {
      width: 14px;
      height: 14px;
    }
  }
  .defaultyi {
    display: none !important;
  }
  .el-input {
    width: 392px !important;
  }
  .add-box {
    display: flex;
    align-items: center;
    color: #5882ef;
    img {
      width: 16px;
      height: 16px;
      margin-right: 10px;
    }
  }
  .radio-content {
    display: flex;
    justify-content: space-between;
    margin: 0 30px;
  }
}
</style>
