<template>
  <div class="AddBuildingBox">
    <PageHeader></PageHeader>
    <div class="AddBuildingBody">
      <div class="title">基本信息</div>
      <div class="addBuildingFormBody">
        <el-form class="formBody" label-position="right" ref="formRef" :model="form" :rules="rules" label-width="130px">
          <el-form-item label="员工姓名" prop="nickName">
            <el-input maxlength="30" show-word-limit v-model.trim="form.nickName" placeholder="请输入员工姓名" />
          </el-form-item>
          <el-form-item label="登录账号" v-if="form.userId == undefined" prop="userName">
            <el-input maxlength="16" show-word-limit v-model.trim="form.userName" placeholder="请输入登录账号" />
          </el-form-item>
          <el-form-item label="登录密码" v-if="form.userId == undefined" prop="password">
            <el-input type="password" clearable v-model.trim="form.password" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="员工性别" prop="chargeScope">
            <el-select v-model="form.sex" placeholder="请选择">
              <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="员工角色" prop="roleIds" v-if="form.userId == null || form.userId != useUserStore().userId">
            <el-select v-model="form.roleIds">
              <el-option
                :disabled="item.status == '1'"
                v-for="(item, index) in roleOptions"
                :key="index"
                :value="item.roleId"
                :label="item.roleName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="管理小区" prop="villageIds">
            <el-select v-model="checkVillage" multiple @change="handleChangeVillage">
              <el-option v-for="(item, index) in villageList" :key="index" :value="item.villageId" :label="item.villageName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号" prop="phonenumber">
            <el-input maxlength="11" v-model.trim="form.phonenumber" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input maxlength="35" v-model.trim="form.email" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input maxlength="200" show-word-limit type="textarea" :rows="5" v-model.trim="form.remark" placeholder="请输入" />
          </el-form-item>
          <el-form-item style="margin-top: 30px">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="cancelForm">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import api from '@/api/system/user';
import { ref } from 'vue';
import PageHeader from '@/components/Pageheader/index.vue';
import { getCommunitylistAPI } from '@/api/system/community';
import { validator } from '@/utils/Reg';
import { useUserStore } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { sys_user_sex } = toRefs<any>(proxy?.useDict('sys_user_sex'));

const router = useRouter();
const route = useRoute();
const formRef = ref();

const userid = ref(null);
const form = ref({
  'userId': null,
  'userName': '', // >= 4 && <= 16 账号
  'nickName': '', // >= 1 && <= 30 昵称
  // 'userType': '', // 用户类型（sys_user系统用户）
  'villageIds': '', // 管理小区id串
  'email': '', // >= 0 && <= 50 邮箱
  'phonenumber': '', // 手机号码
  'sex': '0', // 0男 1女 2未知
  'status': '0', // （0正常 1停用）
  'password': '', // 密码
  'roleIds': '', // 角色组
  'remark': ''
});
const rules = ref({
  // 员工姓名：必填，长度限制
  nickName: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
  ],
  // 登录账号：必填，长度限制，通常建议增加唯一性校验（需后端配合或异步校验）
  userName: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
    { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
  ],
  // 登录密码：必填，新增时必填，编辑时可选（通常逻辑），这里暂按必填处理，建议长度限制
  password: [
    { required: true, message: '请输入登录密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
  ],
  roleIds: [{ required: true, message: '请选择员工角色', trigger: 'change' }],
  phonenumber: [
    {
      validator: (_: any, val: string | number) => validator(val, 'phone'),
      message: '请输入正确的手机号码',
      trigger: 'blur',
      required: true
    }
  ],
  villageIds: [{ required: true, message: '请选择管理小区', trigger: 'blur' }],
  email: [
    { required: false, type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
    {
      validator: (_: any, val: string | number, callback: (arg0?: Error) => any) => {
        if (val === '' || val === null || val === undefined) {
          return callback();
        }
        return validator(val, 'email') ? callback() : callback(new Error('请输入正确的邮箱地址'));
      },
      trigger: 'blur'
    }
  ]
});
// 选择小区
const checkVillage = ref([]);
// 角色列表
const roleOptions = ref([]);

async function init() {
  if (route.query.id) {
    userid.value = route.query.id;
    api.getUser(userid.value).then((res) => {
      form.value = {
        'userId': res.data.user.userId,
        'userName': res.data.user.userName, // >= 0 && <= 30 账号
        'nickName': res.data.user.nickName, // >= 0 && <= 30 昵称
        'villageIds': res.data.user.villageIds, // 管理小区id串
        'status': res.data.user.status, // 0启用 1停用
        'email': res.data.user.email, // >= 0 && <= 50
        'phonenumber': res.data.user.phonenumber, // 手机号码
        'sex': res.data.user.sex, // 0男 1女 2未知
        'password': '', // 密码
        'roleIds': res.data.roleIds[0], // 角色组
        'remark': ''
      };
      roleOptions.value = [];
      roleOptions.value = Array.from(new Map([...res.data.roles, ...res.data.user.roles].map((role) => [role.roleId, role])).values());
      checkVillage.value = res.data.user.villageIds.split(',').filter((item) => item);
    });
  } else {
    const { data } = await api.getUser();
    roleOptions.value = data.roles;
  }
}

// 小区列表
const villageList = ref([]);
/** 查询小区列表  */
const getVillageList = async () => {
  const res = await getCommunitylistAPI();
  villageList.value = res.rows;
  console.log(villageList.value);
};
onMounted(() => {
  getVillageList();
  init();
});

function handleChangeVillage(value: string[]) {
  form.value.villageIds = value.join(',');
}

// !== 提交 =============================================================================
const submitForm = () => {
  const obj = {
    ...form.value,
    'roleIds': [form.value.roleIds]
  };
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (userid.value) {
        api.updateUser(obj).then(() => {
          ElMessage.success('编辑成功');
          cancelForm();
        });
      } else {
        api.addUser(obj).then(() => {
          ElMessage.success('添加成功');
          cancelForm();
        });
      }
    }
  });
};
// 推出
const cancelForm = () => {
  router.back();
};
</script>

<style scoped lang="scss">
.AddBuildingBox {
  padding: 15px;
  height: 100%;
  width: 100%;
}
.AddBuildingBody {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-color: white;
  padding: 15px;
  .title {
    height: 40px;
    line-height: 40px;
    padding-left: 20px;
    background-color: rgba(255, 255, 255, 1);
    color: rgba(16, 16, 16, 1);
    border-bottom: 1px solid #bbbbbb;
    margin-bottom: 60px;
  }

  .formBody {
    width: 550px;
    margin: 0 auto;

    .residentBox {
      max-height: 400px;
      overflow-y: auto;
      padding: 10px 5px;
    }
    .checkoutSideUsesbox {
      // display: grid;
      // grid-template-columns: repeat(3, 1fr);
      // gap: 5px;
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      justify-content: space-between;
      padding: 10px 5px;
      li {
        margin-right: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        min-width: 240px;
        height: 35px;
        padding: 0 10px;
        line-height: 35px;

        background-color: #f3f9ff;
        border: 1px solid #8fc0f1;

        margin-bottom: 10px;

        @media (max-width: 2000px) {
          font-size: 12px;
        }
        @media (max-width: 1650px) {
          font-size: 10px;
        }
        @media (max-width: 1650px) {
          font-size: 8px;
        }
        .el-icon {
          margin-left: 20px;
          cursor: pointer;
          &:hover {
            color: red;
          }
        }
        &.add {
          cursor: pointer;
          justify-content: center;
          color: #409eff;
          border: 1px dashed #409eff;
          background-color: transparent;
          &:hover {
            background-color: #40a0ff10;
          }
          span {
            margin-left: 10px;
          }
        }
      }
    }
    &:deep(.el-form-item__content, .el-select, .el-input) {
      width: 350px !important;
      margin-right: 10px;
      .el-cascader {
        width: 100%;
      }
    }
    .el-form-item {
      margin-bottom: 20px;
      align-items: center;
    }
    .el-button {
      width: 80px;
      height: 35px;
      margin-right: 20px;
    }
  }
}
</style>
