<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 v-if="isDtdc" label="二级设备(不超过5个)" prop="child" :rules="[{ required: true, message: '请选择二级设备' }]" style="width: 200px;margin-right: 50px">
          <el-cascader
              v-model="form.child"
              :props="{ multiple: true }"
              :options="childOptions"
              @change="handleChildChange"></el-cascader>
        </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>
        <date-time-select :data-unit="this.form.dataUnit" @updateDate="(val)=>form.dataRange =val"/>
      </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'
import DateTimeSelect from "./DateTimeSelect.vue";
export default {
  name: "Search",
  mixins: [resize],
  components:{DateTimeSelect},
  computed: {
    isDtdc(){
      return this.form.categoryName === '单体电池'
    }
  },
  data() {
    return {
      chart: null,
      deviceCategoryList:[],//设备列表
      siteList: [],//站点列表
      childOptions:[
        {
          value: '021_DDS_01',
          label: '站点一',
          children:[{
            value: '1',
            label: '1-50',
            children:[{
              value: '001',
              label: '设备一'
            },{
              value: '002',
              label: '设备二'
            },{
              value: '003',
              label: '设备三'
            }]
          }]
        },
        {
          value: '021_DDS_02',
          label: '站点二',
          children:
            [{
              value: '1',
              label: '1-50',
              children:[{
                value: '001',
                label: '设备一'
              },{
                value: '002',
                label: '设备二'
              }, {
                value: '003',
                label: '设备三'
              }]
            },
            {
              value: '2',
              label: '51-100',
              children:[{
                value: '001',
                label: '设备一'
              },{
                value: '002',
                label: '设备二'
              },{
                value: '003',
                label: '设备三'
              }]
            }]

        }
      ],//二级设备列表
      form: {
        dataRange:[],//时间选择范围
        child:[],
        siteIds: [],//当前选中的站点id 默认选中第一个站点
        categoryName: '',//设备
        pointName: '',//点位
        dataUnit: 1,//横坐标
      },
      loading: false,
    }
  },
  methods: {
    handleChildChange(data){
      console.log('选择二级设备',data)
      this.form.child=data
    },
    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){
      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('请输入正确的点位');
          }
          if(this.isDtdc && (this.form.child.length === 0 || this.form.child.length > 5 )){
            return this.$message.error('请选择二级设备且不能超过5个');
          }
          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>
