<template>
  <div class="charts-container">
    <a-select ref="select" size="small" v-model:value="chartsType" style="position: absolute; z-index: 99; top: 2px; left: 2px; width: 98px">
      <a-select-option value="listMonitor">实时监测</a-select-option>
      <a-select-option value="detail">详情监测</a-select-option>
      <a-select-option value="history">历史记录</a-select-option>
    </a-select>

    <div class="charts-box" v-if="chartsType === 'listMonitor'">
      <BarAndLine
        :chartsColumnsType="chartsColumnsType"
        :xAxisPropType="xAxisPropType"
        :dataSource="resultDataSource"
        height="100%"
        :chartsColumns="chartsColumns"
        chartsType="listMonitor"
      />
    </div>
    <div class="charts-box" v-else-if="chartsType === 'detail' && deviceListApi">
      <Select
        :options="options"
        :fieldNames="{ label: 'strname', value: 'id' }"
        v-model:value="deviceId"
        placeholder="请选择查看的设备"
        size="small"
        style="position: absolute; z-index: 99; left: 102px; width: 150px; top: 2px"
      />
      <BarAndLine
        :chartsColumnsType="chartsColumnsType"
        :xAxisPropType="resultXAxisPropType"
        :dataSource="detailDataSource"
        height="100%"
        :chartsColumns="chartsColumns"
        chartsType="detail"
      />
    </div>
    <div class="charts-box" v-else-if="chartsType === 'history'">
      <Select
        :options="options"
        :fieldNames="{ label: 'strname', value: 'id' }"
        v-model:value="deviceId"
        placeholder="请选择查看的设备"
        size="small"
        style="position: absolute; z-index: 99; left: 102px; width: 150px; top: 2px"
      />
      <a-date-picker
        v-model:value="historyParams.tData"
        size="small"
        valueFormat="YYYY-MM-DD"
        placeholder="请选择查询日期"
        style="position: absolute; z-index: 99; left: 254px; width: 150px; top: 2px"
      />
      <a-time-range-picker
        v-model:value="historyParams.ttime"
        size="small"
        valueFormat="HH:mm:ss"
        style="position: absolute; z-index: 99; left: 406px; width: 200px; top: 2px"
      />
      <a-select
        ref="select"
        size="small"
        v-model:value="historyParams.skip"
        placeholder="请选择间隔时间"
        style="position: absolute; z-index: 99; top: 2px; left: 608px; width: 100px"
      >
        <a-select-option value="1">5秒</a-select-option>
        <a-select-option value="2">10秒</a-select-option>
        <a-select-option value="3">1分钟</a-select-option>
        <a-select-option value="4">5分钟</a-select-option>
        <a-select-option value="5">10分钟</a-select-option>
      </a-select>
      <Pagination
        size="small"
        v-model:current="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :show-total="(total) => `共 ${total} 条`"
        style="position: absolute; z-index: 99; top: 2px; right: 30px"
      />
      <BarAndLine
        :chartsColumnsType="chartsColumnsType"
        :xAxisPropType="resultXAxisPropType"
        :dataSource="resultDataSource"
        height="100%"
        :chartsColumns="chartsColumns"
        chartsType="history"
      />
    </div>
  </div>
</template>
<script lang="ts">
  import { ref, defineComponent, watch, reactive, onMounted, watchEffect } from 'vue';
  import BarAndLine from '/@/components/chart/BarAndLine.vue';
  import dayjs from 'dayjs';
  import { defHttp } from '/@/utils/http/axios';
  import { Select, Pagination } from 'ant-design-vue';
  export default defineComponent({
    name: 'DeviceEcharts',
    components: { BarAndLine, Select, Pagination },
    props: {
      chartsColumns: {
        type: Array,
        default: () => [],
      },
      chartsColumnsType: {
        type: String,
        required: true,
      },
      dataSource: {
        type: Array,
        default: () => [],
      },
      deviceListApi: {
        type: Function,
        required: true,
      },
      deviceType: {
        type: String,
        required: true,
      },
      option: {
        type: Object,
        default: () => ({}),
      },
      xAxisPropType: {
        type: String,
        required: true,
      },
    },
    setup(props) {
      const historyList = (params) => defHttp.get({ url: '/ventanaly-device/safety/ventanalyMonitorData/list', params });
      const chartsType = ref('listMonitor');
      const deviceId = ref('');
      const options = ref([]);
      const historyParams = reactive({
        tData: dayjs(),
        ttime: ['', ''],
        ttime_begin: null,
        ttime_end: null,
        skip: null,
      });
      const resultXAxisPropType = ref('');
      const resultDataSource = ref<any[]>([]);
      const detailDataSource = ref<any[]>([]);
      const currentPage = ref<number>(1);
      const pageSize = ref<number>(20);
      const total = ref(0);
      const onChange = (pageNumber: number) => {
        console.log('Page: ', pageNumber);
      };
      watch(
        [chartsType, deviceId, historyParams, pageSize, currentPage],
        async (
          [newChartsType, newDeviceId, newHistoryParams, newPageSize, newCurrentPage],
          [oldChartsType, oldDeviceId, oldHistoryParams, oldPageSize, oldCurrentPage]
        ) => {
          console.log('[ historyParams ] >', historyParams.ttime, dayjs(historyParams.ttime).format('HH:mm:ss'));

          if (newChartsType === 'listMonitor') {
            // 实时监测所有
            resultDataSource.value = props.dataSource;
          } else if (newChartsType === 'history') {
            // 历史
            resultXAxisPropType.value = 'gcreatetime';
            if (newChartsType !== oldChartsType || newDeviceId !== oldDeviceId) {
              currentPage.value = 1;
            }
            const res = await historyList({
              ttime_begin: historyParams.ttime[0] ? historyParams.ttime[0] : null,
              ttime_end: historyParams.ttime[1] ? historyParams.ttime[1] : null,
              tData: dayjs(historyParams.tData).format('YYYY-MM-DD'),
              gdevicetype: props.deviceType + '*',
              gdeviceid: newDeviceId,
              skip: historyParams.skip,
              pageSize: pageSize.value,
              pageNo: currentPage.value,
            });
            resultDataSource.value = res.datalist.records.map((item) => Object.assign(item, item.readData));
            total.value = res.datalist.total;
          } else if (newChartsType === 'detail') {
            // 设备详情
            resultXAxisPropType.value = 'readTime';
            if (newDeviceId !== oldDeviceId) {
              detailDataSource.value = [];
            }
          }
        }
      );
      watchEffect(() => {
        if (chartsType.value === 'detail') {
          const currentData = props.dataSource.find((item: any) => item.deviceID === deviceId.value);
          if (currentData) {
            const isHas = detailDataSource.value.find((item) => item[resultXAxisPropType.value] === currentData[resultXAxisPropType.value]);
            if (!isHas) {
              if (detailDataSource.value.length < 15) {
                detailDataSource.value.push(currentData);
              } else {
                detailDataSource.value.shift();
                detailDataSource.value.push(currentData);
              }
            }
          }
        }
      });

      onMounted(async () => {
        const res = await props.deviceListApi();
        options.value = res.records;
        deviceId.value = options.value[0]['id'];
      });

      return {
        chartsType,
        deviceId,
        resultDataSource,
        historyParams,
        options,
        resultXAxisPropType,
        detailDataSource,
        currentPage,
        pageSize,
        total,
        onChange,
      };
    },
  });
</script>
<style lang="less" scoped>
  @import '/@/design/vent/color.less';
  .charts-container {
    position: relative;
    height: 100%;
    .charts-box {
      height: 100%;
    }
    .ant-picker,
    .ant-select-selector {
      background: #00000017 !important;
      border: 1px solid @vent-form-item-boder !important;
      input,
      .ant-select-selection-item,
      .ant-picker-suffix {
        color: #fff !important;
      }
      .ant-select-selection-placeholder {
        color: #b7b7b7 !important;
      }
    }
    .ant-select-arrow,
    .ant-picker-separator {
      color: #fff !important;
    }
  }
</style>
