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

</script>
<script setup>
import { incomeTableColums } from './configdata.js'
import { filterMoney } from '@/common/js/util'
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()


const exportExcel = computed(() => {
  let baseUrl = import.meta.env.VITE_APP_API_ROOT + "/statistic_report/income_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.filterObj.date[1],
    StartDate: pageState.filterObj.date[0],
    Keyword: pageState.searchVal,
    IsExport: true,
  };
  for (let key in obj) {
    paramStr = `${paramStr}&${key}=${obj[key]}`;
  }
  return `${baseUrl}?${token}${paramStr}`;
})
const Role = computed(() => {
  return localStorage.getItem('Role') || '';
})

const ManageType = computed(() => {
  return localStorage.getItem('ManageType') || '';
})

const pageState = reactive({
  searchVal: sessionStorage.getItem('incomeBack') ? JSON.parse(sessionStorage.getItem('incomeBack')).searchVal : '',
  showTable: false,
  tableData: [],
  isShowloadding: false,
  start_date: '',
  end_date: '',
  /* 筛选条件 */
  filterObj: {
    date: [moment().format("YYYY-MM"), moment().format("YYYY-MM")],
    type: '',
    sale: '',
    area: ''
  },
  salesArr: [],//销售列表
  defaultSalesProps: {
    multiple: true,
    label: 'RealName',
    children: 'ChildrenList',
    value: 'AdminId'
  },//销售级联配置
  typeArr: [
    {
      name: 'ficc'
    }, {
      name: '权益'
    }
  ],//类型
  areaArr: ['国内', '海外'],
  pageSize: 10,
  page_no: sessionStorage.getItem('incomeBack') ? JSON.parse(sessionStorage.getItem('incomeBack')).page_no : 1,
  total: 0,
  data_typeArr: [
    {
      label: '签约合同数'
    },
    {
      label: '签约合同总金额'
    },
  ],//数据类型
  TotalContract: 0,//总合同数
  TotalMoney: 0,//总金额
  perssionList: [],//权限列表
})

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

// 搜索
function handleSearch() {
  if (!pageState.searchVal) {
    pageState.page_no = 1
    pageState.filterObj = {
      date: [moment().format("YYYY-MM"), moment().format("YYYY-MM")],
      type: '',
      sale: '',
      area: ''
    }
    getTableData()
    return
  }
  pageState.page_no = 1
  pageState.filterObj = {
    date: [],
    type: '',
    sale: '',
    area: ''
  }
  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.filterObj.date[1],
    StartDate: pageState.filterObj.date[0],
    Keyword: pageState.searchVal
  }
  dataMainInterface.incomeList(params).then(res => {
    if (res.Ret === 200) {
      pageState.tableData = res.Data.List || [];
      pageState.total = res.Data.Paging.Totals;
      pageState.TotalContract = res.Data.Total;
      pageState.TotalMoney = filterMoney(res.Data.Money);
      pageState.showTable = true;
      pageState.isShowloadding = false
    }
  })
}
/* 获取销售 */
function getSale() {
  customInterence.getSale().then(res => {
    if (res.Ret === 200) {
      pageState.salesArr = res.Data.List;
    }
  })
}
/* 筛选改变时 */
function changeFilter() {
  pageState.page_no = 1;
  pageState.searchVal = ''
  getTableData()
}
/* 选择时间 */
function dateChange(e) {
  if (e[0]) {
    pageState.start_date = e[0];
    pageState.end_date = e[1];
  } else {
    pageState.start_date = '';
    pageState.end_date = '';
  }
  pageState.page_no = 1;
  pageState.searchVal = ''
  getTableData();
}
/* 切换页码 */
function handleCurrentChange(page) {
  pageState.page_no = page;
  getTableData()
}
// 操作
function actionHandle(row) {
  pageState.sendObj = row;
  pageState.isOpenDia = true;
}
/* 跳转 */
function jumpHandle(row, item) {
  if (item.link) {
    router.push({
      path: '/customDetail',
      query: {
        id: row.CompanyId
      }
    })
  }
}
/* 查看权限 */
function openDia(row) {
  pageState.perssionList = row.PermissionList;
}

onMounted(() => {
  getSale();
  if (sessionStorage.getItem('incomeBack')) {
    let backData = JSON.parse(sessionStorage.getItem('incomeBack'));
    pageState.page_no = backData.page_no
    pageState.filterObj = backData.filterObj
    pageState.start_date = backData.start_date
    pageState.end_date = backData.end_date
    pageState.searchVal = backData.searchVal
  }
  getTableData();
})

</script>

<template>
  <div class="dataReport-container">
    <div class="dataReport-main first">
      <div class="main-top" style="display: flex; align-items: center">
        <a :href="exportExcel" download>
          <el-button
            type="primary"
            style="margin-right: 10px; margin-bottom: 8px"
            >导出EXCEL</el-button
          >
        </a>
        <date-picker
          v-model="pageState.filterObj.date"
          type="monthrange"
          value-format="YYYY-MM-DD"
          start-placeholder="请选择月份区间"
          end-placeholder="请选择月份区间"
          :clearable="false"
          :editable="false"
          @change="dateChange"
          style="margin-right: 10px; margin-bottom: 8px"
        />
        <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>
        <el-input
          placeholder="请输入客户名称"
          v-model="pageState.searchVal"
          style="max-width: 400px; margin-left: auto; margin-bottom: 8px"
          @input="handleSearch"
          clearable
          :prefix-icon="Search"
        />
      </div>
      <div class="main-section">
        <el-row :gutter="30">
          <el-col
            :span="12"
            v-for="item in pageState.data_typeArr"
            :key="item.label"
          >
            <el-card class="base-card" shadow>
              <template #header>
                <div class="clearfix">
                  <span>
                    {{ item.label }}
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="
                        item.label === '签约合同数'
                          ? '合同起始日期在所选月份区间内的合同数'
                          : '合同金额的总和'
                      "
                      placement="top"
                    >
                      <el-icon><InfoFilled /></el-icon>
                    </el-tooltip>
                  </span>
                </div>
              </template>

              <div class="card-cont">
                {{
                  item.label === "签约合同数"
                    ? pageState.TotalContract
                    : item.label === "签约合同总金额"
                    ? pageState.TotalMoney
                    : ""
                }}
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <el-table
        :data="pageState.tableData"
        border
        style="margin-top: 20px; min-height: 400px"
        v-loading="pageState.isShowloadding"
        element-loading-text="数据加载中..."
      >
        <template v-for="item in incomeTableColums">
          <el-table-column
            :key="item.label"
            :label="item.label"
            :width="item.widthsty"
            align="center"
            v-if="
              !item.dataType ||
              item.dataType.split(',').includes(filterObj.data_type)
            "
          >
            <template #default="scope">
              <span :style="item.textsty" @click="jumpHandle(scope.row, item)">
                {{
                  item.label == "服务期限" &&
                  scope.row.StartDate.indexOf("/") == -1
                    ? scope.row.StartDate.replace(/-/g, ".") +
                      "~" +
                      scope.row.EndDate.replace(/-/g, ".")
                    : 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]
                }}
              </span>
              <span v-if="item.action" :style="item.textsty">
                <el-popover placement="right" width="400" trigger="click">
                  <div
                    style="
                      display: flex;
                      justify-content: space-between;
                      font-size: 16px;
                    "
                  >
                    <h3>查看权限</h3>
                    <!-- <i class="el-icon-close" style="font-size:20px"></i> -->
                  </div>
                  <ul style="margin: 20px 0">
                    <li
                      style="
                        margin-bottom: 15px;
                        display: flex;
                        align-items: center;
                        flex-wrap: wrap;
                      "
                      v-for="auth in pageState.perssionList"
                      :key="auth.ClassifyName"
                    >
                      <span style="color: #409eff; margin-right: 10px"
                        >{{ auth.ClassifyName }}:</span
                      >
                      <template
                        v-for="sub_auth in auth.PermissionList"
                        :key="sub_auth.ChartPermissionName"
                      >
                        <el-tag size="mini" style="margin: 5px 8px">
                          {{ sub_auth.ChartPermissionName }}
                        </el-tag>
                      </template>
                    </li>
                  </ul>
                  <template #reference>
                    <span class="editsty" @click="openDia(scope.row)"
                      >查看权限详情</span
                    >
                  </template>
                </el-popover>
              </span>
            </template>
          </el-table-column>
        </template>
        <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>