<template>
  <div class="app-container" style="padding-left: 5px;">
    <el-card shadow="hover">
      <el-form 
        ref="tenantRef" 
        :model="form" 
        :rules="rules" 
        label-width="180px" 
        label-position="left"
        class="full-width-form"
      >
        <!-- 企业信息区块 -->
        <h4 class="form-section-title">企业信息</h4>
        
        <el-form-item label="企业名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入企业名称" class="medium-input" />
        </el-form-item>
        <el-form-item label="企业logo" prop="logo">
          <image-upload v-model="form.logo" :limit="1" :file-type="['png', 'jpg', 'jpeg', 'doc', 'docx', 'pdf']" />
        </el-form-item>

        <el-form-item label="官方邮箱" prop="email">
          <div class="input-with-tip">
            <el-input v-model="form.email" placeholder="请输入官方邮箱" class="medium-input" />
            <span v-if="containsSpecial(form.email, 'email')" class="warning-text">不可输入特殊字符！</span>
          </div>
        </el-form-item>

        <el-form-item label="办公地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入办公地址" class="wide-input" />
        </el-form-item>

        <el-form-item label="统一社会信用代码" prop="licenseNumber">
          <el-input v-model="form.licenseNumber" placeholder="请输入统一社会信用代码" class="highlight-input medium-input" />
        </el-form-item>

        <el-form-item label="委托招聘证明">
          <div class="upload-section">
            <div class="upload-item">
              <image-upload v-model="form.companyEntrustProof" :limit="1" :file-type="['png', 'jpg', 'jpeg', 'doc', 'docx', 'pdf']" />
            </div>
            <div class="example-item">
              <div class="example-image-btn">
                <el-icon :size="20"><Picture /></el-icon>
                <span>示例图</span>
                <el-icon class="search-icon"><Search /></el-icon>
              </div>
            </div>
          </div>
          <p class="upload-tip">大小不超过10M，支持扩展名：.png .doc .docx .pdf .jpg</p>
        </el-form-item>

        <el-divider class="divider-mt40" />

        <!-- 联系人信息区块 -->
        <h4 class="form-section-title">联系人信息</h4>

        <el-form-item label="头像账号" class="avatar-item">
          <div class="avatar-uploader-wrapper">
             <image-upload v-model="form.avatar" :limit="1" class="avatar-component" />
             <div class="avatar-edit-mask">编辑</div>
          </div>
        </el-form-item>

        <el-form-item label="姓名" prop="contactUserName">
          <el-input v-model="form.contactUserName" placeholder="请输入姓名" class="small-input" />
        </el-form-item>


        <el-form-item label="手机号" prop="contactPhone">
          <div class="input-with-tip">
            <el-input v-model="form.contactPhone" placeholder="请输入手机号" class="medium-input" />
            <span v-if="containsSpecial(form.contactPhone, 'phone')" class="warning-text">不可输入特殊字符！</span>
          </div>
        </el-form-item>

        <!-- 新增：用户名与密码 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入系统用户名" class="medium-input" maxlength="30" />
        </el-form-item>

        <el-form-item label="用户密码" prop="password">
          <el-input v-model="form.password" type="password" :placeholder="form.id ? '密码为空时不修改密码' : '请输入系统用户密码'" class="medium-input" maxlength="20" show-password />
        </el-form-item>

        <el-form-item label="角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="企业管理员" class="medium-input" disabled>
            <el-option label="企业管理员" value="1" />
          </el-select>
        </el-form-item>

        <!-- 底部按钮区域 -->
        <div class="form-footer mt60">
          <el-button size="large" @click="cancel">返回</el-button>
          <el-button size="large" type="primary" @click="submitForm">提交</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="TenantEdit">
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useTagsViewStore } from "@/store/modules/tagsView";
import { getTenant, addTenant, updateTenant } from "@/api/system/tenant";
import { Picture, Search } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const tagsViewStore = useTagsViewStore();

const tenantRef = ref(null);

const form = reactive({
  id: undefined,
  roleId: '1',
  companyName: '',
  email: '',
  address: '',
  licenseNumber: '',
  contactUserName: '',
  contactPhone: '',
  username: '',
  password: '',
  avatar: '',
  companyEntrustProof: '',
  nickName:'',
  userId:undefined
});

// 计算规则，配置用户名与密码的校验
const rules = {
  companyName: [{ required: true, message: "请输入企业名称", trigger: ["blur", "change"] }],
  email: [{ required: true, message: "请输入官方邮箱", trigger: ["blur", "change"] }],
  address: [{ required: true, message: "请输入办公地址", trigger: ["blur", "change"] }],
  contactUserName: [{ required: true, message: "请输入姓名", trigger: ["blur", "change"] }],
  contactPhone: [{ required: true, message: "请输入手机号", trigger: ["blur", "change"] }],
  username: [
    { required: true, message: "用户名不能为空", trigger: ["blur", "change"] },
    { min: 2, max: 20, message: "用户名称长度必须介于 2 和 20 之间", trigger: ["blur", "change"] }
  ],
  password: [
    {
      validator: (rule, value, callback) => {
        if (form.id) {
          // 编辑模式：密码可以为空
          if (value && (value.length < 5 || value.length > 20)) {
            callback(new Error("用户密码长度必须介于 5 和 20 之间"));
          } else {
            callback();
          }
        } else {
          // 新增模式：密码必填
          if (!value) {
            callback(new Error("密码不能为空"));
          } else if (value.length < 5 || value.length > 20) {
            callback(new Error("用户密码长度必须介于 5 和 20 之间"));
          } else {
            callback();
          }
        }
      },
      trigger: ["blur", "change"]
    }
  ]
};

const containsSpecial = (val, type) => {
  if (!val) return false;
  let regex;
  if (type === 'email') {
    regex = /[^a-zA-Z0-9@._-]/; 
  } else if (type === 'phone') {
    regex = /[^0-9\-+ ]/;
  }
  return regex ? regex.test(val) : false;
};

onMounted(() => {
  // 之前是 const id = route.query.id;
  const tenantId = route.query.tenantId;
  if (tenantId) {
    getTenant(tenantId).then(res => {
      // 显式赋值，确保响应式追踪正常
      const data = res.data;
      Object.assign(form, data);
      
      // 关键：显式转换后端 userName 到前端 username
      if (data.userName) {
        form.username = data.userName;
      }
      
      // 编辑模式下密码通常不回显，置空
      form.password = '';
      
      // 数据加载完成后，清除可能的初始校验错误
      nextTick(() => {
        tenantRef.value?.clearValidate();
      });
    });
  }
});


const submitForm = () => {
  tenantRef.value.validate(valid => {
    if (valid) {
      const submitData = { ...form };
      // 编辑时密码为空则不提交密码字段
      if (submitData.id && !submitData.password) {
        delete submitData.password;
      }
      if (submitData.id) {
        updateTenant(submitData).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          cancel();
        });
      } else {
        addTenant(submitData).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          cancel();
        });
      }
    }
  });
};


const cancel = () => {
  proxy.$tab.closePage();
};
</script>

<style lang="scss" scoped>
:deep(.el-card__body) {
  padding: 30px 40px;
}

.form-section-title {
  font-size: 18px;
  font-weight: bold;
  margin: 10px 0 30px 0;
  color: #333;
}

// 标签优化
:deep(.el-form-item__label) {
  padding-right: 20px;
  display: flex !important;
  align-items: center;
  justify-content: flex-start;
  position: relative;
  
  &::before {
    position: absolute;
    left: -12px;
  }
}

// 宽度控制：适中宽度
.small-input { width: 200px !important; }
.medium-input { width: 460px !important; }
.wide-input { width: 720px !important; }

.input-with-tip {
  display: flex;
  align-items: center;
  
  .warning-text {
    color: #f56c6c;
    font-size: 14px;
    margin-left: 20px;
    white-space: nowrap;
  }
}

.highlight-input :deep(.el-input__wrapper) {
  border: 1px solid #409eff;
  box-shadow: 0 0 0 1px #409eff inset;
}

.upload-section {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  
  .example-image-btn {
    width: 120px;
    height: 120px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #909399;
    background-color: #fcfcfc;
    position: relative;
    cursor: pointer;
    transition: all 0.2s;
    &:hover { border-color: #40a9ff; color: #40a9ff; }
    span { font-size: 13px; margin-top: 8px; }
    .search-icon { position: absolute; bottom: 8px; right: 8px; font-size: 15px; }
  }
}

.upload-tip { font-size: 13px; color: #999; margin-top: 10px; }

.avatar-uploader-wrapper {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid #fff;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);

  .avatar-component {
    :deep(.el-upload--picture-card) {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      margin: 0;
      line-height: 80px;
    }
  }

  .avatar-edit-mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 26px;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    text-align: center;
    line-height: 26px;
    font-size: 12px;
  }
}

.mt60 { margin-top: 60px; }
.divider-mt40 { margin: 40px 0; }

.form-footer {
  text-align: left;
  padding-left: 180px; 
  .el-button {
    min-width: 120px;
    & + .el-button { margin-left: 30px; }
  }
}

@media screen and (max-width: 768px) {
  .small-input, .medium-input, .wide-input { width: 100% !important; }
  .form-footer { padding-left: 0; text-align: center; }
  .input-with-tip {
    flex-direction: column;
    align-items: flex-start;
    .warning-text { margin-left: 0; margin-top: 5px; }
  }
}
</style>
