<template>
	<view class="dataAnalyse">
		这是数据分析
		<view class="header">
			<view class="header-warp">
				<view class="header-left">
					<view class="uni-list">
						<view class="uni-list-cell">
							<view class="uni-list-cell-db">
								<picker @change="bindPickerChange" :value="index" :range="shopArray" range-key="name">
									<view class="uni-input">{{ shopArray[index].name }}</view>
								</picker>
								<image src="../../static/images/downicon.png" mode="" class="icon"></image>
							</view>
						</view>
					</view>
				</view>
				<view class="header-bar header-center">数据分析</view>
				<view class="header-right"><image src="../../static/images/seticon.png" mode="" class="icon" @tap="tosetting"></image></view>
			</view>
			<view class="tabS">
				<view class="tab" :class="activeTab == 0 ? 'active_Tab' : ''" @tap="activeTab = 0">
					<picker mode="date" :value="startDate" @change="dateChange($event, 'startDate')">
						<view class="uni-input">{{ startDate }}</view>
					</picker>
					<image src="../../static/images/downicon.png" mode="" class="icon"></image>
				</view>
				至
				<view class="tab" :class="activeTab == 1 ? 'active_Tab' : ''" @tap="activeTab = 1">
					<picker mode="date" :value="endDate" @change="dateChange($event, 'endDate')">
						<view class="uni-input">{{ endDate }}</view>
					</picker>
					<image src="../../static/images/downicon.png" mode="" class="icon"></image>
				</view>
			</view>
		</view>

		<view class="" style="height: 102rpx;"></view>
		<view class="btnS">
			<view class="btn" :class="activeBtn == 0 ? 'active_Btn' : ''" @tap="activeBtn = 0">售检分析</view>
			<view class="btn" :class="activeBtn == 1 ? 'active_Btn' : ''" @tap="activeBtn = 1">用户分析</view>
		</view>
		<view class="sale_box" v-if="activeBtn == 0">
			<view class="box" v-if="intradayData">
				<view class="todo-list">
					<view class="item">
						<view class="title">预订人次</view>
						<view class="num">{{ intradayData.ydrc }}</view>
					</view>
					<view class="item">
						<view class="title">销售金额</view>
						<view class="num">{{ xsje}}元</view>
					</view>
					<view class="item">
						<view class="title">入园人次</view>
						<view class="num">{{ intradayData.ryrc }}</view>
					</view>
					<view class="item">
						<view class="title">核销金额</view>
						<view class="num">{{ hxje }}元</view>
					</view>
				</view>
			</view>
			<view class="something">
				<view v-if="0 === shopID && shopOrdersTop && shopOrdersTop.length > 0" class="piece">
					<view class="title">店铺订单量排行榜</view>
					<view class="todo-list">
						<cmd-progress
							v-for="(item, i) in shopOrdersTop"
							class="cmd-progress"
							:key="i"
							:total="shopOrdersTop | getMax"
							:value="item.data"
							stroke-color="linear-gradient(to right, #FFE873, #FFD600)"
							status="active"
							stroke-shape="square"
							:title="item.name"
							stroke-width="20"
						></cmd-progress>
					</view>
				</view>
				<view v-if="0 === shopID && shopCheckTop && shopCheckTop.length > 0" class="piece">
					<view class="title">核销金额排行榜</view>
					<view class="todo-list">
						<cmd-progress
							v-for="(item, i) in shopCheckTop"
							class="cmd-progress"
							:key="i"
							:total="shopCheckTop | getMax"
							:value="item.data"
							stroke-color="linear-gradient(to right, #FFE873, #FFD600)"
							status="active"
							stroke-shape="square"
							:title="item.name"
							stroke-width="20"
						></cmd-progress>
					</view>
				</view>
				<view v-if="0 !== shopID && ticketsBooking && ticketsBooking.length > 0" class="piece">
					<view class="title">门票预定占比</view>
					<view class="todo-list"><self-ucharts :series="ticketsBooking"></self-ucharts></view>
				</view>
				<view v-if="0 !== shopID && ticketsSalesAmount && ticketsSalesAmount.length > 0" class="piece">
					<view class="title">门票销售占比</view>
					<view class="todo-list"><self-ucharts :series="ticketsSalesAmount"></self-ucharts></view>
				</view>
				<view v-if="0 !== shopID && checkPoint && checkPoint.length > 0" class="piece">
					<view class="title">核销点销售占比</view>
					<view class="todo-list"><self-ucharts :series="checkPoint"></self-ucharts></view>
				</view>
				<view class="piece">
					<view class="title" v-if="shopSellData">
						<view class="left"><text class="future">产品销售数量走势</text></view>
						<view class="right">
							<view class="today-icon"></view>
							<text class="title">今日</text>
							<view class="yesterday-icon"></view>
							<text class="title">昨日</text>
						</view>
					</view>
					<view class="todo-list"><self-ucharts :datas="shopSellData" type="line"></self-ucharts></view>
				</view>
				<view class="piece">
					<view class="title" v-if="shopMoney">
						<view class="left"><text class="future">产品销售金额走势</text></view>
						<view class="right">
							<view class="today-icon"></view>
							<text class="title">今日</text>
							<view class="yesterday-icon"></view>
							<text class="title">昨日</text>
						</view>
					</view>
					<view class="todo-list"><self-ucharts :datas="shopMoney" type="line"></self-ucharts></view>
				</view>
			</view>
		</view>
		<view class="sale_box" v-else>
			<view class="box">
				<view class="todo-list">
					<view class="item" style="width: 100%;">
						<view class="title">今日新增用户</view>
						<view class="num">{{ todayNewUser }}</view>
					</view>
				</view>
			</view>
			<view class="something">
				<view class="piece">
					<view class="title">
						<view class="left"><text class="future">新增用户走势</text></view>
					</view>
					<view class="todo-list"><self-ucharts :datas="brandNewUser" type="line"></self-ucharts></view>
				</view>
				<view v-if="ageProportion && ageProportion.length > 0" class="piece">
					<view class="title">用户年龄占比</view>
					<view class="todo-list"><self-ucharts :series="ageProportion"></self-ucharts></view>
				</view>
				<view v-if="genderProportion && genderProportion.length > 0" class="piece">
					<view class="title">用户男女占比</view>
					<view class="todo-list"><self-ucharts :series="genderProportion"></self-ucharts></view>
				</view>
			</view>
		</view>

		<rf-loading v-if="loading"></rf-loading>
		<tabBar :currentIndex="typeNum"></tabBar>
	</view>
</template>

<script>
import moment from '@/common/moment'
import cmdProgress from '@/components/cmd-progress/cmd-progress.vue'
import selfUcharts from '@/pages/components/self-ucharts.vue'

export default {
  components: { cmdProgress, selfUcharts },
  computed: {
    xsje () {
      if (this.intradayData === null) {
        return 0
      } else if (this.intradayData.xsje === 0) {
        return 0
      } else {
        return (this.intradayData.xsje / 100).toFixed(2)
      }
    },
    hxje () {
      if (this.intradayData === null) {
        return 0
      } else if (this.intradayData.hxje === 0) {
        return 0
      } else {
        return (this.intradayData.hxje / 100).toFixed(2)
      }
    }
  },
  data () {
    return {
      ticketsBooking: null,
      shopOrdersTop: null,
      shopCheckTop: null,
      intradayData: null,
      ticketsSalesAmount: null,
      checkPoint: null,
      shopSellData: null,
      shopMoney: null,
      typeNum: null,
      shopID: 0,
      index: 0,
      activeTab: 0,
      activeBtn: 0,
      shopArray: [{ name: '全部', id: 0 }],
      loading: true,
      startDate: moment(new Date()).format('YYYY-MM-DD'),
      endDate: moment(new Date()).format('YYYY-MM-DD'),
      todayNewUser: 0,
      brandNewUser: null,
      ageProportion: null,
      genderProportion: null
    }
  },
  mounted () {
    this.loadData()
  },
  watch: {
    activeBtn (n, o) {
      this.loadData()
    }
  },
  filters: {
    getMax (datas) {
      if (Array.isArray(datas) && datas.length > 0) {
        const total = [...datas].reduce((acc, cur) => (acc.data > cur.data ? acc : cur)).data
        return total
      }
      return null
    }
  },
  onShow () {
    // 加载店铺列表
    this.getShopList()
    // 5分钟刷新数据
    setInterval(() => {
      this.loadData()
    }, 1000 * 60 * 5)
  },
  methods: {
    loadData () {
      // 加载数据
      if (this.activeBtn === 0 && this.shopID === 0) {
        this.loadDataForNoShop()
      } else if (this.activeBtn === 0) {
        this.loadDataByShop()
      } else {
        this.loadUserAnalyse()
      }
    },
    loadUserAnalyse () {
      // 用户分析
      const data = {
        filterType: 'day',
        startDate: this.startDate,
        endDate: this.endDate
      }
      // 今日新增用户
      const nowDate = moment(new Date()).format('YYYY-MM-DD')
      this.$http.post('dataAnalyse/brandNewUser', { startDate: nowDate, endDate: nowDate }).then(res => {
        if (res.code === 200 && res.msg === 'OK') {
          this.todayNewUser = res.data[0].value
        }
      })

      // 新增趋势用户
      this.$http.post('dataAnalyse/brandNewUser', data).then(res => {
        if (res.code === 200) {
          const brandNewUser = {
            xdata: [],
            jrdata: [],
            zrdata: []
          }
          res.data.forEach(ele => {
            brandNewUser.xdata.push(ele.name.substr(8))
            brandNewUser.jrdata.push(ele.value)
          })
          this.brandNewUser = JSON.parse(JSON.stringify(brandNewUser))
        }
      })

      // 年龄分布
      this.$http.post('dataAnalyse/ageProportion', {}).then(res => {
        if (res.code === 200 && res.msg === 'OK') {
          const ageProportion = ['0-14', '15-18', '18-30', '30-55', '55以上']
          this.ageProportion = ageProportion.map((item, i) => {
            return { name: item, data: res.data[i] }
          })
        }
      })
      // 男女比例分布
      this.$http.post('dataAnalyse/genderProportion', {}).then(res => {
        if (res.code === 200 && res.msg === 'OK') {
          this.genderProportion = JSON.parse(JSON.stringify(res.data).replaceAll('value', 'data'))
        }
      })
    },
    loadDataForNoShop () {
      // 加 载无 需店铺id数据
      const data = {
        filterType: 'day',
        startDate: this.startDate,
        endDate: this.endDate
      }
      // 获取售检分析顶部数据
      this.$http.post('dataAnalyse/intradayData', data).then(res => {
        if (res.code === 200 && res.msg === 'OK') {
          this.intradayData = res.data
        }
      })
      // 店铺订单量排行榜
      this.$http.post('dataAnalyse/shopOrdersTop', data).then(res => {
        if (res.code === 200 && res.msg === 'OK') {
          this.shopOrdersTop = JSON.parse(JSON.stringify(res.data).replaceAll('value', 'data'))
        }
      })
      // 店铺核销金额排行榜
      this.$http.post('dataAnalyse/shopCheckTop', data).then(res => {
        if (res.code === 200 && res.msg === 'OK') {
          this.shopCheckTop = JSON.parse(JSON.stringify(res.data).replaceAll('value', 'data'))
        }
      })
      // 产品销售数量
      this.$http.get('/homePage/getData2', { date: moment().format('YYYY-MM-DD') }).then(res => {
        if (res.data) {
          const shopSellData = {
            xdata: [],
            jrdata: [],
            zrdata: []
          }
          res.data.forEach(ele => {
            shopSellData.xdata.push(ele.time)
            shopSellData.jrdata.push(ele.jr)
            shopSellData.zrdata.push(ele.zr)
          })
          this.shopSellData = JSON.parse(JSON.stringify(shopSellData))
        }
      })
      // 产品销售金额走势
      this.$http.get('/homePage/getData3', { date: moment().format('YYYY-MM-DD') }).then(res => {
        if (res.data) {
          const shopMoney = {
            xdata: [],
            jrdata: [],
            zrdata: []
          }
          res.data.forEach(ele => {
            shopMoney.xdata.push(ele.time)
            shopMoney.jrdata.push(ele.jr)
            shopMoney.zrdata.push(ele.zr)
          })
          this.shopMoney = JSON.parse(JSON.stringify(shopMoney))
        }
      })
    },
    loadDataByShop () {
      // 加 载需 店铺id数据
      const data = {
        shopId: this.shopID,
        filterType: 'day',
        startDate: this.startDate,
        endDate: this.endDate
      }

      // 预订量比例
      this.$http.post('dataAnalyse/ticketsBooking', data).then(res => {
        if (res.code === 200 && res.msg === 'OK') {
          this.ticketsBooking = JSON.parse(JSON.stringify(res.data).replaceAll('value', 'data'))
        }
      })
      // 销售金额比例
      this.$http.post('dataAnalyse/ticketsSalesAmount', data).then(res => {
        if (res.code === 200 && res.msg === 'OK') {
          this.ticketsSalesAmount = JSON.parse(JSON.stringify(res.data).replaceAll('value', 'data'))
        }
      })
      // 核销量比例
      this.$http.post('dataAnalyse/checkPoint', data).then(res => {
        if (res.code === 200 && res.msg === 'OK') {
          this.checkPoint = JSON.parse(JSON.stringify(res.data).replaceAll('value', 'data'))
        }
      })
    },
    // 选择商铺
    bindPickerChange (e) {
      this.index = e.detail.value
      this.shopID = this.shopArray[this.index].id
      this.loadData()
    },
    // 获取店铺列表
    async getShopList () {
      this.loading = true
      await this.$http.get('/homePage/getShopByMerId').then(res => {
        if (res.data && res.code === 200) {
          this.shopArray = [{ name: '全部', id: 0 }, ...res.data]
          this.loading = false
        }
      })
    },
    dateChange (e, date) {
      this[date] = e.detail.value
      this.loadData()
    },
    // 跳转设置页
    tosetting () {
      this.$mRouter.push({ route: '/pages/index/setting/setting' })
    }
  },
  onLoad () {
    this.typeNum = this.$mStore.state.roleIndex
  }
}
</script>

<style lang="scss" scoped>
/* 请根据需求修改图表容器尺寸，如果父容器没有高度图表则会显示异常 */
.charts-box {
	width: 100%;
	height: 300px;
}
.header {
	width: 100%;
	padding: 0 30rpx;
	background-color: $barColor;
	position: fixed;
	top: 0;
	box-sizing: border-box;
	z-index: 99;
	.header-warp {
		display: flex;
		height: 80rpx;
		color: #231726;
		background-color: #ffcc01;
		position: relative;
		.header-left {
			position: absolute;
			font-size: 28rpx;
			.uni-list:after {
				border-color: transparent;
			}
			.uni-list-cell-db {
				height: 80rpx;
				font-size: 28rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				background-color: $barColor;

				.icon {
					width: 17rpx;
					height: 12rpx;
					margin-left: 10rpx;
				}
			}
		}

		.header-center {
			flex: 1;
			font-size: 36rpx;
			font-weight: 700;
			text-align: center;
			line-height: 80rpx;
		}

		.header-right {
			position: absolute;
			right: 0;
			top: 50%;
			margin-top: -20rpx;
			.icon {
				width: 40rpx;
				height: 40rpx;
			}
		}
	}
	.tabS {
		display: flex;
		justify-content: left;
		align-items: center;
		.tab {
			flex: 1;
			text-align: center;
			padding: 10rpx 0;
			// border: 0.5rpx solid #999;
			display: flex;
			justify-content: center;
			align-items: center;
			.icon {
				width: 17rpx;
				height: 12rpx;
				margin-left: 10rpx;
			}
		}
		.active_tab {
			border: 0.5rpx solid #b15cfa;
			color: #b15cfa;
			background-color: #ffffff;
			border-bottom: 0;
		}
	}
}
.btnS {
	padding: 0 30rpx;
	display: flex;
	justify-content: left;
	background-color: #ffffff;
	.btn {
		flex: 1;
		text-align: center;
		padding: 10rpx 0;
		font-size: 32rpx;
		font-weight: 700;
		color: #2f2f2f;
	}
	.active_Btn {
		// border: 0.5rpx solid #b15cfa;
		// color: #b15cfa;
		// background-color: #FFFFFF;
		border-bottom: 2rpx solid #b15cfa;
	}
}
.sale_box {
	padding: 0 30rpx;
	margin-bottom: 135rpx;
	.box {
		display: flex;
		justify-content: left;
		margin-top: 30rpx;
		padding: 20rpx;
		border-radius: 10rpx;

		.advanceBox {
			height: 200rpx;
			flex: 1;
			text-align: center;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.text {
				height: 60rpx;
				line-height: 60rpx;
			}
		}
	}
}

.todo-list {
	width: 100%;
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	background-color: #ffffff;
	box-sizing: border-box;
	padding: 43rpx 30rpx;
	border-radius: 10rpx;

	.item {
		width: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;

		.title {
			color: $subheadColor;
			font-size: 30rpx;
		}

		.num {
			color: $titleColor;
		}
	}
}

.something {
	margin-top: 30rpx;

	.piece {
		margin-bottom: 45rpx;
		.right {
			display: flex;
			justify-content: center;
			align-items: center;
			box-sizing: border-box;
			.today-icon {
				width: 20rpx;
				height: 9rpx;
				background-color: #ff9c2f;
				margin-right: 10rpx;
			}
			.title {
				font-size: 20rpx;
				margin-right: 20rpx;
			}
			.yesterday-icon {
				width: 20rpx;
				height: 9rpx;
				background-color: #b15cfa;
				margin-left: 10rpx;
			}
		}
		.title {
			justify-content: space-between;
			display: flex;
			.future {
				font-size: 32rpx;
			}
		}
	}

	.title {
		font-size: 32rpx;
		font-weight: 700;
		color: $titleColor;
	}

	.todo-list {
		display: flex;
		// justify-content: center;
		align-items: center;
		flex-wrap: wrap;
		margin-top: 30rpx;
		background-color: #ffffff;
		box-sizing: border-box;
		padding: 43rpx 30rpx;
		border-radius: 10rpx;

		.item {
			width: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			margin-bottom: 30upx;

			.title {
				color: $subheadColor;
				font-size: 30rpx;
			}

			.num {
				color: $titleColor;
			}
		}

		.charts-box {
			width: 100px;
			height: 100px;
		}
		.cmd-progress {
			width: 100%;
		}
	}
}
</style>
