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

</script>

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

const router = useRouter()
const route = useRoute()

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

const exportExcel = computed(() => {
  let baseUrl = import.meta.env.VITE_APP_API_ROOT + "/statistic_report/stack_company_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,
    Date: pageState.filterObj.date,
    DataType: pageState.filterObj.data_type,
    Keyword: pageState.searchVal,
    IsExport: true,
    IsConfirm: pageState.filterObj.data_type == '未续约客户' ? 1 : -1,
    CompanyAscribeId: pageState.noRenewalReasonId,
  };
  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('stockBack') ? JSON.parse(sessionStorage.getItem('stockBack')).searchVal : '',

  tableData: [],
  isShowloadding: false,
  /* 筛选条件 */
  filterObj: {
    date: moment().format("YYYY-MM-DD"),
    type: '',
    sale: '',
    area: '',
    data_type: route.query.type || '新签客户'
  },
  salesArr: [],//销售列表
  defaultSalesProps: {
    multiple: true,
    label: 'RealName',
    children: 'ChildrenList',
    value: 'AdminId'
  },//销售级联配置
  typeArr: [
    {
      name: 'ficc'
    }, {
      name: '权益'
    }
  ],//类型
  areaArr: ['国内', '海外'],
  pageSize: 10,
  page_no: sessionStorage.getItem('stockBack') ? JSON.parse(sessionStorage.getItem('stockBack')).page_no : 1,
  total: 0,
  data_typeArr: [
    {
      label: '新签客户'
    },
    {
      label: '续约客户'
    },
    {
      label: '未续约客户'
    },
  ],//数据类型
  NewCompanyTotal: 0,//新签客户数
  NotRenewalCompanyTotal: 0,//未续约客户数
  RenewalCompanyTotal: 0,//续约客户数
  isRenewalShow: false,	//未续约说明列表弹框是否显示
  rowInfo: null,	// 未续约说明更多行信息
  tabsList: [{ name: '试用', value: '试用' }, { name: '冻结/流失', value: '非试用' }],
  tabsActiveName: '试用',
  NotRenewalNotTryOut: 0,//冻结流失的人数
  NotRenewalTryOut: 0,//试用的人数
  noRenewalReasonList: [],
  noRenewalReasonId: '',
  selectItemRow: {},// 当前选中的row
  //历史备注
  isViewRemarkShow: false,
  historyRemarkList: [],
  //确认不续约
  isConfirmNoRenewalShow: false,
  confirmNoRenewalForm: {
    reason: "",
    detailReason: ""
  }
})


// 搜索
function handleSearch() {
  pageState.page_no = 1
  pageState.filterObj = {
    date: pageState.filterObj.date,
    type: '',
    sale: '',
    area: '',
    data_type: pageState.filterObj.data_type
  }
  getTableData()
}
//tabs 的点击事件
function tabsHandler(item) {
  pageState.tabsActiveName = item.value;
  pageState.page_no = 1;
  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 = {
    PageSize: pageState.pageSize,
    CurrentIndex: pageState.page_no,
    CompanyType: pageState.filterObj.type,
    AdminId: salesArr.join(','),
    RegionType: pageState.filterObj.area,
    Date: pageState.filterObj.date,
    DataType: pageState.filterObj.data_type,
    Keyword: pageState.searchVal,
    TryOutType: pageState.filterObj.data_type == '未续约客户' ? pageState.tabsActiveName : '',
    IsConfirm: -1,
    CompanyAscribeId: pageState.noRenewalReasonId,
  }
  dataMainInterface.stackList(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.NotRenewalTryOut = res.Data.NotRenewalTryOut || 0
      pageState.NotRenewalNotTryOut = res.Data.NotRenewalNotTryOut || 0
      pageState.isShowloadding = false;
    }
  })
}
/* 获取销售 */
function getSale() {
  customInterence.getSale().then(res => {
    if (res.Ret === 200) {
      pageState.salesArr = res.Data.List;
    }
  })
}
/* 切换数据类型 */
function toggleType(label) {
  pageState.filterObj.data_type = label;
  if (label == "未续约客户") {
    getNORenewalReasonList()
  }
  pageState.noRenewalReasonId = ''
  pageState.tabsActiveName = '试用';
  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 jumpHandle(row, item) {
  if (item.link) {
    router.push({
      path: '/customDetail',
      query: {
        id: row.CompanyId
      }
    })
  }
}

// 未续约说明更多按钮
function renewalReasonMore(row) {
  pageState.rowInfo = {
    CompanyId: row.CompanyId,
    ProductId: row.ProductId
  }
  pageState.isRenewalShow = true
}
function getNORenewalReasonList() {
  dataMainInterface.getAscribList().then(res => {
    if (res.Ret == 200) {
      pageState.noRenewalReasonList = res.Data.List || []
    }
  })
}
// 查看历史备注
function viewHistoryRemarkFun(row) {
  // console.log(row);
  dataMainInterface.getNotRenewedRemarkList({ CompanyId: row.CompanyId, ProductId: row.ProductId })
    .then(res => {
      if (res.Ret == 200) {
        pageState.historyRemarkList = res.Data.List || []
        pageState.isViewRemarkShow = true
      }
    })
}
function editReasonLabel(row) {
  // console.log(row);
  dataMainInterface.infoNoRenewedAscribe({ CompanyId: row.CompanyId, ProductId: row.ProductId })
    .then(res => {
      if (res.Ret == 200) {
        pageState.confirmNoRenewalForm.reason = res.Data.Detail ? res.Data.Detail.CompanyAscribeId || "" : ""
        pageState.confirmNoRenewalForm.detailReason = res.Data.Detail ? res.Data.Detail.Content || "" : ""
        pageState.selectItemRow = row
        pageState.isConfirmNoRenewalShow = true
      }
    })
}
function saveLabel(item) {
  // console.log(item);
  let params = {
    CompanyId: pageState.selectItemRow.CompanyId,
    ProductId: pageState.selectItemRow.ProductId,
    CompanyAscribeId: item.CompanyAscribeId,
    Content: item.Content
  }
  dataMainInterface.addNoRenewedAscribe(params).then(res => {
    if (res.Ret == 200) {
      ElMessage.success("确认成功")
      pageState.isConfirmNoRenewalShow = false
      pageState.selectItemRow = {}
      getTableData()
    }
  })
}

onMounted(() => {
  getSale();
  if (sessionStorage.getItem('stockBack')) {
    let backData = JSON.parse(sessionStorage.getItem('stockBack'));
    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"
            >导出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="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-date-picker
          style="margin-bottom: 8px"
          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: 400px; margin-left: auto; margin-bottom: 8px"
          @input="handleSearch"
          clearable
          :prefix-icon="Search"
        >
        </el-input>
      </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>
      <el-select
        v-model="pageState.noRenewalReasonId"
        placeholder="请选择不续约归因"
        v-show="pageState.filterObj.data_type == '未续约客户'"
        clearable
        @change="getTableData"
        style="width: 240px; margin-top: 40px"
      >
        <el-option
          :label="item.AscribeContent"
          :value="item.CompanyAscribeId"
          v-for="item in pageState.noRenewalReasonList"
          :key="item.reasonId"
        ></el-option>
      </el-select>
      <div
        class="tabs-box"
        v-if="pageState.filterObj.data_type == '未续约客户'"
      >
        <span
          @click="tabsHandler(item)"
          :class="pageState.tabsActiveName === item.value ? 'active' : ''"
          v-for="item in pageState.tabsList"
          :key="item"
          >{{ item.name }}({{
            item.name === "试用"
              ? pageState.NotRenewalTryOut
              : pageState.NotRenewalNotTryOut
          }})</span
        >
      </div>
      <el-table
        :data="pageState.tableData"
        border
        v-loading="pageState.isShowloadding"
        element-loading-text="数据加载中..."
        style="margin-top: 20px; min-height: 400px"
      >
        <template v-for="item in stockTableColums">
          <el-table-column
            :key="item.label"
            :label="item.label"
            :width="item.widthsty"
            align="center"
            v-if="
              !item?.dataType ||
              item?.dataType.split(',').includes(pageState.filterObj.data_type)
            "
          >
            <template #default="scope">
              <span
                :style="item.textsty"
                @click="jumpHandle(scope.row, item)"
                v-if="
                  item.label == '服务期限' || item.label == '最近合同到期时间'
                "
              >
                {{
                  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>
              <span v-else-if="item.label == '未续约说明'">
                <span style="display: block" v-if="scope.row[item.key]"
                  >最新情况：{{ scope.row[item.key] }}</span
                >
                <span v-if="scope.row.RenewalTodo"
                  >To Do 事项：{{ scope.row.RenewalTodo }}</span
                >
                <span
                  v-if="scope.row[item.key] || scope.row.RenewalTodo"
                  style="color: #409eff; cursor: pointer"
                  @click="renewalReasonMore(scope.row)"
                  >&emsp;更多>></span
                >
              </span>
              <div v-else-if="item.key == 'CompanyName'" style="padding: 4px 0">
                <span
                  :style="item.textsty"
                  @click="jumpHandle(scope.row, item)"
                >
                  {{ scope.row[item.key] }}
                </span>
                <div
                  class="package-difference"
                  v-if="scope.row.PackageDifference"
                >
                  {{ scope.row.PackageDifference }}
                </div>
              </div>
              <div v-else-if="item.key === 'Remark'" class="remark-row">
                <span
                  class="remark-text"
                  @click="viewHistoryRemarkFun(scope.row)"
                  v-if="scope.row.IsShowNoRenewedNote"
                  >...</span
                >
              </div>
              <div v-else-if="item.key == 'AscribeContent'">
                <span
                  style="color: #409eff; cursor: pointer"
                  @click="editReasonLabel(scope.row)"
                >
                  {{ scope.row[item.key] }}
                </span>
              </div>
              <span
                v-else
                :style="item.textsty"
                @click="jumpHandle(scope.row, item)"
              >
                {{ scope.row[item.key] }}
              </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>
    <!-- 未续约说明列表弹窗 -->
    <renewalListDia
      v-model:isShow="pageState.isRenewalShow"
      :rowInfo="pageState.rowInfo"
    />
    <!-- 历史备注弹窗 -->
    <viewRemark
      v-model:isShow="pageState.isViewRemarkShow"
      :tableData="pageState.historyRemarkList"
    />
    <!-- 确认不续约弹窗 -->
    <confirmedNoRenewal
      v-model:isShow="pageState.isConfirmNoRenewalShow"
      :dataForm="pageState.confirmNoRenewalForm"
      :noRenewalReasonList="pageState.noRenewalReasonList"
      @refreshReasonList="getNORenewalReasonList"
      @saveLabel="saveLabel"
    />
  </div>
</template>

<style lang='scss' scoped>
@import "./index.scss";
.remark-row {
  display: flex;
  justify-content: center;
  .remark-text {
    width: 18px;
    height: 18px;
    margin-right: 8px;
    font-size: 18px;
    color: #409eff;
    cursor: pointer;
  }
}
</style>