<template>
  <div class="ship-info-form">
    <!-- 折叠面板 -->
    <el-collapse v-model="activeNames" class="collapse-panel">
      <el-collapse-item title="涉事主体基本信息" name="1" :border="false">
        <!-- 动态显示添加按钮或表单 -->
        <div v-if="isShowAdd" class="flex-cc">
          <el-button @click="onAddVessels" :icon="Plus">添加船舶</el-button>
          <el-tooltip content="Bottom center" placement="bottom" effect="light">
            <el-button link :icon="Warning">业务说明</el-button>
          </el-tooltip>
        </div>
        <div v-else>
          <!-- 表单核心：通过 isEditable 控制禁用 -->
          <el-form
            ref="ruleFormRef"
            :model="formData"
            :rules="formRules"
            label-width="130px"
            size="default"
            class="form-container"
          >
            <!-- 第一行：中文船名、英文船名、船舶识别号 -->
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="中文船名" prop="chineseName" required>
                  <el-input 
                    v-model="formData.chineseName" 
                    placeholder="请填写中文船名"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="英文船名" prop="englishName">
                  <el-input 
                    v-model="formData.englishName" 
                    placeholder="请填写英文船名"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="船舶识别号" prop="vesselId">
                  <el-input 
                    v-model="formData.vesselId" 
                    placeholder="请填写船舶识别号"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二行：MMSI、IMO编号、呼号 -->
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="MMSI" prop="mmsi">
                  <el-input 
                    v-model="formData.mmsi" 
                    placeholder="请填写MMSI"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="IMO编号" prop="imoNumber">
                  <el-input 
                    v-model="formData.imoNumber" 
                    placeholder="请填写IMO编号"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="呼号" prop="callSign">
                  <el-input 
                    v-model="formData.callSign" 
                    placeholder="请填写呼号"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第三行：牌薄号、船舶种类、船籍港 -->
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="牌薄号" prop="registrationNo">
                  <el-input 
                    v-model="formData.registrationNo" 
                    placeholder="请填写牌薄号"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="船舶种类" prop="vesselType" required>
                  <el-select 
                    v-model="formData.vesselType" 
                    placeholder="请选择船舶种类"
                    :disabled="!isEditable"
                  >
                    <el-option label="散货船" value="bulkCarrier" />
                    <el-option label="集装箱船" value="containerShip" />
                    <el-option label="油船" value="tanker" />
                    <el-option label="杂货船" value="generalCargo" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="船籍港" prop="portOfRegistry" required>
                  <el-input 
                    v-model="formData.portOfRegistry" 
                    placeholder="请填写船籍港"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第四行：国籍 -->
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="国籍" prop="nationality">
                  <el-input 
                    v-model="formData.nationality" 
                    placeholder="请填写国籍"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第五行：船舶所有人、所有人电话 -->
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="船舶所有人" prop="owner" required>
                  <el-input 
                    v-model="formData.owner" 
                    placeholder="请填写船舶所有人"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所有人电话" prop="ownerPhone">
                  <el-input 
                    v-model="formData.ownerPhone" 
                    placeholder="请填写船舶所有人联系电话"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第六行：船舶经营人、经营人电话 -->
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="船舶经营人" prop="operator" required>
                  <el-input 
                    v-model="formData.operator" 
                    placeholder="请填写船舶经营人"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="经营人电话" prop="operatorPhone">
                  <el-input 
                    v-model="formData.operatorPhone" 
                    placeholder="请填写船舶经营人联系电话"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第七行：其他相关组织、其他相关组织电话 -->
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="其他相关组织" prop="otherOrg">
                  <el-input 
                    v-model="formData.otherOrg" 
                    placeholder="请填写其他相关组织"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="其他相关组织电话" prop="otherOrgPhone">
                  <el-input 
                    v-model="formData.otherOrgPhone" 
                    placeholder="请填写其他相关组织联系电话"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第八行：船舶信息描述 -->
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="船舶信息描述" prop="description">
                  <el-input 
                    v-model="formData.description" 
                    placeholder="请填写船舶信息描述"
                    type="textarea" 
                    :rows="4"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <!-- 表单操作按钮：根据 isEditable 控制显示 -->
          <div class="form-actions" v-if="isEditable">
            <el-button 
              type="default" 
              text 
              class="reset-btn" 
              @click="handleReset"
            >
              船舶信息重置
            </el-button>
            <el-tooltip content="Bottom center" placement="bottom" effect="light">
              <el-button link :icon="Warning">业务说明</el-button>
            </el-tooltip>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
    <AddNewVesselsDrawer
      v-model:visible="drawerVisible"
      @selectShip="handleSelectShip"
    ></AddNewVesselsDrawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus';
import { Plus, Warning } from '@element-plus/icons-vue';
import AddNewVesselsDrawer from './addNewVesselsDrawer.vue';

// 路由参数获取
const route = useRoute();
const currentType = ref<'add' | 'edit' | 'detail'>('add'); // 当前页面类型

// 表单基础配置
const ruleFormRef = ref<FormInstance>();
const activeNames = ref(['1']);
const drawerVisible = ref(false);
const isShowAdd = ref(true); // 是否显示添加按钮

// 表单数据与验证规则
const formData = reactive({
  chineseName: '',
  englishName: '',
  vesselId: '',
  mmsi: '',
  imoNumber: '',
  callSign: '',
  registrationNo: '',
  vesselType: '',
  portOfRegistry: '',
  nationality: '',
  owner: '',
  ownerPhone: '',
  operator: '',
  operatorPhone: '',
  otherOrg: '',
  otherOrgPhone: '',
  description: ''
});

const formRules = reactive<FormRules>({
  chineseName: [
    { required: true, message: '请输入中文船名', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  vesselType: [
    { required: true, message: '请选择船舶种类', trigger: 'change' }
  ],
  portOfRegistry: [
    { required: true, message: '请输入船籍港', trigger: 'blur' },
    { max: 30, message: '长度不能超过30个字符', trigger: 'blur' }
  ],
  owner: [
    { required: true, message: '请输入船舶所有人', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  operator: [
    { required: true, message: '请输入船舶经营人', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  ownerPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  operatorPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
});

// 根据路由类型控制可编辑状态
const isEditable = computed(() => {
  return currentType.value === 'add' || currentType.value === 'edit';
});

// 初始化逻辑：获取路由参数 + 加载数据
onMounted(() => {
  // 从路由参数获取 type（默认 'add'）
  const type = route.query.type as 'add' | 'edit' | 'detail';
  if (['add', 'edit', 'detail'].includes(type)) {
    currentType.value = type;
  }

  // 根据类型加载数据
  if (currentType.value === 'edit' || currentType.value === 'detail') {
    fetchShipData(); // 模拟从接口加载船舶数据
  } else if (currentType.value === 'add') {
    // 新增场景可预设默认值
    formData.vesselType = 'bulkCarrier'; // 默认为散货船
  }
});

// 模拟加载船舶数据（edit/detail 场景）
const fetchShipData = () => {
  // 实际项目中替换为接口请求
  setTimeout(() => {
    formData.chineseName = '扬子10';
    formData.englishName = 'YANGZE 10';
    formData.mmsi = '636017533';
    formData.imoNumber = '9574444';
    formData.callSign = 'D5LK6';
    formData.vesselType = 'bulkCarrier'; // 散货船
    formData.portOfRegistry = '蒙罗维亚';
    formData.nationality = '利比里亚';
    formData.owner = '扬子航运有限公司';
    formData.operator = '扬子船务代理公司';
    isShowAdd.value = false; // 编辑/详情场景隐藏添加按钮
  }, 500);
};

// 监听路由参数变化（支持页面内切换类型）
watch(
  () => route.query.type,
  (newType) => {
    if (['add', 'edit', 'detail'].includes(newType as string)) {
      currentType.value = newType as 'add' | 'edit' | 'detail';
      // 重新加载数据
      if (currentType.value === 'edit' || currentType.value === 'detail') {
        fetchShipData();
      } else {
        handleReset(); // 新增场景重置表单
        isShowAdd.value = true; // 新增场景显示添加按钮
      }
    }
  }
);

// 重置表单
const handleReset = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.resetFields();
  // 重置后恢复默认值（新增场景）
  if (currentType.value === 'add') {
    formData.vesselType = 'bulkCarrier';
  }
};

// 选择船舶回调
const handleSelectShip = (data) => {
  console.log('选择船舶数据:', data);
  drawerVisible.value = false;
  isShowAdd.value = false; // 隐藏添加按钮，显示表单
};

// 打开添加船舶抽屉
const onAddVessels = () => {
  drawerVisible.value = true;
};
</script>

<style scoped lang="scss">
@import "@/styles/questionInformation.scss";
</style>