<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',
  };
}
// 收集预警表单Ref
function setWarnFormRef(el: any, index: number) {
  if (el) warnFormRefs.value[index] = el;
}
function addWarnRow() {
  warnList.value.push(getEmptyWarnRow());
  warnFormRefs.value.push(null);
}
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',
  };
}
// 收集控制表单Ref
function setControlFormRef(el: any, index: number) {
  if (el) controlFormRefs.value[index] = el;
}
function addControlRow() {
  controlList.value.push(getEmptyControlRow());
  controlFormRefs.value.push(null);
}
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);
  await workFaceWarningDelete({ id: record.id });
}

// 获取点位列表
async function getDevicePointList(strtype: string) {
  try {
    const result = await workFacePointList({ deviceType: strtype, valueTypes: props.monitorType });
    devicePointList.value = result;
  } catch (error) {
    devicePointList.value = [];
  }
}

// 打开点位选择弹窗
async function selectPoint(model: any) {
  if (!model.deviceType) {
    message.info('请先选择设备！');
    return;
  }
  console.log(model, '=====model');
  // 缓存当前编辑行
  tempCurrentModel.value = model;
  await getDevicePointList(model.deviceType);
  openPointModal(true, { deviceType: model.deviceType });
}

// 选中点位回填到当前行
function setPoint(value: any[]) {
  if (!value || !value.length || !tempCurrentModel.value) return;
  const data = value[0];
  const model = tempCurrentModel.value;
  // 赋值当前行
  model.monitorId = data.id;
  model.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);
  await resetFields();
  title.value = data.isUpdate ? '编辑' : '新增';

  warnFormRefs.value = [];
  controlFormRefs.value = [];
  tempCurrentModel.value = null;

  if (data.isUpdate && data.record) {
    await setFieldsValue(data.record);
    const allAlarms = data.record.alarmList || [];
    const warnings = allAlarms.filter((item: any) => String(item.monitorType) === '2');
    const controls = allAlarms.filter((item: any) => String(item.monitorType) === '1');
    warnList.value = warnings.length ? warnings : [getEmptyWarnRow()];
    controlList.value = controls.length ? controls : [getEmptyControlRow()];
  } else {
    warnList.value = [getEmptyWarnRow()];
    controlList.value = [getEmptyControlRow()];
  }

  if (data.type === 'devicePoint') {
    title.value = unref(data.title);
    if (data.record) {
      await getDevicePointList(data.record['deviceType']);
      devicePointList.value.forEach((item) => {
        if (item.id == data.record.monitorId) {
          const model = data.record;
          model.monitorId = item.id;
          model.pointOptions = [{ value: item.id, label: item.valuename }];
        }
      });
      await setFieldsValue({ ...data.record });
    }
  }
});

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

    // 获取预警数据
    const warnValues = [];
    for (const form of warnFormRefs.value) {
      if (form) {
        const val = await form.getFieldsValue();
        delete val.pointOptions;
        if (val.strtype) {
          val.deviceType = val.strtype;
        }
        delete val.strtype;
        const deviceId = Array.isArray(val.deviceId) ? val.deviceId[0] : val.deviceId || '';
        if (!deviceId) continue;
        warnValues.push({
          ...val,
          monitorType: 2,
          deviceId: deviceId,
        });
      }
    }

    // 获取控制数据
    const controlValues = [];
    for (const form of controlFormRefs.value) {
      if (form) {
        const val = await form.getFieldsValue();
        delete val.pointOptions;

        if (val.strtype) {
          val.deviceType = val.strtype;
        }
        delete val.strtype;
        const deviceId = Array.isArray(val.deviceId) ? val.deviceId[0] : val.deviceId || '';
        if (!deviceId) continue;

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

    const submitData = {
      ...baseForm,
      alarmList: [...warnValues, ...controlValues],
    };

    if (!isUpdate.value) {
      emit('add', submitData);
    } else {
      emit('update', submitData);
    }

    closeModal();
  } catch (error) {
    console.error('提交异常：', error);
    message.error('提交失败，请检查表单');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>

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

.setting-form {
  padding: 0 20px;
}

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

.setting-form__button {
  display: block;
  width: 40%;
  margin: 10px auto;
  color: @vent-gas-primary-text;
  border-color: @vent-gas-primary-text;
  background-color: 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>