<template>
  <div class="app-container">
    <el-dialog
      class="tenantAppModal "
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      top="4%"
    >
      <el-form v-loading="loading" label-width="240px">
        <el-form-item :label="$t('ec.user.tenant')" label-width="180px">
          <el-row>
            <el-col :span="20">
              <el-select v-model="selectedTenants" multiple clearable filterable :placeholder="$t('ec.user.tenant')" @change="selectChange">
                <el-option
                  v-for="item in tenantList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
<!--        <el-form-item v-for="(item, index) in appTenants" :key="item.tenantId" :label="item.tenantName" style="margin: 10px 0">-->
<!--          <el-row>-->
<!--            <el-col :span="14">-->
<!--              <ec-date-range-->
<!--                v-model="appTenants[index]"-->
<!--                begin-key="startDate"-->
<!--                end-key="endDate"-->
<!--                date-type="datetimerange"-->
<!--                format="yyyy-MM-dd HH:mm:ss"-->
<!--                :start-placeholder="$t('ec.date.effectiveTime')"-->
<!--                :end-placeholder="$t('ec.date.expirationTime')"-->
<!--              />-->
<!--            </el-col>-->
<!--            <el-col :offset="3" :span="7">-->
<!--              <span style="cursor: pointer" @click="removeOne(item.tenantId)"><i class="el-icon-remove-outline" /></span>-->
<!--            </el-col>-->
<!--          </el-row>-->
<!--        </el-form-item>-->
      </el-form>

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

<script>
import { getTenantList } from 'ecip-web/api/vue/tenant/saasTenantApi'
import { getTenantByApp, saveAppTenants } from 'ecip-web/api/vue/center/saasTenantAppApi'
import { dateFormat } from 'ecip-web/utils/tableUtil'

export default {
  name: 'AppTenantModal',
  data() {
    return {
      visible: false,
      loading: false,
      saveLoading: false,
      title: '',
      record: {},
      selectedTenants: [], // 已选租户列表
      tenantList: [], //  租户下拉列表
      appTenants: [] //  系统已分配租户信息
    }
  },
  methods: {
    init(row) {
      this.visible = true
      this.record = row
      this.title = this.$t('ec.app.setTenant', { appName: row && row.appName || ''})
      this.getTenantList()
      this.getTenantByApp()
    },
    async getTenantList() {
      this.loading = true
      const { data } = await getTenantList()
      this.tenantList = data
      this.loading = false
    },
    async getTenantByApp() {
      this.loading = true
      const { data } = await getTenantByApp(this.record.appId)
      this.appTenants = data
      this.selectedTenants = data.map(item => item.tenantId)
      this.loading = false
    },
    selectChange(e) {
      // 拿到已选租户实体
      const tenants = this.tenantList.filter(item => e.includes(item.id))

      const appTenantIds = this.appTenants.map(item => item.tenantId)

      // 过滤已存在的
      const existedAppTenants = this.appTenants.filter(item => e.includes(item.tenantId))

      let unExistedAppTenants = tenants.filter(item => !appTenantIds.includes(item.id))

      // 封装新增选中
      if (unExistedAppTenants && unExistedAppTenants.length > 0) {
        unExistedAppTenants = unExistedAppTenants.map(item => {
          return {
            tenantId: item.id,
            tenantName: item.name,
            appId: this.record.appId,
            startDate: dateFormat(new Date(), 'yyyy-MM-dd HH:mm:ss'),
            endDate: dateFormat(new Date(new Date().setDate(new Date().getDate() + 1)), 'yyyy-MM-dd HH:mm:ss')
          }
          // item.tenantId = item.id
          // item.appId = this.record.appId
          // item.tenantName = item.name
          // item.startDate = dateFormat(new Date(), 'yyyy-MM-dd HH:mm:ss')
          // item.endDate = dateFormat(new Date(new Date().setDate(new Date().getDate() + 1)), 'yyyy-MM-dd HH:mm:ss')
        })
      }

      // 设置结果
      this.appTenants = existedAppTenants.concat(unExistedAppTenants)
    },
    removeOne(tenantId) {
      this.appTenants = this.appTenants.filter(item => item.tenantId !== tenantId)
      this.selectedTenants = this.selectedTenants.filter(item => item !== tenantId)
    },
    confirm() {
      this.$confirm(this.record.appName + ':' + this.$t('ec.app.setTenantConfirm'), this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(async() => {
        try {
          this.saveLoading = true
          await saveAppTenants(this.record.appId, this.appTenants)
          this.$notify.success(this.$t('ec.message.saveSuccess'))
          this.visible = false
        } finally {
          this.saveLoading = false
        }
      })
    }
  }
}
</script>

<style scoped>
  .tenantAppModal >>> .el-select {
    display: block;
  }
</style>
