<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    @ok="handleSubmit"
    :title="getTitle"
    width="900px"
    :min-height="600"
    :max-height="1000"
    scrollable
    centered
    destroyOnClose
    :bodyStyle="{ padding: '20px' }"
  >
    <a-form ref="formRef" :model="formData" :rules="formRules" layout="horizontal" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
      <!-- 查看模式 -->
      <div class="que-container" v-if="mode === 'view'">
        <div class="que-status">
          <div>矿井状态：</div>
          <div>
            <span :class="getStatusClass(currentRecord?.mineLinkStatus)" class="status-dot">
              {{ getStatusText(currentRecord?.mineLinkStatus) }}
            </span>
          </div>
        </div>
        <div class="que-item" v-for="(item, index) in queList" :key="index">
          <div class="que-details">
            <div class="que-field">
              <span class="que-value que-goafName">{{ item.queTitle || '-' }}</span>
            </div>
            <div class="que-field time-field">
              <span class="que-label">时间：</span>
              <span class="que-value">{{ formatDate(item.startTime) || '-' }}</span>
              <span class="time-separator">-----</span>
              <span class="que-value">{{ formatDate(item.endTime) || '-' }}</span>
            </div>
            <div class="que-field">
              <span class="que-label">问题描述：</span>
              <span class="que-value">{{ item.queCon || '-' }}</span>
            </div>
            <!-- <div class="que-field">
              <span class="que-label">参数：</span>
              <span class="que-value">{{ (item.param || '-').replace(/,/g, ' ') }}</span>
            </div> -->
          </div>
        </div>
      </div>

      <!-- 编辑/新增模式 -->
      <div v-else class="edit-container">
        <div class="mine-base-info" v-if="mode === 'add'">
          <a-form-item name="deptId" label="煤矿名称">
            <MineCascader
              v-model:value="innerValue"
              :sync-to-store="false"
              :init-from-store="false"
              :change-on-select="false"
              :allow-clear="false"
              @change="changeCascader"
            />
          </a-form-item>
          <a-form-item name="goafId" label="密闭名称">
            <a-select v-model:value="goafId" :options="goafOptions" placeholder="请选择" />
          </a-form-item>
        </div>

        <!-- 问题项编辑区 -->
        <div class="que-item" v-for="(item, index) in queList" :key="item.orderNum || index">
          <div class="que-index">问题 {{ index + 1 }}</div>
          <div class="edit-fields">
            <a-form-item
              v-for="schema in formSchema"
              :key="`${schema.field}-${index}`"
              :name="[`queList`, index, schema.field]"
              :label="schema.label"
              :rules="schema.rules"
            >
              <component
                :is="getComponent(schema.component)"
                v-model:value="item[schema.field]"
                v-bind="schema.componentProps"
                :placeholder="`请输入${schema.label}`"
                style="width: 100%"
              />
            </a-form-item>
            <div class="form-actions">
              <a-button type="text" danger @click="removeItem(index)" :disabled="queList.length <= 1"> 删除 </a-button>
            </div>
          </div>
        </div>

        <a-button type="dashed" class="add-btn" @click="addNewItem"> <plus-outlined /> 新增问题 </a-button>
      </div>
    </a-form>
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, computed, reactive, watch } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { formSchema } from '../problemReport.data';
  import { Select, Input, DatePicker, message } from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import dayjs, { Dayjs } from 'dayjs';
  import MineCascader from '/@/components/Form/src/jeecg/components/MineCascader/MineCascader.vue';
  import type { FormInstance, RuleObject } from 'ant-design-vue/es/form';
  import { JEditor, JImageUpload } from '/@/components/Form';
  import { useInitForm } from '/@/views/analysis/warningAnalysis/connectAnalysis/hooks/form';
  import { useMineDepartmentStore } from '/@/store/modules/mine';

  // 组件映射表
  const componentMap = {
    Input,
    DatePicker,
    Select,
    InputTextArea: Input.TextArea,
    MineCascader,
    JEditor,
    JImageUpload,
  };

  // 定义事件发射
  const emit = defineEmits(['success']);
  const mineStore = useMineDepartmentStore();
  const { goafOptions, goafId, innerValue, initGoafOptions } = useInitForm();

  // 模态框模式：查看/编辑/新增
  const mode = ref<'view' | 'edit' | 'add'>('view');
  // 当前记录数据
  const currentRecord = ref<any>({
    mineCode: '',
    mineLinkStatus: '0',
    queJson: [],
    isOk: false,
    updateTime: '',
    createTime: '',
  });
  // 问题列表
  const queList = ref<any[]>([]);

  // 表单实例（用于校验）
  const formRef = ref<FormInstance>();
  // 表单数据聚合（适配Form组件的model）
  const formData = reactive({
    mineCode: '',
    queList: queList.value,
  });

  // 合并表单规则（从schema中提取）
  const formRules = reactive({
    queList: {
      type: 'array',
      required: true,
      validator: (rule: RuleObject, value: any[], callback: Function) => {
        // 校验每个问题项
        if (value.length === 0) {
          callback(new Error('至少需要填写一条问题信息'));
          return;
        }
        // 逐个校验问题项的必填字段
        for (let i = 0; i < value.length; i++) {
          const item = value[i];
          // 校验工作面名称
          if (!item.goafName) {
            callback(new Error(`第${i + 1}条问题：工作面名称不能为空`));
            return;
          }
          // 校验问题描述
          if (!item.queCon) {
            callback(new Error(`第${i + 1}条问题：问题描述不能为空`));
            return;
          }
          // 校验开始时间
          if (!item.startTime) {
            callback(new Error(`第${i + 1}条问题：开始时间不能为空`));
            return;
          }
          // 校验结束时间
          if (!item.endTime) {
            callback(new Error(`第${i + 1}条问题：结束时间不能为空`));
            return;
          }
          // 校验结束时间不能早于开始时间
          if (dayjs(item.endTime).isBefore(dayjs(item.startTime))) {
            callback(new Error(`第${i + 1}条问题：结束时间不能早于开始时间`));
            return;
          }
          // 校验参数
          if (!item.param) {
            callback(new Error(`第${i + 1}条问题：参数不能为空`));
            return;
          }
        }
        callback();
      },
    },
  });

  // 监听queList变化，同步到formData
  watch(
    queList,
    (newVal) => {
      formData.queList = JSON.parse(JSON.stringify(newVal));
    },
    { deep: true, immediate: true }
  );

  // 监听currentRecord变化，同步mineCode到formData
  watch(
    () => currentRecord.value.mineCode,
    (newVal) => {
      formData.mineCode = newVal;
    },
    { immediate: true }
  );

  // 根据组件名获取对应组件
  const getComponent = (componentName: string) => {
    return componentMap[componentName as keyof typeof componentMap];
  };

  // 日期格式化方法
  const formatDate = (date: string | Dayjs | null) => {
    if (!date) return '';
    return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
  };

  // 根据状态值获取显示文本（在线/离线）
  const getStatusText = (status: string | number) => {
    return status === '1' || status === 1 ? '在线' : '离线';
  };

  // 根据状态值获取样式类
  const getStatusClass = (status: string | number) => {
    return status === '1' || status === 1 ? 'status-online' : 'status-offline';
  };

  // 注册模态框并初始化数据
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });

    // 接收模式参数
    mode.value = data?.mode || 'view';
    // 初始化当前记录
    currentRecord.value = data?.record
      ? JSON.parse(JSON.stringify(data.record))
      : {
          mineCode: '',
          mineLinkStatus: '0',
          queJson: [],
          isOk: false,
          updateTime: '',
          createTime: '',
        };
    // 同步mineCode到formData
    formData.mineCode = currentRecord.value.mineCode;

    // 初始化问题列表
    if (mode.value === 'add') {
      // 新增模式：初始化一条空数据
      queList.value = [
        {
          orderNum: '1',
          goafName: '',
          queCon: '',
          startTime: null,
          endTime: null,
          param: '',
        },
      ];
      formData.queList = JSON.parse(JSON.stringify(queList.value));
      if (formRef.value) {
        formRef.value.resetFields();
      }
    } else {
      // 编辑/查看模式：解析已有问题数据
      try {
        const rawData = currentRecord.value?.queJson
          ? typeof currentRecord.value.queJson === 'string'
            ? currentRecord.value.queJson.trim()
              ? JSON.parse(currentRecord.value.queJson)
              : [] // 兼容空字符串
            : currentRecord.value.queJson
          : [];
        // 兼容日期格式，避免转换失败
        queList.value = rawData.map((item: any) => ({
          ...item,
          startTime: item.startTime ? dayjs(item.startTime, ['YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD']) : null,
          endTime: item.endTime ? dayjs(item.endTime, ['YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD']) : null,
        }));
        // 深拷贝同步到formData，切断引用
        formData.queList = JSON.parse(JSON.stringify(queList.value));
      } catch (error) {
        console.error('解析问题数据失败:', error);
        message.warning('问题数据格式异常，将显示原始数据');
        // 保留原始queJson，而非重置为空数据
        queList.value = currentRecord.value?.queJson ? (typeof currentRecord.value.queJson === 'string' ? [] : currentRecord.value.queJson) : [];
        formData.queList = JSON.parse(JSON.stringify(queList.value));
      }
    }
    // 重置表单校验状态
    if (formRef.value) {
      formRef.value.resetFields();
    }
  });

  // 模态框标题计算属性
  const getTitle = computed(() => {
    const titleMap = {
      view: '密闭墙问题详情',
      edit: '编辑密闭墙问题',
      add: '新增密闭墙问题',
    };
    return titleMap[mode.value];
  });

  // 新增问题项
  const addNewItem = () => {
    const newItem = {
      orderNum: (queList.value.length + 1).toString(),
      goafName: '',
      queCon: '',
      startTime: null,
      endTime: null,
      param: '',
    };
    queList.value.push(newItem);
  };

  // 删除问题项
  const removeItem = (index: number) => {
    queList.value.splice(index, 1);
    queList.value.forEach((item, i) => {
      item.orderNum = (i + 1).toString();
    });
  };

  // 提交表单处理
  async function handleSubmit() {
    try {
      // 查看模式直接提交
      if (mode.value === 'view') {
        closeModal();
        return;
      }

      // 1. 表单校验
      if (!formRef.value) return;
      const validateResult = await formRef.value.validate();
      if (!validateResult) return;

      setModalProps({ confirmLoading: true });
      // 2. 处理问题列表数据（空日期字段置空，避免空字符串）
      const submitQueList = queList.value.map((item) => ({
        ...item,
        startTime: item.startTime ? item.startTime.format('YYYY-MM-DD HH:mm:ss') : null,
        endTime: item.endTime ? item.endTime.format('YYYY-MM-DD HH:mm:ss') : null,
      }));
      // 3. 构造完整提交数据
      const now = dayjs().format('YYYY-MM-DD HH:mm:ss');
      const result = {
        ...currentRecord.value,
        deptId: innerValue.value,
        goafId: goafId.value,
        mineCode: mode.value === 'add' ? mineStore.findDepartById(innerValue.value)?.fax : formData.mineCode,
        queJson: JSON.stringify(submitQueList),
        createTime: mode.value === 'add' ? now : currentRecord.value.createTime || now,
        updateTime: now,
        isOk: mode.value === 'add' ? false : currentRecord.value.isOk,
      };
      // console.log('最终提交数据：', result);
      emit('success', result);
      closeModal();
    } catch (error: any) {
      console.error('提交失败：', error);
      // 显示校验错误提示
      message.error(error.message || '表单校验失败，请检查必填项');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function changeCascader(val) {
    innerValue.value = val;
    initGoafOptions(val);
  }
</script>

<style scoped>
  .que-container {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .que-status {
    display: flex;
    width: 100%;
    background-color: #f8f9fc;
    padding: 8px 16px;
    align-items: center;
    border: 1px solid #cad2e0;
    border-radius: 5px;
  }

  .mine-info {
    padding: 12px 16px;
    border: 1px solid #cad2e0;
    border-radius: 5px;
    background-color: #f8f9fc;
  }

  .mine-field {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
  }

  .status-dot {
    position: relative;
    padding-left: 12px;
    font-weight: 500;
  }

  .status-dot::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background-color: inherit;
  }

  .status-online {
    color: #10952c;
    font-weight: 500;
  }

  .status-offline {
    color: #f5222d;
    font-weight: 500;
  }

  .status-online.status-dot::before {
    background-color: #10952c;
  }

  .status-offline.status-dot::before {
    background-color: #f5222d;
  }

  .que-item {
    padding: 8px 16px;
    border: 1px solid #cad2e0;
    border-radius: 8px;
    background-color: #f8f9fc;
  }

  .que-index {
    font-size: 16px;
    font-weight: 600;
    color: #1890ff;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px dashed #e8e8e8;
  }

  .que-details {
    width: 100%;
  }

  .que-field {
    display: flex;
    align-items: center;
    gap: 8px;
    min-width: 200px;
    margin-bottom: 10px;
  }

  .que-label {
    font-size: 16px;
    color: #868789;
    white-space: nowrap;
  }

  .que-value {
    font-size: 16px;
    color: #838486;
    word-break: break-all;
  }

  .que-goafName {
    color: #4c4c4e;
    font-size: 20px;
  }

  .time-field {
    flex: 1;
    min-width: 420px;
  }

  .time-separator {
    color: #999;
    margin: 0 8px;
  }

  .edit-container {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .mine-base-info {
    padding: 12px 16px;
    border: 1px solid #cad2e0;
    border-radius: 5px;
    background-color: #f8f9fc;
  }

  .edit-fields {
    width: 100%;
  }

  .form-item {
    display: flex;
    margin-bottom: 10px;
    align-items: center;
  }

  .form-label {
    width: 20%;
    color: #666;
    font-size: 14px;
  }

  .add-btn {
    margin-top: 8px;
    width: 100%;
  }

  .form-actions {
    display: flex;
    justify-content: end;
    margin-bottom: 8px;
  }
</style>
