<template>
  <div class="overseas-custom-roadshow-box">
    <div class="tab-box">
      <el-button type="primary" :plain="roadshowTab==1?false:true" class="tab-item" @click="tabChange(1)">客户维度</el-button>
      <el-button type="primary" :plain="roadshowTab==2?false:true" class="tab-item" @click="tabChange(2)">销售维度</el-button>
      <el-button type="primary" :plain="roadshowTab==3?false:true" class="tab-item" @click="tabChange(3)">研究员维度</el-button>
    </div>
    <template v-if="roadshowTab==1">
      <div class="top-wrapper">
        <div class="left-select">
        <el-cascader
            v-model="sales"
            :options="salesOptions"
            :show-all-levels="false"
            :props="{
                expandTrigger: 'hover',
                children: 'ChildrenList',
                emitPath: false,
                label:'RealName',
                value:'AdminId',
                multiple:true
            }"
            collapse-tags
            filterable
            clearable
            placeholder="请选择销售"
            @change="pageChange(1)"
        />
        <el-cascader
            v-model="researchers"
            :options="researchersOptions"
            :show-all-levels="false"
            :props="{
                expandTrigger: 'hover',
                children: 'ResearcherList',
                emitPath: false,
                label:'RealName',
                value:'AdminId',
                multiple:true
            }"
            collapse-tags
            filterable
            clearable
            placeholder="请选择研究员"
            @change="pageChange(1)"
        />

        <el-select 
          v-model="status" 
          placeholder="请选择客户状态"
          @change="pageChange(1)"
          multiple 
          collapse-tags 
          clearable
        >
            <el-option
                v-for="item in statusOptions"
                :key="item.val"
                :label="item.label"
                :value="item.val"
            />
        </el-select>

        <date-picker 
						v-model="date" 
						type="date" 
						range
						value-type="format"
						placeholder="请选择路演日期" 
						@change="pageChange(1)" 
						style="width:200px;margin-right:10px;margin-bottom:8px;"
        />

        </div>
        <el-input 
            prefix-icon="el-icon-search" 
            placeholder="客户名称" 
            style="width:317px;" clearable
            v-model="searchWord"
            @input="pageChange(1)"
        />
      </div>
      <div class="cont-wrapper">
        <el-table
          ref="tableRef"
          :data="tableData"
          :loading="tabeLoading"
          border
          @sort-change="handleSortChange"
        >
          <el-table-column 
              align="center"
              v-for="item in columns" :key="item.key"
              :prop="item.key" :label="item.label"
              :min-width="item.minWidth"
              :sortable="item.sortable?'custom':false"
          >
            <template slot-scope="{row}">
                <!-- 客户名称 -->
                <div v-if="item.key==='CompanyName'" class="editor" @click="toCustomDetail(row)">{{row[item.key]}}</div>

                <span v-else>{{row[item.key]}}</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 页数选择器 -->
        <m-page
          :page_no="currentIndex"
          :pageSize="pageSize"
          :total="total"
          style="position: absolute;right: 50px;bottom: 50px;"
          @handleCurrentChange="pageChange"
        />
      </div>
    </template>
    <template v-else-if="roadshowTab==2">
      <ul class="date-tab-box">
				<li :class="['date-tab-item',{'act':tab === salesDimension.dateTab}]" v-for="tab in staticTabs" :key="tab" @click="changeTabHandle(tab)">
					{{tab}}
				</li>
        <date-picker
          v-model="salesDimension.selectDate"
          type="date" 
          range
          value-type="format"
          :clearable="false"
          @change="dateChange"
          placeholder="请选择统计时间"/>
			</ul>
      <div class="table-body-wrapper" v-show="dataLoading">
				<table>
					<thead>
						<tr>
							<td rowspan="2" class="thead-rs" style="width: 100px;">销售</td>
							<td
								:colspan="['周度统计表','月度统计表'].includes(salesDimension.dateTab) ? 3 : 1"
								v-for="item in salesDimension.tableTheadColumns" 
								:key="item" 
								class="head-column"
							>
								{{item}}
							</td>	
						</tr>
						<tr v-if="['月度统计表','周度统计表'].includes(salesDimension.dateTab)">
							<template v-for="(item,index) in new Array(6)">
								<td :key="index+'_0'">试用</td>
								<td :key="index+'_1'">正式</td>
								<td :key="index+'_2'">关闭</td>
							</template>
						</tr>
					</thead>
					<tbody>
            <tr v-for="item in salesDimension.datalist" :key="item.AdminId">
              <td class="thead-rs">{{item.Name}}</td>
              <td class="data-cell" v-for="(data,data_key) in item.dataArr" :key="data_key" @click="openDiaHandle(data)">
                {{ data.value !== 0 ? data.value : '' }}
              </td>
            </tr>
					</tbody>
					<tfoot>
						<tr>
							<td>合计</td>
							<td v-for="(total_data,total_data_key) in salesDimension.totalGroupArr" :key="total_data_key" 
              class="data-cell" @click="openDiaHandle(total_data)">
								{{ total_data.value !== 0 ? total_data.value : '' }}
							</td>
						</tr>
					</tfoot>
				</table>
			</div>	
    </template>
    <template v-if="roadshowTab==3">
      <ul class="date-tab-box">
				<li :class="['date-tab-item',{'act':tab === researchersDimension.dateTab}]" v-for="tab in staticTabs" :key="tab" @click="changeTabHandle(tab)">
					{{tab}}
				</li>
        <date-picker
          v-model="researchersDimension.selectDate"
          type="date" 
          range
          value-type="format"
          :clearable="false"
          @change="dateChange"
          placeholder="请选择统计时间"/>
			</ul>
      <div class="table-body-wrapper" v-show="dataLoading">
				<table>
					<thead>
						<tr>
							<td rowspan="2" class="thead-rs" style="width: 100px;">研究员</td>
							<td
								:colspan="['周度统计表','月度统计表'].includes(researchersDimension.dateTab) ? 3 : 1"
								v-for="item in researchersDimension.tableTheadColumns" 
								:key="item" 
								class="head-column"
							>
								{{item}}
							</td>	
						</tr>
            <tr v-if="['月度统计表'].includes(researchersDimension.dateTab)">
              <template v-for="(item,index) in new Array(4)">
								<td :key="index+'_0'">试用</td>
								<td :key="index+'_1'">正式</td>
								<td :key="index+'_2'">关闭</td>
              </template>
            </tr>
            <tr v-if="['周度统计表'].includes(researchersDimension.dateTab)">
              <template v-for="(item,index) in new Array(3)">
								<td :key="index+'_0'">试用</td>
								<td :key="index+'_1'">正式</td>
								<td :key="index+'_2'">关闭</td>
              </template>
            </tr>
					</thead>
					<tbody>
            <tr v-for="item in researchersDimension.datalist" :key="item.AdminId">
              <td class="thead-rs">{{item.Name}}</td>
              <td class="data-cell" v-for="(data,data_key) in item.dataArr" :key="data_key" @click="openDiaHandle(data)">
                {{ data.value !== 0 ? data.value : '' }}
              </td>
            </tr>
					</tbody>
					<tfoot>
						<tr>
							<td>合计</td>
							<td v-for="(total_data,total_data_key) in researchersDimension.totalGroupArr" :key="total_data_key" 
              class="data-cell" @click="openDiaHandle(total_data)">
								{{ total_data.value !== 0 ? total_data.value : '' }}
							</td>
						</tr>
					</tfoot>
				</table>
			</div>	
    </template>

    <!-- 详情弹窗 -->
		<actiyityDetailDia
			:isShow.sync="isShowDia"
			:title="diaTitle"
			:form="dialogForm"
			:fromType="roadshowTab==2?'seller':'researcher'"
      region="oversea"
		/>
  </div>
</template>
<script>
import { overseasCustomInterence } from '@/api/modules/overseasCustom.js'
import mPage from '@/components/mPage.vue'
import actiyityDetailDia from '@/views/roadshow_manage/compononts/activityDetailDia';
export default {
  components: { mPage,actiyityDetailDia },
  data() {
    return {
      tabeLoading: false,
      tableData: [],
      total: 0,
      currentIndex: 1,
      pageSize: 10,
      columns: [
        {  label: "客户名称",key: 'CompanyName',minWidth:200 },
        {  label: "状态",key: 'CompanyStatus' },
        {  label: "路演日期",key: 'StartDate',sortable:true },
        {  label: "路演形式",key: 'RoadshowType' },
        {  label: "路演平台/路演城市",key: 'RoadshowPlatform' },
        {  label: "研究员",key: 'ResearcherName' },
        {  label: "对接销售",key: 'SellerName' },
      ],

      sales: [],
      researchers: [],
      date:[],
      searchWord: '',
      status:[],
      sortParams: {
        SortField: '',
        SortDesc: 1,
      },

      salesOptions: [],
      researchersOptions: [],
      statusOptions: [
        { label: '正式', val: '正式' },
        { label: '试用', val: '试用' },
        { label: '关闭', val: '关闭' },
      ],
      roadshowTab:1,
      staticTabs: [ '周度统计表','月度统计表','近1个月','近3个月','近6个月' ],
      dataLoading:false,
      // 销售维度
      salesDimension:{
        dateTab:"周度统计表",
        selectDate:"",
        tableTheadColumns:[],
        datalist:[],//表格数据
        totalGroupArr:[] //合计数据
      },
      // 研究员维度
      researchersDimension:{
        dateTab:"周度统计表",
        selectDate:"",
        tableTheadColumns:[],
        datalist:[],//表格数据
        totalGroupArr:[] //合计数据
      },
      // 详情弹窗
      isShowDia:false,
      diaTitle:'路演详情',
      dialogForm:{}
    }
  },
  mounted(){
    this.getSellerList()
    this.getResearchersList()
    this.getTableData()
  },
  methods:{
    //获取销售列表
    async getSellerList() {
      const res = await overseasCustomInterence.getOverseasRoadShowUsers({AdminType:'seller'})

      if (res.Ret === 200) {
        this.salesOptions = res.Data || [];
      }
    },

    //获取研究员列表
    async getResearchersList() {
      // 发送请求
      const res = await overseasCustomInterence.getOverseasRoadShowUsers({AdminType:'researcher'});
      if (res.Ret === 200) {
        this.researchersOptions = res.Data || [];
      }
    },

    async getTableData() {
      this.tabeLoading = true;
      let params = {
        ResearcherId: this.researchers.join(','),
        SellerId: this.sales.join(','),
        StartDate: this.date[0]||'',
        EndDate: this.date[1]||'',
        CompanyStatus: this.status.join(','),
        CurrentIndex: this.currentIndex,
        PageSize: this.pageSize,
        Keyword: this.searchWord,
        ...this.sortParams
      }
      const res = await overseasCustomInterence.getOverseasRoadShowList(params)

      this.tabeLoading = false;

      if(res.Ret!==200) return

      this.tableData = res.Data.List || [];

      this.total = res.Data.Paging.Totals;
    },

    handleSortChange({prop,order}) {
      console.log(prop,order)
      this.sortParams = {
        SortField: order?prop:'',
        SortDesc: order==='ascending'?2:1
      }

      this.pageChange(1)
    },

    pageChange(page) {
      this.currentIndex = page;
      this.getTableData()
    },

    toCustomDetail(data) {
      const path = data.Source===1?'/detailCustomEn':'/customDetail'
      const query = {
          ...data.Source===1?{
            companyId:data.CompanyId - 10000000
          }:{
              id:data.CompanyId
          },
          from:'overseas'
      }
      const href = this.$router.resolve({path,query}).href
      window.open(href,"_blank")
    },
    /* 切换筛选 */
    changeSelectOpts() {
      
    },
    tabChange(tab){
      if(this.roadshowTab==tab) return 
      this.roadshowTab=tab
      this.changeTabHandle('周度统计表')
    },
    /* 	获取几周前 周一周日日期 或前几月月份*/
		getWeekOrMonthDate(weeknum,type='week') {
			if(type === 'week') {
				const weekStart = this.$moment().subtract(weeknum, 'week').startOf('isoWeek').format('YYYY.MM.DD'); //周一
				const weekEnd = this.$moment().subtract(weeknum, 'week').endOf('isoWeek').format('YYYY.MM.DD'); //周日
	
				// console.log(weekStart,weekEnd)
				return `${weekStart}~${weekEnd}`;
			} else {
				const month = this.$moment().subtract(weeknum,'M').format('YYYY.MM');
				return month;
			}
		},
    changeTabHandle(tab){
      if(this.roadshowTab == 1){
        return
      }else if(this.roadshowTab == 2){
        this.salesDimension.dateTab = tab;
        switch(tab) {
          case '周度统计表':
            this.salesDimension.tableTheadColumns = [
                `本周(${this.getWeekOrMonthDate(0)})`,
                `上一周(${this.getWeekOrMonthDate(1)})`,
                `上两周(${this.getWeekOrMonthDate(2)})`,
                `上三周(${this.getWeekOrMonthDate(3)})`,
                `上四周(${this.getWeekOrMonthDate(4)})`,
                `上五周(${this.getWeekOrMonthDate(5)})`]
            break;
          case '月度统计表':
            this.salesDimension.tableTheadColumns = [
                this.getWeekOrMonthDate(0,'month'),
                this.getWeekOrMonthDate(1,'month'),
                this.getWeekOrMonthDate(2,'month'),
                this.getWeekOrMonthDate(3,'month'),
                this.getWeekOrMonthDate(4,'month'),
                this.getWeekOrMonthDate(5,'month')]
            break;
          default:
          this.salesDimension.tableTheadColumns = ['试用','正式','关闭']

          break;
        }
      }else{
        this.researchersDimension.dateTab = tab;
        switch(tab) {
          case '周度统计表':
            this.researchersDimension.tableTheadColumns =  ['上一周','本周','下一周']
            break;
          case '月度统计表':
            this.researchersDimension.tableTheadColumns = [
              this.getWeekOrMonthDate(0,'month'),
              this.getWeekOrMonthDate(1,'month'),
              this.getWeekOrMonthDate(2,'month'),
              this.getWeekOrMonthDate(3,'month'),
            ]
            break;
          default:
          this.researchersDimension.tableTheadColumns = ['试用','正式','关闭']
          break;
        }
      }
      this.$nextTick(()=>{
        $('.table-body-wrapper')[0].scrollTop = 0;
      })
      let typeObj = {
        '近1个月': 1,
        '近3个月': 3,
        '近6个月': 6,
      };
      typeObj[tab] ? this.filterDate(typeObj[tab]) : this.filterDate(0);

      this.getData();
    },
    dateChange(){
      if(this.roadshowTab==2){
        this.salesDimension.dateTab = '';
        this.salesDimension.tableTheadColumns = ['试用','正式','关闭'];
      }else{
        this.researchersDimension.dateTab = '';
			  this.researchersDimension.tableTheadColumns = ['试用','正式','关闭'];
      }

			this.getData();
    },
    filterDate(month){
      if(month) {
				let date_before = this.$moment().subtract(month,'M').format("YYYY-MM-DD");
				let date_now = this.$moment().format("YYYY-MM-DD");
				let date = [date_before,date_now]
				this.roadshowTab==2?(this.salesDimension.selectDate = date):(this.researchersDimension.selectDate = date);
			}else {
        this.roadshowTab==2?(this.salesDimension.selectDate = ''):(this.researchersDimension.selectDate = '');
			}
    },
    // 销售维度、研究员维度
    getData(){
      let apiName=this.roadshowTab==2?"getOverseasSellerRoadShowList":"getOverseasResearcherRoadShowList"
      let params=this.roadshowTab==2?{
        DataType: this.salesDimension.dateTab === '周度统计表' ? 'week' : this.salesDimension.dateTab === '月度统计表' ? 'month' : 'time_interval',
        StartDate: this.salesDimension.selectDate ? this.salesDimension.selectDate[0] : '',
        EndDate: this.salesDimension.selectDate ? this.salesDimension.selectDate[1] : '',
      }:{
        DataType: this.researchersDimension.dateTab === '周度统计表' ? 'week' : this.researchersDimension.dateTab === '月度统计表' ? 'month' : 'time_interval',
        StartDate: this.researchersDimension.selectDate ? this.researchersDimension.selectDate[0] : '',
        EndDate: this.researchersDimension.selectDate ? this.researchersDimension.selectDate[1] : '',
      }
      this.dataLoading=false
      overseasCustomInterence[apiName](params).then(res=>{
        if(res.Ret == 200){
          // console.log(res,'res');
          const dataList=res.Data.List||[]
          const totalGroupArr=res.Data.RsReportRecordNumList || []
          dataList.forEach((da)=>{
            da.dataArr = this.filterTableData(da.RsReportRecordNumList,[da.AdminId])
          })
          if(this.roadshowTab==2){
            this.salesDimension.datalist=dataList
            this.salesDimension.totalGroupArr=this.filterTableData(totalGroupArr,dataList.map(it => it.AdminId))
          }else{
            this.researchersDimension.datalist=dataList
            this.researchersDimension.totalGroupArr=this.filterTableData(totalGroupArr,dataList.map(it => it.AdminId))
          }
          this.dataLoading=true
        }
      })

    },
    /* 处理数据结构 便于页面渲染 userid 时间用于弹窗获取列表*/
		filterTableData(data,userid=[]) {
			let list = data.map(item => ([
        {
					key: '试用',
					value: item.TryOutNum,
					startDate: item.StartDate,
					endDate: item.EndDate,
					userid
				},
        {
					key: '正式',
					value: item.FormalNum,
					startDate: item.StartDate,
					endDate: item.EndDate,
					userid
				},
				{
					key: '关闭',
					value: item.CloseNum,
					startDate: item.StartDate,
					endDate: item.EndDate,
					userid
				}
			]))
			
			return list.flat(Infinity);
		},
    openDiaHandle({ startDate,endDate,userid,value,key }){
      if(value === 0) return;

      this.dialogForm = {
        startDate,
        endDate,
        userid,
        key
      }
      this.isShowDia = true;
    }
  },
}
</script>
<style scoped lang="scss">
.overseas-custom-roadshow-box {
    min-height: calc(100vh - 110px);
    background-color: white;
    border: 1px solid #ECECEC;
    border-radius: 2px;
    box-sizing: border-box;
    padding: 20px 30px 30px 30px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
    .tab-box{
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      gap: 15px;
      .tab-item{
        min-width: 120px;
        margin: 0;
      }
    }
    .top-wrapper {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
    }
    .cont-wrapper {
      margin-top: 10px;
      padding-bottom: 40px;
    }
    .editor{
        color:#409EFF;
        cursor: pointer;
        &:hover{
            text-decoration: underline;
        }
    }
    .date-tab-box{
      display: flex;
			align-items: center;
			color: #333;
			margin-bottom: 30px;
      gap: 20px;
      .date-tab-item{
        cursor: pointer;
        &:hover {
					color: #409EFF;
				}
				&.act {
					color: #409EFF;
					position: relative;
					&::after {
						content: "";
						width: 100%;
						height: 2px;
						position: absolute;
						bottom: -10px;
						left: 50%;
						transform: translateX(-50%);
						background: #409EFF;
					}
				}
      }
    }
    .table-body-wrapper {
			max-height: calc(100vh - 300px);
			margin-right: -6px;
			overflow-y: scroll;
			overflow-x: auto;
			border-bottom: 1px solid #dcdfe6;
			border-top: 1px solid #dcdfe6;
		}

		table {
			width: 100%;
			font-size: 14px;
			color: #666;
			thead{
				position: sticky;
				top: 0;
				left: 0;
				border-left: 1px solid #dcdfe6;
				border-right: 1px solid #dcdfe6;
				td{
					border: none;
					outline-color: #dcdfe6;
					outline-style: solid;
					outline-width: 0.5px;
				}
			}
			td,
			th {
				min-width: 35px;
				// word-break: break-all;
				border: 1px solid #dcdfe6;
				height: 45px;
				text-align: center;
				background-color: #fff;
			}
	
			.head-column {
				background-color: #F0F2F5;
			}
	
			.data-cell{
				color: #409EFF;
				cursor: pointer;
			}

			.thead-sticky {
				position: sticky;
				top: 0;
			}
		}
}
</style>

