<template>
  <view>
    <view class="bg-white">
      <SearchForm
        :schemas="searchFormSchema"
        @submit="handleSubmit"
      ></SearchForm>
    </view>
    <view class="h-80vh flex-center">
      <view class="w-full">
        <qiun-data-charts
          :loadingType="loadingType"
          type="column"
          :opts="opts"
          :chartData="chartData"
        />
      </view>
    </view>
  </view>
</template>
<script>
import SearchForm from '@/components/search-form'
import { http } from '@/api/index.js'
import { formatDataByObject } from '@/utils/index.js'
import QiunDataCharts from '@/components/qiun-data-charts/qiun-data-charts.vue'
export default {
  components: {
    SearchForm,
    QiunDataCharts,
  },
  data() {
    return {
      loadingType: 1,
      filterParmas: {},
      searchFormSchema: [
        {
          field: 'base',
          label: '基地',
          component: 'ApiSelect',
          componentProps: ({ formActionType }) => {
            return {
              api: async (e) => {
                const { data } = await http.get(
                  '/api/agricultural-device-basic',
                  {
                    params: e,
                  }
                )
                return data.data
              },
              onOptionsChange: (options) => {
                const { setFieldsValue } = formActionType
                if (options.length) {
                  setFieldsValue({
                    base: options[0].value,
                  })
                }
              },
              labelField: 'name',
              valueField: 'id',
              params: {
                device_type: 5,
              },
            }
          },
        },
        {
          field: 'device_id',
          component: 'ApiSelect',
          label: '监控点',
          componentProps: ({ formModel, formActionType }) => {
            return {
              placeholder: '监控点',
              api: async (e) => {
                if (e.agricultural_basic == null) return []
                const { data } = await http.get(
                  `/api/agricultural-device-point/${e.agricultural_basic}`,
                  {
                    params: e,
                  }
                )
                return formatDataByObject(data.data)
              },
              onOptionsChange: (options) => {
                const { setFieldsValue } = formActionType

                if (options.length)
                  setFieldsValue({
                    device_id: options[0].value,
                  })
              },
              params: {
                device_type: 5,
                agricultural_basic: formModel.base,
              },
              labelField: 'label',
              valueField: 'value',
            }
          },
        },
        {
          field: '[start_time, end_time]',
          label: '日期',
          component: 'Calendar',
          defaultValue: [
            this.$u.timeFormat(
              new Date().getTime() - 1000 * 60 * 60 * 24 * 7,
              'yyyy-mm-dd'
            ),
            this.$u.timeFormat(new Date().getTime(), 'yyyy-mm-dd'),
          ],
          componentProps: {
            mode: 'range',
            placeholder: ['开始时间', '结束时间'],
          },
        },
      ],
      opts: {
        timing: 'easeOut',
        duration: 1000,
        rotate: false,
        rotateLock: false,
        color: [
          '#1890FF',
          '#91CB74',
          '#FAC858',
          '#EE6666',
          '#73C0DE',
          '#3CA272',
          '#FC8452',
          '#9A60B4',
          '#ea7ccc',
        ],
        padding: [15, 15, 15, 5],
        fontSize: 13,
        fontColor: '#666666',
        dataLabel: true,
        dataPointShape: true,
        dataPointShapeType: 'solid',
        touchMoveLimit: 60,
        enableScroll: false,
        enableMarkLine: false,
        legend: {
          show: false,
        },
        xAxis: {
          disableGrid: true,
          labelCount: 7,
          rotateLabel: true,
          rotateAngle: 30,
        },
        yAxis: {
          min: 1,
          data: [
            {
              tofix: 1,
              min: 0,
            },
          ],
        },
        extra: {
          column: {
            type: 'group',
            width: 30,
            activeBgColor: '#000000',
            activeBgOpacity: 0.08,
            seriesGap: 2,
            categoryGap: 3,
            barBorderCircle: false,
            linearType: 'none',
            linearOpacity: 1,
            colorStop: 0,
            meterBorder: 1,
            meterFillColor: '#FFFFFF',
            labelPosition: 'outside',
          },
          tooltip: {
            showBox: true,
            showArrow: true,
            showCategory: false,
            borderWidth: 0,
            borderRadius: 0,
            borderColor: '#000000',
            borderOpacity: 0.7,
            bgColor: '#000000',
            bgOpacity: 0.7,
            gridType: 'solid',
            dashLength: 4,
            gridColor: '#CCCCCC',
            boxPadding: 3,
            fontSize: 13,
            lineHeight: 20,
            fontColor: '#FFFFFF',
            legendShow: true,
            legendShape: 'auto',
            splitLine: true,
            horizentalLine: false,
            xAxisLabel: false,
            yAxisLabel: false,
            labelBgColor: '#FFFFFF',
            labelBgOpacity: 0.7,
            labelFontColor: '#666666',
          },
          markLine: {
            type: 'solid',
            dashLength: 4,
            data: [],
          },
        },
      },
      chartData: {},
    }
  },

  methods: {
    handleSubmit(e) {
      this.filterParmas = e
      this.getData()
    },
    async getData() {
      if (!this.filterParmas.device_id) {
        this.$u.toast('没有关联基地')
        this.loadingType = 0
        return (this.chartData = { series: [] })
      }
      try {
        const { data } = await http.get(
          `/api/devices/${this.filterParmas.device_id}/worm-statics`,
          {
            params: this.filterParmas,
          }
        )
        const { data: resData } = data

        const xAxis = []
        const seriesData = []

        Object.keys(resData ?? {}).forEach((key) => {
          xAxis.push(key)
          seriesData.push(resData[key])
        })
        const max = Math.max(...seriesData)

        if (max > 5) {
          let maxN = Math.ceil(max / 5) * 5
          maxN = maxN === 0 ? 5 : maxN
          this.opts.yAxis.data[0].max = maxN
        } else {
          this.opts.yAxis.splitNumber = max
        }

        let res = {
          categories: xAxis,
          series: [
            {
              name: '虫情统计',
              data: seriesData,
            },
          ],
        }
        this.chartData = JSON.parse(JSON.stringify(res))
      } catch (error) {}
    },
  },
}
</script>
