<template>
  <PageWrapper>
    <Card>
      <Form ref="formRef" :model="formState">
        <Row :gutter="[16, 16]">
          <Col
            :xs="{ span: 24 }"
            :sm="{ span: 12 }"
            :md="{ span: 8 }"
            :lg="{ span: 6 }"
            :xl="{ span: 6 }"
            :xxl="{ span: 4 }"
          >
            <FormItem label="基地">
              <Select
                @select="onChange('base_id')"
                :fieldNames="{ label: 'name', value: 'id' }"
                :options="baseDate"
                v-model:value="formState.base_id"
                placeholder="请选择基地"
              ></Select>
            </FormItem>
          </Col>
          <Col
            :xs="{ span: 24 }"
            :sm="{ span: 12 }"
            :md="{ span: 8 }"
            :lg="{ span: 6 }"
            :xl="{ span: 6 }"
            :xxl="{ span: 4 }"
          >
            <FormItem label="检测点">
              <Select
                @select="onChange('')"
                placeholder="请选择检测点"
                :options="pointDate"
                v-model:value="formState.device_id"
              ></Select>
            </FormItem>
          </Col>
          <Col
            :xs="{ span: 24 }"
            :sm="{ span: 12 }"
            :md="{ span: 8 }"
            :lg="{ span: 6 }"
            :xl="{ span: 6 }"
            :xxl="{ span: 4 }"
          >
            <FormItem label="日期">
              <RangePicker
                :disabledDate="disabledDate"
                @change="onChangTime"
                v-model:value="formState.time"
              ></RangePicker>
            </FormItem>
          </Col>
          <Col
            :xs="{ span: 24 }"
            :sm="{ span: 12 }"
            :md="{ span: 8 }"
            :lg="{ span: 6 }"
            :xl="{ span: 6 }"
            :xxl="{ span: 4 }"
          >
            <FormItem>
              <RadioGroup
                @change="onChange('time_interval')"
                button-style="solid"
                v-model:value="formState.time_interval"
              >
                <RadioButton value="day">今天</RadioButton>
                <RadioButton value="week">近一周</RadioButton>
                <RadioButton value="month">近一个月</RadioButton>
              </RadioGroup>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <!--  -->
      <div class="flex justify-between">
        <span class="text-xl">预警数据统计</span>
        <Button @click="handleSetting">设置</Button>
      </div>
      <div class="mt-20px flex">
        <EarlyWarningItem
          class="mr-16px last:mr-0"
          v-for="(item, index) in earlyWarningList"
          :key="index"
          :data="item"
        />
      </div>
      <div class="flex items-center">
        <div
          v-for="item in tagMenus"
          :key="item.value"
          class="flex items-center mr-28px font-medium text-[#828fa2] mt-24px cursor-pointer"
          :class="{ active: item.value == activeKey }"
          @click="onChangeTag(item.value)"
        >
          <img
            class="w-16px h-16px"
            :src="item.value == activeKey ? item.icon : item.icon1"
            alt=""
          />
          <div class="ml-3px">{{ item.lable }}</div>
        </div>
      </div>
      <div class="mt-20px">
        <LineCharts
          :company="formState.time_interval"
          :extra="extra"
          :loading="false"
          :title="currentActiveLable"
          :data="chartData"
          :time="formState.time"
        />
      </div>
    </Card>
    <FormDrawer @register="registerDrawer" @success="handleSuccess" />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import dayjs from 'dayjs'
  import { formatDataByObject, getWeek, getMonth } from '/@/utils/index'
  import { PageWrapper } from '/@/components/Page'
  import { ref, reactive, onMounted, computed } from 'vue'
  import EarlyWarningItem from './components/EarlyWarningItem.vue'
  import icon1 from '/@/assets/images/icon_1.png'
  import uicon1 from '/@/assets/images/uicon_1.png'
  import LineCharts from './components/LineCharts.vue'
  import FormDrawer from './components/FormDrawer.vue'
  import { useDrawer } from '/@/components/Drawer'

  import {
    getGriculturalDeviceBasic,
    getaGriculturalDevicePoint,
    getAmonitoringData,
    getDeviceWarningNums,
  } from '/@/api/sys/user'
  import {
    Card,
    Form,
    FormItem,
    Select,
    Row,
    Col,
    RadioGroup,
    Radio,
    RangePicker,
    Button,
    message,
  } from 'ant-design-vue'
  import type { FormInstance } from 'ant-design-vue'
  const RadioButton = Radio.Button
  const [registerDrawer, { openDrawer }] = useDrawer()
  const formRef = ref<FormInstance>()
  const formState = reactive({
    base_id: undefined, //基地
    device_id: undefined, //监控点
    time: undefined, //时间
    time_interval: 'day',
  })
  const baseDate = ref([])
  const pointDate = ref<any>([])
  const statisData = ref<any>({})
  // 预警数量
  const earlyNums = ref<any>({})
  // 选中
  const activeKey = ref('conductivity')
  interface EarlyWarningItem {
    icon: String
    title: String
    value: String | Number
  }
  const earlyWarningList = computed(() => {
    const arr: EarlyWarningItem[] = [
      {
        icon: 'yujing1',
        title: 'Ⅰ级预警',
        value: '',
      },
      {
        icon: 'yujing2',
        title: 'Ⅱ级预警',
        value: '',
      },
      {
        icon: 'yujing3',
        title: 'Ⅲ级预警',
        value: '',
      },
      {
        icon: 'yujing4',
        title: 'Ⅳ级预警',
        value: '',
      },
    ]
    Object.values(earlyNums.value).forEach((v: number | string, index: number) => {
      arr[index].value = v
    })
    return arr
  })
  const currentActiveLable = computed(
    () => tagMenus.find((e) => e.value === activeKey.value)?.lable ?? '',
  )
  const chartData = computed(() => statisData.value[activeKey.value])
  const extra = computed(() => {
    const name1 = baseDate.value?.find((e: any) => e.id === formState.base_id)?.name
    const name2 = pointDate.value?.find((e: any) => e.value === formState.device_id)?.label ?? ''
    return name1 + '-' + name2
  })
  const tagMenus = [
    {
      lable: '电导率',
      value: 'conductivity',
      icon: icon1,
      icon1: uicon1,
    },
    {
      lable: '湿度',
      value: 'humidity',
      icon: icon1,
      icon1: uicon1,
    },
    {
      lable: '温度',
      value: 'temperature',
      icon: icon1,
      icon1: uicon1,
    },
    {
      lable: '氮',
      value: 'k',
      icon: icon1,
      icon1: uicon1,
    },
    {
      lable: '磷',
      value: 'n',
      icon: icon1,
      icon1: uicon1,
    },
    {
      lable: '钾',
      value: 'p',
      icon: icon1,
      icon1: uicon1,
    },
  ]

  const disabledDate = (current) => {
    return current && current > dayjs().endOf('day')
  }
  // 获取基地数据
  const getBase = async () => {
    const res = await getGriculturalDeviceBasic({ device_type: 2 })
    baseDate.value = res
    if (!formState.base_id) formState.base_id = res?.[0]?.id ?? undefined
    getPoint()
  }
  // 获取监控点数据
  const getPoint = async () => {
    const res = await getaGriculturalDevicePoint({
      device_type: 2,
      agricultural_basic: formState.base_id,
    })
    pointDate.value = formatDataByObject(res)
    if (!formState.device_id) formState.device_id = pointDate.value?.[0]?.value ?? undefined
    getDate()
    getNums()
  }
  // 获取数据
  const getDate = async () => {
    const params = {
      device_id: formState.device_id,
      start_time: '',
      end_time: '',
    }
    if (formState.time) {
      params.start_time = dayjs(formState.time?.[0]).format('YYYY-MM-DD')
      params.end_time = dayjs(formState.time?.[1]).format('YYYY-MM-DD')
    }
    if (formState.time_interval === 'week') {
      const { WeekStartDate, WeekEndDate } = getWeek()
      params.start_time = WeekStartDate
      params.end_time = WeekEndDate
    } else if (formState.time_interval === 'month') {
      const { MonthStartDate, MonthEndDate } = getMonth()
      params.start_time = MonthStartDate
      params.end_time = MonthEndDate
    } else if (formState.time_interval === 'day') {
      params.start_time = ''
      params.end_time = ''
    }
    const res = await getAmonitoringData(params)
    statisData.value = res
  }
  // 获取预警数量
  const getNums = async () => {
    let res = await getDeviceWarningNums({
      base: formState.base_id,
      device: formState.device_id,
      status: 0,
    })
    earlyNums.value = res
  }
  const onChange = (e: string | undefined) => {
    if (e === 'base_id') formState.device_id = undefined
    if (e === 'time') formState.time_interval = ''
    if (e === 'time_interval') formState.time = undefined
    getPoint()
  }

  const onChangTime = (e) => {
    if (e === null) formState.time_interval = 'day'
    else formState.time_interval = ''
    getPoint()
  }

  const handleSetting = () => {
    openDrawer(true, {
      isUpdate: false,
    })
  }
  const handleSuccess = () => {
    message.success('操作成功')
  }
  //
  const onChangeTag = (e: string) => {
    activeKey.value = e
  }
  onMounted(() => {
    getBase()
  })
</script>

<style scoped lang="less">
  .active {
    @apply text-primary;
  }
</style>
