<template>
  <div class="" v-if="loading">
    <div class="charts-container">
      <a-form
        class="form-container"
        :model="historyParams"
        layout="inline"
        :label-col="{ style: { width: '100px' } }"
        :wrapper-col="{ span: 8 }"
        autocomplete="off"
        @submit.prevent="getDataSource"
      >
        <a-form-item label="查询设备">
          <a-select v-model:value="historyParams.selectedDeviceId" style="width: 200px">
            <a-select-option v-for="d in deviceOptions" :key="d.label" :value="d.value">{{ d.label }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="间隔时间">
          <a-select v-model:value="historyParams.interval" style="width: 200px">
            <a-select-option v-for="[key, value] in Array.from(intervalMap)" :key="key" :value="key">
              {{ value }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="开始时间">
          <a-date-picker
            v-model:value="historyParams.startTime"
            style="width: 200px"
            show-time
            valueFormat="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始时间"
          />
        </a-form-item>
        <a-form-item label="结束时间">
          <a-date-picker
            v-model:value="historyParams.endTime"
            style="width: 200px"
            show-time
            valueFormat="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择结束时间"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">查询</a-button>
        </a-form-item>
      </a-form>
    </div>
    <Pagination
      v-model:current="pagination.current"
      v-model:pageSize="pagination.pageSize"
      :total="pagination.total"
      size="small"
      @change="handlePageChange"
      style="position: absolute; z-index: 99; top: 53px; right: 30px"
    />
    <div class="history-chart">
      <BarAndLine
        :charts-columns="chartsColumns"
        chartsType="history"
        :option="{
          legend: {
            top: '5',
          },
          grid: {
            top: 50,
            left: 100,
            right: 100,
            bottom: 50,
          },
        }"
        :data-source="dataSource"
        height="290px"
        :x-axis-prop-type="stationType !== 'redis' ? 'ttime' : 'time'"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
//ts语法
import { watchEffect, ref, watch, nextTick, reactive, onMounted, computed } from 'vue';
import { FormSchema } from '/@/components/Form/index';
import { defHttp } from '/@/utils/http/axios';
import { Pagination } from 'ant-design-vue';
import dayjs from 'dayjs';
import BarAndLine from '/@/components/chart/BarAndLine.vue';
import { getDictItemsByCode } from '/@/utils/dict';
import { get } from 'lodash-es';

const props = defineProps({
  columnsType: {
    type: String,
  },
  columns: {
    type: Array,
    // required: true,
    default: () => [],
  },
  deviceType: {
    type: String,
    required: true,
  },
  deviceListApi: {
    type: Function,
  },
  deviceArr: {
    type: Array,
    // required: true,
    default: () => [],
  },
  designScope: {
    type: String,
  },
  sysId: {
    type: String,
  },
  deviceId: {
    type: String,
  },
  scroll: {
    type: Object,
    default: { y: 0 },
  },
  formSchemas: {
    type: Array<FormSchema>,
    default: () => [],
  },
  /** 仅展示已绑定设备，选择是则从系统中获取sysId下已绑定设备。仅能查询到已绑定设备的历史数据 */
  onlyBounedDevices: {
    type: Boolean,
    default: false,
  },
  showHistoryCurve: {
    type: Boolean,
    default: false,
  },
});
const getDeviceListApi = (params) => defHttp.post({ url: '/monitor/device', params });
const historyTable = ref();
const loading = ref(false);
const stationType = ref('plc1');
const dataSource = ref([]);
const intervalMap = new Map([
  ['1', '1秒'],
  ['2', '5秒'],
  ['3', '10秒'],
  ['4', '30秒'],
  ['5', '1分钟'],
  ['6', '10分钟'],
  ['7', '30分钟'],
  ['8', '1小时'],
  ['9', '1天'],
]);
const historyParams = reactive({
  startTime: dayjs().startOf('date').format('YYYY-MM-DD HH:mm:ss').toString(),
  endTime: dayjs().format('YYYY-MM-DD HH:mm:ss').toString(),
  skip: '8',
  interval: '1小时',
  selectedDeviceId: '',
});
const emit = defineEmits(['change']);

const historyType = ref('');
const deviceKide = ref('');
let deviceOptions = ref([]);
const deviceTypeStr = ref('');
const deviceTypeName = ref('');
const deviceType = ref('');
const chartsColumns = ref([
  // {
  //   legend: '压差',
  //   seriesName: '(Pa)',
  //   ymax: 100,
  //   yname: 'Pa',
  //   linetype: 'bar',
  //   yaxispos: 'left',
  //   color: '#37BCF2',
  //   sort: 1,
  //   xRotate: 0,
  //   dataIndex: 'frontRearDP',
  // },
  {
    legend: '前门推力',
    seriesName: '',
    ymax: 100,
    yname: '前门推力',
    linetype: 'line',
    yaxispos: 'left',
    color: '#37BCF2',
    sort: 1,
    xRotate: 0,
    dataIndex: '1zdqfktl',
  },
  {
    legend: '后门推力',
    seriesName: '-',
    ymax: 100,
    yname: '后门推力',
    linetype: 'line',
    yaxispos: 'right',
    color: '#FC4327',
    sort: 2,
    xRotate: 0,
    dataIndex: '2zdqfktl',
  },
]);
loading.value = true;
const pagination = {
  current: 1,
  pageSize: 20,
  showQuickJumper: false,
  total: 0,
};
const selectedOption = computed<Record<string, any> | undefined>(() => {
  let idval: string | undefined = getForm()?.getFieldsValue()?.gdeviceids;
  if (VENT_PARAM.historyIsMultiple && idval) {
    const arr = idval.split(',');
    idval = arr[arr.length - 1];
  }
  return deviceOptions.value.find((e: any) => {
    return e.value === idval;
  });
});

watch(
  () => {
    return props.columnsType;
  },
  async (newVal) => {
    if (!newVal) return;
    deviceKide.value = newVal;
    if (historyTable.value) {
      getForm().resetFields();
      // getForm().updateSchema();
      // getForm();
    }
    dataSource.value = [];
    // const column = getTableHeaderColumns(newVal.includes('_history') ? newVal : newVal + '_history');
    // if (column && column.length < 1) {
    //   const arr = newVal.split('_');
    //   console.log('历史记录列表表头------------>', arr[0] + '_monitor');
    //   columns.value = getTableHeaderColumns(arr[0] + '_history');
    //   if (columns.value.length < 1) {
    //     if (historyType.value) {
    //       columns.value = getTableHeaderColumns(historyType.value + '_history');
    //     }
    //   }
    // } else {
    //   columns.value = column;
    // }
    await getDeviceList();
    nextTick(() => {
      getDataSource();
    });

    if (historyTable.value) reload();
  },
  {
    immediate: true,
  }
);

watch(historyType, (type) => {
  if (!type) return;
  // if (historyTable.value) getForm().resetFields()

  // const column = getTableHeaderColumns(type.includes('_history') ? type : type + '_history');
  // if (column && column.length < 1) {
  //   const arr = type.split('_');
  //   columns.value = getTableHeaderColumns(arr[0] + '_history');
  // } else {
  //   columns.value = column;
  // }
  // setColumns(columns.value);
});

const showCurve = ref(false);

// 是否显示历史曲线，在devices_shows_history_curve字典里可以配置哪些设备类型需要显示曲线
// 字典内的字段可以是前缀，例如fanlocal之于fanlocal_normal
// 安全监控设备需要更多的配置，除去配置safetymonitor，还需要配置哪些安全监控设备需要曲线
// 因此可以配置例如A1001的dataTypeName代码（可以查看真实数据参考）
function calcShowCurveValue() {
  const historyCurveDicts = getDictItemsByCode('devices_shows_history_curve') || [];
  const findDict = (str) => historyCurveDicts.some(({ value }) => str.startsWith(value));

  if (!props.showHistoryCurve) return false;
  const dt = props.deviceType; // 依赖项

  if (!findDict(dt)) return false;
  if (!dt.startsWith('safetymonitor')) return true;

  // 和字典的设备类型匹配后，如果是安全监控设备，需要额外的匹配安全监控类型
  const dtns = get(selectedOption.value, 'readData.dataTypeName', ''); // 依赖项
  return findDict(dtns);
}

// const tableScroll = computed(() => {
//   if (props.scroll.y && showCurve.value) return { y: props.scroll.y - 450 };
//   if (props.scroll.y) return { y: props.scroll.y - 100 };
//   return {};
// });

watch(
  () => props.deviceId,
  async () => {
    // await getForm().setFieldsValue({});
    await getDeviceList();
  }
);

/** 获取可供查询历史数据的设备列表 */
async function getDeviceList() {
  // if (props.deviceType.split('_')[1] && props.deviceType.split('_')[1] === 'history') return;
  let result;
  let response;
  if (props.onlyBounedDevices) {
    response = await getDeviceListApi({
      systemID: props.sysId,
      devicetype: 'sys',
    }).then(({ msgTxt }) => {
      return { msgTxt: msgTxt.filter((e) => e.type === props.deviceType) };
    });
  } else if (props.sysId) {
    response = await getDeviceListApi({
      sysId: props.sysId,
      devicetype: props.deviceType.startsWith('vehicle') ? 'location_normal' : props.deviceType,
      pageSize: 10000,
    });
  } else if (props.deviceListApi) {
    response = await props.deviceListApi();
  } else {
    response = await getDeviceListApi({ devicetype: props.deviceType, pageSize: 10000 });
  }

  // 处理不同格式的数据
  if (response['records'] && response['records'].length > 0) {
    result = response['records'];
  } else if (response['msgTxt'] && response['msgTxt'][0] && response['msgTxt'][0]['datalist']) {
    result = response['msgTxt'][0]['datalist'];
  }
  if (response['msgTxt'] && response['msgTxt'][0]) {
    deviceTypeName.value = response['msgTxt'][0]['typeName'];
    deviceType.value = response['msgTxt'][0]['type'];
  }

  if (result) {
    deviceOptions.value = [];
    deviceOptions.value = result.map((item, index) => {
      return {
        label: item['strinstallpos'],
        value: item['id'] || item['deviceID'],
        strtype: item['strtype'] || item['deviceType'],
        strinstallpos: item['strinstallpos'],
        devicekind: item['devicekind'],
        stationtype: item['stationtype'],
        readData: item['readData'],
      };
    });

    stationType.value = deviceOptions.value[0]['stationtype'];
    if (props.deviceType.startsWith('vehicle')) {
      historyType.value = 'vehicle';
    } else {
      historyType.value = deviceOptions.value[0]['strtype'] || deviceOptions.value[0]['devicekind'];
    }

    /** 此处使用nextTick是由于可能表单暂未更新，而下面的方法依赖表单项 */
    nextTick(() => {
      showCurve.value = calcShowCurveValue();
      // initHistoryCurveColumns();
    });
  }
  if (VENT_PARAM.historyIsMultiple) {
    // await getForm().setFieldsValue({
    //   gdeviceids: [props.deviceId ? props.deviceId : deviceOptions.value[0] ? deviceOptions.value[0]['value'] : ''],
    // });
    // await getForm().updateSchema({
    //   field: 'gdeviceids',
    //   componentProps: {
    //     mode: 'multiple',
    //     maxTagCount: 'responsive',
    //   },
    // });
  } else {
    // await getForm().setFieldsValue({
    //   gdeviceids: props.deviceId ? props.deviceId : deviceOptions.value[0] ? deviceOptions.value[0]['value'] : '',
    // });
    // await getForm().updateSchema({
    //   field: 'gdeviceids',
    // });
  }
}
function handlePageChange(page, size) {
  console.log('当前页:', page, '每页条数:', size);
  // 此处发起数据请求
  pagination.current = page;
  pagination.pageSize = size;
  getDataSource();
}
function resetFormParam() {
  const formData = {};
  formData['pageNo'] = pagination.current;
  formData['pageSize'] = pagination.pageSize;
  formData['ttime_begin'] = historyParams.startTime;
  formData['ttime_end'] = historyParams.endTime;
  formData['column'] = 'createTime';
  formData['gdeviceids'] = props.deviceId ? props.deviceId : deviceOptions.value[0] ? deviceOptions.value[0]['value'] : '';

  if (stationType.value !== 'redis' && deviceOptions.value[0]) {
    formData['strtype'] = deviceTypeStr.value
      ? deviceTypeStr.value
      : deviceOptions.value[0]['strtype']
      ? deviceOptions.value[0]['strtype']
      : props.deviceType + '*';
    if (props.sysId) {
      formData['sysId'] = props.sysId;
    }
    return formData;
  } else {
    const params = {
      pageNum: pagination['current'],
      pageSize: pagination['pageSize'],
      column: pagination['createTime'],
      startTime: formData['ttime_begin'],
      endTime: formData['ttime_end'],
      deviceId: formData['gdeviceids'],
      strtype: props.deviceType + '*',
      sysId: props.sysId,
      interval: intervalMap.get(formData['skip']) ? intervalMap.get(formData['skip']) : '1h',
      isEmployee: props.deviceType.startsWith('vehicle') ? false : true,
    };
    return params;
  }
}

async function getDataSource() {
  dataSource.value = [];
  const params = await resetFormParam();
  if (stationType.value !== 'redis') {
    const result = await defHttp.get({ url: '/safety/ventanalyMonitorData/listdays', params: params });
    pagination.total = Math.abs(result['datalist']['total']) || 0;
    if (result['datalist']['records'].length > 0) {
      dataSource.value = result['datalist']['records'].map((item: any) => {
        return Object.assign(item, item['readData']);
      });
    } else {
      dataSource.value = [];
    }
  } else {
    const result = await defHttp.post({ url: '/monitor/history/getHistoryData', params: params });
    pagination.total = Math.abs(result['total']) || 0;
    dataSource.value = result['records'] || [];
  }
}

watchEffect(() => {
  if (historyTable.value && dataSource) {
    const data = dataSource.value || [];
    emit('change', data);
  }
});

onMounted(async () => {
  await getDeviceList();
  console.log(deviceOptions.value, 'abacaca');
  if (deviceOptions.value[0]) {
    nextTick(async () => {
      await getDataSource();
    });
  }
});
</script>

<style scoped lang="less">
@import '/@/design/theme.less';

:deep(.@{ventSpace}-table-body) {
  height: auto !important;
}
:deep(.zxm-picker) {
  height: 30px !important;
}
.history-table {
  width: 100%;
  :deep(.jeecg-basic-table-form-container) {
    .@{ventSpace}-form {
      padding: 0 !important;
      border: none !important;
      margin-bottom: 0 !important;
      .@{ventSpace}-picker,
      .@{ventSpace}-select-selector {
        width: 100% !important;
        height: 100%;
        background: #00000017;
        border: 1px solid #b7b7b7;
        input,
        .@{ventSpace}-select-selection-item,
        .@{ventSpace}-picker-suffix {
          color: #fff;
        }
        .@{ventSpace}-select-selection-placeholder {
          color: #ffffffaa;
        }
      }
    }
    .@{ventSpace}-table-title {
      min-height: 0 !important;
    }
  }
  .pagination-box {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .page-num {
      border: 1px solid #0090d8;
      padding: 4px 8px;
      margin-right: 5px;
      color: #0090d8;
    }
    .btn {
      margin-right: 10px;
    }
  }
}

.history-chart {
  background-color: #0090d822;
  margin: 0 10px;
}

.charts-container {
  --image-no-camera_bg: url('/@/assets/images/vent/no-data.png');
  position: relative;
  height: 100%;
  .form-container {
    display: flex;
    // justify-content: center;
    margin-top: 10px !important;
    margin-bottom: 10px !important;
  }
  .charts-box {
    width: 100%;
    height: 100%;
    position: absolute;
    bottom: 0;
    top: 0px;
  }

  .@{ventSpace}-picker,
  .@{ventSpace}-select-selector {
    background: #00000017 !important;
    border: 1px solid @vent-form-item-border !important;
    input,
    .@{ventSpace}-select-selection-item,
    .@{ventSpace}-picker-suffix {
      color: #fff !important;
    }
    .@{ventSpace}-select-selection-placeholder {
      color: #b7b7b7 !important;
    }
  }
  .@{ventSpace}-select-arrow,
  .@{ventSpace}-picker-separator {
    color: #fff !important;
  }
}

.no-data {
  width: 100%;
  height: 475px;
  padding-top: 80px;
  background: var(--image-no-camera_bg) no-repeat;
  background-position: center;
  display: flex;
  justify-content: center;
  font-size: 50px;
  color: var(--vent-text-base);
}
:deep(.@{ventSpace}-select-dropdown) {
  color: #000 !important;
  .@{ventSpace}-select-item {
    color: #000 !important;
  }
}
.zxm-form-inline .zxm-form-item > .zxm-form-item-label > label {
  color: #fff !important;
}
.page-info {
  width: 100%;
  height: 100%;
}
</style>
