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

</script>
<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { incrementTableColums } from './configdata.js'
import { dataMainInterface, customInterence } from '@/api/api.js'
import mPage from '@/components/mPage.vue'
import renewalListDia from './components/renewalListDia.vue'
import addRemark from './components/noRenewalReasonDia/addRemark.vue'
import viewRemark from './components/noRenewalReasonDia/viewRemark.vue'
import confirmedNoRenewal from './components/noRenewalReasonDia/confirmedNoRenewal.vue'
import moment from 'moment'
import { onBeforeRouteLeave, 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 pageState = reactive({
  searchVal: sessionStorage.getItem('incrementBack') ? JSON.parse(sessionStorage.getItem('incrementBack')).searchVal : '',
  tableData: [],
  isShowloadding: false,
  start_date: '',
  end_date: '',
  /* 筛选条件 */
  filterObj: {
    month: '近1个月',
    date: [],
    type: '',
    sale: '',
    area: '',
    data_type: '新增试用客户'
  },
  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('incrementBack') ? JSON.parse(sessionStorage.getItem('incrementBack')).page_no : 1,
  total: 0,
  data_typeArr: [
    {
      label: '新增试用客户'
    },
    {
      label: '新签客户'
    },
    {
      label: '续约客户'
    },
    {
      label: '未续约客户'
    },
  ],//数据类型
  TrialTotal: 0,//新增试用数
  NewCompanyTotal: 0,//新签客户数
  NotRenewalCompanyTotal: 0,//未续约客户数
  RenewalCompanyTotal: 0,//续约客户数
  isRenewalShow: false,	//未续约说明列表弹框是否显示
  rowInfo: null,	// 未续约说明更多行信息
  tabsList: [{ name: '试用', value: '试用' }, { name: '冻结/流失', value: '非试用' }],
  tabsActiveName: '试用',
  NotRenewalNotTryOut: 0,//冻结流失的人数
  NotRenewalTryOut: 0,//试用的人数
  isNotRenewedConfirm: 1,//未续约的是否已确认
  noRenewalReasonList: [],
  noRenewalReasonId: '',
  selectItemRow: {},// 当前选中的row
  // 添加备注
  isAddRemarkShow: false,
  //历史备注
  isViewRemarkShow: false,
  historyRemarkList: [],
  //确认不续约
  isConfirmNoRenewalShow: false,
  confirmNoRenewalForm: {
    reason: "",
    detailReason: ""
  }
})
const exportExcel = computed(() => {
  let baseUrl = import.meta.env.VITE_APP_API_ROOT + "/statistic_report/incremental_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 = {
    CompanyType: pageState.filterObj.type,
    AdminId: salesArr.join(','),
    RegionType: pageState.filterObj.area,
    EndDate: pageState.end_date,
    StartDate: pageState.start_date,
    DataType: pageState.filterObj.data_type == '新增试用客户' ? '新增试用' : 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 canConfirmNotRenewed = computed(() => {
  return ['admin', 'rai_admin'].includes(Role.value)
})
/* 页面跳转前记录参数 */
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()
})

function controlTableColumnShow(item) {
  return !item.dataType ||
    (item.dataType === pageState.filterObj.data_type &&
      (!item.notRenewedConfirm || item.notRenewedConfirm == pageState.isNotRenewedConfirm)) // 已确认和待确认
}
// 搜索
function handleSearch() {
  if (!pageState.searchVal) {
    pageState.page_no = 1
    pageState.filterObj = {
      month: '近1个月',
      date: [],
      type: '',
      sale: '',
      area: '',
      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: [],
    type: '',
    sale: '',
    area: '',
    data_type: pageState.filterObj.data_type
  }
  pageState.start_date = '';
  pageState.end_date = '';
  getTableData()
}
//tabs 的点击事件
function tabsHandler(item) {
  pageState.tabsActiveName = item.value;
  pageState.noRenewalReasonId = ''
  pageState.page_no = 1;
  getTableData()
}
function notRenewedConfirmChange() {
  pageState.tabsActiveName = '试用'
  pageState.noRenewalReasonId = ''
  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 = {
    Keyword: pageState.searchVal,
    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,
    DataType: pageState.filterObj.data_type == '新增试用客户' ? '新增试用' : pageState.filterObj.data_type,
    TryOutType: pageState.filterObj.data_type == '未续约客户' && pageState.isNotRenewedConfirm == 1 ? pageState.tabsActiveName : '',
    IsConfirm: pageState.filterObj.data_type == '未续约客户' ? pageState.isNotRenewedConfirm : -1,
    CompanyAscribeId: pageState.noRenewalReasonId
  }
  dataMainInterface.incrementalList(params).then(res => {
    if (res.Ret === 200) {
      pageState.tableData = res.Data.List || [];
      pageState.total = res.Data.Paging.Totals;
      pageState.TrialTotal = res.Data.TrialTotal;
      pageState.NewCompanyTotal = res.Data.NewCompanyTotal;
      pageState.RenewalCompanyTotal = res.Data.RenewalCompanyTotal;
      pageState.NotRenewalCompanyTotal = res.Data.NotRenewalCompanyTotal;
      pageState.NotRenewalTryOut = res.Data.NotRenewalTryOut
      pageState.NotRenewalNotTryOut = res.Data.NotRenewalNotTryOut
      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 toggleType(label) {
  pageState.filterObj.data_type = label;
  pageState.noRenewalReasonId = ''
  if (label == "未续约客户") {
    getNORenewalReasonList()
  }
  pageState.tabsActiveName = '试用';
  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 jumpHandle(row, item) {
  if (item.link) {
    router.push({
      path: '/customDetail',
      query: {
        id: row.CompanyId
      }
    })
  }
}
function getNORenewalReasonList() {
  dataMainInterface.getAscribList().then(res => {
    if (res.Ret == 200) {
      pageState.noRenewalReasonList = res.Data.List || []
    }
  })
}
// 未续约说明更多按钮
function renewalReasonMore(row) {
  pageState.rowInfo = {
    CompanyId: row.CompanyId,
    ProductId: row.ProductId
  }
  pageState.isRenewalShow = true
}
// 添加备注
function addRemarkFun(row) {
  pageState.selectItemRow = row
  pageState.isAddRemarkShow = true
}
// 添加备注 保存
function saveRemark(remark) {
  // console.log(remark);
  let params = {
    CompanyId: pageState.selectItemRow.CompanyId,
    ProductId: pageState.selectItemRow.ProductId,
    Content: remark
  }
  dataMainInterface.addNotRenewedRemark(params).then(res => {
    if (res.Ret == 200) {
      ElMessage.success("添加成功")
      getTableData()
      pageState.isAddRemarkShow = false
      pageState.selectItemRow = {}
    }
  })
}
// 查看历史备注
function viewHistoryRemarkFun(row) {
  dataMainInterface.getNotRenewedRemarkList({ CompanyId: row.CompanyId, ProductId: row.ProductId })
    .then(res => {
      if (res.Ret == 200) {
        pageState.historyRemarkList = res.Data.List || []
        pageState.isViewRemarkShow = true
      }
    })
}
function confirmedNoRenewalFun(row) {
  pageState.confirmNoRenewalForm.reason = ""
  pageState.confirmNoRenewalForm.detailReason = ""
  pageState.selectItemRow = row
  pageState.isConfirmNoRenewalShow = true
}
function editReasonLabel(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) {
  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('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
        style="max-width: 300px"
        v-model="pageState.filterObj.date"
        type="daterange"
        range
        value-format="YYYY-MM-DD"
        placeholder="自定义时间段"
        :clearable="false"
        :editable="false"
        @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-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-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.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 === '新签客户'
                          ? '新签合同的起始日期包含在所选时间段内的客户'
                          : item.label === '续约客户'
                          ? '续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户'
                          : '筛选时间段内有过正式转试用记录，且当前为非正式、非永续状态的客户'
                      "
                      placement="top"
                    >
                      <el-icon><InfoFilled /></el-icon>
                    </el-tooltip>
                  </span>
                </div>
              </template>

              <div class="card-cont">
                {{
                  item.label === "新增试用客户"
                    ? pageState.TrialTotal
                    : item.label === "新签客户"
                    ? pageState.NewCompanyTotal
                    : item.label === "续约客户"
                    ? pageState.RenewalCompanyTotal
                    : item.label === "未续约客户"
                    ? pageState.NotRenewalCompanyTotal
                    : ""
                }}
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <div
        class="tabs-box"
        v-if="pageState.filterObj.data_type == '未续约客户'"
      >
        <el-radio-group
          v-model="pageState.isNotRenewedConfirm"
          class="tabs-box-confirm"
          @change="notRenewedConfirmChange"
        >
          <el-radio-button :label="1">已确认</el-radio-button>
          <div class="center-line"></div>
          <el-radio-button :label="0">待确认</el-radio-button>
        </el-radio-group>
        <div class="tabs-box-status" v-show="pageState.isNotRenewedConfirm">
          <el-select
            v-model="pageState.noRenewalReasonId"
            placeholder="请选择不续约归因"
            clearable
            @change="getTableData"
            style="width: 240px; margin-right: 50px"
          >
            <el-option
              :label="item.AscribeContent"
              :value="item.CompanyAscribeId"
              v-for="item in pageState.noRenewalReasonList"
              :key="item.reasonId"
            ></el-option>
          </el-select>
          <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>
      </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 incrementTableColums">
          <el-table-column
            :key="item.label"
            :label="item.label"
            :width="item.widthsty"
            align="center"
            v-if="controlTableColumnShow(item)"
          >
            <template #default="scope">
              <span
                :style="item.textsty"
                @click="jumpHandle(scope.row, item)"
                v-if="
                  item.key === 'CreateTime' ||
                  item.key === 'StartDate' ||
                  item.key === 'EndDate'
                "
              >
                {{ 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
                >
                <span
                  class="operation-button"
                  v-show="
                    pageState.canConfirmNotRenewed &&
                    !pageState.isNotRenewedConfirm
                  "
                  style="margin-right: 0"
                  @click="addRemarkFun(scope.row)"
                  >添加</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>
        <el-table-column
          label="操作"
          width="180px"
          align="center"
          v-if="
            pageState.canConfirmNotRenewed &&
            !pageState.isNotRenewedConfirm &&
            pageState.filterObj.data_type == '未续约客户'
          "
        >
          <template #default="scope">
            <div class="operation-row">
              <span
                class="operation-button"
                @click="confirmedNoRenewalFun(scope.row)"
                >确认不续约</span
              >
            </div>
          </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>
    <!-- 未续约说明列表弹窗 -->
    <renewalListDia
      v-model:isShow="pageState.isRenewalShow"
      :rowInfo="pageState.rowInfo"
    />
    <!-- 添加备注弹窗 -->
    <addRemark
      v-model:isShow="pageState.isAddRemarkShow"
      @saveRemark="saveRemark"
    />
    <!-- 历史备注弹窗 -->
    <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";
.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;
    }
  }
}
.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;
    }
  }
}
</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;
      border-radius: 4px;
    }
  }
}
</style>