<template>
  <div>
    <el-dialog
      class="permission "
      :title="`${record.realName}-` + $t('ec.table.permission')"
      :visible.sync="visible"
      width="80%"
      top="4%"
      :append-to-body="isAppendBody"
    >
      <el-form
        v-loading="loading"
        label-suffix=":"
      >
        <el-form-item
          v-if="showTenantSelect && userTenantId"
          :label="$t('ec.user.tenant')"
          style="padding-left: 12px;"
        >
          <ec-user-tenant
            ref="ecUserTenant"
            v-model="userTenantId"
            @getData="getUserTenantData"
            @getTenantListData="getTenantListData"
          />
        </el-form-item>
        <el-form-item
          :label="$t('ec.user.accessibleApp')"
          label-width="100px"
          style="margin-bottom: 0;"
        >
          <el-select
            v-model="accessedAppList"
            style="display: block"
            multiple
            clearable
            filterable
            :placeholder="$t('ec.user.accessibleApp')"
            @change="selectChange"
          >
            <el-option
              v-for="item in appList"
              :key="item.appId"
              :label="item.appName"
              :value="item.appId"
            />
          </el-select>
        </el-form-item>
        <div
          v-loading="loading"
          class="permission-content"
        >
          <el-card
            v-for="(item, index) in appRoles"
            :key="item.appId"
            style="margin-top: 20px"
          >
            <div
              slot="header"
              class=""
              style="display: flex;justify-content: space-between;"
            >
              <div><strong>{{ item.appName }}</strong></div>
              <div style="display: flex;justify-content: space-between;">
                <span style="display: flex;align-items: center;">组织机构：</span>
                <ec-dept-select
                  :data="{ appId: item.appId }"
                  v-model="appRoles[index].deptId"
                  placeholder="组织机构过滤"
                  check-strictly
                />
              </div>
            </div>
            <div v-if="item.roleList && item.roleList.length === 0">
              <el-alert
                :closable="false"
                type="info"
                :title="$t('ec.app.noRole')"
                show-icon
              />
            </div>
            <div v-else>
              <el-form-item
                :label="$t('ec.user.role')"
                :inline="true"
                style="margin-bottom: 0"
              >
                <el-checkbox-group
                  v-model="appRoles[index].userRoles"
                  style="display: inline-block;"
                >

                  <template v-for="role in item.roleList">
                    <el-checkbox
                      :key="role.id"
                      :label="role.id"
                      v-if="roleNameShowBol(item.deptId, role.deptId, role.id, item.userRoles)"
                    >
                      <!-- v-if="(appRoles[index].deptId && role.deptId === appRoles[index].deptId) || !appRoles[index].deptId && !role.deptId" -->
                      {{ role.roleName }}
                    </el-checkbox>
                  </template>

                </el-checkbox-group>
              </el-form-item>
            </div>
          </el-card>
        </div>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="visible = false">{{ $t('ec.table.close') }}</el-button>
        <el-button
          type="primary"
          :loading="saveLoading"
          @click="save"
        >{{ $t('ec.table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { accessibleAppsByTenantNew } from 'ecip-web/api/vue/app/sysrRegisterAppApi'
import {
  findUserApp,
  findAppRoles,
  saveAppByTenantId
} from 'ecip-web/api/vue/user/sysrUserApi'
import de from 'element-ui/src/locale/lang/de'
export default {
  name: 'UserAllRoleVue',
  computed: {
    de() {
      return de
    }
  },
  data() {
    return {
      isAppendBody: false,
      appLoading: false,
      saveLoading: false,
      visible: false,
      loading: false,
      record: {},
      appRoles: [],
      accessedAppList: [],
      appList: [],
      userTenantId: '',
      showTenantSelect: true,
      deptId: ''
    }
  },
  methods: {
    roleNameShowBol(deptId, roleDeptId, roleId, userRoles) {
      const BolA = (deptId && roleDeptId === deptId) || (!deptId && !roleDeptId)

      let BolB = false

      // 组织机构为空时
      if (!deptId) {
        if (roleId && userRoles) {
          // 显示所有已选过的选项
          userRoles.find((one) => {
            return (BolB = one === roleId)
          })
        }
      }

      return BolA || BolB
    },

    getTenantListData(list) {
      this.showTenantSelect = Boolean(list && list.length > 2)
    },
    init(row, isAppendBody) {
      // 是否在最外层，多层dialog嵌套时用
      this.isAppendBody = Boolean(isAppendBody)
      this.visible = true
      this.record = row
      this.userTenantId = row.tenantId
      this.showTenantSelect = true

      this.$nextTick(() => {
        if (this.userTenantId) {
          this.$refs.ecUserTenant.init()
        }
        this.tenantChange(row.tenantId)
      })
    },
    getUserTenantData(userTenantId) {
      this.tenantChange(userTenantId)
    },
    async tenantChange(userTenantId) {
      this.userTenantId = userTenantId
      this.appLoading = true
      await this.findTenantAccessApps(userTenantId)
      await this.findUserApps(this.record.id, userTenantId)
      await this.findAppRoles(
        this.record.id,
        userTenantId,
        this.accessedAppList
      )
      this.loading = false
    },
    async findTenantAccessApps(tenantId) {
      const { data } = await accessibleAppsByTenantNew({
        tenantId: tenantId,
        userId: this.record.id
      })
      this.appList = data
    },
    async findUserApps(userId, tenantId) {
      const { data } = await findUserApp({ userId, tenantId })
      this.accessedAppList = data
    },
    async findAppRoles(userId, tenantId, accessedAppList) {
      try {
        this.loading = true
        const { data } = await findAppRoles(userId, tenantId, accessedAppList)
        this.appRoles = data
      } finally {
        this.loading = false
      }
    },
    async selectChange(e) {
      // 过滤已存在的
      const existedAppRoles = this.appRoles.filter((item) =>
        e.includes(item.appId)
      )
      const existedAppIds = existedAppRoles.map((item) => item.appId)

      const unExistedAppIds = e.filter(
        (appId) => !existedAppIds.includes(appId)
      )

      // 封装新增选中
      if (unExistedAppIds && unExistedAppIds.length > 0) {
        this.loading = true
        const { data } = await findAppRoles(
          this.record.id,
          this.userTenantId,
          unExistedAppIds
        )
        this.loading = false
        this.appRoles = existedAppRoles.concat(data)
        return
      }
      // 设置结果
      this.appRoles = existedAppRoles
    },
    async save() {
      const appIds = []
      let roleIds = []
      this.appRoles.forEach((item) => {
        appIds.push(item.appId)
        roleIds = roleIds.concat(item.userRoles)
      })
      this.saveLoading = true
      // await saveUserApps(this.record.id, appIds)
      // await saveUserRoles(this.record.id, roleIds)
      try {
        await saveAppByTenantId({
          userId: this.record.id,
          tenantId: this.userTenantId,
          appIds,
          roleIds
        })
        this.$emit('change', appIds, roleIds)
        this.$notify.success(this.$t('ec.user.userPermissionSuccess'))
        this.visible = false
        this.saveLoading = false
      } catch (e) {
        this.saveLoading = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
.permission {
  .permission-content {
    max-height: 57vh;
    overflow-y: scroll;
  }
}
</style>
