<script setup>
import mPage from "@/components/mPage.vue";
import { dataMainInterface, customInterence } from "@/api/api.js";
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from "vue-router"
import { Search,InfoFilled } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const defaultSalesProps = {
    multiple: true,
    label: "RealName",
    children: "ChildrenList",
    value: "AdminId",
} //销售级联配置

const clientOptions = [
    {
        label: "正式",
        value: "1",
    },
    {
        label: "试用",
        value: "2",
    },
    {
        label: "永续",
        value: "3",
    },
]//状态

let dialogVisibleDetail = ref(false)
let sellOptions = ref([]) //销售
let sellName = ref("") //销售
let clientState = ref("") //状态
let pageSize = ref(10)
let page_no = ref(1)
let total = ref(0)
let tableData = ref([])
let tableDataDlg = ref([])
let keyword = ref("")
let orderNumber = ref("1")
let visitTotal = ref("")
let chartName = ref("")

let exportExcel = computed(()=>{
    let arr = sellName.value.length ? sellName.value.map((item) => item[item.length - 1]) : "";
    let sellUname = arr.length ? arr.join(",") : "";
    let str = `&Keyword=${keyword.value}&CompanyStatus=${clientState.value}&SellerId${sellUname}`;
    return (import.meta.env.VITE_APP_API_ROOT + "/yb/chartCensus/exportChartVisitDetailCensusList?" + localStorage.getItem("auth") || "") + "&ClassifyId=" + route.query.id + str;
})

watch(keyword,(newVal)=>{
    sellName.value = "";
    clientState.value = "";
    page_no.value = 1;
    getTableList();
})

onMounted(()=>{
    if (!route.query.name) {
      router.push("/readStatistics");
    } else {
      chartName.value = route.query.name;
      getTableList();
      getSale();
    }
})
/* 获取销售 */
function getSale() {
    customInterence.getSale().then((res) => {
        if (res.Ret === 200) {
            sellOptions.value = res.Data.List;
        }
    });
}
function sortChangeHandle(item) {
    if (item.prop === "LastVisitTime") {
        orderNumber.value = item.order === "ascending" ? "1" : "2";
        getTableList();
    }
}
//分页
function handleCurrentChange(page) {
    page_no.value = page;
    getTableList();
}
//获取表格数据
async function getTableList() {
    let arr = sellName.value.length ? sellName.value.map((item) => item[item.length - 1]) : "";
    const res = await dataMainInterface.getchartgetVisitDetailList({
        PageSize: pageSize.value,
        CurrentIndex: page_no.value,
        ClassifyId: route.query.id,
        Order: orderNumber.value,
        SellerId: arr.length ? arr.join(",") : "",
        CompanyStatus: clientState.value,
        Keyword:keyword.value,
    });
    if (res.Ret === 200) {
        tableData.value = res.Data.List;
        visitTotal.value = res.Data.VisitTotal;
        total.value = res.Data.Paging.Totals;
    }
}
function goChartList() {
    /**
     * 先禁掉，这个会跳到原先my eta的页面，这个页面现在再ETA系统里
     * 如果后面需要跳转，获取临时token跳到ETA系统 参考 dataReport_manage/components/CollectList.vue -> showChartDetail
     * 
     */
    /* router.push({
        path: "/readChart",
        query: {
            id: route.query.id,
        },
    }); */
}
//表格的 change 事件
function changeTableDate() {
    page_no.value = 1;
    getTableList();
}
function dlgCancel() {
    dialogVisibleDetail.value = false;
}
async function cisitCountBtn(item) {
    const res = await dataMainInterface.getCompanyChartVisitDetail({
        UserId: item.UserId,
        ClassifyId: route.query.id,
    });
    if (res.Ret === 200) {
        dialogVisibleDetail.value = true;
        nextTick(() => {
            tableDataDlg.value = res.Data || [];
        });
    }
}
function goDetail(item) {
    router.replace({
        path: "/customDetail",
        query: {
            id: item.CompanyId,
        },
    });
}
//table表头自定义
function renderHeader(h, { column, $index }) {
    return h("div", { attrs: { style: "padding:0;" } }, [
        h("span", column.label),
        h("el-tooltip", { props: { placement: "top" } }, [
            h("p", { slot: "content", attrs: { style: "display:block;padding:5px 0;" } }, "展示该图表详情累计阅读次数（当天重复阅读不纳入统计）"),
            h("el-button", { props: { icon: "el-icon-info" }, attrs: { style: "border:none;background:none;pading:2px" } }, ""),
        ]),
    ]);
}
</script>
<template>
    <div class="container-readClassify">
      <el-card>
        <div class="top-box">
          <div>
            <a :href="exportExcel" download>
              <el-button type="primary">导出EXCEL</el-button>
            </a>
            <el-cascader
              v-model="sellName"
              placeholder="请选择销售"
              style="width: 230px; margin: 0 30px"
              :options="sellOptions"
              :props="defaultSalesProps"
              :show-all-levels="false"
              collapse-tags
              clearable
              filterable
              @change="changeTableDate"
            >
            </el-cascader>
            <el-select style="width: 230px" v-model="clientState" @change="changeTableDate" placeholder="请选择客户状态" clearable>
              <el-option v-for="item in clientOptions" :key="item.label" :label="item.label" :value="item.label"> </el-option>
            </el-select>
          </div>
          <div style="width: 400px">
            <el-input :prefix-icon="Search" v-model="keyword" placeholder="联系人姓名/客户名称" clearable>
            </el-input>
          </div>
        </div>
      </el-card>
      <el-card style="margin-top: 30px">
        <div class="content-text">
          图分类： <span @click="goChartList">{{ chartName }}</span> |&nbsp;&nbsp;&nbsp; 阅读人数： <span>{{ visitTotal }}</span>
        </div>
        <el-table :data="tableData" border style="width: 100%" @sort-change="sortChangeHandle">
          <el-table-column prop="UserName" label="联系人姓名" align="center"></el-table-column>
          <el-table-column prop="CompanyName" label="客户名称" align="center">
            <template #default="scope">
              <span class="editsty" @click="goDetail(scope.row)">{{ scope.row.CompanyName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="SellerName" label="所属销售" align="center"></el-table-column>
          <el-table-column prop="CompanyStatus" label="客户状态" align="center"></el-table-column>
          <el-table-column prop="VisitCount" label="查看明细" align="center">
            <template #default="scope">
              <span class="editsty" @click="cisitCountBtn(scope.row)">{{ scope.row.VisitCount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="LastVisitTime" label="最近一次查看时间" align="center" sortable="custom"></el-table-column>
        </el-table>
        <el-col :span="24" class="toolbar">
          <m-page :total="total" :page_no="page_no" @handleCurrentChange="handleCurrentChange" />
        </el-col>
      </el-card>
      <el-dialog :close-on-click-modal="false" :modal-append-to-body="false" v-model="dialogVisibleDetail" width="661px" @close="dlgCancel">
        <template #header>
            <div style="display: flex; align-items: center">
                <img :src="$icons.warn" style="color: #fff; width: 16px; height: 16px; margin-right: 5px" />
                <span style="font-size: 16px"> 查看明细 </span>
            </div>
        </template>
        
        <div>
          <p>图分类：{{ chartName }}</p>
          <el-table :data="tableDataDlg" border style="width: 100%; margin: 20px 0 30px" height="350">
            <el-table-column prop="ChartName" label="图表名称" align="center"></el-table-column>
            <el-table-column prop="VisitCount" align="center">
                <template #header>
                    <div>
                        <span>查看次数</span>
                        <el-tooltip effect="dark" content="展示该图表详情累计阅读次数（当天重复阅读不纳入统计）" placement="top">
                                <InfoFilled style="width:14px;height:14px;"/>
                        </el-tooltip>
                    </div>
                </template>
                <template #default="scope">
                    {{ scope.row.VisitCount }}
                </template>
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>
    </div>
</template>
  <style scoped lang="scss">
  .container-readClassify {
    .top-box {
      display: flex;
      justify-content: space-between;
    }
    .content-text {
      margin-bottom: 30px;
      span {
        color: #409eff;
      }
      :first-child {
        margin-right: 10px;
      }
    }
  }
  </style>
