<template>
  <section class="tagsManage">
    <el-form ref="PersonalAssets" :model="form" size="small" label-width="0" :rules="rules">
      <ai-edit-card title="标签信息" :show-btn="permissions('app_appresident_edit')"
                    @save="submitTags" @cancel="getTags">
        <template #edit>
          <el-form-item prop="tags">
            <el-checkbox-group v-model="form.tags">
              <el-checkbox v-for="tag in tags" :key="tag.id" :label="tag.id">
                {{ tag.labelName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </template>
        <template>
          <el-tag effect="dark" v-for="tag in selecteds" :key="tag.id">{{ tag.labelName }}</el-tag>
          <ai-empty v-if="selecteds.length==0"/>
        </template>
      </ai-edit-card>
    </el-form>
  </section>
</template>

<script>
import {mapState} from "vuex";
import AiEditCard from "./AiEditCard";

export default {
  name: "tagsManage",
  components: {AiEditCard},
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
    residentId: {required: true, default: ""}
  },
  computed: {
    ...mapState(['user'])
  },
  data() {
    return {
      tags: [],
      form: {tags: []},
      selecteds: [],
      rules: {
        tags: {required: true, message: "请选择标签信息"}
      }
    }
  },
  methods: {
    getOptions() {
      this.instance.post("/app/appresidentlabelinfo/list", null, {
        params: {size: 999}
      }).then(res => {
        if (res?.data) {
          this.tags = res.data.records
        }
      })
    },
    getTags() {
      //获取选取的标签
      let {residentId} = this
      this.instance.post("/app/appresidentlabel/list", null, {
        params: {residentId}
      }).then(res => {
        if (res?.data) {
          this.selecteds = res.data.records
          this.form.tags = res.data.records?.filter(e => e.labelType == 1)?.map(e => e.labelId) || []
        }
      })
    },
    submitTags(cb) {
      this.$refs.PersonalAssets.validate(v => {
        if (v) {
          let {residentId} = this, residentLabelList = this.tags.filter(e => this.form.tags.includes(e.id)).map(e => ({
            labelId: e.id,
            labelName: e.labelName
          }))
          this.instance.post("/app/appresidentlabel/update", {
            residentId, residentLabelList
          }).then(res => {
            if (res?.code == 0) {
              this.$message.success("提交成功")
              this.getTags()
              cb?.()
            }
          })
        }
      })
    },
  },
  created() {
    this.getTags()
    this.getOptions()
  }
}
</script>

<style lang="scss" scoped>
.tagsManage {
  .el-tag + .el-tag {
    margin-left: 16px;
  }
}
</style>
