<template>
  <div class="container-contactsList">
    <div class="top-wrap">
      <el-input style="width: 200px; margin-right: 20px" v-model="contactWay" placeholder="手机号/邮箱/姓名/公司名" prefix-icon="el-icon-search" clearable></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; margin: 0 20px 20px 0"
        :options="salesArr"
        :props="defaultSalesProps"
        :show-all-levels="false"
        collapse-tags
        clearable
        filterable
        @change="handelGetData"
      >
      </el-cascader>
      <el-cascader
        style="width: 200px; margin-right: 20px"
        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"
        prefix-icon="el-icon-search"
        clearable
        class="inline-input"
        v-model="userLabel"
        :fetch-suggestions="querySearchHandler"
        placeholder="用户标签搜索"
        @clear="handelGetData"
        :trigger-on-focus="false"
        @select="handelGetData"
      >
        <template slot-scope="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="姓名">
          <template slot-scope="{ row }">
            <span>{{ row.RealName }}</span>
            
            <img width="16" v-if="row.HaveMoveButton" style="vertical-align: middle; cursor: pointer" src="../../../assets/img/contact_transfer.jpg" alt="" @click="clickContactTransfer(row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Mobile" width="110" label="手机号/邮箱">
          <template slot-scope="{ row }"> {{ row.Mobile || row.Email }} </template>
        </el-table-column>
        <el-table-column align="center" prop="CompanyName" label="公司名称">
          <template slot-scope="{ row }">
            <el-tooltip effect="dark" placement="top-start" content="过去4周，kp均未覆盖服务" v-if="row.IsUserMaker == -1">
              <span class="deletesty" @click="goDetail(row)">{{ row.CompanyName }}</span>
            </el-tooltip>
            <span v-else class="editsty" @click="goDetail(row)">{{ row.CompanyName }}</span>
            <!-- <span class="editsty" @click="goDetail(scope.row)">{{ scope.row.CompanyName }}</span> -->
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Status" width="110" 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 slot-scope="{ row }">
            {{ row.IsMaker == 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="RegisterTime" width="110" label="注册时间"> </el-table-column>
        <el-table-column align="center" width="120" label="是否关注公众号">
          <template slot-scope="{ row }">
            {{ row.IsSubscribeCygx == 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="InteractionNum" width="110" label="互动量" :render-header="renderHeader" sortable="custom">
          <template slot-scope="{ 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>
              <span slot="reference" class="editsty" @click="lookInteraction(row, '机构')">{{ row.CompanyInteractionNum }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="" width="350">
          <div slot="header" slot-scope="{}" style="text-align: center">标签</div>
          <template slot-scope="{ row }">
            <div class="popover-item">
              <el-tag size="mini" 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 slot-scope="{ 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="160">
          <template slot-scope="{ row }">
            <span :class="row.IsRemind ? 'deletesty' : 'editsty'" @click="remindHandler(row)">{{ row.IsRemind ? "取消提醒" : "互动提醒" }}</span>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <span class="editsty" @click="feedbackHandler(row)">交流反馈</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 v-dialogDrag :visible.sync="remarkDlgShow" :close-on-click-modal="false" :modal-append-to-body="false" @close="cancelHandle" center :width="addRemarFrom.IsShowSee ? '800px' : '500px'">
      <div slot="title">
        <i class="el-icon-close" style="fontsize: 24px; cursor: pointer; position: absolute; right: 20px; top: 50%; transform: translateY(-50%)" @click="cancelHandle"></i>
        <span style="fontsize: 16px">{{ addRemarFrom.IsShowSee ? "历史备注" : "添加备注" }}</span>
      </div>
      <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.sync="interactionDlg" :interactionFrom="interactionFrom" />
    <label-dlg :isShowLabelDlg.sync="isShowLabelDlg" :dlgLabelList.sync="dlgLabelList" @labelChildren="labelChildren" :userLabel="userLabel" />
    <remind-dlg :isShowRemindDlg.sync="isShowRemindDlg" :remindList.sync="remindList" />
    <FeedbackDlg :showFeedbackDlg.sync="showFeedbackDlg" :remindList.sync="remindList" />
    <ContactTransfer :contactTransferDlgVisible.sync="contactTransferDlgVisible" :TransferMobile.sync="TransferMobile" />
  </div>
</template>

<script>
import { customInterence, equityContacts } from "@/api/api.js";
import mPage from "@/components/mPage.vue";
import mDialog from "@/components/mDialog.vue";
import InteractionDlg from "./compontents/interactionDlg.vue";
import LabelDlg from "./compontents/labelDlg.vue";
import RemindDlg from "./compontents/remindDlg.vue";
import FeedbackDlg from "./compontents/feedbackDlg.vue";
import ContactTransfer from "../customList/components/ContactTransferDlg.vue";

export default {
  name: "",
  components: { mPage, mDialog, InteractionDlg, LabelDlg, RemindDlg, FeedbackDlg, ContactTransfer },
  props: {},
  data() {
    return {
      contactWay: "", //手机号/邮箱/姓名/公司名
      decisionValue: "",
      isFollowValue: "", //是否关注公众号
      decisionOptions: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],
      registerValue: 1,
      registerOptions: [
        {
          label: "已注册",
          value: 1,
        },
        {
          label: "未注册",
          value: 0,
        },
      ],
      sales: [],
      salesArr: [], //销售
      defaultSalesProps: {
        multiple: true,
        label: "RealName",
        children: "ChildrenList",
        value: "AdminId",
      }, //销售级联配置
      clientStatus: "",
      clientOptions: ["试用", "冻结", "正式"],
      tableData: [],
      total: 0, //条数
      pageSize: 10, //每页显示几条
      page_no: sessionStorage.getItem("contactsListBack") ? JSON.parse(sessionStorage.getItem("contactsListBack")).page_no : 1,
      remarkDlgShow: false, // 查看
      addRemarFrom: {}, //、添加备注
      addRemarText: "",
      lableRemarkList: [],
      lookLabelList: "啤酒,冷冻烘焙,立高食品,鸿合科技,智能交互平板,速冻火锅料及预制菜,安井食品,千味央厨,速冻米面,视源股份,xx",
      userLabel: "",
      interactionDlg: false, //互助的弹框
      interactionFrom: {}, //互助的数据
      orderTable: "",
      organizationTableL: [], //互助量机构的
      isShowLabelDlg: false, //
      dlgLabelList: {}, //
      isShowRemindDlg: false, // 消息提醒的弹框
      remindList: {}, // 消息提醒的数据
      showFeedbackDlg: false, // 交流反馈的弹框

      TransferMobile: 0,

      contactTransferDlgVisible: false, //联系人转移的弹框
    };
  },
  computed: {},
  watch: {
    contactWay: {
      handler(newval) {
        this.clientStatus = "";
        this.decisionValue = "";
        this.registerValue = "";
        this.selesArr = [];
        this.page_no = 1;
        this.getCygxContactsList();
      },
    },
  },
  created() {},
  mounted() {
    if (sessionStorage.getItem("contactsListBack")) {
      const { keyword, decisionValue, registerValue, sales, clientStatus, userLabel, isFollowValue } = JSON.parse(sessionStorage.getItem("contactsListBack"));
      this.contactWay = keyword;
      this.decisionValue = decisionValue;
      this.registerValue = registerValue;
      this.sales = sales;
      this.clientStatus = clientStatus;
      this.userLabel = userLabel;
      this.isFollowValue = isFollowValue;
    }
    this.getUserStatusTable();
    this.getCygxContactsList();
    this.getSale();
  },
  methods: {
    async getUserStatusTable() {
      const res = await equityContacts.getUserStatusTable();
      if (res.Ret == 200) {
        this.clientOptions = res.Data.List || [];
      }
    },
    /* 获取销售 */
    getSale() {
      customInterence.getSalesRaiData().then((res) => {
        if (res.Ret === 200) {
          this.salesArr = res.Data.List;
        }
      });
    },
    /* 获取列表 */
    async getCygxContactsList() {
      let salesArr = [];
      if (this.sales.length) {
        salesArr = this.sales.map((item) => {
          return item[item.length - 1];
        });
      }
      const res = await equityContacts.getCygxContactsList({
        PageSize: this.pageSize,
        CurrentIndex: this.page_no,
        Status: this.clientStatus[0] ? this.clientStatus[0] : "",
        TryStage: this.clientStatus[1] ? this.clientStatus[1] : "",
        IsMaker: this.decisionValue === 1 ? this.decisionValue : this.decisionValue === 0 ? this.decisionValue : 2,
        IsRegister: this.registerValue === 1 ? this.registerValue : this.registerValue === 0 ? this.registerValue : 2,
        AdminId: salesArr.join(","),
        KeyWord: this.contactWay,
        Label: this.userLabel,
        SortType: this.orderTable,
        IsSubscribeCygx: this.isFollowValue,
      });
      if (res.Ret === 200) {
        this.tableData = res.Data.List || [];
        this.total = res.Data.Paging.Totals;
      }
    },
    //table表头自定义
    renderHeader(h, { column, $index }) {
      return h("div", { attrs: { style: "display:inline-block;" } }, [
        h("span", column.label),
        h("el-tooltip", { props: { placement: "top" } }, [
          h("p", { slot: "content", attrs: { style: "display:block;width:280px;text-align: center" } }, "个人互动量 /  机构总互动量"),
          h("p", { slot: "content", attrs: { style: "display:block;width:280px;" } }, "点击右侧排序按钮可按照个人互动量升序/降序排列"),
          h("el-button", { props: { icon: "el-icon-info" }, attrs: { style: "border:none;background:none;width:20px;padding:0 0 0 5px;" } }, ""),
        ]),
      ]);
    },
    /* 页码改变事件 */
    handleCurrentChange(page) {
      this.page_no = page;
      this.getCygxContactsList();
    },
    /* 详情页 */
    goDetail(item) {
      this.$router.push({
        path: "/customDetail",
        query: {
          id: item.CompanyId,
        },
      });
    },
    /* 点击了添加备注 和查看 */
    async lookOver(item, type) {
      this.addRemarFrom = _.cloneDeep(item);
      this.addRemarFrom.IsShowSee = type === "历史";
      this.remarkDlgShow = true;
      if (this.addRemarFrom.IsShowSee) {
        const res = await equityContacts.getCygxRemarkList({ UserId: this.addRemarFrom.UserId });
        if (res.Ret === 200) {
          this.$nextTick(() => {
            this.lableRemarkList = res.Data.List || [];
          });
        }
      }
    },
    /* 弹框的关闭 */
    cancelHandle() {
      this.remarkDlgShow = false;
      this.addRemarText = "";
      this.addRemarFrom = {};
    },
    /* 弹框的确认 */
    async saveHandle() {
      if (this.addRemarFrom.IsShowSee) {
        this.addRemarFrom.IsShowSee = false;
      } else {
        if (this.addRemarText == "") return this.$message.error("请输入备注信息");
        const res = await equityContacts.getCygxAddRemarks({
          Content: this.addRemarText,
          UserId: this.addRemarFrom.UserId,
        });
        if (res.Ret === 200) {
          this.$message.success("添加成功");
          this.getCygxContactsList();
          this.remarkDlgShow = false;
          this.addRemarText = "";
          this.addRemarFrom = {};
        }
      }
    },
    /* 筛选的change 事件 */
    handelGetData() {
      this.page_no = 1;
      this.getCygxContactsList();
    },
    /* 互助量点击 */
    lookInteraction(item, type) {
      const { href } = this.$router.resolve({
        path: type === "个人" ? "/mutualList" : "/organizationList",
        query: {
          id: item.UserId,
          CompanyId: item.CompanyId,
        },
      });
      window.open(href, "_blank");
    },
    /* 标签下的单独的某一个 */
    labelChildren(key, row) {
      this.interactionDlg = true;
      this.interactionFrom = {
        id: row.UserId,
        key,
      };
    },
    //鼠标经过了 机构互助量
    async isShowOrganization(row) {
      const res = await equityContacts.getInteractionNum({
        UserId: row.UserId,
      });
      if (res.Ret === 200) {
        this.organizationTableL = res.Data.List || [];
      }
    },
    // 查看标签
    async lookLabels(item) {
      this.lookLabelList = [];
      const res = await equityContacts.getCygxLabelDetail({
        UserId: item.UserId,
      });
      if (res.Ret === 200) {
        this.lookLabelList = res.Data.Label && res.Data.Label.split(",");
      }
    },
    async 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([{}]);
        }
      }
    },
    //点击操作的互助提醒
    async remindHandler(item) {
      this.remindList = item;
      this.isShowRemindDlg = true;
    },
    sortChangeHandle(item) {
      console.log(item.order);
      this.orderTable = item.order === "ascending" ? "asc" : item.order === "descending" ? "desc" : "";
      this.getCygxContactsList();
    },
    // 处理标签不能超过10个
    lookLabelListNumber(row) {
      let arr = row.Labels ? row.Labels.split(",").splice(0, 10) : [];
      return arr;
    },
    // 展示弹框
    showLabelDlg(row) {
      this.dlgLabelList = row;
      this.isShowLabelDlg = true;
    },
    // 点击了交流反馈
    feedbackHandler(item) {
      this.remindList = item;
      this.showFeedbackDlg = true;
    },
    // 点击了共享联系人
    clickContactTransfer(item) {
      this.contactTransferDlgVisible = true;
      this.TransferMobile = item.Mobile;
    },
  },
  /* 页面跳转前记录参数 */
  beforeRouteLeave(to, from, next) {
    let backData = {
      page_no: this.page_no,
      keyword: this.contactWay,
      decisionValue: this.decisionValue,
      registerValue: this.registerValue,
      sales: this.sales,
      clientStatus: this.clientStatus,
      userLabel: this.userLabel,
      isFollowValue: this.isFollowValue,
    };
    sessionStorage.setItem("contactsListBack", JSON.stringify(backData));
    next();
  },
  /* 页面进入前是否清除参数 */
  beforeRouteEnter(to, from, next) {
    if (from.path !== "/mutualList" && from.path !== "/customDetail") {
      sessionStorage.removeItem("contactsListBack");
    }
    next();
  },
};
</script>
<style scoped lang="scss">
.container-contactsList {
  .el-select {
    width: 200px;
    margin-right: 20px;
    margin-bottom: 20px;
  }
  .top-wrap {
    margin-bottom: 28px;
    padding: 20px 30px 0;
    background: #fff;
    border: 1px solid #ececec;
    border-radius: 4px;
    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>
