<template>
  <div v-loading="loading" class="ems-dashboard-editor-container" style="background-color: #ffffff">
    <el-form ref="form" :model="form" label-position="top">
      <el-form-item
          label="站点"
          prop="siteIds"
          :rules="[{ required: true, message: '请选择站点' }]"
      >
        <el-checkbox-group v-model="form.siteIds">
          <el-checkbox v-for="(item,index) in siteList" :key="index+'zdListSearch'" :label="item.siteId">
            {{ item.siteName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="设备" prop="categoryName" :rules="[{ required: true, message: '请选择设备' }]">
        <el-radio-group v-model="form.categoryName" >
          <el-radio v-for="(key,index) in deviceCategoryList" :key="index+'sbListSearch'" :label="key">
            {{ key }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <div style="display: flex">
        <el-form-item label="点位" prop="pointName"  :rules="[{ required: true, message: '请输入点位' }]" style="width: 200px;margin-right: 50px">
          <el-autocomplete
              v-model="form.pointName"
              placeholder="请输入点位"
              :fetch-suggestions="querySearchAsync"
              @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="横坐标" prop="dataUnit" :rules="[{ required: true, message: '请选择横坐标' }]">
          <el-radio-group v-model="form.dataUnit">
            <el-radio :label="1">分钟</el-radio>
            <el-radio :label="2">小时</el-radio>
            <el-radio :label="3">天</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <el-form-item>
        <el-button type="primary" @click="submitForm">生成图表</el-button>
      </el-form-item>
    </el-form>
    <el-card shadow="always" class="common-card-container common-card-container-body-no-padding time-range-card">
      <div slot="header" class="time-range-header">
        <span class="card-title"></span>
      </div>
      <div style="height: 310px" id="searchChart"></div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import resize from '@/mixins/ems/resize'
import {getAllSites} from "@/api/ems/zddt";
import {getAllDeviceCategory,getPointValueList,pointFuzzyQuery} from '@/api/ems/search'
export default {
  name: "Search",
  mixins: [resize],
  computed: {
  },
  data() {
    return {
      chart: null,
      deviceCategoryList:[],//设备列表
      siteList: [],//站点列表
      form: {
        siteIds: [],//当前选中的站点id 默认选中第一个站点
        categoryName: '',//设备
        pointName: '',//点位
        dataUnit: '',//横坐标
      },
      loading: false,
    }
  },
  methods: {
    showLoading(){
      this.chart && this.chart.showLoading()
    },
    hideLoading(){
      this.chart && this.chart.hideLoading()
    },
    initChart() {
      this.chart = echarts.init(document.querySelector('#searchChart'))
    },
    setOption(data) {
      if(!this.chart) return
      this.chart.clear()
      console.log('返回的数据',data)
      let dataset=[]
      if(data.length>0){
        data.forEach((item,index)=>{
          item.deviceList.forEach(inner=>{
            dataset.push({
              name:`${this.siteList.find(s=>s.siteId === item.siteId)?.siteName || ''}-${inner.deviceId}`,
              type:'line',
              xdata:[],
              data:[]
            })
            const length = dataset.length
            inner.pointValueList.forEach(value=>{
              dataset[length-1].xdata.push(value.valueDate)
              dataset[length-1].data.push(value.pointValue)
            })
          })
        })
      }else{
        this.$message.warning('暂无数据')
      }
      console.log('图表数据',dataset)
      this.chart.setOption({
        legend: {
          left: 'center',
          top: '10',
        },
        grid: {
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        textStyle:{
          color:"#333333",
        },
        xAxis: {type:'category',data:dataset?.[0]?.xdata || []},
        yAxis: {
          type: 'value',
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end: 100
          }
        ],
        series: dataset
      })
    },
    submitForm() {
      this.getDate()
    },
    handleSelect(data){
      this.form.pointName = data.value
    },
    querySearchAsync(query,cb){
      // query = query.trim()
      console.log('查询数据',query)
      if(this.form.siteIds.length===0 || !this.form.categoryName){
        this.$message({
          type: 'warning',
          message: '请先选择站点和设备',
        })
        return cb([])
      }
      pointFuzzyQuery({
        siteIds:this.form.siteIds,
        categoryName:this.form.categoryName,
        pointName:query,
      }).then(response => {
        const data  = response?.data || []
        cb(data.map(item => {
          return {name: item, value: item}
        }))
      })
    },
    // 获取所有设备
    getDeviceCategory(){
      return getAllDeviceCategory().then(response => {
        this.deviceCategoryList=response?.data || []
      })
    },
    getZdList() {
      return getAllSites().then(response => {
        this.siteList = response.data || []
      }).finally(() => {
      })
    },
    getDate(){
      this.$refs.form.validate(valid => {
        if(valid){
          if(!this.form.pointName){
            return this.$message.error('请输入正确的点位');
          }
          this.loading = true
          const{siteIds,dataUnit,categoryName,pointName}=this.form
          getPointValueList({siteIds,dataUnit,categoryName,pointName}).then(response => {
            this.setOption(response?.data || [])
          }).finally(()=>{
            this.loading = false
          })
        }
      })
    },
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  mounted() {
    this.loading= true
    this.$nextTick(()=>{
      this.initChart()
      Promise.all([this.getDeviceCategory(), this.getZdList()]).finally(()=>this.loading=false)
    })
  }
}
</script>

<style lang="scss" scoped>

</style>
