<script setup>
import { ref, nextTick, watch } from "vue";
import { InfoFilled, Search } from "@element-plus/icons-vue";
import { useRouter, onBeforeRouteLeave } from "vue-router";
import { ElMessage } from "element-plus";
import { customInterence, equityContacts } from "@/api/api.js";
import mPage from "@/components/mPage.vue";
import InteractionDlg from "./compontents/interactionDlg.vue";
import LabelDlg from "./compontents/labelDlg.vue";
import RemindDlg from "./compontents/remindDlg.vue";
const router = useRouter();


const defaultSalesProps = {
  multiple: true,
  label: "RealName",
  children: "ChildrenList",
  value: "AdminId",
}; //销售级联配置
const registerOptions = [
  {
    label: "已注册",
    value: 1,
  },
  {
    label: "未注册",
    value: 0,
  },
];
const decisionOptions = [
  {
    label: "是",
    value: 1,
  },
  {
    label: "否",
    value: 0,
  },
];

const clientOptions = ref([]);
async function getUserStatusTable() {
  const res = await equityContacts.getUserStatusTable();
  if (res.Ret === 200) {
    clientOptions.value = res.Data.List || [];
  }
}
getUserStatusTable();

/* 获取销售 */
const salesArr = ref([]);
function getSale() {
  customInterence.getSalesRaiData().then((res) => {
    if (res.Ret === 200) {
      salesArr.value = res.Data.List;
    }
  });
}
getSale();

/* 获取列表 */
const sales = ref([]);
const tableData = ref([]);
const total = ref(0); //条数
const pageSize = ref(10); //每页显示几条
const page_no = ref(
  sessionStorage.getItem("contactsListBack")
    ? JSON.parse(sessionStorage.getItem("contactsListBack")).page_no
    : 1
);
const clientStatus = ref("");
const decisionValue = ref("");
const registerValue = ref(1);
const contactWay = ref(""); //手机号/邮箱/姓名/公司名
const userLabel = ref("");
const orderTable = ref("");
const isFollowValue = ref(""); //是否关注公众号
async function getCygxContactsList() {
  let salesArr = [];
  if (sales.value.length) {
    salesArr = sales.value.map((item) => {
      return item[item.length - 1];
    });
  }
  const res = await equityContacts.getCygxContactsList({
    PageSize: pageSize.value,
    CurrentIndex: page_no.value,
    Status: clientStatus.value[0] ? clientStatus.value[0] : "",
    TryStage: clientStatus.value[1] ? clientStatus.value[1] : "",
    IsMaker:
      decisionValue.value === 1
        ? decisionValue.value
        : decisionValue.value === 0
        ? decisionValue.value
        : 2,
    IsRegister:
      registerValue.value === 1
        ? registerValue.value
        : registerValue.value === 0
        ? registerValue.value
        : 2,
    AdminId: salesArr.join(","),
    KeyWord: contactWay.value,
    Label: userLabel.value,
    SortType: orderTable.value,
    IsSubscribeCygx: isFollowValue.value,
  });
  if (res.Ret === 200) {
    tableData.value = res.Data.List || [];
    total.value = res.Data.Paging.Totals;
  }
}
getCygxContactsList();

/* 页码改变事件 */
function handleCurrentChange(page) {
  page_no.value = page;
  getCygxContactsList();
}

function sortChangeHandle(item) {
  console.log(item.order);
  orderTable.value =
    item.order === "ascending"
      ? "asc"
      : item.order === "descending"
      ? "desc"
      : "";
  getCygxContactsList();
}

/* 筛选的change 事件 */
function handelGetData() {
  page_no.value = 1;
  getCygxContactsList();
}

/* 详情页 */
function goDetail(item) {
  router.push({
    path: "/customDetail",
    query: {
      id: item.CompanyId,
    },
  });
}

/* 点击了添加备注 和查看 */
const remarkDlgShow = ref(false); // 查看
const addRemarFrom = ref({}); //、添加备注
const addRemarText = ref("");
const lableRemarkList = ref([]);
async function lookOver(item, type) {
  addRemarFrom.value = _.cloneDeep(item);
  addRemarFrom.value.IsShowSee = type === "历史";
  remarkDlgShow.value = true;
  if (addRemarFrom.value.IsShowSee) {
    const res = await equityContacts.getCygxRemarkList({
      UserId: addRemarFrom.value.UserId,
    });
    if (res.Ret === 200) {
      nextTick(() => {
        lableRemarkList.value = res.Data.List || [];
      });
    }
  }
}
/* 弹框的关闭 */
function cancelHandle() {
  remarkDlgShow.value = false;
  addRemarText.value = "";
  addRemarFrom.value = {};
}
/* 弹框的确认 */
async function saveHandle() {
  if (addRemarFrom.value.IsShowSee) {
    addRemarFrom.value.IsShowSee = false;
  } else {
    if (addRemarText.value == "") return ElMessage.error("请输入备注信息");
    const res = await equityContacts.getCygxAddRemarks({
      Content: addRemarText.value,
      UserId: addRemarFrom.value.UserId,
    });
    if (res.Ret === 200) {
      ElMessage.success("添加成功");
      getCygxContactsList();
      cancelHandle();
    }
  }
}

/* 互助量点击 */
function lookInteraction(item, type) {
  const { href } = router.resolve({
    path: type === "个人" ? "/mutualList" : "/organizationList",
    query: {
      id: item.UserId,
      CompanyId: item.CompanyId,
    },
  });
  window.open(href, "_blank");
}

/* 标签下的单独的某一个 */
const interactionDlg = ref(false); //互助的弹框
const interactionFrom = ref({}); //互助的数据
function labelChildren(key, row) {
  interactionDlg.value = true;
  interactionFrom.value = {
    id: row.UserId,
    key,
  };
}

//鼠标经过了 机构互助量
const organizationTableL = ref([]); //互助量机构的
async function isShowOrganization(row) {
  const res = await equityContacts.getInteractionNum({
    UserId: row.UserId,
  });
  if (res.Ret === 200) {
    organizationTableL.value = res.Data.List || [];
  }
}

// 查看标签
const lookLabelList = ref([]);
async function lookLabels(item) {
  lookLabelList.value = [];
  const res = await equityContacts.getCygxLabelDetail({
    UserId: item.UserId,
  });
  if (res.Ret === 200) {
    lookLabelList.value = res.Data.Label && res.Data.Label.split(",");
  }
}

async function querySearchHandler(query, cb) {
  cb([]);
  if (!query) return;
  const res = await equityContacts.industrialManagementSearch({
    KeyWord: query,
  });
  if (res.Ret === 200) {
    if (res.Data && res.Data.List.length > 0) {
      let arr = res.Data.List.map((item) => {
        return { value: item.IndustryName, ...item };
      });
      cb(arr);
    } else {
      cb([{}]);
    }
  }
}

//点击操作的互助提醒
const isShowRemindDlg = ref(false); // 消息提醒的弹框
const remindList = ref({}); // 消息提醒的数据
async function remindHandler(item) {
  remindList.value = item;
  isShowRemindDlg.value = true;
}

// 处理标签不能超过10个
function lookLabelListNumber(row) {
  let arr = row.Labels ? row.Labels.split(",").splice(0, 10) : [];
  return arr;
}

// 标签展示弹框
const dlgLabelList = ref({});
const isShowLabelDlg = ref(false);
function showLabelDlg(row) {
  dlgLabelList.value = row;
  isShowLabelDlg.value = true;
}

watch(
  () => contactWay,
  () => {
    clientStatus.value = "";
    decisionValue.value = "";
    registerValue.value = "";
    sales.value = [];
    page_no.value = 1;
    getCygxContactsList();
  }
);

onBeforeRouteLeave((to, form, next) => {
  let backData = {
    page_no: page_no.value,
    keyword: contactWay.value,
    decisionValue: decisionValue.value,
    registerValue: registerValue.value,
    sales: sales.value,
    clientStatus: clientStatus.value,
    userLabel: userLabel.value,
    isFollowValue: isFollowValue.value,
  };
  sessionStorage.setItem("contactsListBack", JSON.stringify(backData));
  next();
});
</script>

<script>
import { defineComponent } from "vue";
export default defineComponent({
  //进入前是否清除参数
  beforeRouteEnter(to, from, next) {
    if (from.path !== "/mutualList" && from.path !== "/customDetail") {
      sessionStorage.removeItem("contactsListBack");
    }
    next();
  },
});
</script>

<template>
  <div class="container-contactsList">
    <div class="top-wrap">
      <el-input
        :prefix-icon="Search"
        v-model="contactWay"
        placeholder="手机号/邮箱/姓名/公司名"
        clearable
        style="width:200px"
      >
      </el-input>
      <el-select
        v-model="decisionValue"
        placeholder="是否KP"
        @change="handelGetData"
        clearable
      >
        <el-option
          v-for="item in decisionOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-select
        v-model="registerValue"
        placeholder="是否注册"
        @change="handelGetData"
        clearable
      >
        <el-option
          v-for="item in registerOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-select
        v-model="isFollowValue"
        placeholder="是否关注公众号"
        @change="handelGetData"
        clearable
      >
        <el-option
          v-for="item in decisionOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-cascader
        v-model="sales"
        placeholder="请选择销售"
        style="width: 200px;"
        :options="salesArr"
        :props="defaultSalesProps"
        :show-all-levels="false"
        collapse-tags
        clearable
        filterable
        @change="handelGetData"
      >
      </el-cascader>
      <el-cascader
        style="width: 200px;"
        v-model="clientStatus"
        :options="clientOptions"
        placeholder="请选择客户状态"
        clearable
        :props="{
          value: 'TryStage',
          label: 'Name',
          children: 'List',
          checkStrictly: true,
        }"
        @change="handelGetData"
      ></el-cascader>
      <el-autocomplete
        style="width: 200px; margin-bottom: 20px"
        clearable
        class="inline-input"
        v-model="userLabel"
        :fetch-suggestions="querySearchHandler"
        placeholder="用户标签搜索"
        @clear="handelGetData"
        :trigger-on-focus="false"
        @select="handelGetData"
      >
        <template #prefix>
          <el-icon class="el-input__icon"><search /></el-icon>
        </template>
        <template #default="scope">
          <div v-if="scope.item.IndustryName">
            {{ scope.item.IndustryName }}
          </div>
          <div v-else style="text-align: center">暂无数据</div>
        </template>
      </el-autocomplete>
    </div>
    <el-card>
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        @sort-change="sortChangeHandle"
      >
        <el-table-column align="center" prop="RealName" width="90" label="姓名">
        </el-table-column>
        <el-table-column
          align="center"
          prop="Mobile"
          width="130"
          label="手机号/邮箱"
        >
          <template #default="{ row }">
            {{ row.Mobile || row.Email }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="CompanyName" label="公司名称">
          <template #default="scope">
            <span class="editsty" @click="goDetail(scope.row)">{{
              scope.row.CompanyName
            }}</span></template
          >
        </el-table-column>
        <el-table-column align="center" prop="Status" width="100" label="状态">
        </el-table-column>
        <el-table-column
          align="center"
          prop="SellerName"
          width="110"
          label="所属销售"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="IsMaker"
          width="80"
          label="是否KP"
        >
          <template #default="{ row }">
            {{ row.IsMaker == 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="RegisterTime"
          width="130"
          label="注册时间"
        >
        </el-table-column>
        <el-table-column align="center" width="130" label="是否关注公众号">
          <template #default="{ row }">
            {{ row.IsSubscribeCygx == 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="InteractionNum"
          width="130"
          label="互动量"
          sortable="custom"
        >
          <template #header>
            互动量
            <el-tooltip placement="top">
              <template #content>
                <div>
                  个人互动量 / 机构总互动量<br />
                  点击右侧排序按钮可按照个人互动量升序/降序排列
                </div>
              </template>
              <el-icon><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
          <template #default="{ row }">
            <span class="editsty" @click="lookInteraction(row, '个人')">{{
              row.InteractionNum
            }}</span>
            /
            <el-popover
              trigger="hover"
              placement="right"
              @show="isShowOrganization(row)"
            >
              <table class="table-wrap-table-popover">
                <tr v-for="(item, index) in organizationTableL" :key="index">
                  <td class="table-item">{{ item.DateTime }}</td>
                  <td class="table-item">{{ item.InteractionNum }}</td>
                </tr>
              </table>
              <template #reference>
                <div>
                  <span class="editsty" @click="lookInteraction(row, '机构')">{{
                    row.CompanyInteractionNum
                  }}</span>
                </div>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="" width="350">
          <template #header>
            <div style="text-align: center">标签</div>
          </template>
          <template #default="{ row }">
            <div class="popover-item">
              <el-tag
                size="small"
                style="margin: 5px 8px; cursor: pointer"
                v-for="item in lookLabelListNumber(row)"
                :key="item"
                :type="userLabel === item ? 'danger' : ''"
                @click="labelChildren(item, row)"
              >
                {{ item }}
              </el-tag>
              <span
                @click="showLabelDlg(row)"
                style="font-weight: 700; padding: 5px 10px"
                class="editsty"
                v-if="row.Labels && row.Labels.split(',').length > 10"
                >...</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="" label="备注" width="90">
          <template #default="{ row }">
            <div class="remark-list">
              <div class="button">
                <span class="editsty" @click="lookOver(row, '添加')">添加</span>
                <span
                  v-if="row.Content"
                  style="font-weight: 700; padding: 5px 10px"
                  class="editsty"
                  @click="lookOver(row, '历史')"
                  >...</span
                >
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="" label="操作" width="100">
          <template #default="{ row }">
            <span
              :class="row.IsRemind ? 'deletesty' : 'editsty'"
              @click="remindHandler(row)"
              >{{ row.IsRemind ? "取消提醒" : "互动提醒" }}</span
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-col :span="24" class="toolbar">
        <m-page
          :total="total"
          :page_no="page_no"
          :pageSize="10"
          @handleCurrentChange="handleCurrentChange"
        />
      </el-col>
    </el-card>

    <el-dialog
      draggable
      v-model="remarkDlgShow"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      @close="cancelHandle"
      center
      :width="addRemarFrom.IsShowSee ? '800px' : '500px'"
    >
      <template #header>
        <div>
          <i
            class="el-icon-close"
            style="
              font-size: 24px;
              cursor: pointer;
              position: absolute;
              right: 20px;
              top: 50%;
              transform: translateY(-50%);
            "
            @click="cancelHandle"
          ></i>
          <span style="font-size: 16px">{{
            addRemarFrom.IsShowSee ? "历史备注" : "添加备注"
          }}</span>
        </div>
      </template>
      <div v-if="addRemarFrom.IsShowSee">
        <el-table
          :data="lableRemarkList"
          style="width: 100%"
          border
          height="350"
        >
          <el-table-column align="center" prop="Content" label="备注信息">
          </el-table-column>
          <el-table-column align="center" prop="CreateTime" label="备注时间">
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入备注信息"
          v-model.trim="addRemarText"
        >
        </el-input>
      </div>
      <div style="display: flex; justify-content: center; margin: 40px 0">
        <template v-if="!addRemarFrom.IsShowSee">
          <el-button type="primary" @click="saveHandle">确定</el-button>
          <el-button type="primary" plain @click="cancelHandle">取消</el-button>
        </template>
      </div>
    </el-dialog>
    <InteractionDlg
      :interactionDlg="interactionDlg"
      :interactionFrom="interactionFrom"
      @close="interactionDlg = false"
    />
    <label-dlg
      :isShowLabelDlg="isShowLabelDlg"
      :dlgLabelList="dlgLabelList"
      @labelChildren="labelChildren"
      :userLabel="userLabel"
      @close="isShowLabelDlg = false"
    />
    <remind-dlg
      :isShowRemindDlg="isShowRemindDlg"
      :remindList="remindList"
      @success="getCygxContactsList"
    />
  </div>
</template>
<style scoped lang="scss">
.container-contactsList {
  .el-select {
    width: 200px;
  }
  .top-wrap {
    margin-bottom: 28px;
    padding: 20px 30px 0;
    background: #fff;
    border: 1px solid #ececec;
    border-radius: 4px;
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  }
  .table-item {
    display: inline-block;
    width: 90px;
    height: 22px;
    background: #e8f3ff;
    border-radius: 4px;
    color: #2d8cf0;
    text-align: center;
    line-height: 22px;
    margin-bottom: 5px;
    margin-left: 5px;

    &:last-child {
      margin-bottom: 0px;
    }
  }
  .remark-list {
    .button {
      display: flex;
      flex-direction: row-reverse;
      justify-content: space-between;
      align-content: center;
      flex-shrink: 0;
    }
  }
}
.table-wrap-table-popover {
  color: #666;
  width: 100%;
  border-top: 1px solid #dcdfe6;
  border-left: 1px solid #dcdfe6;
  .table-item {
    padding: 5px 10px;
    border-right: 1px solid #dcdfe6;
    border-bottom: 1px solid #dcdfe6;
  }
}
.popover-item {
  overflow: hidden;
  overflow-y: auto;
}
.popover-not-have {
  width: 100%;
  text-align: center;
}
</style>
