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

</script>


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

const router = useRouter()

const Role = computed(() => {
  return localStorage.getItem('Role') || '';
})
//管理权限
const ManageType = computed(() => {
  return localStorage.getItem('ManageType') || '';
})
const exportExcel = computed(() => {
  let baseUrl = import.meta.env.VITE_APP_API_ROOT + "/statistic_report/will_expire_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 = {
    PageSize: pageState.pageSize,
    CurrentIndex: pageState.page_no,
    CompanyType: pageState.filterObj.type,
    AdminId: salesArr.join(','),
    RegionType: pageState.filterObj.area,
    EndDate: pageState.end_date,
    StartDate: pageState.start_date,
    Keyword: pageState.searchVal,
    IsExport: true
  };
  for (let key in obj) {
    paramStr = `${paramStr}&${key}=${obj[key]}`;
  }
  return `${baseUrl}?${token}${paramStr}`;
})

const pageState = reactive({
  searchVal: sessionStorage.getItem('expiringListBack') ? JSON.parse(sessionStorage.getItem('expiringListBack')).searchVal : '',//搜索关键词
  isShowloadding: false,
  start_date: '',
  end_date: '',
  /* 筛选条件 */
  filterObj: {
    month: '未来1个月',
    date: [],
    type: '',
    sale: '',
    area: ''
  },
  monthLabel: [
    {
      label: "未来1个月"
    },
    {
      label: "未来2个月"
    },
    {
      label: "未来3个月"
    }
  ],
  salesArr: [],//销售列表
  defaultSalesProps: {
    multiple: true,
    label: 'RealName',
    children: 'ChildrenList',
    value: 'AdminId'
  },//销售级联配置
  typeArr: [
    {
      name: 'ficc'
    }, {
      name: '权益'
    }
  ],//类型
  areaArr: ['国内', '海外'],
  pageSize: 10,
  page_no: sessionStorage.getItem('expiringListBack') ? JSON.parse(sessionStorage.getItem('expiringListBack')).page_no : 1,
  total: 0,
  totalCompany: 0,//总客户数
})

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


// 搜索
function handleSearch() {
  if (!pageState.searchVal) {
    pageState.page_no = 1
    pageState.filterObj = {
      month: '未来1个月',
      date: [],
      type: '',
      sale: '',
      area: ''
    }
    let date_now = moment().format("YYYY-MM-DD");
    let date_after = moment().add(1, 'M').format("YYYY-MM-DD");
    let date = [date_now, date_after]
    pageState.start_date = date_now;
    pageState.end_date = date_after;
    pageState.filterObj.date = date;
    getTableData()
    return
  }
  pageState.page_no = 1
  pageState.filterObj = {
    month: '',
    date: [],
    type: '',
    sale: '',
    area: ''
  }
  pageState.start_date = '';
  pageState.end_date = '';
  getTableData()
}

/* 获取表格 */
function getTableData() {
  // 处理销售筛选
  let salesArr = []
  if (pageState.filterObj.sale.length) {
    salesArr = pageState.filterObj.sale.map(item => {
      return item[item.length - 1]
    })
  }
  pageState.isShowloadding = true;
  let params = {
    PageSize: pageState.pageSize,
    CurrentIndex: pageState.page_no,
    CompanyType: pageState.filterObj.type,
    AdminId: salesArr.join(','),
    RegionType: pageState.filterObj.area,
    EndDate: pageState.end_date,
    StartDate: pageState.start_date,
    Keyword: pageState.searchVal,
  }
  dataMainInterface.expireList(params).then(res => {
    if (res.Ret === 200) {
      pageState.tableData = res.Data.List || [];
      pageState.total = res.Data.Paging.Totals;
      pageState.totalCompany = res.Data.TotalCompany;
      pageState.isShowloadding = false;
    }
  })
}
/* 获取销售 */
function getSale() {
  customInterence.getSale().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 changeFilter() {
  pageState.page_no = 1;
  pageState.searchVal = ''
  getTableData()
}
/* 切换页码 */
function handleCurrentChange(page) {
  pageState.page_no = page;
  getTableData()
}
/* 定义今天之前的日期不可选择 */
function disabledBeforeToday(date) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return date < today;
}
/* 获取未来几个月的日期范围 */
function filterDate(month) {
  if (month) {
    let date_now = moment().format("YYYY-MM-DD");
    let date_after = moment().add(month, 'M').format("YYYY-MM-DD");
    let date = [date_now, date_after]
    pageState.start_date = date_now;
    pageState.end_date = date_after;
    pageState.filterObj.date = date;
    pageState.page_no = 1;
    pageState.searchVal = ''
    getTableData();
  }
}
/* 跳转 */
function jumpHandle(row, item) {
  if (item.link) {
    router.push({
      path: '/customDetail',
      query: {
        id: row.CompanyId
      }
    })
  }
}


onMounted(() => {
  getSale();
  if (sessionStorage.getItem('expiringListBack')) {
    let backData = JSON.parse(sessionStorage.getItem('expiringListBack'));
    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);
})


function getTableColumContent(scope, item) {
  item.label == "服务期限" &&
    scope.row.StartDate.indexOf("/") == -1
    ? scope.row.StartDate + "~" + scope.row.EndDate
    : item.label == "服务期限" &&
      scope.row.StartDate.indexOf("/") != -1
      ? scope.row.StartDate.substr(0, 10) +
      "~" +
      scope.row.EndDate.substr(0, 10) +
      "/" +
      scope.row.StartDate.substr(11) +
      "~" +
      scope.row.EndDate.substr(11)
      : scope.row[item.key] | formatTime
}






</script>

<template>
  <div class="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"
        :disabled-date="disabledBeforeToday"
        @change="dateChange"
      />
      <el-input
        placeholder="请输入客户名称"
        v-model="pageState.searchVal"
        style="max-width: 400px; margin-left: auto"
        @input="handleSearch"
        clearable
        :prefix-icon="Search"
      >
      </el-input>
    </div>
    <div class="dataReport-main">
      <div class="main-top">
        <!-- <el-select 
				v-model="filterObj.sale" 
				placeholder="请选择销售" 
				style="width:150px;marginRight:10px;marginBottom:8px;" 
				v-if="Role=='admin'||Role=='ficc_admin'||Role=='rai_admin'||ManageType!=0" 
				clearable  
				@change="changeFilter" 
				filterable>
					<el-option
						v-for="item in salesArr"
						:key="item"
						:label="item.RealName"
						:value="item.AdminId">
					</el-option>
				</el-select> -->
        <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>
        <el-select
          v-model="pageState.filterObj.type"
          placeholder="请选择客户类型"
          style="width: 150px; margin-right: 10px; margin-bottom: 8px"
          v-if="Role == 'finance' || Role == 'admin'"
          clearable
          @change="changeFilter"
        >
          <el-option
            v-for="item in pageState.typeArr"
            :key="item"
            :label="item.name"
            :value="item.name"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="pageState.filterObj.area"
          placeholder="请选择所属区域"
          style="width: 150px; margin-right: 10px; margin-bottom: 8px"
          clearable
          @change="changeFilter"
        >
          <el-option
            v-for="item in pageState.areaArr"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </div>
      <div class="main-section">
        <el-card class="main-card" shadow="always">
          <template #header>
            <div class="clearfix">
              <span>
                即将到期客户数
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="服务期限截止日期在所选时间段内的客户"
                  placement="top-start"
                >
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
              </span>
            </div>
          </template>

          <div class="card-cont">{{ pageState.totalCompany }}</div>
        </el-card>
      </div>
      <el-table
        :data="pageState.tableData"
        border
        style="margin-top: 20px; min-height: 400px"
        v-loading="pageState.isShowloadding"
        element-loading-text="数据加载中..."
      >
        <el-table-column
          v-for="item in expringTableColums"
          :key="item.label"
          :label="item.label"
          :width="item.widthsty"
          align="center"
        >
          <template #default="scope">
            <span :style="item.textsty" @click="jumpHandle(scope.row, item)">
              {{
                item.label == "服务期限" &&
                scope.row.StartDate.indexOf("/") == -1
                  ? scope.row.StartDate + "~" + scope.row.EndDate
                  : item.label == "服务期限" &&
                    scope.row.StartDate.indexOf("/") != -1
                  ? scope.row.StartDate.substr(0, 10) +
                    "~" +
                    scope.row.EndDate.substr(0, 10) +
                    "/" +
                    scope.row.StartDate.substr(11) +
                    "~" +
                    scope.row.EndDate.substr(11)
                  : formatTime(scope.row[item.key])
              }}
            </span>
          </template>
        </el-table-column>
        <template #empty>
          <div style="line-height: 44px; margin: 60px 0; color: #999">
            <img
              src="~@/assets/img/cus_m/nodata.png"
              alt=""
              style="display: block; width: 160px; height: 128px; margin: auto"
            />
            <span>暂无数据</span>
          </div>
        </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'>
@import "./index.scss";
</style>