<template>
  <el-dialog :title="title" :visible.sync="visible" width="900px" append-to-body @close="handleClose">
    <!-- 新增模式：显示类型选择卡片 -->
    <div v-if="isAddMode && !selectedType" class="type-selector">
      <div class="type-cards">
        <div
          class="type-card"
          :class="{ 'selected': tempSelectedType === '1' }"
          @click="handleTypeSelect('1')"
        >
          <i class="el-icon-user type-card-icon"></i>
          <div class="type-card-title">个人</div>
          <div class="type-card-desc">添加个人中介信息</div>
        </div>
        <div
          class="type-card"
          :class="{ 'selected': tempSelectedType === '2' }"
          @click="handleTypeSelect('2')"
        >
          <i class="el-icon-office-building type-card-icon"></i>
          <div class="type-card-title">机构</div>
          <div class="type-card-desc">添加机构中介信息</div>
        </div>
      </div>
    </div>

    <!-- 表单区域：选择类型后或修改模式显示 -->
    <div v-show="selectedType || !isAddMode" class="form-container" :class="{ 'fade-in': shouldAnimate }">
      <el-divider v-if="isAddMode" content-position="left">{{ getTypeDividerText }}</el-divider>

      <!-- 个人类型表单 -->
      <el-form
        v-if="form.intermediaryType === '1'"
        ref="indivForm"
        :model="form"
        :rules="indivRules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号" prop="personId">
              <el-input v-model="form.personId" placeholder="请输入证件号码" maxlength="50" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="人员类型">
              <el-select v-model="form.personType" placeholder="请选择人员类型" clearable style="width: 100%">
                <el-option
                  v-for="item in indivTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人员子类型">
              <el-input v-model="form.personSubType" placeholder="请输入人员子类型" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="form.gender" placeholder="请选择性别" clearable style="width: 100%">
                <el-option
                  v-for="item in genderOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件类型">
              <el-select v-model="form.idType" placeholder="请选择证件类型" clearable style="width: 100%">
                <el-option
                  v-for="item in certTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码">
              <el-input v-model="form.mobile" placeholder="请输入手机号码" maxlength="20" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信号">
              <el-input v-model="form.wechatNo" placeholder="请输入微信号" maxlength="50" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="联系地址">
          <el-input v-model="form.contactAddress" placeholder="请输入联系地址" maxlength="200" clearable/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所在公司">
              <el-input v-model="form.company" placeholder="请输入所在公司" maxlength="200" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位">
              <el-input v-model="form.position" placeholder="请输入职位" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业统一信用码">
              <el-input v-model="form.socialCreditCode" placeholder="请输入企业统一信用码" maxlength="50" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联人员ID">
              <el-input v-model="form.relatedNumId" placeholder="请输入关联人员ID" maxlength="50" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="关联关系">
              <el-select v-model="form.relationType" placeholder="请选择关联关系" clearable style="width: 100%">
                <el-option
                  v-for="item in relationTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注"
            maxlength="500"
            :rows="3"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <!-- 机构类型表单 -->
      <el-form
        v-else-if="form.intermediaryType === '2'"
        ref="corpForm"
        :model="form"
        :rules="corpRules"
        label-width="140px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="机构名称" prop="enterpriseName">
              <el-input v-model="form.enterpriseName" placeholder="请输入机构名称" maxlength="200" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号" prop="socialCreditCode">
              <el-input
                v-model="form.socialCreditCode"
                placeholder="统一社会信用代码"
                maxlength="50"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主体类型">
              <el-select v-model="form.enterpriseType" placeholder="请选择主体类型" clearable style="width: 100%">
                <el-option
                  v-for="item in corpTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业性质">
              <el-select v-model="form.enterpriseNature" placeholder="请选择企业性质" clearable style="width: 100%">
                <el-option
                  v-for="item in corpNatureOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="成立日期">
              <el-date-picker
                v-model="form.establishDate"
                type="date"
                placeholder="选择成立日期"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行业分类">
              <el-input v-model="form.industryClass" placeholder="请输入行业分类" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属行业">
              <el-input v-model="form.industryName" placeholder="请输入所属行业" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="注册地址">
          <el-input v-model="form.registerAddress" type="textarea" placeholder="请输入注册地址" maxlength="500" :rows="2"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="法定代表人">
              <el-input v-model="form.legalRepresentative" placeholder="请输入法定代表人" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法定代表人证件类型">
              <el-select v-model="form.legalCertType" placeholder="请选择证件类型" clearable style="width: 100%">
                <el-option
                  v-for="item in certTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="法定代表人证件号码">
          <el-input v-model="form.legalCertNo" placeholder="请输入法定代表人证件号码" maxlength="50" clearable/>
        </el-form-item>
        <el-divider content-position="left">股东信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="股东1">
              <el-input v-model="form.shareholder1" placeholder="请输入股东1" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="股东2">
              <el-input v-model="form.shareholder2" placeholder="请输入股东2" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="股东3">
              <el-input v-model="form.shareholder3" placeholder="请输入股东3" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="股东4">
              <el-input v-model="form.shareholder4" placeholder="请输入股东4" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="股东5">
              <el-input v-model="form.shareholder5" placeholder="请输入股东5" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注"
            maxlength="500"
            :rows="3"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        :disabled="isAddMode && !selectedType"
        @click="handleSubmit"
      >确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "EditDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    },
    form: {
      type: Object,
      default: () => ({})
    },
    indivTypeOptions: {
      type: Array,
      default: () => []
    },
    genderOptions: {
      type: Array,
      default: () => []
    },
    certTypeOptions: {
      type: Array,
      default: () => []
    },
    relationTypeOptions: {
      type: Array,
      default: () => []
    },
    corpTypeOptions: {
      type: Array,
      default: () => []
    },
    corpNatureOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 新增模式：是否为新增操作（通过 computed 动态计算）
      // isAddMode: true,
      // 已选择的类型（确认后的类型）
      selectedType: null,
      // 临时选择的类型（用于卡片高亮）
      tempSelectedType: null,
      // 是否需要显示淡入动画
      shouldAnimate: false,
      // 个人类型验证规则
      indivRules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          { max: 100, message: "姓名长度不能超过100个字符", trigger: "blur" }
        ],
        personId: [
          { required: true, message: "证件号不能为空", trigger: "blur" },
          { max: 50, message: "证件号长度不能超过50个字符", trigger: "blur" }
        ],
        remark: [
          { max: 500, message: "备注长度不能超过500个字符", trigger: "blur" }
        ]
      },
      // 机构类型验证规则
      corpRules: {
        enterpriseName: [
          { required: true, message: "机构名称不能为空", trigger: "blur" },
          { max: 200, message: "机构名称长度不能超过200个字符", trigger: "blur" }
        ],
        socialCreditCode: [
          { required: true, message: "统一社会信用代码不能为空", trigger: "blur" },
          { max: 50, message: "统一社会信用代码长度不能超过50个字符", trigger: "blur" }
        ],
        remark: [
          { max: 500, message: "备注长度不能超过500个字符", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    // 判断是否为新增模式
    isAddMode() {
      return !this.form || !this.form.bizId;
    },
    // 根据选择的类型返回分隔线文本
    getTypeDividerText() {
      if (this.form.intermediaryType === '1') {
        return '个人信息';
      } else if (this.form.intermediaryType === '2') {
        return '机构信息';
      }
      return '';
    }
  },
  watch: {
    // 监听 visible 变化，重置状态
    visible(newVal) {
      if (newVal) {
        // 延迟初始化，确保 form 数据已经传入
        this.$nextTick(() => {
          this.initDialogState();
        });
      }
    }
  },
  methods: {
    /**
     * 初始化弹窗状态
     */
    initDialogState() {
      // 始终基于当前的 form 状态判断
      const isAdd = !this.form || !this.form.bizId;

      if (isAdd) {
        // 新增模式：重置选择状态
        this.selectedType = null;
        this.tempSelectedType = null;
        this.shouldAnimate = false;
        // 重置为个人类型（默认）
        if (this.form) {
          this.form.intermediaryType = '1';
        }
      } else {
        // 修改模式：设置已选择的类型
        if (this.form && this.form.intermediaryType) {
          this.selectedType = this.form.intermediaryType;
        }
        this.shouldAnimate = false;
      }
    },

    /**
     * 处理类型选择
     */
    handleTypeSelect(type) {
      this.tempSelectedType = type;
      this.form.intermediaryType = type;
      // 延迟设置 selectedType，使表单显示带动画效果
      setTimeout(() => {
        this.selectedType = type;
        this.shouldAnimate = true;
        // 清除表单验证状态，避免立即显示验证错误
        this.$nextTick(() => {
          const formRef = type === '1' ? 'indivForm' : 'corpForm';
          if (this.$refs[formRef]) {
            this.$refs[formRef].clearValidate();
          }
        });
      }, 50);
    },

    /**
     * 提交表单
     */
    handleSubmit() {
      // 未选择类型时不提交
      if (this.isAddMode && !this.selectedType) {
        this.$message.warning('请先选择中介类型');
        return;
      }

      // 根据类型验证不同的表单
      const formRef = this.form.intermediaryType === '1' ? 'indivForm' : 'corpForm';

      this.$refs[formRef].validate(valid => {
        if (valid) {
          this.$emit("submit");
        } else {
          // 验证失败：滚动到第一个错误字段
          this.scrollToFirstError();
        }
      });
    },

    /**
     * 滚动到第一个错误字段
     */
    scrollToFirstError() {
      const firstError = document.querySelector('.el-form-item__error');
      if (firstError) {
        firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
    },

    /**
     * 关闭弹窗
     */
    handleClose() {
      // 清除表单验证状态
      this.$nextTick(() => {
        if (this.$refs.indivForm) {
          this.$refs.indivForm.clearValidate();
        }
        if (this.$refs.corpForm) {
          this.$refs.corpForm.clearValidate();
        }
      });
      this.$emit("close");
    },

    /**
     * 验证表单（供父组件调用）
     */
    validateForm() {
      const formRef = this.form.intermediaryType === '1' ? 'indivForm' : 'corpForm';
      return this.$refs[formRef] ? this.$refs[formRef].validate() : Promise.reject();
    }
  }
};
</script>

<style scoped lang="scss">
/* 类型选择器区域 */
.type-selector {
  padding: 20px 0;
  text-align: center;
}

.type-cards {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin-bottom: 20px;
}

.type-card {
  flex: 1;
  max-width: 200px;
  padding: 30px 20px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #fff;

  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 12px rgba(64, 158, 255, 0.2);
    transform: translateY(-2px);
  }

  &.selected {
    border-color: #409eff;
    background-color: #ecf5ff;
    box-shadow: 0 4px 16px rgba(64, 158, 255, 0.3);
  }

  &-icon {
    font-size: 48px;
    color: #909399;
    margin-bottom: 10px;
    transition: color 0.3s ease;
  }

  &.selected &-icon {
    color: #409eff;
  }

  &-title {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 8px;
  }

  &-desc {
    font-size: 14px;
    color: #909399;
  }
}

/* 表单容器 */
.form-container {
  padding: 10px 0;

  &.fade-in {
    animation: fadeIn 0.3s ease-in-out;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 分隔线样式 */
::v-deep .el-divider {
  margin: 20px 0;

  .el-divider__text {
    font-weight: bold;
    color: #409eff;
  }
}

/* 必填项星号样式 */
::v-deep .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label::before {
  color: #f56c6c;
}
</style>
