<template>
  <view>
    <u-modal v-model="visible" :show-title="false" :show-confirm-button="false" :mask-close-able="true" width="90%">
    <view class="slot-content">
      <view class="model-item-box">
        <Section :title="title + '\xa0' + $t('homePage.device.historyData')" />
        <view class="time-box" @click="openHistoryTime">
						<view class="time">
							{{ time[0] }}
						</view>~
						<view class="time">
							{{ time[1] }}
						</view>
					</view>

        <view class="chart-box">
          <zero-loading v-if="chartLoading"></zero-loading>
          <charts v-else-if="!chartLoading && valData.length" :id="'historyChart'" :options="history_option"></charts>
					<view v-else-if="!chartLoading && !valData.length" class="empty">{{$t('homePage.home.noData')}}</view>
      </view>
    </view>
		</view>
  </u-modal>
  <view style="position: fixed; z-index: 99999999">
			<uni-datetime-picker ref="hisTime" @change="selectHisTime" v-model="time" :clearIcon="false"
				type="datetimerange" :end="endTime" rangeSeparator="~" />
		</view>
  </view>
  
</template>
<script>
import Section from "@/components/section/index.vue";
import charts from "@/components/charts/index.vue";
import {  beforeDayTime,dataConversion } from '@/common/common.js'
export default {
  components: { Section, charts },
  props:{
    isShow: { // 弹窗是否展示
      type: Boolean,
      default: false
    },
    title:{
      type:String,
      default:''
    },
    params:{
      type:Object,
      default:()=>{}
    }
  },
  computed: {
    visible: {
      get() {
        return this.isShow
      },
      set(val) {
        this.$emit('update:isShow', false)
      }
    },
    currentStation() {
      return this.vuex_currentStation;
    },
  },
  watch: {
    currentStation: {
      handler(val) {
        if (val && val.id) {
          this.stationId = val.id
          this.time = beforeDayTime()
        }
      },
      deep: true,
      immediate: true
    },
    visible: {
      handler(val) {
        if(val && this.stationId){
					this.time = beforeDayTime()
          this.getHistoryData()
        }
      },
      deep: true,
      immediate: true
    },
    
  },
  data() {
    return {
      histroy_show: false,
      history_option: {},
      stationId:null,
      time:[],
      endTime: dataConversion(new Date()),
      chartLoading:false,
			valData:[]
    }
  },
  methods: {
    selectHisTime() {
			this.getHistoryData()	
    },
    openHistoryTime() {
			this.$refs.hisTime.show();
		},
    getHistoryData() {
      const self = this;
      self.chartLoading = true
			return new Promise((resolve, reject) => {
				self.$u.api.homePageData
					.GetHistoryData({
						stationId: this.stationId,
						beginTime: this.time[0],
						endTime: this.time[1],
						modelCol:  this.params.modelCol,
						deviceType: this.params.modelType,
						srcId:this.params.srcId 
					})
					.then((res) => {
            setTimeout(() => {
              this.chartLoading = false
              self.initHistoryChart(res.data)
            }, 800);
						resolve();
					})
					.catch((err) => {
						reject("error");
					});
			});
    },
    initHistoryChart(val){
      let dateArr = [];
			let nameArr = [];
			let valueArr = [];
			let serveArr = [];
		
      if (val && val.length > 0) {
				if (val[0].staticCurveList) {
					this.valData = val[0].staticCurveList
					val[0].staticCurveList.forEach((item) => {
						dateArr.push(item.date);
					})
				}else{
					this.valData = []
				}
				val.forEach((item, index) => {
					nameArr.push(item.deviceName);
					const arr = [];
					valueArr[index] = []
					if (item.staticCurveList) {
						item.staticCurveList.forEach((item2) => {
							arr.push(item2.digital);
							valueArr[index] = arr;
						});
					}


					serveArr.push({
						name: nameArr[index],
						type: "line",
						smooth: true,
						lineStyle: {
							width: 2,
						},
						itemStyle: {
							normal: {
								label: {
									show: false,
								},
							},
						},
						showSymbol: false,
						data: valueArr[index],
					});
				});

				this.history_option = {
					animationDuration: 500,
					animationEasing: "cubicInOut",
					color: ["#009458", "#BFE49F", "#00E6B0"],
					grid: {
						left: '10%',
						right: '8%',
						top: '12%',
						bottom: '5%',
						containLabel: true
					},
					tooltip: {
						trigger: "axis",
						axisPointer: {},
						textStyle: {
							textShadowBlur: 10, // 重点
							textShadowColor: "transparent", // 重点
						},
						confine: true,
						position: function (point, params, dom, rect, size) {
							var x = 0;
							var y = 0;
							var pointX = point[0];
							var pointY = point[1];
							var boxWidth = size.contentSize[0];
							var boxHeight = size.contentSize[1];
							if (boxWidth > pointX) {
								x = 5;
								y -= 15;
							} else {
								x = pointX - boxWidth - 15;
							}
							if (boxHeight + 20 > pointY) {
								y = pointY + 15;
							} else if (boxHeight > pointY) {
								y = 5;
							} else {
								y += pointY - boxHeight;
							}
							return [x, y];
						},
					},
					xAxis: {
						data: dateArr,
						axisLine: {
							show: false,
							lineStyle: {
								color: "#4F5458",
							},
						},
						axisTick: {
							show: false,
						},
						axisLabel: {
							show: true,
							color: "#A3A3A3",
							formatter: function (params) {
								let newParamsName = "";
								const paramsNameNumber = params.length; // 文字总长度
								const provideNumber = 11; //一行显示几个字
								const rowNumber = Math.ceil(paramsNameNumber / provideNumber);
								if (paramsNameNumber > provideNumber) {
									for (let p = 0; p < rowNumber; p++) {
										const start = p * provideNumber;
										const end = start + provideNumber;
										const tempStr =
											p === rowNumber - 1 ?
												params.substring(start, paramsNameNumber) :
												params.substring(start, end) + "\n";
										newParamsName += tempStr;
									}
								} else {
									newParamsName = params;
								}
								return newParamsName;
							},
						},
					},
					yAxis: [{
						name: this.params.unit ? this.title + this.params.unit :  this.title,
						type: "value",
						axisLine: {
							show: false,
							lineStyle: {
								color: "#4F5458",
							},
						},
						axisLabel: {
							show: true,
							color: "#A3A3A3",
						},
						min: function (value) {
							return Math.floor(
								(Math.abs(value.min) < value.max ?
									-value.max * 1.05 :
									value.min * 1.05
								).toFixed(2)
							);
						},
						max: function (value) {
							return Math.ceil(
								(Math.abs(value.min) < value.max ?
									value.max * 1.05 :
									-value.min * 1.05
								).toFixed(2)
							);
						},
					}],

					series: serveArr,
				};
			}

    }
  },
}
</script>
<style lang="scss" scoped>
.slot-content {
  padding: 20rpx;
}
.chart-box {
  width: 100%;
  height: 500rpx;
  margin-top: 20rpx;
}

.time-box {
		display: flex;
		justify-content: space-around;
		align-items: center;
		font-size: 28rpx;
		margin-top: 20rpx;
		// border: 1px solid #a3a3a3;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		padding: 10rpx;

		.time {
			z-index: 9999999999;
			font-size: 28rpx;
			white-space: nowrap;
		}
	}
	.empty{
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		// font-size: 24rpx;
		color: #2a2a2a;
	}

</style>