<template>
    <!-- 小型弹窗，用于完成，删除，保存等操作 -->
    <el-dialog class="l-dialog" :class="lDialog" :title="title" :visible.sync="dialogVisible" :showClose="true"
        :closeOnClickModal="false" @close="handleClose" :append-to-body="true">
        <div class="dialog-content-scrollable">
            <el-form :model="form" :rules="rules" ref="ruleForm" label-width="110px" label-position="top">
                <el-form-item label="团队名称" prop="teamName">
                    <el-input class="form-item" v-model="form.teamName" clearable show-word-limit placeholder="请输入团队名称"
                        maxlength="32"></el-input>
                </el-form-item>

            <el-form-item label="团队成员" prop="memberIds">
                <el-select
                    v-model="form.memberIds"
                    multiple
                    clearable
                    filterable
                    placeholder="请选择团队成员"
                    class="form-item"
                    v-loading="false">
                  <el-option
                    v-for="person in personList"
                    :key="person.userId"
                    :label="person.userName"
                    :value="person.userId">
                  </el-option>
                </el-select>
            </el-form-item>

                <el-form-item label="备注" prop="teamRemark">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" class="form-item"
                        v-model.trim="form.teamRemark" clearable show-word-limit placeholder="请输入备注"
                        maxlength="200" ></el-input>
                </el-form-item>
            </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" class="confirm-btn"
                @click="submitForm('ruleForm')">确认</el-button>
            <el-button class="cancel-btn" @click="handleClose">取消</el-button>
        </span>
    </el-dialog>
</template>
<script>
import _ from 'lodash'
import { addTeamAPI, editTeamAPI } from '@/api/system/team'
import { listUser } from '@/api/system/user'
// 默认参数
export default {
    name: "TeamForm",
    props: ["width", "rowData", "title", "isAdd"],
    data() {
        return {
            lDialog: this.width > 500 ? "w700" : "w500",
            dialogVisible: true,
            form: {
                teamId: null,
                teamName: '',
                teamRemark: '',
                memberIds: [],
            },
            rules: {
                teamName: [
                    { required: true, message: '团队名称不能为空', trigger: 'blur' }
                ],
            memberIds: [
                    { required: true, message: '请选择至少一名团队成员', trigger: 'change' }
                ],
            },
          personList: [], // 人员列表数据源
          personLoading: false // 人员列表加载状态
        };
    },
    watch: {
        isAdd: {
            handler(newVal) {
                if (newVal === 'edit') {
                    this.initFormData();
                }
            },
            immediate: true,
        },
    },

    created() {
      this.initPersonList();
    },

    methods: {

        async initPersonList() {
          try {
            this.personLoading = true;
            const res = await listUser({});
            if (res.code === 200) {
              const userList = res.rows || [];
              this.personList = userList.map(item => {
                return {
                  userId: item.userId, // 主键ID
                  userName: item.userName, // 显示名称
                };
              });
            } else {
              this.$modal.msgError('获取人员列表失败：' + res.msg);
            }
          } catch (error) {
            this.$modal.msgError('获取人员列表异常：' + error.message);
            console.error('获取人员列表失败：', error);
          } finally {
            this.personLoading = false;
          }
        },

        /** 初始化表单数据 */
        async initFormData() {
          if (!this.rowData) return;
            // 编辑模式：填充表单数据
            this.form = {
                teamId: this.rowData.teamId,
                teamName: this.rowData.teamName || '',
                teamRemark: this.rowData.teamRemark || '',
                memberIds: this.rowData.memberIds || [], // 回显已选的用户ID数组
            };
        },
        /*关闭弹窗 */
        handleClose() {
            this.dialogVisible = false;
            this.$emit("closeDialog");
        },
        /**确认弹窗 */
        sureBtnClick() {
            this.dialogVisible = false;
            this.$emit("closeDialog");
        },
        /**重置表单*/
        reset() {
            this.form = {
                teamId: null,
                teamName: '',
                teamRemark: '',
            };
            this.resetForm("ruleForm");
        },
        handleReuslt(res) {
            this.$modal.msgSuccess(res.msg);
            this.reset();
            this.$emit('handleQuery');
            this.handleClose();
        },
        validate(formName) {
            return new Promise((resolve, reject) => {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        resolve(this.form) // 校验成功返回表单数据
                    } else {
                        reject(new Error('数据未填写完整'))
                    }
                })
            })
        },
        /**验证 */
        async submitForm(formName) {
            try {
                const data = await this.validate(formName);
                // 所有校验通过，组装完整数据
                let formData = {
                    ...data,
                }
                // 显示遮罩层
                this.loading = this.$loading({
                    lock: true,
                    text: "数据提交中，请稍候...",
                    background: 'rgba(0,0,0,0.5)',
                    target: this.$el.querySelector('.el-dialog') || document.body
                })
                console.log('所有表单校验通过，完整数据:', formData)
                const res = await this.saveData(formData)
                if (res.code === 200) {
                    this.handleReuslt(res);
                } else {
                    this.$modal.msgError(res.msg);
                }
            } catch (error) {

            } finally {
                if(this.loading){
                    this.loading.close()
                }
            }
        },

        // 保存接口
        async saveData(formData) {
            return new Promise((resolve, reject) => {
                if (this.isAdd === 'add') { // 新增
                    addTeamAPI(formData).then(res => {
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                } else { // 修改
                    editTeamAPI(formData).then(res => {
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                }

            })
        },
    }
};
</script>
<style lang="scss" scoped>
.w700 ::v-deep .el-dialog {
    width: 700px;
    font-family: Source Han Sans CN, Source Han Sans CN;
    max-height: 90vh;
    display: flex;
    flex-direction: column;
    margin-top: 5vh !important;
    margin-bottom: 5vh !important;
}

.w500 ::v-deep .el-dialog {
    width: 500px;
    font-family: Source Han Sans CN, Source Han Sans CN;
    max-height: 90vh;
    display: flex;
    flex-direction: column;
    margin-top: 5vh !important;
    margin-bottom: 5vh !important;
}

// 弹窗主体区域
.w500 ::v-deep .el-dialog__body,
.w700 ::v-deep .el-dialog__body {
    flex: 1;
    overflow: hidden;
    padding: 20px;
    display: flex;
    flex-direction: column;
}

.w500 ::v-deep .el-dialog__header,
.w700 ::v-deep .el-dialog__header {
    flex-shrink: 0;
    border-bottom: 1px solid #EBEEF5;

    .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%;
}

::v-deep .el-select__tags {
  flex-wrap: wrap;
}

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

.confirm-btn {
    width: 98px;
    height: 36px;
    background: #1F72EA;
    box-shadow: 0px 4px 8px 0px rgba(51, 135, 255, 0.5);
    border-radius: 4px 4px 4px 4px;
    color: #fff;
    border: none;
    font-size: 14px;
    transition: all 0.3s;

    &:hover {
        background: #4A8BFF;
        box-shadow: 0px 6px 12px 0px rgba(51, 135, 255, 0.6);
    }
}

.cancel-btn {
    width: 98px;
    height: 36px;
    background: #E5E5E5;
    box-shadow: 0px 4px 8px 0px rgba(76, 76, 76, 0.2);
    border-radius: 4px 4px 4px 4px;
    color: #333;
    border: none;
    font-size: 14px;
    transition: all 0.3s;

    &:hover {
        background: #d0d0d0;
        box-shadow: 0px 6px 12px 0px rgba(76, 76, 76, 0.3);
    }
}

::v-deep .el-dialog__footer {
    text-align: center;
    flex-shrink: 0;
}

// 内容区域可滚动
.dialog-content-scrollable {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 6px;
    max-height: calc(90vh - 120px); // 减去头部和底部的高度

    // 自定义滚动条样式
    &::-webkit-scrollbar {
        width: 6px;
    }

    &::-webkit-scrollbar-track {
        background: transparent;
    }

    &::-webkit-scrollbar-thumb {
        background: rgba(0, 0, 0, 0.2);
        border-radius: 3px;

        &:hover {
            background: rgba(0, 0, 0, 0.3);
        }
    }
}
</style>
