<template>
  <div class="vent-table">
    <a-radio-group v-model:value="selectRowIndex" @change="setSelectedRowKeys" style="width: 100%">
      <a-table
        :columns="columns"
        :pagination="false"
        :data-source="dataTableSource"
        ref="tableRef"
        bordered
        style="margin-top: 5px"
        :scroll="tableScroll"
        :selectType="'radio'"
        :customRow="rowClick"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'isCheck'">
            <a-radio :value="record.deviceID" />
          </template>
          <a-tag v-if="column.dataIndex === 'warnFlag'" :color="record.warnFlag == '0' ? 'green' : 'red'">{{
            record.warnFlag == '0' ? '正常' : '报警'
          }}</a-tag>
          <a-tag v-if="column.dataIndex === 'netStatus'" :color="record.netStatus == '0' ? '#f00' : 'green'">{{
            record.netStatus == '0' ? '断开' : '连接'
          }}</a-tag>
          <slot name="bodyCell" v-bind="{ column, record }"></slot>
        </template>
        <template #operation="{ column, record }">
          <slot name="action" v-bind="{ column, record }"></slot>
        </template>
      </a-table>
    </a-radio-group>
  </div>
</template>

<script lang="ts" setup>
  //ts语法
  import { toRaw, watch, ref, onMounted, onUnmounted, nextTick, inject } from 'vue';
  import { getTableHeaderColumns } from '/@/hooks/web/useWebColumns';
  import { useGlobSetting } from '/@/hooks/setting';

  const { sysOrgCode } = useGlobSetting();
  const globalConfig = inject('globalConfig');
  const props = defineProps({
    columnsType: {
      type: String,
      required: true,
    },
    dataSource: {
      type: Array,
      required: true,
    },
    deviceType: {
      type: String,
    },
    designScope: {
      type: String,
    },
    title: {
      type: String,
    },
    scroll: {
      type: Object,
      default: () => null,
    },
    isAction: {
      type: Boolean,
      default: false,
    },
    isShowSelect: {
      type: Boolean,
      default: true,
    },
  });
  const tableRef = ref();
  const emits = defineEmits(['selectRow']);
  const dataTableSource = ref<any[]>([]);
  const loading = ref(true);
  const tableScroll = props.scroll.y ? ref({ y: props.scroll.y, x: 'max-content' }) : ref({});
  let scrollY = 0;
  const columns = ref<any[]>([]);
  // 默认初始是第一行
  const selectRowIndex = ref(-1);
  const headElHeight = ref(0);

  const rowClick = (record) => {
    return {
      onClick: () => {
        setSelectedRowKeys(record['deviceID']);
      },
    };
  };

  const setSelectedRowKeys = (target) => {
    if (Object.prototype.toString.call(target) === '[object String]') {
      selectRowIndex.value = target;
      emits('selectRow', target);
    } else if (Object.prototype.toString.call(target) === '[object Object]') {
      const data = target.target.value;
      selectRowIndex.value = data;
      emits('selectRow', data);
    }
  };

  function setColumns(columnsType) {
    const isCheckColumn = {
      title: '',
      dataIndex: 'isCheck',
      width: 40,
      align: 'center',
      customCell: (_, index) => {
        const columnNum = _.modalTyoe ? (_.modalTyoe.endsWith('_3') ? 3 : _.modalTyoe.endsWith('_1') ? 1 : 2) : 2;
        if (_.rowIndex % columnNum == 0) {
          return { rowSpan: columnNum };
        } else {
          return { rowSpan: 0 };
        }
      },
    };
    const indexColumn = {
      title: '序号',
      dataIndex: 'key',
      width: 80,
      align: 'center',
      customCell: (_, index) => {
        const columnNum = _.modalTyoe ? (_.modalTyoe.endsWith('_3') ? 3 : _.modalTyoe.endsWith('_1') ? 1 : 2) : 2;
        if (_.rowIndex % columnNum == 0) {
          return { rowSpan: columnNum };
        } else {
          return { rowSpan: 0 };
        }
      },
      customRender: ({ text, record, index }) => {
        return record.index + 1;
      },
    };
    const runDevice = {
      title: '风机',
      dataIndex: 'runDevice',
      width: 80,
      align: 'center',
    };

    columns.value = getTableHeaderColumns(columnsType);
    console.log('风机columns------------------>', columnsType);
    if (columns.value && columns.value.length < 1) {
      columns.value = getTableHeaderColumns(columnsType.split('_')[0] + '_monitor');
    }

    const strinstallpos = columns.value.find((item) => {
      return item.dataIndex === 'strinstallpos' || item.dataIndex === 'strname';
    });
    if (strinstallpos) {
      strinstallpos.customCell = (_, index) => {
        const columnNum = _.modalTyoe ? (_.modalTyoe.endsWith('_3') ? 3 : _.modalTyoe.endsWith('_1') ? 1 : 2) : 2;
        if (_.rowIndex % columnNum == 0) {
          return { rowSpan: columnNum };
        } else {
          return { rowSpan: 0 };
        }
      };
    }
    columns.value.forEach((item) => {
      if (item.dataIndex === 'strinstallpos' || item.dataIndex === 'strname' || item.dataIndex.endsWith('_merge')) {
        item.customCell = (_, index) => {
          const columnNum = _.modalTyoe ? (_.modalTyoe.endsWith('_3') ? 3 : _.modalTyoe.endsWith('_1') ? 1 : 2) : 2;
          if (_.rowIndex % columnNum == 0) {
            return { rowSpan: columnNum };
          } else {
            return { rowSpan: 0 };
          }
        };
      }
    });

    columns.value.splice(1, 0, runDevice);
    if (props.isShowSelect) {
      columns.value = [isCheckColumn, indexColumn, ...columns.value];
    } else {
      columns.value = [indexColumn, ...columns.value];
    }

    if (props.isAction) {
      columns.value = [
        ...columns.value,
        {
          title: '操作',
          dataIndex: 'operation',
          width: 120,
          align: 'center',
          slots: { customRender: 'operation' },
          customCell: (_, index) => {
            const columnNum = _.modalTyoe ? (_.modalTyoe.endsWith('_3') ? 3 : _.modalTyoe.endsWith('_1') ? 1 : 2) : 2;
            if (_.rowIndex % columnNum == 0) {
              return { rowSpan: columnNum };
            } else {
              return { rowSpan: 0 };
            }
          },
        },
      ];
    }
    // columns.value = [...columns.value, ...columns.value]
    return columns;
  }

  watch(
    () => {
      return props.columnsType;
    },
    (newVal, oldVal) => {
      if (!newVal) return;
      setColumns(newVal);
      nextTick(() => {
        const headEl = document.querySelector(`.zxm-table-thead`);
        if (headEl) {
          headElHeight.value = headEl.clientHeight;
          tableScroll.value = { y: (scrollY || props.scroll.y) - (headElHeight.value - 56), x: 'max-content' };
        }
      });
    },
    {
      immediate: true,
    }
  );
  watch(
    () => {
      return props.dataSource;
    },
    (newVal, oldVal) => {
      const list: unknown[] = [];
      newVal.forEach((item, index) => {
        const data: any = toRaw(item);
        if (data.deviceType.startsWith('fanlocal') && data.install_kind) {
          data['modalTyoe'] = data.install_kind;
        }
        const modalTyoe = data.modalTyoe;
        const resultData1 = {};
        const resultData2 = {};
        const resultData3 = {};
        // 将主风机、备风机的数据进行拆分
        columns.value.forEach((column) => {
          const columnKey = column.dataIndex;
          if (columnKey) {
            if (columnKey.startsWith('Fan')) {
              const key1 = columnKey.replace('Fan', 'Fan1');
              const key2 = columnKey.replace('Fan', 'Fan2');
              const key3 = columnKey.replace('Fan', 'Fan3');
              if (columnKey.endsWith('_merge')) {
                resultData1[columnKey] = data[key1] == 0 || data[key1] == null || data[key1] == undefined ? data[key2] : data[key1] || data[key3];
              } else {
                if (columnKey.startsWith('FanStartStatus')) {
                  resultData1[columnKey] = data[key1];
                  resultData2[columnKey] = data[key2];
                  resultData3[columnKey] = data[key3];
                } else {
                  resultData1[columnKey] = data['Fan1StartStatus'] == '0' && globalConfig?.simulatedPassword ? '-' : data[key1];
                  resultData2[columnKey] = data['Fan2StartStatus'] == '0' && globalConfig?.simulatedPassword ? '-' : data[key2];
                  resultData3[columnKey] = data['Fan3StartStatus'] == '0' && globalConfig?.simulatedPassword ? '-' : data[key3];
                }
                if (resultData1[columnKey] == undefined && resultData2[columnKey] == undefined) {
                  resultData1[columnKey] = data[columnKey];
                  resultData2[columnKey] = data[columnKey];
                  resultData3[columnKey] = data[columnKey];
                }
              }
            } else if (columnKey.startsWith('fan')) {
              const key1 = columnKey.replace('fan', 'fan1');
              const key2 = columnKey.replace('fan', 'fan2');
              const key3 = columnKey.replace('fan', 'fan3');
              if (columnKey.endsWith('_merge')) {
                resultData1[columnKey] =
                  !data[key1] || data[key1] == 0 || data[key1] == null || data[key1] == undefined ? data[key2] : data[key1] || data[key3];
              } else {
                if (columnKey.startsWith('fanStartStatus')) {
                  resultData1[columnKey] = data[key1];
                  resultData2[columnKey] = data[key2];
                  resultData3[columnKey] = data[key3];
                } else {
                  resultData1[columnKey] = data['fan1StartStatus'] == '0' && globalConfig?.simulatedPassword ? '-' : data[key1];
                  resultData2[columnKey] = data['fan2StartStatus'] == '0' && globalConfig?.simulatedPassword ? '-' : data[key2];
                  resultData3[columnKey] = data['fan3StartStatus'] == '0' && globalConfig?.simulatedPassword ? '-' : data[key3];
                }
                if (resultData1[columnKey] == undefined && resultData2[columnKey] == undefined) {
                  resultData1[columnKey] = data[columnKey];
                  resultData2[columnKey] = data[columnKey];
                  resultData3[columnKey] = data[columnKey];
                }
              }
            } else if (columnKey.endsWith('_merge')) {
              resultData1[columnKey] = data[columnKey];
            } else {
              resultData1[columnKey] = resultData2[columnKey] = resultData3[columnKey] = data[columnKey];
            }
          }
        });
        resultData1['deviceID'] = resultData2['deviceID'] = data['deviceID'];
        if (props.columnsType.startsWith('fanlocal') && sysOrgCode !== 'zmhjhzmy') {
          resultData1['runDevice'] = '主机';
          resultData2['runDevice'] = '备机';
        } else {
          resultData1['runDevice'] = '1#风机';
          resultData2['runDevice'] = '2#风机';
          resultData3['runDevice'] = '3#风机';
        }
        resultData1['modalTyoe'] = modalTyoe;
        resultData2['modalTyoe'] = modalTyoe;
        resultData3['modalTyoe'] = modalTyoe;

        resultData1['rowIndex'] = 0;
        resultData2['rowIndex'] = 1;
        resultData3['rowIndex'] = 2;

        resultData1['index'] = index;
        resultData2['index'] = index;
        resultData3['index'] = index;
        if (modalTyoe && modalTyoe.endsWith('_3')) {
          list.push(resultData1, resultData2, resultData3);
        } else if (modalTyoe && modalTyoe.endsWith('_1')) {
          list.push(resultData1);
          // list.push(resultData1, resultData2);
        } else {
          list.push(resultData1, resultData2);
        }
      });

      dataTableSource.value = list;
      loading.value = false;
    }
  );

  watch(
    () => props.scroll.y,
    (newVal) => {
      if (newVal) {
        scrollY = newVal;
        tableScroll.value = { y: newVal - (headElHeight.value - 56), x: 'max-content' };
      } else {
        tableScroll.value = {};
      }
    }
  );

  onMounted(() => {
    // 如果是https
    // 反之是websocket
  });

  onUnmounted(() => {});

  defineExpose({
    setSelectedRowKeys,
  });
</script>

<style scoped lang="less">
  @ventSpace: zxm;

  :deep(.@{ventSpace}-table-body) {
    height: auto !important;
    &::-webkit-scrollbar {
      height: 10px !important;
    }
  }
  :deep(.jeecg-basic-table .@{ventSpace}-table-wrapper .@{ventSpace}-table-title) {
    min-height: 0;
  }
</style>
