<template>
  <div class="app-container">
    <el-card shadow="never" class="mb8">
      <div slot="header"><span>字典同步配置</span></div>
      <el-form ref="syncForm" :model="syncForm" label-width="110px" size="small">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="同步模式" required>
              <el-select v-model="syncForm.syncMode" style="width: 100%">
                <el-option label="MERGE - 合并（推荐）" value="MERGE" />
                <el-option label="APPEND - 仅追加缺失项" value="APPEND" />
                <el-option label="OVERWRITE - 覆盖平台管控项" value="OVERWRITE" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="租户范围" required>
              <el-select v-model="syncForm.scopeType" style="width: 100%">
                <el-option label="全部启用租户" value="ALL" />
                <el-option label="仅指定租户" value="INCLUDE" />
                <el-option label="排除指定租户" value="EXCLUDE" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="并行执行">
              <el-switch v-model="syncForm.parallel" />
              <el-input-number v-if="syncForm.parallel" v-model="syncForm.threads" :min="1" :max="16" style="margin-left: 12px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="指定租户" v-if="syncForm.scopeType !== 'ALL'">
              <el-select v-model="syncForm.tenantIds" multiple filterable placeholder="选择租户" style="width: 100%">
                <el-option v-for="t in tenantOptions" :key="t.id" :label="t.tenantName + ' (' + t.tenantCode + ')'" :value="t.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典类型">
              <el-select v-model="syncForm.dictTypes" multiple filterable clearable placeholder="空=全部模板类型" style="width: 100%">
                <el-option v-for="t in templateTypeOptions" :key="t.dictType" :label="t.dictName + ' / ' + t.dictType" :value="t.dictType" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="syncForm.syncMode === 'OVERWRITE'">
          <el-checkbox v-model="syncForm.overwriteConfirm">我已了解 OVERWRITE 将覆盖各租户中「平台管控」的字典项，租户自有扩展项不受影响</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="info" icon="el-icon-view" @click="handleSync(true)" v-hasPermi="['tenant:dict:sync']">全量预览</el-button>
          <el-button type="warning" icon="el-icon-upload2" @click="handleSync(false)" v-hasPermi="['tenant:dict:sync']">开始同步</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" v-if="previewList.length">
      <div slot="header">预览结果（未写入）</div>
      <el-table :data="previewList" border size="small">
        <el-table-column label="租户" prop="tenantName" />
        <el-table-column label="编码" prop="tenantCode" width="120" />
        <el-table-column label="新增类型" prop="typeAdded" width="90" align="center" />
        <el-table-column label="更新类型" prop="typeUpdated" width="90" align="center" />
        <el-table-column label="新增数据" prop="dataAdded" width="90" align="center" />
        <el-table-column label="更新数据" prop="dataUpdated" width="90" align="center" />
        <el-table-column label="跳过" prop="dataSkipped" width="80" align="center" />
        <el-table-column label="移除" prop="dataRemoved" width="80" align="center" />
      </el-table>
    </el-card>

    <el-card shadow="never" class="mt8" v-if="taskNo">
      <div slot="header">
        <span>同步任务 {{ taskNo }}</span>
        <el-button style="float: right" type="text" icon="el-icon-refresh" @click="pollTask">刷新</el-button>
      </div>
      <el-descriptions :column="4" border size="small" v-if="taskInfo">
        <el-descriptions-item label="状态"><el-tag :type="taskStatusType">{{ taskInfo.status }}</el-tag></el-descriptions-item>
        <el-descriptions-item label="模式">{{ taskInfo.syncMode }}</el-descriptions-item>
        <el-descriptions-item label="成功/总数">{{ taskInfo.successTenants }} / {{ taskInfo.totalTenants }}</el-descriptions-item>
        <el-descriptions-item label="失败">{{ taskInfo.failedTenants }}</el-descriptions-item>
      </el-descriptions>
      <el-table v-if="taskInfo && taskInfo.details" :data="taskInfo.details" border size="small" class="mt8">
        <el-table-column label="租户" prop="tenantName" />
        <el-table-column label="状态" prop="status" width="90" />
        <el-table-column label="新增类型" prop="typeAdded" width="90" align="center" />
        <el-table-column label="更新类型" prop="typeUpdated" width="90" align="center" />
        <el-table-column label="新增数据" prop="dataAdded" width="90" align="center" />
        <el-table-column label="更新数据" prop="dataUpdated" width="90" align="center" />
        <el-table-column label="跳过" prop="dataSkipped" width="80" align="center" />
        <el-table-column label="错误" prop="errorMsg" :show-overflow-tooltip="true" />
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { tenantList } from '@/api/tenant/tenant'
import { runDictSync, getDictSyncTask, previewDictSync, templateDictTypeOptions } from '@/api/tenant/dict'

export default {
  name: 'TenantDictSync',
  data() {
    return {
      tenantOptions: [],
      templateTypeOptions: [],
      previewList: [],
      taskNo: '',
      taskInfo: null,
      pollTimer: null,
      syncForm: {
        syncMode: 'MERGE',
        scopeType: 'ALL',
        tenantIds: [],
        dictTypes: [],
        parallel: true,
        threads: 4,
        overwriteConfirm: false,
        dryRun: false
      }
    }
  },
  computed: {
    taskStatusType() {
      const s = this.taskInfo && this.taskInfo.status
      if (s === 'SUCCESS') return 'success'
      if (s === 'FAILED') return 'danger'
      if (s === 'PARTIAL') return 'warning'
      return 'info'
    }
  },
  created() {
    tenantList().then(r => { this.tenantOptions = r.rows || r.data || [] })
    templateDictTypeOptions().then(r => { this.templateTypeOptions = r.data || [] })
  },
  beforeDestroy() {
    if (this.pollTimer) clearInterval(this.pollTimer)
  },
  methods: {
    buildPayload(dryRun) {
      return {
        syncMode: this.syncForm.syncMode,
        scopeType: this.syncForm.scopeType,
        tenantIds: this.syncForm.scopeType === 'ALL' ? [] : this.syncForm.tenantIds,
        dictTypes: this.syncForm.dictTypes,
        parallel: this.syncForm.parallel,
        threads: this.syncForm.threads,
        overwriteConfirm: this.syncForm.overwriteConfirm,
        dryRun: dryRun
      }
    },
    handlePreview() {
      if (this.syncForm.scopeType === 'INCLUDE' && (!this.syncForm.tenantIds || !this.syncForm.tenantIds.length)) {
        this.$message.warning('请选择要预览的租户')
        return
      }
      const tenantId = this.syncForm.scopeType === 'INCLUDE' ? this.syncForm.tenantIds[0] : (this.tenantOptions[0] && this.tenantOptions[0].id)
      if (!tenantId) {
        this.$message.warning('无可用租户')
        return
      }
      previewDictSync(tenantId, this.syncForm.dictTypes).then(r => {
        this.previewList = r.data || []
        this.$message.success('预览完成（仅首个租户示例，完整预览请用 dryRun 同步）')
      })
    },
    handleSync(dryRun) {
      if (this.syncForm.syncMode === 'OVERWRITE' && !this.syncForm.overwriteConfirm) {
        this.$message.error('OVERWRITE 模式请先勾选确认')
        return
      }
      if (this.syncForm.scopeType !== 'ALL' && (!this.syncForm.tenantIds || !this.syncForm.tenantIds.length)) {
        this.$message.warning('请选择租户')
        return
      }
      this.$confirm(dryRun ? '确认预览同步差异？' : '确认开始字典同步任务？', '提示', { type: 'warning' }).then(() => {
        return runDictSync(this.buildPayload(dryRun))
      }).then(r => {
        const data = r.data || {}
        if (data.dryRun) {
          this.previewList = data.preview || []
          this.$message.success('全量预览完成')
          return
        }
        this.taskNo = data.taskNo
        this.taskInfo = { status: 'RUNNING', syncMode: data.syncMode, totalTenants: data.totalTenants, successTenants: 0, failedTenants: 0, details: [] }
        this.startPoll()
        this.$message.success('同步任务已启动')
      }).catch(() => {})
    },
    startPoll() {
      if (this.pollTimer) clearInterval(this.pollTimer)
      this.pollTask()
      this.pollTimer = setInterval(() => this.pollTask(), 3000)
    },
    pollTask() {
      if (!this.taskNo) return
      getDictSyncTask(this.taskNo).then(r => {
        this.taskInfo = r.data
        if (this.taskInfo && ['SUCCESS', 'FAILED', 'PARTIAL'].includes(this.taskInfo.status)) {
          clearInterval(this.pollTimer)
          this.pollTimer = null
        }
      })
    }
  }
}
</script>

<style scoped>
.mb8 { margin-bottom: 12px; }
.mt8 { margin-top: 12px; }
</style>
