<template>
  <div>
    <a-form :model="formState" layout="inline" :label-col="{ style: { width: '80px' } }"
                    :wrapper-col="{ span: 8 }" autocomplete="off" @submit.prevent="handleQuery">
      <a-form-item label="查询设备">
        <a-select v-model:value="formState.selectedDeviceId" style="width: 180px">
          <a-select-option v-for="d in deviceList" :key="d.deviceId" :value="d.deviceId">{{ d.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="分析点位">
        <a-select v-model:value="formState.selectedValueCode" style="width: 180px">
          <a-select-option v-for="item in valueCodeList" :key="item.valuecode" :value="item.valuecode">
            {{ item.valuename || item.valuecode }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="开始时间">
        <a-date-picker
          v-model:value="formState.startTime"
          style="width:180px"
          show-time
          valueFormat="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择开始时间"
          :disabled-date="disabledStartDate"
        />
      </a-form-item>
      <a-form-item label="结束时间">
        <a-date-picker
          v-model:value="formState.endTime"
          style="width:180px"
          show-time
          valueFormat="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择结束时间"
          :disabled-date="disabledEndDate"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">查询</a-button>
      </a-form-item>
    </a-form>
    
    <div style="margin-top: 16px;" class="wang">
      <BarAndLine
        :key="chartKey"
        v-if="finalDataSource.length && finalChartsColumns.length"
        :chartsColumnsType="chartsColumnsType"
        :xAxisPropType="xAxisPropType"
        :dataSource="finalDataSource"
        :height="height"
        :chartsColumns="finalChartsColumns"
        :chartsType="chartsType"
        :option="option"
        @refresh="$emit('refresh')"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch, onMounted, computed, reactive } from 'vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import BarAndLine from './BarAndLine.vue';
import { getDeviceHistoryData } from '@/views/vent/monitorManager/deviceMonitor/components/device/device.api';
import { getTableHeaderColumns } from '/@/hooks/web/useWebColumns';

export default defineComponent({
  name: 'DeviceHistoryChart',
  components: { BarAndLine },
  props: {
    chartsColumnsType: String,
    xAxisPropType: String,
    dataSource: {
      type: Array,
      default: () => [],
    },
    height: {
      type: String,
      default: '400px',
    },
    chartsColumns: {
      type: Array,
      default: () => [],
    },
    chartsType: {
      type: String,
      default: 'history',
    },
    option: {
      type: Object,
      default: () => ({
        grid: { top: '20%', left: '10px', right: '5px', bottom: '10%', containLabel: true },
        toolbox: { feature: {} },
      }),
    },
  },
  emits: ['refresh'],
  setup(props, { emit }) {
    // 查询表单相关
    const deviceList = ref([
      { deviceId: '1657545388451663016', name: '辅运平硐111' },
    ]);
    const valueCodeList = ref(props.chartsColumns);
    // 用reactive统一管理表单状态
    const formState = reactive({
      selectedDeviceId: deviceList.value[0]?.deviceId || '',
      selectedValueCode: valueCodeList.value[0]?.valuecode || '',
      startTime: dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    });
    const chartData = ref<any[]>([]);
    const chartColumns = ref<any[]>([]);
    const isQueried = ref(false);
    // 图表key，用于查询后强制刷新图表
    const chartKey = ref(0);

    function disabledStartDate(current: any) {
      if (!formState.endTime) return false;
      return current && current.valueOf() > dayjs(formState.endTime).valueOf();
    }
    function disabledEndDate(current: any) {
      if (!formState.startTime) return false;
      return current && current.valueOf() < dayjs(formState.startTime).valueOf();
    }

    watch(() => formState.selectedDeviceId, (newVal) => {
      if (!newVal) return;
      chartColumns.value = getTableHeaderColumns(formState.selectedDeviceId + '_chart');
    });

    onMounted(() => {
      chartColumns.value = getTableHeaderColumns(formState.selectedDeviceId + '_chart');
    });

    async function handleQuery() {
      if (!formState.selectedDeviceId || !formState.selectedValueCode) {
        message.warning('请选择设备和分析点位');
        return;
      }
      try {
        const res = await getDeviceHistoryData({
          deviceId: formState.selectedDeviceId,
          valueCode: formState.selectedValueCode,
          startTime: formState.startTime,
          endTime: formState.endTime,
        });
        if (res && Array.isArray(res.list)) {
          chartData.value = res.list.map(item => ({
            ...item,
            [formState.selectedValueCode]: Number(item.val),
          }));
          chartColumns.value = getTableHeaderColumns(formState.selectedDeviceId + '_chart');
          isQueried.value = true;
          // 查询成功后更新key，强制刷新图表
          chartKey.value += 1;
        } else {
          chartData.value = [];
          chartColumns.value = [];
          isQueried.value = true;
          message.info('未查询到数据');
        }
      } catch (e) {
        chartData.value = [];
        chartColumns.value = [];
        isQueried.value = true;
        message.error('查询失败');
      }
    }

    // 只要查询过就用查询数据，否则用外部props
    const finalDataSource = computed(() => {
      return isQueried.value ? chartData.value : props.dataSource;
    });
    
    const finalChartsColumns = computed(() => {
      return isQueried.value ? chartColumns.value : props.chartsColumns;
    });

    return {
      deviceList,
      valueCodeList,
      formState,
      chartData,
      chartColumns,
      handleQuery,
      finalDataSource,
      finalChartsColumns,
      chartsColumnsType: props.chartsColumnsType,
      xAxisPropType: props.xAxisPropType,
      height: props.height,
      chartsType: props.chartsType,
      option: props.option,
      disabledStartDate,
      disabledEndDate,
      chartKey,
    };
  },
});
</script>
<style lang="less" scoped>
@import '/@/design/theme.less';

.zxm-form-item {
  margin-right: 26px ;
  ::v-deep .zxm-form-item-label {
    color: #fff;
    > label {
      color: #fff;
    }
  }
}

</style>