<template>
  <div class="search-table">
    <div class="search-area" v-if="config.type === 'C'">
      <div class="list-title">
        <span>联动规则列表</span>
      </div>
      <div class="search-btn" @click="handleAdd">
        <div class="btn-item">配置</div>
      </div>
    </div>
    <div v-if="config.type === 'D'" class="search-new">
      <div class="list-title">
        <span>联动日志</span>
      </div>
      <div class="time-picker-wrap">
        <div class="form-row">
          <label class="form-label">开始时间:</label>
          <a-date-picker
            v-model:value="filterForm.startDate"
            placeholder="请选择开始时间"
            class="date-picker"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            style="width: 300px !important"
          />
        </div>
      </div>
      <div class="time-select">
        <span class="span">快捷时间:</span>
        <div class="btn" :class="{ active: timeType === 1 }" @click="setTimeRange(1)">今日</div>
        <div class="btn" :class="{ active: timeType === 2 }" @click="setTimeRange(2)">近三天</div>
        <div class="btn" :class="{ active: timeType === 3 }" @click="setTimeRange(3)">近一月</div>
        <div class="search-btn" @click="confirmDetail">
          <div class="btn-item">详情</div>
        </div>
      </div>
    </div>
    <div class="content-area">
      <div class="table-container">
        <table class="warning-table">
          <colgroup>
            <col
              v-for="col in config.type === 'C' ? config.columns : filterDeviceColumns"
              :key="col.dataIndex || col.prop"
              :style="{ width: col.width }"
            />
          </colgroup>
          <thead class="table-header">
            <tr>
              <th v-for="col in config.type === 'C' ? config.columns : filterDeviceColumns" :key="col.dataIndex || col.prop">
                {{ col.title || col.name }}
              </th>
            </tr>
          </thead>
          <tbody class="table-body">
            <tr
              v-for="(row, index) in realTableData"
              :key="index"
              class="table-row"
              :class="config.type === 'C' ? { box_active: isCurrentSelectRow(row) } : ''"
              @click="config.type === 'C' ? handleRowClick(row) : ''"
            >
              <td v-for="col in config.type === 'C' ? config.columns : filterDeviceColumns" :key="col.dataIndex || col.prop" class="table-cell">
                <template v-if="config.type === 'C' && col.prop === 'operation'">
                  <span class="text-look" @click="handleEditClick(row)">编辑</span>
                </template>
                <template v-else>
                  <span class="text-ellipsis" :title="getCellText(row, col)">
                    {{ getCellText(row, col) }}
                  </span>
                </template>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <DeviceModal
      @register="registerModal"
      :show-tab="true"
      @saveOrUpdate="saveOrUpdateHandler"
      :device-type="deviceType"
      :select-sys-alarm-id="currentSelectInfo.alarmId"
      :select-sys-id="currentSelectInfo.sysId"
    />
    <RuleTableModal
      @register="register"
      @update="onSubmit"
      :destroy-on-close="true"
      @success="handleModalSuccess"
      :form-schemas="workFaceWarningSchemas"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, nextTick, computed } from 'vue';
import dayjs, { Dayjs } from 'dayjs';
import { message } from 'ant-design-vue';
import DeviceModal from './deviceModal.vue';
import { useModal } from '/@/components/Modal';
import { getAlarmLogList } from '../hsqHome.api.js';
import { getTableHeaderColumns } from '/@/hooks/web/useWebColumns';
import { func } from 'vue-types';
import { useLinkRuleStore } from '/@/store/modules/linkRule';
import RuleTableModal from '../../../deviceManager/comment/warningTabel/RuleTableModal.vue';
import { FormSchema } from '/@/components/Table';
import { warningLogEdit, warningLogList } from '../../../deviceManager/comment/warningTabel/warning.api';
import { workFaceWarningFormSchemas } from '../../../deviceManager/comment/warningTabel/warning.data';
const FIXED_STRTYPE = 'sys_openair_fire';
const deviceType = ref('managesys');
const isUpdate = ref(false);
const instanceId = ref(`${Date.now()}_${Math.floor(Math.random() * 10000)}`);
const [registerModal, { openModal, closeModal }] = useModal(instanceId.value);
const linkRuleStore = useLinkRuleStore();
const emit = defineEmits(['row-change', 'table-refresh']);
const currentSelectInfo = ref({
  sysId: '',
  alarmId: '',
});
const alarmMap: Record<string, string> = {
  '102': '黄色预警',
  '103': '橙色预警',
  '104': '红色预警',
};
// 获取单元格文本内容
const getCellText = (row: any, col: any) => {
  const field = col.dataIndex ?? col.prop;
  const val = row[field];
  if (field === 'alarmLevel' && alarmMap[val]) {
    return alarmMap[val];
  }
  return val ?? '-';
};
const deviceColumns = getTableHeaderColumns('alarm_history') as [];

// 过滤日志只展示指定4列
const filterDeviceColumns = computed(() => {
  const showKeys = ['devicename', 'wardescrip', 'starttime', 'warntime'];
  return deviceColumns.filter((item) => showKeys.includes(item.dataIndex));
});

const realTableData = computed(() => {
  return props.config.type === 'D' ? alarmList.value : tableList.value;
});
const props = defineProps<{
  config: {
    type: string;
    tableReadFrom: string;
    columns: {
      name: string;
      prop: string;
      width?: string;
    }[];
  };
  data: Record<string, any>;
  selectedRow?: any | null;
}>();

const handleEditClick = (row: any) => {
  openModalRule(true, {
    isUpdate: true,
    record: row,
  });
};
// 弹窗保存成功触发
const handleModalSuccess = () => {
  emit('table-refresh');
};
const workFaceWarningSchemas: FormSchema[] = [
  ...workFaceWarningFormSchemas,
  {
    label: '关联条目',
    field: 'relatedEntries',
    component: 'ApiSelect',
    componentProps: {
      labelField: 'alarmName',
      valueField: 'id',
      resultField: 'records',
      api: warningLogList.bind(null, { sysId: currentSelectInfo.value.sysId }),
    },
  },
  {
    label: '预警后自动控制',
    field: 'isAutoControl',
    component: 'RadioGroup',
    componentProps: {
      //options里面由一个一个的radio组成,支持disabled
      options: [
        { label: '是', value: true },
        { label: '否', value: false },
      ],
    },
  },
  {
    label: '解除后自动复位',
    field: 'isAutoReset',
    component: 'RadioGroup',
    componentProps: {
      //options里面由一个一个的radio组成,支持disabled
      options: [
        { label: '是', value: true },
        { label: '否', value: false },
      ],
    },
  },
];
const [register, { openModal: openModalRule, closeModal: closeModalRule }] = useModal();
async function onSubmit(flag, values) {
  await warningLogEdit(values);
  closeModalRule();
  // 通知外层刷新表格
  handleModalSuccess();
}
// C类型数据源
const tableList = ref<any[]>([]);
// D类型数据源
const alarmList = ref<any[]>([]);

const timeType = ref(3);
const filterForm = reactive<{ startDate: Dayjs | null }>({
  startDate: null,
});
// 默认选中第一条（仅Type='C'时执行）
const autoSelectFirstRow = async () => {
  await nextTick();
  if (props.config.type !== 'C') return;

  const list = realTableData.value;
  if (list.length > 0) {
    const firstRow = list[0];
    emit('row-change', firstRow);
    linkRuleStore.setSelectedRow(firstRow);
    currentSelectInfo.value.sysId = firstRow.sysId ?? '';
    currentSelectInfo.value.alarmId = firstRow.alarmId ?? '';
  } else {
    emit('row-change', null);
    linkRuleStore.clearSelectedRow();
    currentSelectInfo.value = { sysId: '', alarmId: '' };
  }
};
const isCurrentSelectRow = (row: any) => {
  if (!props.selectedRow) return false;
  return props.selectedRow === row;
};

const handleRowClick = (row: any) => {
  emit('row-change', row);
  linkRuleStore.setSelectedRow(row);
  currentSelectInfo.value.sysId = row.sysId ?? '';
  currentSelectInfo.value.alarmId = row.alarmId ?? '';
};

async function getAlarmHistory() {
  const res = await getAlarmLogList({
    column: 'createTime',
    deviceKind: null,
    isOk: false,
    pageNo: 1,
    pageSize: 100,
    startTime: filterForm.startDate?.format('YYYY-MM-DD HH:mm:ss'),
    systemType: 'ventS',
  });
  alarmList.value = res.records || [];
}

onMounted(() => {
  getAlarmHistory();
  autoSelectFirstRow();
  setTimeRange(3);
});

// 监听父组件传入数据，赋值给tableList（Type为C时生效）
watch(
  () => props.data,
  (newData) => {
    const list = newData?.[props.config.tableReadFrom];
    tableList.value = list || [];
    autoSelectFirstRow();
  },
  { deep: true, immediate: true }
);

async function handleAdd() {
  isUpdate.value = false;
  openModal(true, {});
}

const saveOrUpdateHandler = async () => {
  try {
    message.success(isUpdate.value ? '编辑成功' : '新增成功');
    closeModal();
  } catch (error) {
    message.error('保存失败，请联系管理员');
  }
};

const setTimeRange = (type: number) => {
  timeType.value = type;
  let start: Dayjs;
  switch (type) {
    case 1:
      start = dayjs().startOf('day');
      break;
    case 2:
      start = dayjs().subtract(3, 'day').startOf('day');
      break;
    case 3:
      start = dayjs().subtract(30, 'day').startOf('day');
      break;
    default:
      start = dayjs().startOf('day');
  }
  filterForm.startDate = start;
  getAlarmHistory();
};

// 跳转详情
function confirmDetail() {
  window.open('/monitorChannel/device-monitor/warningHistory/home');
}
</script>

<style lang="less" scoped>
@import '/@/design/theme.less';
.search-table {
  --image-box-bg: url('@/assets/images/home-container/configurable/hsq/2-5.png');
  --image-box-bg2: url('@/assets/images/home-container/configurable/hsq/2-24.png');
  position: relative;
  width: 100%;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
}
.list-title {
  width: 177px;
  height: 30px;
  line-height: 22px;
  color: #01fefc;
  font-weight: bolder;
  background: var(--image-box-bg) no-repeat;
  background-size: 80% 100%;
  margin-bottom: 5px;
}
.search-area {
  height: 42px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}
.search-btn {
  width: 85px;
  height: 30px;
  border: 1px solid #01fefc;
  border-radius: 4px;
  padding: 3px;
  cursor: pointer;
}
.search-new .time-picker-wrap {
  padding: 10px;
  .form-row {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    .form-label {
      width: 60px;
      font-size: 13px;
      color: #fff;
      flex-shrink: 0;
    }
  }
}
:deep(.zxm-picker) {
  border: 1px solid #3ae1ff !important;
  background-color: #104064 !important;
}
:deep(.zxm-picker-input > input) {
  color: #fff !important;
}
:deep(.zxm-picker-suffix) {
  color: #fff !important;
}
.time-select {
  display: flex;
  align-items: center;
  padding-left: 10px;
  margin-bottom: 8px;
  gap: 6px;
  white-space: nowrap;
  .span {
    color: #fff;
    font-size: 13px;
  }
  .btn {
    padding: 3px 8px;
    background: #114268;
    border: 1px solid transparent;
    border-radius: 4px;
    color: #fff;
    cursor: pointer;
    font-size: 13px;
    &.active {
      background-color: #185f8e;
      border-color: #2084c0;
    }
  }
}
.btn-item {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: rgba(32, 166, 169);
}
.content-area {
  height: 100%;
}
.table-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
}
.warning-table {
  width: 100%;
  table-layout: fixed;
  border-collapse: collapse;
}
.table-header tr {
  position: sticky;
  top: 0;
  z-index: 10;
  background: var(--image-box-bg2) no-repeat;
  background-size: 100% 100%;
}
.table-row {
  height: 36px;
  &:nth-child(odd) {
    background-color: #0e3455;
  }
  &:nth-child(even) {
    background-color: #114268;
  }
  &.box_active {
    box-shadow: 2px 0 0 0 #ffa024, inset 0 0 0 2px #ffa024;
  }
}

th,
.table-cell {
  text-align: center;
  padding: 5px;
  font-size: 14px;
  box-sizing: border-box;
  vertical-align: middle;
}
th {
  font-weight: bold;
  color: #38e4ef;
  height: 30px;
}
.text-look {
  padding: 0 3px;
  margin: 0 2px;
  border-radius: 2px;
  background-color: #2484bc;
  cursor: pointer;
}
/* 文字省略样式 */
.text-ellipsis {
  display: block;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
