<template>
	<sc-dialog v-model="visible" title="选择用户授权项目" :width="500" @closed="$emit('closed')">
		<el-form ref="dialogForm" :model="form" label-width="112px">
			<el-row :gutter="15">
				<el-col :xs="24">
					<el-form-item label="用户授权项目:">
                        <el-select v-model="form.projectId" multiple filterable clearable collapse-tags collapse-tags-tooltip placeholder="请选择用户授权项目">
                            <el-option v-for="item in projects" :key="item.id" :label="item.projectName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
				</el-col>
			</el-row>
		</el-form>

		<template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit">确 定</el-button>
		</template>
	</sc-dialog>
</template>

<script>
	export default {
		emits: ["success", "closed"],

		data() {
			return {
				visible: false,
				isSaveing: false,
                projects: [],

				form: {
					userId: null,
					projectId: [],
					projectIds: ""
				}
			}
		},

        mounted() {
            this.getProjects();
        },

		methods: {
			// 显示
			open() {
				this.visible = true;
				return this;
			},

            async getProjects() {
                this.projects = await this.$API.system.project.all({ orderBy: "id_desc", projectStatus: "active" });
            },

			// 表单注入数据
			async setData(data) {
                this.form.userId = data.id;
                const userPro = await this.$API.system.userProject.get({ userId: data.id });
                this.form.projectId = userPro.map(p => p.projectId);
                this.form.projectIds = this.form.projectId.join();
            },

			// 表单提交方法
			submit() {
				this.$refs.dialogForm.validate(valid => {
					if (valid) {
                        const data = {
                            userId: this.form.userId,
                            projectIds: this.form.projectId.join()
                        }

						this.isSaveing = true;
						this.$API.system.userProject.saveBatch(data).then(() => {
							this.isSaveing = false;
							this.$message.success("操作成功");
							this.visible = false;
							this.$emit("success", this.mode);
						}).catch(() => this.isSaveing = false);
					} else {
						return false;
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
.el-form {
  padding: 10px 30px;
}

@media (max-width: 992px) {
  .el-form {
    padding: 10px;
  }
}
</style>