<template>
  <div class="ship-info-form">
    <el-collapse v-model="activeNames">
      <el-collapse-item title="水上交通安全通报信息" name="1" :border="false">
        <el-form
          v-for="(item, index) in noticeItems"
          :key="index"
          :ref="(el) => noticeFormRefs[index] = el"
          :model="item"
          :rules="formRules"
          label-width="160px"
          size="default"
          class="notice-form"
        >
          <!-- 通报信息标题 + 删除按钮 -->
          <div class="notification-header">
            <div class="notification-matters">{{ '通报信息' + (index + 1) }}</div>
            <!-- 删除按钮：仅当表单数量 > 1 时显示 -->
            <el-button
              v-if="noticeItems.length > 1"
              type="danger"
              text
              size="small"
              :icon="Delete"
              @click="handleDelete(index)"
            >
              删除
            </el-button>
          </div>

          <!-- 通报事项 -->
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="通报事项" prop="noticeItem" required>
                <el-input
                  v-model="item.noticeItem"
                  placeholder="请填写通报事项"
                  maxlength="500"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 通报标准或具体行为 -->
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="通报标准或具体行为" prop="noticeStandard" required>
                <el-input
                  v-model="item.noticeStandard"
                  placeholder="请输入通报依据，内容1000字以内"
                  maxlength="1000"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 通报类别（单选框） -->
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="通报类别" prop="noticeType" required>
                <el-radio-group v-model="item.noticeType">
                  <el-radio label="info" border>信息告知类</el-radio>
                  <el-radio label="assist" border>协助处置类</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 水上交通安全信息（多行文本） -->
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="水上交通安全信息" prop="safetyInfo" required>
                <el-input
                  v-model="item.safetyInfo"
                  type="textarea"
                  :rows="4"
                  placeholder="违法违规信息（内容3000字以内）"
                  maxlength="3000"
                  show-word-limit
                />
                <div class="example-text mt-1 text-primary">
                  通报标准1:具体行为列举<br>
                  具体的业务描述XXXXXX
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 接收单位名称（下拉选择） -->
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="接收单位名称" prop="receiveUnit" required>
                <el-select
                  v-model="item.receiveUnit"
                  placeholder="请选择单位名称"
                  style="width: 100%"
                >
                  <el-option label="单位名称1" value="unit1" />
                  <el-option label="单位名称2" value="unit2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 行业外分类和接收单位 -->
          <el-row :gutter="24" class="industry-row">
            <el-col :span="6">
              <el-form-item label="行业外分类" prop="industryType">
                <el-select
                  v-model="item.industryType"
                  placeholder="请选择行业外分类"
                >
                  <el-option label="海警机构" value="marine" />
                  <el-option label="公安机关" value="public" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="行业外接收单位名称" prop="otherUnit">
                <el-input
                  v-model="item.otherUnit"
                  placeholder="请输入行业外接收单位名称 如：XXX1海警机构，XXX2海警机构，XX公安机关"
                  maxlength="200"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 上传附件区域 -->
          <el-row :gutter="24" class="upload-area">
            <el-col :span="24">
              <div class="upload-cards">
                <div class="upload-card">
                  <div class="card-title">行政处罚决定</div>
                  <el-upload
                    class="upload-demo"
                    drag
                    action="#"
                    multiple
                    :before-upload="beforeUpload"
                  >
                    <el-icon class="el-icon-upload"><UploadFilled /></el-icon>
                    <div class="el-upload__text">点击上传文件</div>
                  </el-upload>
                </div>
                <div class="upload-card">
                  <div class="card-title">通报事项的相关证据 <span class="required-mark">*</span></div>
                  <el-upload
                    class="upload-demo"
                    drag
                    action="#"
                    multiple
                    :before-upload="beforeUpload"
                  >
                    <el-icon class="el-icon-upload"><UploadFilled /></el-icon>
                    <div class="el-upload__text">点击上传文件</div>
                  </el-upload>
                </div>
                <div class="upload-card">
                  <div class="card-title">通报事项的其他材料</div>
                  <el-upload
                    class="upload-demo"
                    drag
                    action="#"
                    multiple
                    :before-upload="beforeUpload"
                  >
                    <el-icon class="el-icon-upload"><UploadFilled /></el-icon>
                    <div class="el-upload__text">点击上传文件</div>
                  </el-upload>
                </div>
                <div class="upload-tip text-danger">
                  提示：目前支持的文件格式：*.gif, *.jpeg, *.jpg, *.png, *.rar, *.zip, *.doc, *.ppt, *.xls, *.pdf, *.docx *.xlsx, *.bmp, *.xml,*.ofd,*.wps。文件大小支持：100M以内。
                </div>
              </div>
            </el-col>
          </el-row>

          <!-- 安全管理建议 -->
          <el-row :gutter="24" class="mt-4">
            <el-col :span="24">
              <el-form-item label="安全管理建议" prop="safetySuggestion" required>
                <el-input
                  v-model="item.safetySuggestion"
                  type="textarea"
                  :rows="2"
                  placeholder="安全管理建议（内容200字以内）"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 安全管理建议附件 -->
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="安全管理建议附件">
                <el-upload
                  class="upload-demo mt-2"
                  action="#"
                  multiple
                  :before-upload="beforeUpload"
                >
                  <el-button size="small" type="primary">上传文件</el-button>
                </el-upload>
              </el-form-item>
              <div class="upload-tip text-danger text-sm">
                提示：目前支持的文件格式：*.gif, *.jpeg, *.jpg, *.png, *.rar, *.zip, *.doc, *.ppt, *.xls, *.pdf, *.docx *.xlsx, *.bmp, *.xml,*.ofd,*.wps。文件大小支持：100M以内。
              </div>
            </el-col>
          </el-row>

          <!-- 是否需要反馈 -->
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="是否需要反馈" prop="needFeedback" required>
                <el-radio-group v-model="item.needFeedback" disabled>
                  <el-radio label="no" border>否</el-radio>
                  <el-radio label="yes" border>是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 分隔线（区分多个通报事项） -->
          <el-divider v-if="index !== noticeItems.length - 1" />
        </el-form>

        <!-- 添加通报事项按钮 -->
        <div class="add-matters">
          <el-button type="primary" plain :icon="Plus" @click="addNoticeItem">添加通报事项</el-button>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, defineEmits, defineExpose } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { UploadFilled, Plus, Delete } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const activeNames = ref(['1']);

const noticeItems = ref([
  {
    noticeItem: '',
    noticeStandard: '',
    noticeType: 'info',
    safetyInfo: '',
    receiveUnit: '',
    industryType: '',
    otherUnit: '',
    safetySuggestion: '',
    needFeedback: 'no'
  },
  {
    noticeItem: '',
    noticeStandard: '',
    noticeType: 'info',
    safetyInfo: '',
    receiveUnit: '',
    industryType: '',
    otherUnit: '',
    safetySuggestion: '',
    needFeedback: 'no'
  }
]);

const noticeFormRefs = ref<(FormInstance | undefined)[]>([]);

const formRules = reactive<FormRules>({
  noticeItem: [
    { required: true, message: '请填写通报事项', trigger: 'blur' },
    { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
  ],
  noticeStandard: [
    { required: true, message: '请输入通报标准或具体行为', trigger: 'blur' },
    { max: 1000, message: '长度不能超过1000个字符', trigger: 'blur' }
  ],
  noticeType: [
    { required: true, message: '请选择通报类别', trigger: 'change' }
  ],
  safetyInfo: [
    { required: true, message: '请填写水上交通安全信息', trigger: 'blur' },
    { max: 3000, message: '长度不能超过3000个字符', trigger: 'blur' }
  ],
  receiveUnit: [
    { required: true, message: '请选择接收单位名称', trigger: 'change' }
  ],
  otherUnit: [
    { 
      pattern: /^[\u4e00-\u9fa5a-zA-Z0-9,，\s]{0,200}$/, 
      message: '请输入合法的单位名称（支持中文、字母、数字和逗号）', 
      trigger: 'blur' 
    }
  ],
  safetySuggestion: [
    { required: true, message: '请填写安全管理建议', trigger: 'blur' },
    { max: 200, message: '长度不能超过200个字符', trigger: 'blur' }
  ],
  needFeedback: [
    { required: true, message: '请选择是否需要反馈', trigger: 'change' }
  ]
});

const handleDelete = (index: number) => {
  if (noticeItems.value.length <= 1) {
    ElMessage.warning('至少保留一个通报事项');
    return;
  }
  noticeItems.value.splice(index, 1);
  noticeFormRefs.value.splice(index, 1);
  noticeFormRefs.value = [];
};

const addNoticeItem = () => {
  noticeItems.value.push({
    noticeItem: '',
    noticeStandard: '',
    noticeType: 'info',
    safetyInfo: '',
    receiveUnit: '',
    industryType: '',
    otherUnit: '',
    safetySuggestion: '',
    needFeedback: 'no'
  });
  // 添加后表单实例会通过:ref自动绑定到noticeFormRefs
};

// 批量校验所有动态表单
const validateForm = async () => {
  let isAllValid = true;
  const invalidForms: { formIndex: number; fields: any }[] = [];

  for (let i = 0; i < noticeFormRefs.value.length; i++) {
    const formRef = noticeFormRefs.value[i];
    if (!formRef) continue;

    try {
      await formRef.validate();
    } catch (error: any) {
      isAllValid = false;
      invalidForms.push({ formIndex: i, fields: error.fields });
    }
  }

  emit('validate', isAllValid, invalidForms);
  return isAllValid;
};

// 重置所有表单
const resetAllForms = () => {
  noticeFormRefs.value.forEach(formRef => {
    formRef?.resetFields();
  });
};

// 通知父组件校验结果
const emit = defineEmits<{
  (e: 'validate', isValid: boolean, invalidForms?: { formIndex: number; fields: any }[]): void;
}>();

// 暴露方法给父组件
defineExpose({
  validateForm,
  resetAllForms
});

// 文件上传前校验（示例）
const beforeUpload = (file: File) => {
  console.log('文件上传前校验:', file.name);
  return false; // 阻止默认上传，实际项目中替换为真实上传逻辑
};
</script>

<style scoped lang="scss">
.ship-info-form {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

// 折叠面板样式
:deep .el-collapse-item__header {
  color: #5070ae;
  size: 24px;
  background: linear-gradient(135deg, #d2e8ff, #fcfeff);
	box-shadow: 0 8px 20px #fcfeff;
	text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  padding-left: 20px;
}

:deep .el-collapse-item__content {
  padding-top: 25px;
}

// 表单标题+删除按钮容器
.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

// 通报事项标题样式
.notification-matters {
  font-size: 20px;
  color: #163a8a;
  font-weight: 500;
  margin-bottom: 0;
}

// 删除按钮样式
:deep .el-button--text {
  color: #f56c6c;
  &:hover {
    color: #ff4d4f;
    background: rgba(245, 108, 108, 0.1);
  }
}

// 表单样式
.notice-form {
  .el-form-item__label {
    color: #333;
    font-weight: 500;
  }

  .el-form-item {
    align-items: center;
    margin-bottom: 15px;
  }

  .example-text {
    font-size: 14px;
    line-height: 1.5;
  }

  .industry-row {
    margin-top: 15px;
  }

  .upload-area {
    margin: 20px 0;

    .upload-tip {
      font-size: 14px;
      line-height: 1.5;
      margin-bottom: 15px;
    }

    .upload-cards {
      display: flex;
      gap: 20px;
      flex-wrap: wrap;

      .upload-card {
        flex: 1;
        min-width: 250px;
        border: 1px dashed #e0e0e0;
        border-radius: 4px;
        padding: 15px;

        .card-title {
          font-weight: 500;
          margin-bottom: 10px;
          color: #333;

          .required-mark {
            color: #f56c6c;
          }
        }
      }
    }
  }

  .upload-tip {
    font-size: 14px;
    line-height: 1.5;
  }
}

// 上传组件样式
:deep .el-upload--text {
  .el-upload-dragger {
    padding: 30px 0;
  }
}

// 添加按钮样式
.add-matters {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

// 分隔线样式
:deep .el-divider {
  margin: 25px 0;
  border-color: #f0f0f0;
}

// 响应式调整
@media (max-width: 768px) {
  .notice-form .upload-cards {
    flex-direction: column;
  }

  .notification-matters {
    font-size: 18px;
  }
}
</style>