<template>
  <div class="app-container">
    <el-dialog
      :title="$t('ec.resource.sync')"
      :close-on-click-modal="false"
      width="80%"
      :visible.sync="visible"
      top="4%"
    >
      <el-row v-loading="sourceLoading || targetLoading || saveLoading" :gutter="24">
        <el-col :span="12">
          <el-form ref="sourceForm" inline :model="copyModel" label-width="110px">
            <el-form-item :label="$t('ec.copyModal.sourceTenant')" v-if="enableTenant" prop="sourceTenantId">
              <ec-tenant
                v-model="copyModel.sourceTenantId"
                clearable
                filterable
                @change="(tenantId) => getSourceRsrcData(tenantId, copyModel.sourceAppId)"
              />
            </el-form-item>
            <el-form-item :label="$t('ec.copyModal.sourceApp')" prop="sourceAppId" :rules="[{ required: true, message: $t('ec.copyModal.sourceApp') + $t('ec.table.emptyError'), trigger: 'blur'}]">
              <ec-register-app
                v-model="copyModel.sourceAppId"
                :tenant-id="copyModel.sourceTenantId"
                :clearable="true"
                filterable
                @change="(appId) => getSourceRsrcData(copyModel.sourceTenantId, appId)"
              />
            </el-form-item>
          </el-form>
          <el-alert :title="$t('ec.resource.sourceResource')" type="warning" :closable="false" show-icon />
          <vxe-virtual-tree
            ref="sourceRsrcVxe"
            row-key
            show-overflow
            show-header-overflow
            border
            highlight-hover-row
            max-height="1000"
            class="vxe-table-element"
            resizable
            sync-resize
            auto-resize
            :loading="sourceLoading"
            :columns="sourceColumns"
            :tree-config="{children: 'children'}"
            :data="sourceRsrcData"
            :checkbox-config="{ checkStrictly: checkStrictly, checkField: 'checked', halfField: 'indeterminate'}"
          />
          <el-switch v-model="checkStrictly" :active-value="false" :inactive-value="true" active-text="级联选择" />

        </el-col>
        <el-col :span="12">
          <el-form ref="targetForm" inline :model="copyModel" label-width="110px">
            <el-form-item :label="$t('ec.copyModal.targetTenant')" v-if="enableTenant" prop="targetTenantId">
              <ec-tenant
                v-model="copyModel.targetTenantId"
                clearable
                filterable
                @change="(tenantId) => getTargetRsrcData(tenantId, copyModel.targetAppId)"
              />
            </el-form-item>
            <el-form-item :label="$t('ec.copyModal.targetApp')" prop="targetAppId" :rules="[{ required: true, message: $t('ec.copyModal.targetApp') + $t('ec.table.emptyError'), trigger: 'blur'}]">
              <ec-register-app
                v-model="copyModel.targetAppId"
                :tenant-id="copyModel.targetTenantId"
                :clearable="true"
                filterable
                @change="(appId) => getTargetRsrcData(copyModel.targetTenantId, appId)"
              />
            </el-form-item>
          </el-form>
          <el-alert :title="$t('ec.resource.targetResource')" type="warning" :closable="false" show-icon />
          <vxe-grid
            ref="targetRsrcVxe"
            border
            highlight-hover-row
            max-height="1000"
            class="vxe-table-element"
            resizable
            sync-resize
            auto-resize
            :loading="targetLoading"
            :columns="targetColumns"
            :tree-config="{children: 'children'}"
            :data="targetRsrcData"
          />
        </el-col>
      </el-row>
      <span 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>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getData, syncResource } from 'ecip-web/api/vue/resource/sysrResourceApi'
const enableTenant =
    window._CONFIG['enableTenant'] === undefined
        ? true
        : window._CONFIG['enableTenant']

export default {
  name: 'RsrcSyncModal',
  data() {
    return {
      visible: false,
      enableTenant,
      checkStrictly: false,
      sourceLoading: false,
      targetLoading: false,
      saveLoading: false,
      sourceRsrcData: [],
      targetRsrcData: [],
      sourceColumns: [
        { type: 'checkbox', width: 40, fixed: 'left', align: 'center' },
        { title: 'ec.resource.name', field: 'rsrcName', minWidth: 200, treeNode: true, showOverflow: true },
        { title: 'ec.table.code', field: 'code', minWidth: 200, showOverflow: true },
        { title: 'ec.table.enableStatus', field: 'rsrcStatus', minWidth: 200, showOverflow: true, formatter: ['dict', 'enableState'] }
      ],
      targetColumns: [
        { title: 'ec.resource.name', field: 'rsrcName', minWidth: 200, treeNode: true, showOverflow: true },
        { title: 'ec.table.code', field: 'code', minWidth: 200, showOverflow: true },
        { title: 'ec.table.enableStatus', field: 'rsrcStatus', minWidth: 200, showOverflow: true, formatter: ['dict', 'enableState'] }
      ],
      copyModel: {
        sourceTenantId: '',
        sourceAppId: '',
        targetTenantId: '',
        targetAppId: '',
        sourceIdList: []
      }
    }
  },
  methods: {
    init() {
      this.visible = true
      this.$nextTick(() => {
        this.sourceRsrcData = []
        this.targetRsrcData = []
        this.$refs.sourceForm.resetFields()
        this.$refs.targetForm.resetFields()
        this.copyModel.sourceIdList = []
      })
    },
    // 源资源
    async getSourceRsrcData(tenantId, appId) {
      if (!appId) {
        this.sourceRsrcData = []
        return
      }
      try {
        this.sourceLoading = true
        const { data } = await getData({ tenantId: tenantId, appId: appId })
        this.sourceRsrcData = data
      } finally {
        this.sourceLoading = false
      }
    },
    // 目标资源
    async getTargetRsrcData(tenantId, appId) {
      if (!appId) {
        this.targetRsrcData = []
        return
      }
      try {
        this.targetLoading = true
        const { data } = await getData({ tenantId: tenantId, appId: appId })
        this.targetRsrcData = data
      } finally {
        this.targetLoading = false
      }
    },
    async save() {
      this.copyModel.sourceIdList = this.$refs.sourceRsrcVxe.getCheckboxRecords().map(item => item.id)
      if (this.copyModel.sourceIdList.length === 0) {
        this.$notify.warning(this.$t('ec.message.selectEmpty'))
        return
      }
      let sourceValid = false
      let targetValid = false
      await this.$refs.sourceForm.validate(valid => { sourceValid = valid })
      await this.$refs.targetForm.validate(valid => { targetValid = valid })

      if (sourceValid && targetValid) {
        try {
          this.saveLoading = true
          await syncResource(this.copyModel)
          // this.visible = false
          this.$notify.success(this.$t('ec.resource.sync') + this.$t('ec.message.success'))
          await this.getTargetRsrcData(this.copyModel.targetTenantId, this.copyModel.targetAppId)
        } finally {
          this.saveLoading = false
        }
      } else {
        this.$notify.warning(this.$t('ec.table.verifyError'))
      }
    }
  }
}
</script>

<style scoped>
.el-alert {
  margin-bottom: 10px;
}
.el-switch {
  margin-top: 10px;
}
</style>
