<template>
  <!-- 小型弹窗，用于完成，删除，保存等操作 -->
  <el-dialog class="l-dialog" :class="lDialog" :title="title" :visible.sync="dialogVisible" :showClose="true"
             :closeOnClickModal="false" @close="handleClose" :append-to-body="true">
    <div>
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="110px">
        <el-form-item label="用户账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户账号" maxlength="32" show-word-limit :disabled="isRead"/>
        </el-form-item>
        <el-form-item label="用户姓名" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入用户姓名" maxlength="32" show-word-limit/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" show-word-limit/>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <treeselect v-model="form.deptId" :options="treeDataList" placeholder="请选择部门" value-key="id"
                      :disable-branch-nodes="true" noChildrenText="没有数据了" noOptionsText="没有数据了"
                      noResultsText="没有搜索结果"/>
        </el-form-item>
        <el-form-item label="所属团队" prop="teamIds">
          <el-select
            v-model="form.teamIds"
            placeholder="请选择所属团队"
            class="form-item"
            multiple
          clearable>
          <el-option
            v-for="item in teamOptions"
            :key="item.teamId"
            :label="item.teamName"
            :value="item.teamId">
          </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择系统角色" class="form-item" clearable>
            <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
            <el-button class="clear-btn" @click="handleClose" :disabled="disabled">取消</el-button>
            <el-button type="primary" class="search-btn" :disabled="disabled"
                       @click="submitForm('ruleForm')">确认</el-button>
        </span>

  </el-dialog>
</template>
<script>
import _ from 'lodash'
import {
  addUser,
  updateUser,
} from '@/api/system/user'
import { getDeptSelectApi, getRoleSelectApi } from '@/api/select'
import { listTeamAPI } from '@/api/system/team'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { validMobile } from '@/utils/validate'

export default {
  name: "UserForm",
  props: ["width", "dataForm", "title", "disabled", "isAdd", "rowData"],
  components: { Treeselect },
  data() {
    return {
      lDialog: this.width > 500 ? "w700" : "w500",
      dialogVisible: true,
      isDisabled: true,
      form: {
        userName: null,
        nickName: null,
        phonenumber: null,
        deptId: undefined,  // 原有部门字段：保持不变
        teamIds: [],        // 新增：团队ID数组（存储多选的团队ID）
        roleId: undefined
      },
      treeDataList: [],
      checkTreeData: [],
      loading: null,
      roleOptions: [],
      teamOptions: [],      // 新增：团队下拉选项列表
      phonenumberDes: null,
      rules: {
        userName: [
          { required: true, message: '请输入用户账号', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: (rule, value, callback) => this.validateMobile(rule, value, callback), trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '请选择所属部门', trigger: 'change' }
        ],
        teamIds: [
          { required: true, message: '请至少选择一个所属团队', trigger: 'change' },
          { type: 'array', min: 1, message: '请至少选择一个所属团队', trigger: 'change' }
        ],
        roleId: [
          { required: true, message: '请选择系统角色', trigger: 'change' }
        ],
      },
      errorObj: {
        userName: '用户账号',
        nickName: '用户姓名',
        phonenumber: '手机号码',
        deptId: '所属部门',
        teamIds: '所属团队'
      },

    };
  },
  created() {
    this.initFormData();
  },
  computed: {
    isRead(){
      return this.isAdd === 'edit';
    }
  },
  methods: {
    // 手机号校验（中国大陆，支持可选国家码）
    validateMobile(rule, value, callback) {
      const str = String(value || '').trim()
      if (!str) return callback()
      if(!this.phonenumberDes || this.phonenumberDes !== this.form.phonenumber){
        if (!validMobile(str)) {
          return callback(new Error('请输入合法的手机号码'))
        }
      }

      callback()
    },
    /** 初始化表单数据 */
    async initFormData() {
      // 加载角色列表：原有逻辑
      await getRoleSelectApi().then(res => {
        this.roleOptions = res.data;
      });
      // 加载部门树
      await getDeptSelectApi().then(res => {
        this.treeDataList = this.convertToVueTree(res.data);
      });
      //加载团队列表
      await listTeamAPI().then(res => {
        this.teamOptions = res.rows || [];
      });

      if ((this.isAdd === 'edit' || this.isAdd === 'detail') && this.rowData) {
        console.log(this.rowData)
        // 编辑模式：填充表单数据
        this.form = {
          userId: this.rowData.userId || null,
          userName: this.rowData.userName || undefined,
          nickName: this.rowData.nickName || undefined,
          phonenumber: this.rowData.phonenumberDes || null,
          deptId: this.rowData.deptId || null,  // 原有部门字段：保持不变
          teamIds: this.rowData.teamIds ?
            (Array.isArray(this.rowData.teamIds) ? this.rowData.teamIds : [this.rowData.teamIds]) :
            [],
          roleId: this.rowData.roles[0]?.roleId || null, // 可选链避免报错
        };
        this.phonenumberDes = this.rowData.phonenumberDes || null;
      } else {
        // 新增模式：重置表单
        this.form = {
          userName: null,
          nickName: null,
          phonenumber: null,
          deptId: undefined,
          teamIds: [],        // 团队初始化为空数组
          roleId: undefined
        };
      }
    },

    closeDialog() {
      this.isflag = false;
    },
    showColose() {
      this.isflag = false;
    },
    /*关闭弹窗 */
    handleClose() {
      this.dialogVisible = false;
      this.$emit("closeDialog");
    },
    /**确认弹窗 */
    sureBtnClick() {
      this.dialogVisible = false;
      this.$emit("closeDialog");
    },
    /**重置表单*/
    reset() {
      this.form = {
        userName: null,
        nickName: null,
        phonenumber: null,
        deptId: undefined,
        teamIds: [],        // 团队重置为空数组
        roleId: undefined
      };
      this.$refs.ruleForm.resetFields(); // 修正原有错误的重置方法
    },
    handleReuslt(res) {
      this.$modal.msgSuccess(res.msg);
      this.reset();
      this.$emit('handleQuery');
      this.handleClose();
    },
    /**验证 */
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 显示遮罩层
          this.loading = this.$loading({
            lock: true,
            text: "数据提交中，请稍候...",
            background: 'rgba(0,0,0,0.5)',
            target: this.$el.querySelector('.el-dialog') || document.body
          })
          let params = _.cloneDeep(this.form);

          console.log(params);

          if (this.isAdd === 'add') {
            addUser(params).then(res => {
              this.loading.close();
              if (res.code === 200) {
                this.handleReuslt(res);
              } else {
                this.$modal.msgError(res.msg);
              }
            }).catch(error => {
              this.loading.close();
              this.$modal.msgError(this.errorMsg(error));
            });
          } else {
            updateUser(params).then(res => {
              this.loading.close();
              if (res.code === 200) {
                this.handleReuslt(res);
              } else {
                this.$modal.msgError(res.msg);
              }
            }).catch(error => {
              this.loading.close();
              this.$modal.msgError(this.errorMsg(error));
            });
          }
        }
      });
    },
    // 树数据过滤 - 支持无限层级转换（原有逻辑：保持不变）
    convertToVueTree(data, level = 1) {
      if (!data || !Array.isArray(data)) {
        return []
      }

      return data.map(item => {
        const node = {
          id: item.deptId,
          label: item.deptName,
        }

        if (item.children && Array.isArray(item.children) && item.children.length > 0) {
          if (level < 3) {
            const children = this.convertToVueTree(item.children, level + 1)
            if (children.length > 0) node.children = children
          }
        }

        return node
      })
    },
    findNodeById(nodes, id) {
      for (const node of nodes) {
        if (node.id === id) return node;
        if (node.children) {
          const found = this.findNodeById(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },
    errorMsg(error) {
      const errorMessage = error.message;
      const errorArr = errorMessage.split('：');
      const errorObjData = errorArr.length > 1 ? JSON.parse(errorArr[1]) : '';
      if(errorObjData){
        return this.errorObj[errorObjData.paramName] + errorArr[0] + ':' + errorObjData.originalValue;
      }else{
        return errorMessage;
      }

    }
  }
};
</script>
<style lang="scss" scoped>
.w700 ::v-deep .el-dialog {
  width: 700px;
}

.w500 ::v-deep .el-dialog {
  width: 500px;
}

.w500 ::v-deep .el-dialog__header,
.w700 ::v-deep .el-dialog__header {
  .el-dialog__title {
    font-size: 16px;
  }
}

.yxq .el-range-separator {
  margin-right: 7px !important;
}

.el-date-editor--daterange.el-input__inner {
  width: 260px;
}

.form-item {
  width: 100%;
}

.select-style {
  display: flex;
  justify-content: space-between;
}

/* 新增：优化多选团队的显示样式 */
::v-deep .el-select__tags {
  flex-wrap: wrap;
}
::v-deep .el-select__tag {
  margin: 2px;
}
</style>
