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

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

const router = useRouter()

onBeforeRouteLeave((to, form, next) => {
  let backData = {
    page_no: pageState.page_no,
    end_date: pageState.end_date,
    start_date: pageState.start_date,
    filterObj: pageState.filterObj,
  };
  sessionStorage.setItem("incrementBack", JSON.stringify(backData));
  next();
})

const pageState = reactive({
  searchVal: sessionStorage.getItem("incrementBack") ? JSON.parse(sessionStorage.getItem("incrementBack")).searchVal : "",
  tableData: [],
  isShowloadding: false,
  start_date: "",
  end_date: "",
  /* 筛选条件 */
  filterObj: {
    month: "近1个月",
    date: [],
    sale: "",
    data_type: "行业新签",
  },
  monthLabel: [
    {
      label: "近1个月",
    },
    {
      label: "近2个月",
    },
    {
      label: "近3个月",
    },
  ],
  salesArr: [], //销售列表
  defaultSalesProps: {
    multiple: true,
    label: "RealName",
    children: "ChildrenList",
    value: "AdminId",
  }, //销售级联配置
  pageSize: 10,
  page_no: sessionStorage.getItem("incrementBack") ? JSON.parse(sessionStorage.getItem("incrementBack")).page_no : 1,
  total: 0,
  data_typeArr: [
    {
      label: "行业新签",
    },
    {
      label: "行业续约",
    },
    {
      label: "行业未续约",
    },
  ], //数据类型
  NewCompanyTotal: 0, //行业新签数
  NotRenewalCompanyTotal: 0, //行业未续约数
  RenewalCompanyTotal: 0, //行业续约数
  listPermissionName: [],
  tabsPitchon: "医药",
})

const exportExcel = computed(() => {
  let baseUrl = import.meta.env.VITE_APP_API_ROOT + "/statistic_report/merge_company/company_contract_permission/list";
  let token = localStorage.getItem("auth") || "";
  let paramStr = "";
  // 处理销售筛选
  let salesArr = [];
  if (pageState.filterObj.sale.length) {
    salesArr = pageState.filterObj.sale.map((item) => {
      return item[item.length - 1];
    });
  }
  let obj = {
    IsExport: true,
    Keyword: pageState.searchVal,
    AdminId: salesArr.join(","),
    EndDate: pageState.end_date,
    StartDate: pageState.start_date,
    DataType: pageState.filterObj.data_type,
    PermissionName: pageState.tabsPitchon,
  };
  for (let key in obj) {
    paramStr = `${paramStr}&${key}=${obj[key]}`;
  }
  return `${baseUrl}?${token}${paramStr}`;
})
const Role = computed(() => {
  let role = localStorage.getItem("Role") || "";
  return role;
})
//管理权限
const ManageType = computed(() => {
  return localStorage.getItem("ManageType") || "";
})
//确认未续约权限
const canConfirmNotRenewed = computed(() => {
  return ["admin", "rai_admin"].includes(pageState.Role);
})



// 搜索
function handleSearch() {
  if (!pageState.searchVal) {
    pageState.page_no = 1;
    pageState.filterObj = {
      month: "近1个月",
      date: [],
      sale: "",
      data_type: pageState.filterObj.data_type,
    };
    let date_before = moment().subtract(1, "M").format("YYYY-MM-DD");
    let date_now = moment().format("YYYY-MM-DD");
    let date = [date_before, date_now];
    pageState.start_date = date_before;
    pageState.end_date = date_now;
    pageState.filterObj.date = date;
    getTableData();
    return;
  }
  pageState.page_no = 1;
  pageState.filterObj = {
    month: "",
    date: [],
    sale: "",
    data_type: pageState.filterObj.data_type,
  };
  pageState.start_date = "";
  pageState.end_date = "";
  getTableData();
}
/* 获取表格 */
function getTableData() {
  pageState.isShowloadding = true;
  // 处理销售筛选
  let salesArr = [];
  if (pageState.filterObj.sale.length) {
    salesArr = pageState.filterObj.sale.map((item) => {
      return item[item.length - 1];
    });
  }
  let params = {
    Keyword: pageState.searchVal,
    PageSize: pageState.pageSize,
    CurrentIndex: pageState.page_no,
    AdminId: salesArr.join(","),
    EndDate: pageState.end_date,
    StartDate: pageState.start_date,
    DataType: pageState.filterObj.data_type,
    PermissionName: pageState.tabsPitchon,
  };
  dataMainInterface.incrementalCompanyContractPermissionList(params).then((res) => {
    if (res.Ret === 200) {
      pageState.tableData = res.Data.List || [];
      pageState.total = res.Data.Paging.Totals;
      pageState.NewCompanyTotal = res.Data.NewCompanyTotal;
      pageState.RenewalCompanyTotal = res.Data.RenewalCompanyTotal;
      pageState.NotRenewalCompanyTotal = res.Data.NotRenewalCompanyTotal;
      pageState.isShowloadding = false;
      pageState.listPermissionName = res.Data.ListPermissionName;
    }
  });
}
/* 获取销售 */
function getSale() {
  customInterence.getSalesRaiData().then((res) => {
    if (res.Ret === 200) {
      pageState.salesArr = res.Data.List;
    }
  });
}
/* 切换月份 */
function toggleMonth(label) {
  pageState.filterObj.month = label;
  let days = label == "近1个月" ? 1 : label == "近2个月" ? 2 : label == "近3个月" ? 3 : 0;
  filterDate(days);
}
/* 选择服务日期 */
function dateChange(e) {
  if (e[0]) {
    pageState.start_date = e[0];
    pageState.end_date = e[1];
  } else {
    pageState.start_date = "";
    pageState.end_date = "";
  }
  pageState.filterObj.month = "";
  pageState.page_no = 1;
  pageState.searchVal = "";
  getTableData();
}
/* 切换数据类型 */
function toggleType(label) {
  pageState.tabsPitchon = "医药";
  pageState.filterObj.data_type = label;
  pageState.page_no = 1;
  getTableData();
}
/* 筛选改变时 */
function changeFilter() {
  pageState.page_no = 1;
  pageState.searchVal = "";
  getTableData();
}
/* 切换页码 */
function handleCurrentChange(page) {
  pageState.page_no = page;
  getTableData();
}
/* 获取近几个月的日期范围 */
function filterDate(month) {
  if (month) {
    let date_before = moment().subtract(month, "M").format("YYYY-MM-DD");
    let date_now = moment().format("YYYY-MM-DD");
    let date = [date_before, date_now];
    pageState.start_date = date_before;
    pageState.end_date = date_now;
    pageState.filterObj.date = date;
    pageState.page_no = 1;
    pageState.searchVal = "";
    getTableData();
  }
}
function tabsBoxBtn(item) {
  pageState.tabsPitchon = item.PermissionName;
  changeFilter();
}
// 去往公司详情
function goCompanyHandle(row) {
  let { href } = router.resolve({
    path: "/customDetail",
    query: {
      id: row.CompanyId,
    },
  });
  window.open(href, "_blank");
}

onMounted(() => {
  getSale();
  if (sessionStorage.getItem("incrementBack")) {
    let backData = JSON.parse(sessionStorage.getItem("incrementBack"));
    pageState.page_no = backData.page_no;
    pageState.end_date = backData.end_date;
    pageState.start_date = backData.start_date;
    pageState.filterObj = backData.filterObj;
    pageState.searchVal = backData.searchVal;
  }
  /* 默认选中近1个月 */
  filterDate(pageState.filterObj.month === "近1个月" ? 1 : pageState.filterObj.month === "近2个月" ? 2 : pageState.filterObj.month === "近3个月" ? 3 : 0);
})



</script>

<template>
  <div class="dataReport-container" id="dataReport-container">
    <div class="dataReport-top">
      <a :href="exportExcel" download>
        <button class="button-sty act">导出EXCEL</button>
      </a>
      <button
        :class="['button-sty', { act: pageState.filterObj.month === item.label }]"
        v-for="item in pageState.monthLabel"
        @click="toggleMonth(item.label)"
        :key="item.label"
      >
        {{ item.label }}
      </button>
      <el-date-picker
        v-model="pageState.filterObj.date"
        type="daterange"
        value-format="yyyy-MM-dd"
        placeholder="自定义时间段"
        :clearable="false"
        :editable="false"
        @change="dateChange"
      />
      <el-input
        placeholder="请输入客户名称"
        v-model="pageState.searchVal"
        style="width: 400px; margin-left: auto"
        @input="handleSearch"
        clearable
        :prefix-icon="Search"
      >
      </el-input>
    </div>
    <div class="dataReport-main">
      <div class="main-top">
        <el-cascader
          v-if="
            Role == 'finance' ||
            Role == 'admin' ||
            Role == 'ficc_admin' ||
            Role == 'rai_admin' ||
            ManageType != 0
          "
          v-model="pageState.filterObj.sale"
          placeholder="请选择销售"
          style="min-width: 250px; margin-right: 10px; margin-bottom: 8px"
          :options="pageState.salesArr"
          :props="pageState.defaultSalesProps"
          :show-all-levels="false"
          collapse-tags
          clearable
          filterable
          @change="changeFilter"
        >
        </el-cascader>
      </div>
      <div class="main-section">
        <el-row :gutter="36">
          <el-col :span="8" v-for="item in pageState.data_typeArr" :key="item.label">
            <el-card
              :class="[
                'base-card',
                { 'main-card': pageState.filterObj.data_type === item.label },
              ]"
              shadow="hover"
              @click="toggleType(item.label)"
            >
              <template #header>
              <div class="clearfix">
                <span>
                  {{ item.label }}
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="
                      item.label === '行业新签'
                        ? '行业合同开始时间在查询时间段内，且该行业在历史上没有转正记录'
                        : item.label === '行业续约'
                        ? '行业合同开始时间在查询时间段内，且该行业历史上有过正式到期记录'
                        : '行业合同到期时间在查询时间段内，且该行业当前状态是非正式状态'
                    "
                    placement="top"
                  >
                    <el-icon><InfoFilled /></el-icon>
                  </el-tooltip>
                </span>
              </div>
              </template>
              <div class="card-cont">
                {{
                  item.label === "行业新签"
                    ? pageState.NewCompanyTotal
                    : item.label === "行业续约"
                    ? pageState.RenewalCompanyTotal
                    : item.label === "行业未续约"
                    ? pageState.NotRenewalCompanyTotal
                    : ""
                }}
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <div class="tabs-content-box">
        <span
          v-for="item in pageState.listPermissionName"
          :key="item.ChartPermissionId"
          @click="tabsBoxBtn(item)"
          :class="item.PermissionName == pageState.tabsPitchon ? 'pitch' : ''"
        >
          {{ item.PermissionName }} （{{ item.Total }}）
        </span>
      </div>
      <el-table
        :data="pageState.tableData"
        border
        style="margin-top: 20px; min-height: 400px"
        v-loading="pageState.isShowloadding"
        element-loading-text="数据加载中..."
      >
        <el-table-column label="公司名称" prop="CompanyName" align="center">
          <template #default="{ row }">
            <span class="editsty" @click="goCompanyHandle(row)">{{
              row.CompanyName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          width="100"
          label="所属销售"
          prop="SellerName"
          align="center"
        >
        </el-table-column>
        <el-table-column label="合同金额" prop="Money" align="center">
        </el-table-column>
        <el-table-column label="合同期限" prop="StartDate" align="center">
          <template #default="{ row }">
            <span>{{ row.StartDate }} ~ {{ row.EndDate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="签约套餐" prop="PermissionName" align="center">
          <template #default="{ row }">
            <template v-if="row.PermissionName.length">
              <el-tag
                size="mini"
                style="margin: 0 10px 10px 0"
                v-for="key in row.PermissionName.split(',')"
                :key="key"
                >{{ key }}</el-tag
              >
            </template>
          </template>
        </el-table-column>
        <template v-if="pageState.filterObj.data_type == '行业未续约'">
          <el-table-column
            width="118"
            label="当前行业状态"
            prop="PermissionNameStatus"
            align="center"
          >
          </el-table-column>
          <el-table-column
            width="118"
            label="当前客户状态"
            prop="CompanyProductStatus"
            align="center"
          >
          </el-table-column>
        </template>
      </el-table>
      <el-col :span="24" class="toolbar" v-if="pageState.total">
        <m-page
          :total="pageState.total"
          :page_no="pageState.page_no"
          @handleCurrentChange="handleCurrentChange"
        />
      </el-col>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "./index.scss";
.tabs-box {
  flex-direction: column;
  .tabs-box-confirm {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .center-line {
      width: 1px;
      height: 21px;
      background-color: #333333;
      margin: 0 20px;
    }
    .confirm-box-li {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      width: 120px;
      height: 40px;
      border-radius: 4px;
    }
    .active {
      background-color: #409eff;
      color: #fff;
    }
  }
}
.operation-button {
  color: #409eff;
  cursor: pointer;
  font-size: 14px;
  margin-right: 10px;
}
.remark-row {
  display: flex;
  justify-content: center;
  .remark-text {
    width: 18px;
    height: 18px;
    margin-right: 8px;
    font-size: 18px;
    color: #409eff;
    cursor: pointer;
  }
}
.operation-row {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  .operation-button {
    &:last-child {
      margin-right: 0;
    }
  }
}
.package-difference {
  cursor: pointer;
}
.tabs-content-box {
  margin-top: 20px;
  span {
    display: inline-block;
    padding: 9px 24px;
    background-color: #e9f4ff;
    border: 1px solid #b3d8ff;
    border-radius: 4px;
    margin-right: 30px;
    color: #409eff;
    cursor: pointer;
  }
  .pitch {
    background-color: #409eff;
    border: none;
    color: #fff;
  }
}
</style>
<style lang="scss">
#dataReport-container {
  .tabs-box {
    .el-radio-button {
      margin-right: 0;
    }
    .el-radio-button .el-radio-button__inner {
      border: none;
      width: 120px;
      height: 40px;
      border-radius: 4px;
    }
  }
}
</style>