<template>
  <div class="dataReport-service-container">
    <el-card>
      <el-cascader
        v-model="filterObj.sale"
        placeholder="请选择销售"
        style="width: 230px; margin-right: 10px"
        :options="salesArr"
        :props="defaultSalesProps"
        :show-all-levels="false"
        collapse-tags
        clearable
        filterable
        @change="changeFilter"
      >
      </el-cascader>
      <el-cascader
        v-model="filterObj.serveTypeId"
        placeholder="请选择销售"
        style="width: 230px; margin-right: 10px"
        :options="customSellerList"
        :props="defaultSalesProps"
        :show-all-levels="false"
        collapse-tags
        clearable
        filterable
        @change="changeFilter"
      >
      </el-cascader>
      <!-- <el-select clearable multiple v-model="filterObj.serveTypeId" placeholder="请选择咨询销售" style="width: 230px; margin-right: 10px" @change="changeFilter">
        <el-option v-for="item in customSellerList" :key="item.AdminId" :label="item.RealName" :value="item.AdminId"> </el-option>
      </el-select> -->
      <el-select clearable v-model="filterObj.status" placeholder="客户状态" style="width: 230px; margin-right: 10px" @change="changeFilter">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
      </el-select>
      <el-select clearable v-model="filterObj.serviceType" placeholder="服务类型" style="width: 230px; margin-right: 10px" @change="changeFilter">
        <el-option v-for="item in serviceTypeOptions" :key="item.ServeTypeId" :label="item.ServeTypeName" :value="item.ServeTypeId"> </el-option>
      </el-select>
      <el-select
        v-model="filterObj.lable"
        clearable
        filterable
        remote
        reserve-keyword
        placeholder="请输入服务主题标签"
        :remote-method="remoteMethod"
        style="width: 230px; margin-right: 10px"
        @change="selectLableHandler"
      >
        <el-option v-for="item in lableOptions" :key="item.Md5Key" :label="item.TagName" :value="item.Md5Key"> </el-option>
      </el-select>
      <el-input placeholder="请输入客户名称" v-model="searchVal" style="width: 230px; margin-right: 10px" @input="handleSearch" clearable>
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <a :href="exportExcel" download>
        <el-button type="primary">下载</el-button>
      </a>
    </el-card>
    <el-card style="margin-top: 20px">
      <el-table :data="tableData" border style="width: 100%" @sort-change="sortChangeHandle">
        <el-table-column align="center" prop="CompanyName" label="客户名称" width="180">
          <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>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="ServeCoverageRate" width="180">
          <template slot="header" slot-scope="{}">
            <span>近4周平均服务覆盖率</span>
            <el-tooltip effect="dark" placement="top-start">
              <div slot="content">
                <p>近4周服务覆盖率的平均值</p>
              </div>
              <i class="el-icon-warning"></i>
            </el-tooltip>
          </template>
          <template slot-scope="{ row }">
            <span @click="clickCoverage(row)" class="editsty">{{ row.ServeCoverageRate }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Status" label="当前状态" width="80"> </el-table-column>
        <el-table-column align="center" prop="SellerName" label="销售" width="100"> </el-table-column>
        <el-table-column align="center" prop="ShareSeller" label="服务组销售" width="100"> </el-table-column>
        <el-table-column align="center" prop="StartDate" sortable="custom" label="合同期限" width="180">
          <template slot-scope="{ row }">
            <span>{{ row.StartDate }}~{{ row.EndDate }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Money" sortable="custom" label="合同金额" width="110"> </el-table-column>
        <el-table-column align="center" prop="PermissionName" label="签约套餐"> </el-table-column>
        <el-table-column align="center" prop="ThisWeekAmount" width="118">
          <template slot="header" slot-scope="{}">
            <p>本周服务量</p>
            <p>{{ getWeekRange(0) }}</p>
          </template>
          <template slot-scope="{ row }">
            <span @click="billClickHandler(row, 1)" class="editsty">{{ row.ThisWeekAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="LastWeekAmount" width="118">
          <template slot="header" slot-scope="{}">
            <p>上周服务量</p>
            <p>{{ getWeekRange(-1) }}</p>
          </template>
          <template slot-scope="{ row }">
            <span @click="billClickHandler(row, 2)" class="editsty">{{ row.LastWeekAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="TwoWeekAmount" width="118">
          <template slot="header" slot-scope="{}">
            <p>上上周服务量</p>
            <p>{{ getWeekRange(-2) }}</p>
          </template>
          <template slot-scope="{ row }">
            <span @click="billClickHandler(row, 3)" class="editsty">{{ row.TwoWeekAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="ThreeWeekAmount" width="118">
          <template slot="header" slot-scope="{}">
            <p>上三周服务量</p>
            <p>{{ getWeekRange(-3) }}</p>
          </template>
          <template slot-scope="{ row }">
            <span @click="billClickHandler(row, 4)" class="editsty">{{ row.ThreeWeekAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="80" v-if="isRoleType == 'admin' || isRoleType == '权益'">
          <template slot-scope="{ row }">
            <span @click="historicalNotesClickHandler(row)" class="editsty">历史备注</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页数选择器 -->
      <m-page style="margin: 20px 0" :page_no="page_no" :pageSize="pageSize" :total="total" @handleCurrentChange="pageChange" />
    </el-card>
    <!-- 覆盖率弹框 -->
    <coverage-rate-dlg :isCoverageRateShow.sync="isCoverageRateShow" :dlgForm.sync="dlgForm" />
    <!-- 服务明细- -->
    <service-details-dlg
      :isServiceDetailsShow.sync="isServiceDetailsShow"
      :dlgForm.sync="dlgForm"
      :selectForm="{
        TagType: this.tagType,
        TagId: this.tagId,
        ServeTypeId: this.filterObj.serviceType,
        WhatWeek: this.whatWeek,
      }"
    />
    <historical-notes-dlg :historicalNotesDlgVisible.sync="historicalNotesDlgVisible" :CompanyId.sync="historicalNotesId" />
  </div>
</template>

<script>
import { dataMainInterface, customInterence } from "@/api/api.js";
import CoverageRateDlg from "./components/CoverageRateDlg.vue";
import ServiceDetailsDlg from "./components/ServiceDetailsDlg.vue";
import mPage from "@/components/mPage.vue";
import HistoricalNotesDlg from "@/components/historicalNotesDlg.vue";

export default {
  name: "",
  components: { CoverageRateDlg, ServiceDetailsDlg, mPage, HistoricalNotesDlg },
  props: {},
  data() {
    return {
      page_no: 1,
      total: 0,
      pageSize: 10,
      salesArr: [], //销售列表
      tableData: [],
      defaultSalesProps: {
        multiple: true,
        label: "RealName",
        children: "ChildrenList",
        value: "AdminId",
      }, //销售级联配置
      filterObj: {
        sale: "",
        status: "",
        serviceType: "",
        lable: "",
        ServeTypeId: "",
      },
      statusOptions: [
        { label: "正式客户", value: "正式" },
        { label: "未续约客户", value: "未续约" },
      ],
      serviceTypeOptions: [],
      isCoverageRateShow: false, //覆盖率弹框
      isServiceDetailsShow: false, //服务明细弹框
      dlgForm: {},
      sortType: "",
      sortParam: "",
      lableOptions: [],
      tagType: "",
      tagId: "",
      whatWeek: "",
      customSellerList: [],
      searchVal: "", //客户名称

      historicalNotesDlgVisible: false, //历史备注的弹框
      historicalNotesId: 0,
    };
  },
  computed: {
    exportExcel() {
      let salesArr = [];
      if (this.filterObj.sale.length) {
        salesArr = this.filterObj.sale.map((item) => {
          return item[item.length - 1];
        });
      }
      let SellerIds = [];
      if (this.filterObj.serveTypeId && this.filterObj.serveTypeId.length) {
        SellerIds = this.filterObj.serveTypeId.map((item) => {
          return item[item.length - 1];
        });
      }
      let baseUrl = process.env.API_ROOT + "/cygx/rai_serve/list";
      let token = localStorage.getItem("auth") || "";
      let paramStr = "";
      let parmsa = {
        SellerId: salesArr.join(","),
        ShareSellerId: SellerIds.join(","), //共享小时id
        ServeTypeId: this.filterObj.serviceType,
        TagType: this.tagType,
        TagId: this.tagId,
        Status: this.filterObj.status,
        SortType: this.sortType,
        IsExport: true,
        KeyWord: this.searchVal,
      };
      for (let key in parmsa) {
        paramStr = `${paramStr}&${key}=${parmsa[key]}`;
      }
      return `${baseUrl}?${token}${paramStr}`;
    },
    // crm 15.9.1 区分权益FICC的展示
    isRoleType() {
      return localStorage.getItem("RoleType") || "";
    },
  },
  watch: {},
  created() {},
  mounted() {
    this.getSale();
    this.getRaiServeTypeList();
    this.getDataList();
    this.getRaiServeCustomSellerList();
  },
  methods: {
    handleSearch() {
      this.page_no = 1;
      this.getDataList();
    },
    /* 获取销售 */
    getSale() {
      customInterence.getSalesRaiData().then((res) => {
        if (res.Ret === 200) {
          this.salesArr = res.Data.List;
        }
      });
    },
    /* 筛选改变时 */
    changeFilter() {
      this.page_no = 1;
      this.getDataList();
    },
    // 时间的计算
    getWeekRange(offset) {
      const now = new Date();
      const startOfWeek = new Date(now);
      startOfWeek.setDate(now.getDate() - now.getDay() + 1 + offset * 7); // 设置为每周的周一
      const endOfWeek = new Date(startOfWeek);
      endOfWeek.setDate(startOfWeek.getDate() + 6); // 设置为每周的周日

      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = ("0" + (date.getMonth() + 1)).slice(-2);
        const day = ("0" + date.getDate()).slice(-2);
        return `${month}-${day}`;
      };

      return `(${formatDate(startOfWeek)} ~ ${formatDate(endOfWeek)})`;
    },
    pageChange(page_no) {
      this.page_no = page_no;
      this.getDataList();
    },
    // 获取表格数据
    async getDataList() {
      let salesArr = [];
      if (this.filterObj.sale.length) {
        salesArr = this.filterObj.sale.map((item) => {
          return item[item.length - 1];
        });
      }
      let SellerIds = [];
      if (this.filterObj.serveTypeId && this.filterObj.serveTypeId.length) {
        SellerIds = this.filterObj.serveTypeId.map((item) => {
          return item[item.length - 1];
        });
      }
      const res = await dataMainInterface.getRaiServeList({
        PageSize: this.pageSize,
        CurrentIndex: this.page_no,
        SellerId: salesArr.join(","),
        ShareSellerId: SellerIds.join(","), //共享小时id
        ServeTypeId: this.filterObj.serviceType,
        TagType: this.tagType,
        TagId: this.tagId,
        Status: this.filterObj.status,
        SortType: this.sortType,
        KeyWord: this.searchVal,
        SortParam: this.sortParam,
      });
      if (res.Ret === 200) {
        this.tableData = res.Data.List || [];
        this.total = res.Data.Paging.Totals;
      }
    },

    sortChangeHandle({ column, prop, order }) {
      this.sortType = order === "ascending" ? "asc" : order === "descending" ? "desc" : "";
      this.sortParam = prop == "Money" ? "money" : prop == "StartDate" ? "endDate" : "";
      this.getDataList();
    },
    /* 详情页 */
    goDetail(item) {
      const { href } = this.$router.resolve({
        path: "/customDetail",
        query: {
          id: item.CompanyId,
        },
      });
      window.open(href, "_blank");
    },
    // 搜索标签
    async remoteMethod(query) {
      if (query !== "") {
        const res = await dataMainInterface.getRaiServeSearchTag({
          KeyWord: query,
        });
        if (res.Ret === 200) {
          this.lableOptions = res.Data.List || [];
        }
      } else {
        this.lableOptions;
      }
    },
    // 远程搜索标签
    selectLableHandler() {
      if (this.filterObj.lable) {
        this.lableOptions.forEach((item) => {
          if (item.Md5Key === this.filterObj.lable) {
            this.tagType = item.TagType;
            this.tagId = item.TagId;
          }
        });
      } else {
        this.tagType = "";
        this.tagId = "";
      }
      this.changeFilter();
    },
    // 近四周覆盖率
    clickCoverage(item) {
      this.isCoverageRateShow = true;
      this.dlgForm = item;
    },
    // 点击了明细
    billClickHandler(item, type) {
      this.whatWeek = type;
      this.isServiceDetailsShow = true;
      this.dlgForm = item;
    },
    // 获取服务类型列表
    async getRaiServeTypeList() {
      const res = await dataMainInterface.getRaiServeTypeList();
      if (res.Ret === 200) {
        this.serviceTypeOptions = res.Data.List || [];
      }
    },
    //
    async getRaiServeCustomSellerList() {
      const res = await dataMainInterface.getRaiServeCustomSellerList();
      if (res.Ret === 200) {
        this.customSellerList = res.Data || [];
      }
    },
    // 点击了历史留言
    historicalNotesClickHandler(item) {
      this.historicalNotesDlgVisible = true;
      this.historicalNotesId = item.CompanyId;
    },
  },
};
</script>
<style scoped lang="scss">
.dataReport-service-container {
}
</style>
