<template>
  <el-drawer
    title="应用角色配置"
    :visible.sync="visible"
    :direction="direction"
    size="40%"
  >
    <div class="appRole-detail">
      <section>
        <el-form ref="form" v-loading="loading" :model="formItem" label-width="100px">
          <el-form-item
            :label="$t('ec.role.name')"
            prop="roleName"
            :rules="[
              {required: true, message: $t('ec.role.name') + $t('ec.table.emptyError'), trigger:'blur'}
            ]"
          >
            <el-input v-model="formItem.roleName" type="text" :placeholder="$t('ec.role.name')"  maxlength="64" />
          </el-form-item>
          <el-form-item
            :label="$t('ec.role.code')"
            prop="code"
            :rules="[
              {required: true, message: $t('ec.role.code') + $t('ec.table.emptyError'), trigger:'blur'},
              {validator: validateCode, trigger:'blur'}
            ]"
          >
            <el-input v-model="formItem.code" type="text" :placeholder="$t('ec.role.code')"  maxlength="32" />
          </el-form-item>
          <el-form-item
            v-if="superAdmin && enableTenant===true"
            :label="$t('ec.user.tenant')"
            prop="tenantId"
          >
            <ec-tenant v-model="formItem.tenantId" />
          </el-form-item>
          <el-form-item
            v-if="superAdmin"
            :label="$t('ec.app.app')"
            prop="appId"
            :rules="[
              {required: true, message: $t('ec.app.app') + $t('ec.table.emptyError'), trigger:'blur'}
            ]"
          >
            <ec-register-app v-model="formItem.appId" :tenantId="formItem.tenantId" :clearable="false" filterable :default-first="false" />
          </el-form-item>
          <el-form-item
            :label="$t('ec.table.status')"
            prop="status"
            :rules="[
            ]"
          >
            <ec-radio-group v-model="formItem.status" dict-type="enableState" />
          </el-form-item>
          <el-form-item
            :label="$t('ec.table.sort')"
            prop="sortNum"
            :rules="[
            ]"
          >
            <el-input-number v-model="formItem.sortNum" type="text" :placeholder="$t('ec.table.sort')" />
          </el-form-item>
          <el-form-item
            :label="$t('ec.role.remarks')"
            prop="remark"
            :rules="[
            ]"
          >
            <div v-if="!editRemark">
              <p style="margin: 0">
                {{ formItem.remark }}
                <br>
                <span style="color: gray">{{ formItem.remarkInfo }}</span>
              </p>
              <el-button type="text" size="large" @click="editRemark=true">{{ $t('ec.role.editRemarks') }}</el-button>
            </div>
            <el-input v-else v-model="formItem.remark" type="textarea" :autosize="{minRows: 3, maxRows: 5}" />
          </el-form-item>
        </el-form>

        <footer>
          <el-button @click="visible = false">{{ $t('ec.table.close') }}</el-button>
          <el-button v-if="method !== 'view'" type="primary" :loading="saveLoading" @click="save">{{ $t('ec.table.confirm') }}</el-button>
        </footer>

        <el-tabs style="padding-left: 20px;padding-right: 20px;">
          <el-tab-pane :label="$t('ec.role.rsrcAuth')">
            <rsrc-auth-tab
              ref="rsrcAuthTab"
              :role-id="role.id || ''"
            />
          </el-tab-pane>
        </el-tabs>
      </section>
    </div>
  </el-drawer>
</template>
<script>
import mixin from 'ecip-web/utils/common-mixin'
import { getById, saveRoleAndResource, update, checkCode } from 'ecip-web/api/vue/role/sysrRoleApi'
import { cloneDeep } from 'ecip-web/utils'
import RsrcAuthTab from '../components/rsrcAuthTab'
const enableTenant = window._CONFIG['enableTenant'] === undefined ? true : window._CONFIG['enableTenant']
export default {
  name: 'AppRoleDetail',
  components: { RsrcAuthTab },
  mixins: [...mixin],
  data() {
    return {
      enableTenant,
      direction: 'rtl',
      visible: false,
      loading: false,
      saveLoading: false,
      role: {},
      method: '',
      title: '',
      editRemark: true,
      formItem: {
        tenantId: '',
        appId: '',
        name: '',
        code: '',
        roleName: '',
        status: '1',
        sortNum: 30,
        remark: ''
      }
    }
  },
  watch: {
    'formItem.tenantId': function(tenantId) {
      this.$refs.rsrcAuthTab.init(this.formItem.appId, tenantId)
    },
    'formItem.appId': function(appId) {
      this.$refs.rsrcAuthTab.init(appId, this.formItem.tenantId)
    }
  },
  methods: {
    init(method, tenantId, appId, row) {
      this.method = method
      this.role = row || {}
      if (method === 'add') {
        this.title = this.$t('ec.table.add')
      } else if (method === 'edit') {
        this.title = this.$t('ec.table.edit') + row.roleName
      } else if (method === 'view') {
        this.title = this.$t('ec.table.view') + row.roleName
      }
      this.visible = true
      this.loading = false
      this.$nextTick(async() => {
        // 清空初始化
        this.$refs.form.clearValidate()
        this.$refs.form.resetFields()
        Object.assign(this.$data.formItem, this.$options.data().formItem)
        this.formItem.tenanId = tenantId
        this.formItem.appId = appId
        this.$refs.rsrcAuthTab.init(appId, tenantId)
        if (method === 'edit' || method === 'view') { // 修改或者查看
          try {
            this.loading = true
            const { data } = await getById(row.id)
            if (data.remark) {
              this.editRemark = false
            }
            // this.formItem = data
            cloneDeep(this.formItem, data)
          } finally {
            this.loading = false
          }
        }
      })
    },
    getData() {
      if (this.id) { //  编辑
        getById(this.id).then(res => {
          this.formItem = res.data
          if (res.data.remark) {
            this.editRemark = false
          }
        })
      } else {
        this.formItem = {
        }
      }
    },
    async validateCode(rule, value, callback) {
      const { data } = await checkCode((this.role && this.role.id) || '', value, this.formItem.tenantId, this.formItem.appId)
      if (data.valid) {
        callback()
      } else {
        callback(new Error(this.$t('ec.table.code') + this.$t('ec.table.exist')))
      }
    },
    save() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            this.saveLoading = true
            if (this.method === 'edit') {
              await update(this.role.id, this.formItem)
            } else {
              const c = this.$refs.rsrcAuthTab.rsrcSelected.map(item => item.id)
              await saveRoleAndResource({ sysrRole: this.formItem, resourceIds: c })
            }
            this.$notify.success(this.$t('ec.message.saveSuccess'))
            this.$emit('refreshData')
            this.visible = false
          } finally {
            this.saveLoading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
 .appRole-detail{
   position: relative;
   height: 100%;
   overflow: hidden;
   >section{
     height: calc(100% - 100px);
     overflow-y: scroll;
     >footer{
       display: flex;
       align-items: center;
       justify-content: center;
       height: 60px;
     }
   }

 }
</style>
<style lang="scss">
 .appRole-detail{
    .app-container{
      padding-left: 0;
      padding-top: 0;
    }
 }
</style>
