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

</script>

<script setup>
import { contractTableColums } from './configdata.js'
import { filterMoney } from '@/common/js/util'
import { dataMainInterface, customInterence } from '@/api/api.js'
import mPage from '@/components/mPage.vue'
import ContractDia from './components/ContractDia.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/contract_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,
    Keyword: pageState.searchVal,
    IsExport: true,
    DataType: pageState.selectType === '系统合同/上传附件' ? '类型数据' : '',
    SourceType: pageState.filterObj.contractType,
  };
  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('contractBack') ? JSON.parse(sessionStorage.getItem('contractBack')).searchVal : '',
  showTable: false,
  tableData: [],
  isShowloadding: false,
  /* 筛选条件 */
  filterObj: {
    date: moment().format("YYYY-MM-DD"),
    type: '',
    sale: '',
    area: '',
    contractType: ''
  },
  salesArr: [],//销售列表
  defaultSalesProps: {
    multiple: true,
    label: 'RealName',
    children: 'ChildrenList',
    value: 'AdminId'
  },//销售级联配置
  typeArr: [
    {
      name: 'ficc'
    }, {
      name: '权益'
    }
  ],//类型
  areaArr: ['国内', '海外'],
  pageSize: 10,
  page_no: sessionStorage.getItem('contractBack') ? JSON.parse(sessionStorage.getItem('contractBack')).page_no : 1,
  total: 0,
  data_typeArr: [
    {
      label: '有效合同总数'
    },
    {
      label: '有效合同总金额'
    },
    {
      label: '正式客户数'
    },
    {
      label: '系统合同/上传附件'
    }
  ],//数据类型
  TotalContract: 0,//总合同数
  TotalMoney: 0,//总金额
  TotalCompany: 0,//客户数
  TotalContract2: '0/0',//系统合同/上传附件 数
  /* 弹窗 */
  isOpenDia: false,
  sendObj: {},//传输的props

  selectType: sessionStorage.getItem('contractBack') ? JSON.parse(sessionStorage.getItem('contractBack')).selectType : '有效合同总数',//选择的 四个 label
})

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

// 切换
function handleChangeType(e) {
  pageState.selectType = e
  pageState.page_no = 1
  getTableData()
}

// 搜索
function handleSearch() {
  pageState.page_no = 1
  pageState.filterObj = {
    date: pageState.filterObj.date,
    type: '',
    sale: '',
    area: '',
    contractType: ''
  }
  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,
    Keyword: pageState.searchVal,
    DataType: pageState.selectType === '系统合同/上传附件' ? '类型数据' : '',
    SourceType: pageState.filterObj.contractType,
  }
  dataMainInterface.contractList(params).then(res => {
    if (res.Ret === 200) {
      pageState.tableData = res.Data.List || [];
      pageState.tableData.forEach(item => {
        if (item.CreateTime) {
          item.CreateTime = item.CreateTime.replace(/-/g, '.')
        }
      })
      pageState.total = res.Data.Paging.Totals;
      pageState.TotalContract = res.Data.TotalContract;
      pageState.TotalMoney = filterMoney(res.Data.TotalMoney);
      pageState.TotalCompany = res.Data.TotalCompany;
      pageState.TotalContract2 = `${res.Data.TotalSystemContract}/${res.Data.TotalFileContract}`
      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 handleCurrentChange(page) {
  pageState.page_no = page;
  getTableData()
}
// 操作
function actionHandle(row) {
  pageState.sendObj = { ...row, selectType: pageState.selectType };
  pageState.isOpenDia = true;
}
/* 跳转 */
function jumpHandle(row, item) {
  if (item.link) {
    if (!row.CompanyId) return
    router.push({
      path: '/customDetail',
      query: {
        id: row.CompanyId
      }
    })
  }
}

onMounted(() => {
  getSale();
  if (sessionStorage.getItem('contractBack')) {
    let backData = JSON.parse(sessionStorage.getItem('contractBack'));
    pageState.page_no = backData.page_no
    pageState.filterObj = backData.filterObj
    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; padding: 12px 15px"
            >导出EXCEL</el-button
          >
        </a>
        <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="
            min-width: 150px;
            margin-right: 10px;
            margin-bottom: 8px;
            max-width: 150px;
          "
          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="
            min-width: 150px;
            margin-right: 10px;
            margin-bottom: 8px;
            max-width: 150px;
          "
          clearable
          @change="changeFilter"
        >
          <el-option
            v-for="item in pageState.areaArr"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          v-if="pageState.selectType === '系统合同/上传附件'"
          v-model="pageState.filterObj.contractType"
          placeholder="请选择合同类型"
          style="
            min-width: 150px;
            margin-right: 10px;
            margin-bottom: 8px;
            max-width: 150px;
          "
          clearable
          @change="changeFilter"
        >
          <el-option
            key="系统合同"
            label="系统合同"
            value="系统合同"
          ></el-option>
          <el-option
            key="上传附件"
            label="上传附件"
            value="上传附件"
          ></el-option>
        </el-select>
        <el-date-picker
          style="margin-bottom: 8px; min-width: 150px; max-width: 150px"
          v-model="pageState.filterObj.date"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择日期"
          :clearable="false"
          :editable="false"
          @change="changeFilter"
        />
        <el-input
          placeholder="请输入客户名称"
          v-model="pageState.searchVal"
          style="max-width: 330px; margin-left: auto; margin-bottom: 8px"
          @input="handleSearch"
          clearable
          :prefix-icon="Search"
        />
      </div>
      <div class="main-section">
        <el-row :gutter="36">
          <el-col
            :span="6"
            v-for="item in pageState.data_typeArr"
            :key="item.label"
          >
            <el-card
              :class="[
                'base-card',
                { 'main-card': pageState.selectType === item.label },
              ]"
              @click="handleChangeType(item.label)"
              shadow="hover"
            >
              <template #header>
                <div class="clearfix">
                  <span>
                    {{ item.label }}
                    <el-tooltip
                      v-if="item.label != '系统合同/上传附件'"
                      class="item"
                      effect="dark"
                      :content="
                        item.label === '有效合同总数'
                          ? '当前未到期的合同总数量(合同截止日期≥所选日期)'
                          : item.label === '有效合同总金额'
                          ? '当前未到期的合同金额总和'
                          : 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
                    : item.label === "正式客户数"
                    ? pageState.TotalCompany
                    : item.label === "系统合同/上传附件"
                    ? pageState.TotalContract2
                    : ""
                }}
              </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 contractTableColums">
          <el-table-column
            :key="item.label"
            :label="item.label"
            :width="item.widthsty"
            align="center"
            v-if="
              !item.dataType || item.dataType.split(',').includes(pageState.selectType)
            "
          >
            <template #default="scope">
              <span
                :style="item.textsty"
                :class="item.link && !scope.row.CompanyId ? 'no-link' : ''"
                @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)
                    : scope.row[item.key]
                }}
              </span>
              <span
                v-if="item.action"
                :style="item.textsty"
                @click="actionHandle(scope.row)"
              >
                {{ item.action.name }}
              </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>
    <!-- 弹窗 -->
    <ContractDia
      :isOpenDia="pageState.isOpenDia"
      :item="pageState.sendObj"
      :date="pageState.filterObj.date"
      @cancel="pageState.isOpenDia = false"
    />
  </div>
</template>

<style lang='scss'>
@import "./index.scss";
.no-link {
  color: #333 !important;
  cursor: default !important;
}
</style>