<template>
  <el-dialog
    v-if="visible"
    :visible.sync="visible"
    v-dialogDrag
    width="540px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    :title="$t('toggleRole:tip:title')"
    center
    top="30vh"
    :show-close="false"
    :before-close="cancel"
  >
    <template v-if="hasRole">
      <el-radio-group v-model="form.userRoleId" class="roles">
        <el-radio
          v-for="item in roles"
          :key="item.Id"
          :label="item.Id"
          :disabled="item.IsUserRoleDisabled"
          style="margin-bottom: 10px"
        >
          {{ item.UserTypeShortName }}
        </el-radio>
      </el-radio-group>
    </template>

    <div v-else style="text-align: center">
      {{ $t('toggleRole:tip:noRole') }}
    </div>
    <div slot="footer">
      <!-- 取消 -->
      <el-button size="small" @click="cancel()">
        {{ $t('common:button:cancel') }}
      </el-button>
      <!-- 保存 -->
      <el-button
        type="primary"
        size="small"
        @click="save"
        :disabled="saveDisabled"
        :loading="loading"
        v-if="hasRole"
      >
        {{ $t('common:button:confirm') }}
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
export default {
  name: 'toggleRole',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    loading: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      form: {
        userRoleId: null,
      },
    }
  },
  created() {
    this.form.userRoleId = zzSessionStorage.getItem('userId')
  },
  computed: {
    roles() {
      return this.$store.state.user.roles
    },
    hasRole() {
      return this.roles && this.roles.length > 0
    },
    saveDisabled() {
      return this.form.userRoleId === zzSessionStorage.getItem('userId')
    },
  },
  methods: {
    cancel() {
      this.$emit('update:visible', false)
      this.$emit('cancel')
    },
    async save() {
      try {
        if (!this.form.userRoleId)
          return this.$message.warning(this.$t('toggleRole:ruleMessage:select'))
          zzSessionStorage.removeItem('lastWorkbench')
        this.$emit('save', this.form.userRoleId)
      } catch (err) {
        console.log(err)
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.roles {
  max-width: 365px;
  width: fit-content;
  display: flex;
  align-content: center;
  // justify-content: center;
  flex-wrap: wrap;
  margin: auto;
}

::v-deep .el-radio__original {
  display: none !important; /* 隐藏原生 radio 输入，但仍然允许交互 */
}

::v-deep.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled)
  .el-radio__inner {
  box-shadow: none !important;
}
.el-radio {
  width: 60px;
}
</style>