<template>
  <el-dialog title="模块配置" :visible.sync="visible" width="700px" append-to-body @close="handleClose">
    <el-transfer
      v-model="selectedModules"
      :data="allModules"
      :titles="['可用模块', '已选模块']"
      :props="{ key: 'moduleId', label: 'moduleName' }"
      filterable
      filter-placeholder="请输入模块名称"
    ></el-transfer>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listModule } from '@/api/generator/module';
// Assuming listProjectModules, addProjectModule, delProjectModule are correctly added to project.js
import { listProjectModules, addProjectModule, delProjectModule } from '@/api/generator/project';

export default {
  name: 'ProjectModuleConfig',
  data() {
    return {
      visible: false,
      projectId: null,
      allModules: [], // All available modules { moduleId, moduleName, ... }
      selectedModules: [], // Array of moduleId for selected modules in the transfer component
      // To store the original project-module relationship objects { id, projectId, moduleId, ... }
      // This is needed to get the 'id' (relationship PK) for deletion.
      projectModuleRelations: []
    }
  },
  methods: {
    async init(projectId) {
      this.projectId = projectId
      this.visible = true
      this.selectedModules = []
      this.allModules = []
      this.projectModuleRelations = []
      await this.loadAllModules()
      await this.loadProjectModules()
    },
    async loadAllModules() {
      this.loadingAll = true
      try {
        // Assuming modules are not excessively numerous, otherwise pagination/search would be needed
        const response = await listModule({ pageNum: 1, pageSize: 1000 })
        this.allModules = response.rows.map(module => ({
          moduleId: module.moduleId,
          moduleName: module.moduleName
          // disabled: module.status === '1' // Example: disable selection if module is inactive
        }))
      } catch (error) {
        this.$modal.msgError('加载可用模块列表失败')
        console.error('Error loading all modules:', error)
      } finally {
        this.loadingAll = false
      }
    },
    async loadProjectModules() {
      if (!this.projectId) return
      this.loadingProjectModules = true
      try {
        const response = await listProjectModules(this.projectId, { pageNum: 1, pageSize: 1000 })
        this.projectModuleRelations = response.rows // Store the full relation objects
        this.selectedModules = response.rows.map(pm => pm.moduleId) // Populate transfer with moduleIds
      } catch (error) {
        this.$modal.msgError('加载项目已选模块失败')
        console.error('Error loading project modules:', error)
      } finally {
        this.loadingProjectModules = false
      }
    },
    async submitForm() {
      if (!this.projectId) {
        this.$modal.msgError('项目ID丢失，无法保存')
        return
      }

      this.saving = true
      try {
        // 1. Identify IDs of relations to be deleted
        // These are relations present initially but whose moduleId is NOT in the final selectedModules list
        const currentRelationModuleIds = this.projectModuleRelations.map(r => r.moduleId)
        const relationIdsToDelete = this.projectModuleRelations
          .filter(relation => !this.selectedModules.includes(relation.moduleId))
          .map(relation => relation.id)

        if (relationIdsToDelete.length > 0) {
          await delProjectModule(relationIdsToDelete.join(','))
        }

        // 2. Identify moduleIds to be added
        // These are moduleIds in selectedModules that were not in the initial projectModuleRelations
        const modulesToAdd = this.selectedModules.filter(moduleId =>
          !currentRelationModuleIds.includes(moduleId)
        )

        const addPromises = modulesToAdd.map(moduleId => {
          return addProjectModule({ projectId: this.projectId, moduleId: moduleId })
        })

        await Promise.all(addPromises)

        this.$modal.msgSuccess('模块配置保存成功')
        this.visible = false
        this.$emit('ok') // Notify parent to refresh or take action
      } catch (error) {
        console.error('Error saving project modules:', error)
        this.$modal.msgError('模块配置保存失败: ' + (error.message || '请查看控制台'))
      } finally {
        this.saving = false
      }
    },
    cancel() {
      this.visible = false
      this.handleClose()
    },
    handleClose() {
      // Reset data when dialog is closed
      this.visible = false
      this.projectId = null
      this.allModules = []
      this.selectedModules = []
      this.projectModuleRelations = []
    }
  }
}
</script>

<style scoped>
.el-transfer {
  display: flex;
  justify-content: center; /* Center the transfer component */
  align-items: center;
}
/* Ensure transfer panels have enough width */
::v-deep .el-transfer-panel {
  width: 250px; /* Adjust as needed */
}
</style> 