<template>
  <div class="app-container">
    <el-dialog
      class="tenantAppModal "
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      top="4%"
      width="60%"
    >
      <el-form v-loading="loading" label-width="240px">
        <el-form-item :label="$t('ec.app.app')" label-width="180px">
          <el-row>
            <el-col :span="20">
              <el-select v-model="selectedApps" multiple clearable filterable :placeholder="$t('ec.app.app')" @change="selectChange">
                <el-option
                  v-for="item in appList"
                  :key="item.appId"
                  :label="item.appName"
                  :value="item.appId"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <template v-for="(item, index) in tenantApps">
          <el-form-item :key="item.appId" :label="item.appName" style="margin: 10px 0">
            <el-row>
              <el-col :span="14">
                <ec-date-range
                  v-model="tenantApps[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.appId)"><i class="el-icon-remove-outline" /></span>
              </el-col>
            </el-row>

          </el-form-item>
        </template>
      </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 { getAppList } from 'ecip-web/api/vue/app/sysrRegisterAppApi'
import { getAppByTenant, saveTenantApps } from 'ecip-web/api/vue/center/saasTenantAppApi'
import { dateFormat } from 'ecip-web/utils/tableUtil'

export default {
  name: 'TenantAppModal',
  data() {
    return {
      visible: false,
      loading: false,
      saveLoading: false,
      title: '',
      record: {},
      selectedApps: [], // 已选系统列表
      appList: [], //  系统下拉列表
      tenantApps: [] //  租户已分配系统信息
    }
  },
  methods: {
    init(row) {
      this.visible = true
      this.record = row
      this.title = (row && row.name || '') + this.$t('ec.tenant.assignApp')
      this.getAppList()
      this.getAppByTenant()
    },
    async getAppList() {
      this.loading = true
      const { data } = await getAppList()
      this.appList = data
      this.loading = false
    },
    async getAppByTenant() {
      this.loading = true
      const { data } = await getAppByTenant(this.record.id)
      this.tenantApps = data
      this.selectedApps = data.map(item => item.appId)
      this.loading = false
    },
    selectChange(e) {
      // 拿到已选app实体
      const apps = this.appList.filter(app => e.includes(app.appId))

      const tenantAppIds = this.tenantApps.map(item => item.appId)

      // 过滤已存在的
      const existedTenantApps = this.tenantApps.filter(item => e.includes(item.appId))

      let unExistedTenantApps = apps.filter(app => !tenantAppIds.includes(app.appId))

      // 封装新增选中
      if (unExistedTenantApps && unExistedTenantApps.length > 0) {
        unExistedTenantApps = unExistedTenantApps.map(item => {
          return {
            tenantId: this.record.id,
            appName: item.appName,
            appId: item.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 = this.record.id
          // 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')
          // item.startDate = new Date()
          // item.endDate = new Date(new Date().setDate(new Date().getDate() + 1))
        })
      }

      // 设置结果
      this.tenantApps = existedTenantApps.concat(unExistedTenantApps)
    },
    removeOne(appId) {
      this.tenantApps = this.tenantApps.filter(item => item.appId !== appId)
      this.selectedApps = this.selectedApps.filter(item => item !== appId)
    },
    confirm() {
      this.$confirm(this.record.name + this.$t('ec.tenant.assignAppConfirm'), 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 saveTenantApps(this.record.id, this.tenantApps)
          this.$notify.success(this.$t('ec.tenant.assignAppSuccess'))
          this.close()
        } finally {
          this.saveLoading = false
        }
      })
    }
  }
}
</script>

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