<template>
  <BasicModal @register="register" :title="title" :width="1600" :min-height="500" v-bind="$attrs" @ok="onSubmit">
    <BasicForm @register="registerForm" />
    <div class="double-form__layout">
      <!-- 配置预警设备 -->
      <div class="setting-form__wrapper">
        <h3 class="panel-title">配置预警设备</h3>
        <div class="form-row" v-for="(item, idx) in warnList" :key="`warn-${idx}`">
          <BasicForm
            :ref="(el) => setWarnFormRef(el, idx)"
            :model="item"
            :schemas="formSchemas"
            layout="horizontal"
            label-width="150px"
            :show-action-button-group="false"
          >
            <template #monitor="{ model }">
              <div class="vent-flex-row-between">
                <a-input :value="model.pointOptions?.[0]?.label || ''" disabled style="width: calc(100% - 65px); border: 1px solid #1f7699" />
                <a-button type="primary" @click="selectPoint(model)" style="position: absolute; right: 0; top: 1px">选择</a-button>
              </div>
            </template>
          </BasicForm>
          <a-button type="link" normal @click="delWarnRow(idx)" :disabled="warnList.length <= 1">删除</a-button>
        </div>
        <a-button type="dashed" block @click="addWarnRow" class="setting-form__button">新增预警配置</a-button>
      </div>

      <!-- 配置控制设备 -->
      <div class="setting-form__wrapper">
        <h3 class="panel-title">配置控制设备</h3>
        <div class="form-row" v-for="(item, idx) in controlList" :key="`control-${idx}`">
          <BasicForm
            :ref="(el) => setControlFormRef(el, idx)"
            :model="item"
            :schemas="formSchemas1"
            layout="horizontal"
            label-width="120px"
            :show-action-button-group="false"
          >
            <template #monitor="{ model }">
              <div class="vent-flex-row-between">
                <a-input :value="model.pointOptions?.[0]?.label || ''" disabled style="width: calc(100% - 65px); border: 1px solid #1f7699" />
                <a-button type="primary" @click="selectPoint(model)" style="position: absolute; right: 0; top: 1px">选择</a-button>
              </div>
            </template>
          </BasicForm>
          <a-button type="link" normal @click="delControlRow(idx, item)" :disabled="controlList.length <= 1">删除</a-button>
        </div>
        <a-button type="dashed" block @click="addControlRow" class="setting-form__button">新增控制配置</a-button>
      </div>
    </div>
  </BasicModal>
  <DevicePointTable @register="registerPointModal" :data-source="devicePointList" @reload="setPoint" />
</template>

<script lang="ts" setup>
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { ref, unref, nextTick } from 'vue';
import { BasicForm, useForm } from '/@/components/Form';
import { message } from 'ant-design-vue';
import { deviceFormColumns, deviceControlColumns } from './warning.data';
import { workFaceWarningDelete, workFacePointList } from './warning.api';
import DevicePointTable from './DevicePointTable.vue';
import type { FormSchema } from '/@/components/Form/src/types/form';
import type { FormActionType } from '/@/components/Form';

const props = defineProps({
  formSchemas: {
    type: Array as PropType<FormSchema[]>,
    default: () => [],
  },
  deviceId: String,
  monitorType: String,
});
const emit = defineEmits(['add', 'update']);

const [registerPointModal, { openModal: openPointModal }] = useModal();
const formSchemas = deviceFormColumns();
const formSchemas1 = deviceControlColumns();

const title = ref('');
const isUpdate = ref(false);

// 表单Ref数组
const warnFormRefs = ref<FormActionType[]>([]);
const controlFormRefs = ref<FormActionType[]>([]);
const tempCurrentModel = ref<any>(null);
const devicePointList = ref<any[]>([]);

// 预警列表
const warnList = ref([getEmptyWarnRow()]);
function getEmptyWarnRow() {
  return {
    deviceType: '',
    monitorId: '',
    pointOptions: [],
    fmax: null,
    fmin: null,
    cxTime: null,
    dataTrend: '',
    trendCxTime: null,
    monitorType: '2',
  };
}
function setWarnFormRef(el: any, index: number) {
  if (el) warnFormRefs.value[index] = el;
}
function addWarnRow() {
  warnList.value.push(getEmptyWarnRow());
}
function delWarnRow(idx: number) {
  if (warnList.value.length <= 1) return message.warning('至少保留一行');
  warnList.value.splice(idx, 1);
  warnFormRefs.value.splice(idx, 1);
}

// 控制列表
const controlList = ref([getEmptyControlRow()]);
function getEmptyControlRow() {
  return {
    deviceType: '',
    monitorId: '',
    pointOptions: [],
    value: '',
    orderNum: null,
    remark: '',
    monitorType: '1',
  };
}
function setControlFormRef(el: any, index: number) {
  if (el) controlFormRefs.value[index] = el;
}
function addControlRow() {
  controlList.value.push(getEmptyControlRow());
}
async function delControlRow(idx: number, record: any) {
  if (controlList.value.length <= 1) return message.warning('至少保留一行');
  controlList.value.splice(idx, 1);
  controlFormRefs.value.splice(idx, 1);
  if (record.id) await workFaceWarningDelete({ id: record.id });
}

// 获取点位
async function getDevicePointList(strtype: string) {
  try {
    const res = await workFacePointList({ deviceType: strtype, valueTypes: props.monitorType });
    devicePointList.value = res;
  } catch {
    devicePointList.value = [];
  }
}
async function selectPoint(model: any) {
  if (!model.deviceType) return message.info('请先选择设备！');
  tempCurrentModel.value = model;
  await getDevicePointList(model.deviceType);
  openPointModal(true, { deviceType: model.deviceType });
}
function setPoint(value: any[]) {
  if (!value?.length || !tempCurrentModel.value) return;
  const data = value[0];
  const m = tempCurrentModel.value;
  m.monitorId = data.id;
  m.pointOptions = [{ value: data.id, label: data.valuename }];
}

// 主表单
const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
  schemas: props.formSchemas,
  showActionButtonGroup: false,
});

// 弹窗
const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
  isUpdate.value = unref(data.isUpdate);
  title.value = data.isUpdate ? '编辑' : '新增';
  await resetFields();
  warnFormRefs.value = [];
  controlFormRefs.value = [];
  tempCurrentModel.value = null;
  warnList.value = [getEmptyWarnRow()];
  controlList.value = [getEmptyControlRow()];
  if (data.isUpdate && data.record) {
    await setFieldsValue(data.record);
    const all = data.record.alarmList || [];
    warnList.value = all.filter((i) => String(i.monitorType) === '2') || [getEmptyWarnRow()];
    controlList.value = all.filter((i) => String(i.monitorType) === '1') || [getEmptyControlRow()];
    await nextTick();
    for (let i = 0; i < warnList.value.length; i++) {
      const form = warnFormRefs.value[i];
      const row = warnList.value[i];
      if (form && row) await form.setFieldsValue(row);
    }
    for (let i = 0; i < controlList.value.length; i++) {
      const form = controlFormRefs.value[i];
      const row = controlList.value[i];
      if (form && row) await form.setFieldsValue(row);
    }
  }
});

// ✅ 提交修复
async function onSubmit() {
  setModalProps({ confirmLoading: true });
  try {
    const baseForm = await getFieldsValue();

    // 读取预警行 —— 没有 monitorId 则过滤不提交
    const warnData = [];
    for (let i = 0; i < warnFormRefs.value.length; i++) {
      const form = warnFormRefs.value[i];
      if (!form) continue;
      const val = await form.getFieldsValue();
      delete val.pointOptions;
      if (val.strtype) val.deviceType = val.strtype;
      delete val.strtype;
      if (!val.monitorId) continue;

      warnData.push({ ...val, monitorType: 2 });
    }

    // 读取控制行 —— 没有 monitorId 则过滤不提交
    const controlData = [];
    for (let i = 0; i < controlFormRefs.value.length; i++) {
      const form = controlFormRefs.value[i];
      if (!form) continue;
      const val = await form.getFieldsValue();
      delete val.pointOptions;
      if (val.strtype) val.deviceType = val.strtype;
      delete val.strtype;

      // ✅ 关键：没有 monitorId 就跳过，不提交
      if (!val.monitorId) continue;

      controlData.push({ ...val, monitorType: 1 });
    }

    const params = {
      ...baseForm,
      alarmList: [...warnData, ...controlData],
    };

    isUpdate.value ? emit('update', params) : emit('add', params);
    closeModal();
  } catch (err) {
    console.error(err);
    message.error('提交失败');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>

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

.setting-form__wrapper {
  width: 49%;
  color: #fff;
  border-top: 3px solid @vent-gas-primary-text;
  background-color: @vent-gas-primary-trasparent-bg;
  padding: 10px;
}

.setting-form__button {
  width: 40%;
  margin: 10px auto;
  color: @vent-gas-primary-text;
  border-color: @vent-gas-primary-text;
  background: transparent !important;
}

.double-form__layout {
  display: flex;
  gap: 16px;
  margin-top: 16px;
}

.panel-title {
  margin: 0 0 10px;
  font-size: 14px;
  font-weight: bold;
  color: #fafafa;
}

.form-row {
  border: 1px solid #2e7695;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  margin-top: 10px;
}
</style>