<script setup>
import { computed, ref,reactive, toRefs } from 'vue';
import { useRoute,useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue';
import { organizationTableColums, screenList, meetingList } from "./compontents/contactsColums";
import { customInterence, equityContacts } from "@/api/api.js";
import mPage from "@/components/mPage.vue";
import ChartItem from "./compontents/chartItem.vue";
import DatePicker from 'vue-datepicker-next';
import moment from 'moment';
import _ from 'lodash';
import { useList } from './hooks/use-list'


const route = useRoute();
const router = useRouter()

const exportExcel = computed(()=> {
  let baseUrl = import.meta.env.VITE_APP_API_ROOT + "/cygx/user/company/export/interaction";
  let token = localStorage.getItem("auth") || "";
  let paramStr = "";
  let params = {
    CompanyId: Number(route.query.CompanyId),
    Source: tableFilterState.activeName,
    IsMeeting: tableFilterState.checkMeetingList.join(","),
    MeetType: tableFilterState.checkActiveList.join(","),
    EndDate: tableFilterState.end_date,
    StartDate: tableFilterState.start_date,
    KeyWord: tableFilterState.searchVal,
    ActivityName: tableFilterState.activityName,
  };
  for (let key in params) {
    paramStr = `${paramStr}&${key}=${params[key]}`;
  }
  return `${baseUrl}?${token}${paramStr}`;
})


const { monthLabel,handleRowContent } = useList()


//获取基础数据
const list = ref([])
const userForm = ref({})
async function getCygxMutualList() {
  const res = await equityContacts.getCompanyTableList({
    CompanyId: Number(route.query.CompanyId),
  });
  if (res.Ret === 200) {
    list.value = res.Data.List || [];
    userForm.value = res.Data;
    getTableData();
  }
}
getCygxMutualList()

//获取表格数据
const tableLoading = ref(false)
const tableColums = ref(organizationTableColums(1))
const tableData = ref([])
const total = ref(0)
const tableFilterState = reactive({
  activeName: 1,
  page_no: 1,
  pageSize: 10,
  publicHaveMove: true,
  checkActiveList: [1, 2], //活动的方式
  checkMeetingList: [1, 2], //是否到会
  searchVal: "",
  start_date: "",
  end_date: "",
  month: "",
  date: [],
  activityName: ""
})
async function getTableData() {
  tableLoading.value = true;
  const res = await equityContacts.getCompanyInteractionDetail({
    CompanyId: Number(route.query.CompanyId),
    Source: tableFilterState.activeName,
    PageSize: tableFilterState.pageSize,
    CurrentIndex: tableFilterState.page_no,
    IsMeeting: tableFilterState.checkMeetingList.join(","),
    MeetType: tableFilterState.checkActiveList.join(","),
    EndDate: tableFilterState.end_date,
    StartDate: tableFilterState.start_date,
    KeyWord: tableFilterState.searchVal,
    ActivityName: tableFilterState.activityName,
    
  });
  if (res.Ret === 200) {
    total.value = res.Data.Paging.Totals;
    tableLoading.value = false;
    tableData.value = res.Data.List || [];
  }
}

//一级的点击事件
function handleTabsClick(item) {
  if (tableFilterState.activeName != item.Source) {
    tableFilterState.activeName = item.Source;
    this.tableColums = organizationTableColums(tableFilterState.activeName);
  }
  tableFilterState.checkActiveList = [1, 2]; //活动的方式
  tableFilterState.checkMeetingList = [1, 2]; //是否到会
  tableFilterState.month = '';
  tableFilterState.date = [];

  tableFilterState.searchVal = "";
  tableFilterState.activityName = "";
  tableFilterState.chartList = [];
  tableFilterState.end_date = "";
  tableFilterState.start_date = "";
  tableFilterState.page_no = 1;
  if (tableFilterState.activeName !== 4) {
    getTableData();
  } else {
    getChartData();
  }
}

//获取图表
const chartList = ref([])
const publicHaveMoveCompany = ref(false)
async function getChartData() {
  const res = await equityContacts.getCompanyInteractionDetail({
    CompanyId: Number(route.query.CompanyId),
    Source: tableFilterState.activeName,
    CurrentIndex: tableFilterState.page_no,
    IdentityType: 2,
    KeyWord: tableFilterState.searchVal,
  });
  if (res.Ret === 200) {
    tableFilterState.publicHaveMove = res.Data ? tableFilterState.page_no < res.Data.Paging.Pages : false;
    publicHaveMoveCompany.value = res.Data.List.length > 0;
    chartList.value = res.Data ? (tableFilterState.page_no === 1 ? res.Data.List : [...chartList.value, ...res.Data.List]) : [];
  }
}


//去往全机构详情
function goWholeDetail() {
  const { href } = router.resolve("/wholeOrganization");
  window.open(href, "_blank");
}


//销售的选择
function handleSalesChange() {
  if (tableFilterState.activeName !== 4) return;
  tableFilterState.page_no = 1;
  getChartData();
}


const handleSearchActivity = _.debounce(function () {
  tableFilterState.page_no = 1;
  if (tableFilterState.activeName !== 4) {
    getTableData();
  } else {
    chartList.value = [];
    getChartData();
  }
}, 1000)


/* 选择服务日期 */
function dateChange(e) {
  if (e[0]) {
    tableFilterState.start_date = e[0];
    tableFilterState.end_date = e[1];
  } else {
    tableFilterState.start_date = "";
    tableFilterState.end_date = "";
  }
  tableFilterState.month = "";
  tableFilterState.page_no = 1;
  tableFilterState.searchVal = "";
  getTableData();
}

/* 切换月份 */
function toggleMonth(label) {
  tableFilterState.month = label;
  let days = label == "近1个月" ? -1 : label == "近3个月" ? -3 : 0;
  filterDate(days);
}
/* 获取未来几个月的日期范围 */
function filterDate(month) {
  if (month) {
    let date_now = moment().add(month, "M").format("YYYY-MM-DD");
    let date_after = moment().format("YYYY-MM-DD");
    let date = [date_now, date_after];
    tableFilterState.start_date = date_now;
    tableFilterState.end_date = date_after;
    tableFilterState.date = date;
    tableFilterState.page_no = 1;
    tableFilterState.searchVal = "";
    getTableData();
  }
}


// 搜索
function handleSearch() {
  tableFilterState.page_no = 1;
  getTableData();
}

// 页码改变事件
function handleCurrentChange(page, index) {
  tableFilterState.page_no = page;
  getTableData();
}


/* 表格行的样式 */
function handleRowStyle(key) {
  const style = {
    Title: "color: #409eff; cursor: pointer",
    ActivityName: "color: #409eff; cursor: pointer",
  };
  return style[key] && ([1,8].includes(tableFilterState.activeName)) ? style[key] : "";
}

/* 表格行的点击事件 */
function handleRowClick(row, key) {
  if (key === "Title") {
    if (row.SpecialType > 0) {
      let href = `${import.meta.env.VITE_CYGX_WEB}/column/detail/${row.ArticleId}`;
      window.open(href, "_blank");
      return;
    }
    if (row.ArticleType == 1) {
      let url =
        import.meta.env.MODE === "production"
          ? "https://details.hzinsights.com/cygx/report"
          : import.meta.env.MODE === "test"
          ? "http://xcxh5test.hzinsights.com/xcx_h5/cygx/report"
          : "http://xcxh5test.hzinsights.com/xcx_h5/cygx/report";
      let href = `${url}?id=${row.ArticleIdMd5}`;
      window.open(href, "_blank");
    } else {
      let href = `https://vmp.hzinsights.com/v2/articles/${row.ArticleId}`;
      window.open(href, "_blank");
    }
  } else if (key === "ActivityName" && tableFilterState.activeName === 8) {
    themeDetails(row.ActivityId);
  }
}

const { 
  activeName,
  page_no,
  pageSize,
  publicHaveMove,
  checkActiveList, //活动的方式
  checkMeetingList, //是否到会
  searchVal,
  month,
  date,
  activityName } = toRefs(tableFilterState)
</script>
<template>
  <div class="container-organization">
    <el-card>
      <div class="introduce">
        <span class="synopsis-btn">{{ userForm.ComapnyName }}</span>
        <span class="attention">注：机构的互动详情，是截止至昨天24点的数据，非当前实时数据</span>
        <span class="organization-details" @click="goWholeDetail">全机构互动详情>></span>
      </div>
      <div class="tabs">
        <span :class="['item', activeName == item.Source && 'active']" v-for="item in list" :key="item.Source" @click="handleTabsClick(item)">{{ item.PermissionName }} ({{ item.TotalNum }})</span>
      </div>
      <div class="son-box">
        <div style="display: flex; align-items: center" v-if="activeName == 2">
          <el-checkbox-group v-model="checkActiveList" @change="handleSearch">
            <el-checkbox :label="item.key" v-for="item in screenList" :key="item.key">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
          <el-checkbox-group style="margin-left: 25px" v-model="checkMeetingList" @change="handleSearch">
            <el-checkbox :label="item.key" v-for="item in meetingList" :key="item.key">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
          <el-tooltip class="tooltip-item" effect="dark" content="线上活动设置预约外呼/会议提醒/预约纪要，线下活动报名/预约纪要，但实际未参会的活动" placement="top-start">
            <i class="el-icon-info"></i>
          </el-tooltip>
        </div>
        <div class="dataReport-top">
          <template v-if="activeName == 1 || activeName == 2">
            <date-picker
              v-model:value="date"
              type="date"
              range
              value-type="format"
              :placeholder="activeName == 2 ? '活动时间' : '阅读时间'"
              :editable="false"
              @change="dateChange"
              style="width: 200px; margin-right: 20px"
            />
            <button :class="['button-sty', { act: month === item.label }]" v-for="item in monthLabel" @click="toggleMonth(item.label)" :key="item.label">
              {{ item.label }}
            </button>
          </template>
          <el-input placeholder="手机号/邮箱/姓名" v-model="searchVal" style="width: 200px; margin-right: 20px" @input="handleSearchActivity" clearable>
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
          <el-input v-if="activeName == 2" placeholder="活动名称" v-model="activityName" style="width: 200px" @input="handleSearchActivity" clearable>
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
          <a :href="exportExcel" download v-if="activeName == 1 || activeName == 2">
            <button class="button-sty act">下载EXCEL</button>
          </a>
        </div>
      </div>
      <template v-if="activeName != 4">
        <el-table style="margin-top: 20px" :data="tableData" v-loading="tableLoading" element-loading-text="数据加载中..." border>
          <el-table-column v-for="item in tableColums" :key="item.label" :label="item.label" :width="item.widthsty" :min-width="item.minwidthsty" align="center">
            <template #default="{ row }">
              <span @click="handleRowClick(row, item.key)" :style="handleRowStyle(item.key)">{{ handleRowContent(row, item.key) }}</span>
            </template>
          </el-table-column>
          <template #empty>
            <div style="padding: 20px 0">
              <img src="~@/assets/img/data_m/table_no.png" alt="" style="display: block; width: 135px; height: 90px; margin: 0 auto" />
              <span>暂无数据</span>
            </div>
          </template>
        </el-table>
        <el-col :span="24" class="toolbar">
          <m-page :total="total" :page_no="page_no" :pageSize="10" @handleCurrentChange="handleCurrentChange" />
        </el-col>
      </template>
      <template v-else>
        <template v-if="publicHaveMoveCompany">
          <div v-for="item in chartList" :key="item.UserId">
            <template v-if="item.ListChart">
              <ChartItem :chartData="item" />
            </template>
          </div>
        </template>
        <template v-else>
          <img src="~@/assets/img/data_m/table_no.png" alt="" style="display: block; width: 135px; height: 90px; margin: 30px auto" />
          <p class="chart-no-data">暂无收藏的图表</p>
        </template>
      </template>
    </el-card>
  </div>
</template>
<style scoped lang="scss">
.container-organization {
  .introduce {
    .attention {
      font-size: 14px;
      color: #999999;
      display: inline-block;
      margin: 0 20px;
    }
    .organization-details {
      cursor: pointer;
      font-size: 14px;
      color: #3385ff;
    }
  }
  @import "./compontents/details.scss";
  .synopsis-btn {
    margin-top: 20px;
    display: inline-block;
    height: 32px;
    padding: 0 20px;
    background: #eaf2ff;
    border-radius: 2px;
    border: 1px solid #3385ff;
    color: #3385ff;
    line-height: 30px;
  }
}
</style>
