<template>
  <div class="wps365-config">
    <div class="config-container">
      <!-- 左侧：配置表单 -->
      <div class="config-left">
        <!-- 授权状态 -->
        <el-card class="config-section">
          <div slot="header" class="section-header">
            <i class="el-icon-key"></i>
            <span>授权状态</span>
          </div>
          <div class="auth-status">
            <el-tag v-if="isAuthorized" type="success" size="medium">
              <i class="el-icon-circle-check"></i> 已授权
            </el-tag>
            <el-tag v-else type="danger" size="medium">
              <i class="el-icon-circle-close"></i> 未授权
            </el-tag>
            <el-button
              v-if="!isAuthorized"
              type="primary"
              size="small"
              icon="el-icon-unlock"
              @click="handleAuthorize"
              style="margin-left: 10px;"
            >
              立即授权
            </el-button>
            <el-button
              v-else
              type="info"
              size="small"
              icon="el-icon-refresh"
              @click="handleRefreshAuth"
              style="margin-left: 10px;"
            >
              刷新状态
            </el-button>
          </div>
          <div v-if="isAuthorized && tokenInfo" class="token-info" style="margin-top: 15px;">
            <el-descriptions :column="2" border size="small">
              <el-descriptions-item label="用户ID">{{ tokenInfo.userId || '-' }}</el-descriptions-item>
              <el-descriptions-item label="Token状态">
                <el-tag v-if="tokenInfo.isValid" type="success" size="small">有效</el-tag>
                <el-tag v-else type="warning" size="small">已过期</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="有效期" v-if="tokenInfo.expiresIn">
                {{ Math.floor(tokenInfo.expiresIn / 60) }} 分钟
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>

        <!-- 文档配置表单 -->
        <el-card class="config-section">
          <div slot="header" class="section-header">
            <i class="el-icon-document"></i>
            <span>H-TF订单自动写入配置</span>
            <el-tag v-if="config.isConfigured" type="success" size="mini" style="margin-left: 10px;">
              <i class="el-icon-success"></i> 已配置
            </el-tag>
            <el-tag v-else type="warning" size="mini" style="margin-left: 10px;">
              <i class="el-icon-warning"></i> 未配置
            </el-tag>
          </div>
          <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
            <el-form-item label="文件ID" prop="fileId">
              <el-input
                v-model="form.fileId"
                placeholder="例如：VbHZwButmh（从WPS365在线表格URL中获取）"
                clearable
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="handleTestRead"
                  :disabled="!form.fileId || !isAuthorized"
                >
                  测试读取
                </el-button>
              </el-input>
            </el-form-item>

            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="表头行号" prop="headerRow">
                  <el-input-number
                    v-model="form.headerRow"
                    :min="1"
                    controls-position="right"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="起始行号" prop="startRow">
                  <el-input-number
                    v-model="form.startRow"
                    :min="1"
                    controls-position="right"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item>
              <el-button type="primary" @click="handleSave" :loading="saveLoading" icon="el-icon-check">
                保存配置
              </el-button>
              <el-button @click="handleTest" :loading="testLoading" icon="el-icon-setting">
                测试配置
              </el-button>
              <el-button @click="handleClear" :loading="clearLoading" type="danger" plain icon="el-icon-delete">
                清除配置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 右侧：状态信息 -->
      <div class="config-right">
        <!-- 配置状态提示 -->
        <el-card class="status-card-wrapper">
          <div class="status-card" :class="config.isConfigured ? 'success' : 'warning'">
            <div class="status-icon" :class="config.isConfigured ? 'success' : 'warning'">
              <i :class="config.isConfigured ? 'el-icon-success' : 'el-icon-warning'"></i>
            </div>
            <div class="status-text">
              <div class="status-title">{{ config.isConfigured ? '配置完成' : '配置未完成' }}</div>
              <div class="status-desc">{{ config.hint || (config.isConfigured ? 'H-TF订单将自动写入WPS365在线表格' : '请完成配置') }}</div>
            </div>
          </div>
        </el-card>

        <!-- 快速帮助 -->
        <el-card class="help-card-wrapper">
          <div slot="header" class="card-header">
            <i class="el-icon-question"></i>
            <span>配置说明</span>
          </div>
          <div class="help-content">
            <div class="help-item">
              <i class="el-icon-check"></i>
              <span>文件ID从WPS365在线表格URL中获取</span>
            </div>
            <div class="help-item">
              <i class="el-icon-check"></i>
              <span>点击"测试读取"验证文件ID是否正确</span>
            </div>
            <div class="help-item">
              <i class="el-icon-check"></i>
              <span>表头行号默认为第2行</span>
            </div>
            <div class="help-item">
              <i class="el-icon-check"></i>
              <span>数据起始行默认为第3行</span>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getWPS365AuthUrl,
  getWPS365TokenStatus,
  readWPS365AirSheetCells,
  updateWPS365AirSheetCells
} from '@/api/jarvis/wps365'

export default {
  name: 'WPS365Config',
  data() {
    return {
      isAuthorized: false,
      userId: null,
      tokenInfo: null,
      config: {
        isConfigured: false,
        hint: ''
      },
      form: {
        fileId: '',
        headerRow: 2,
        startRow: 3
      },
      rules: {
        fileId: [
          { required: true, message: '请输入文件ID', trigger: 'blur' }
        ],
        headerRow: [
          { required: true, message: '请输入表头行号', trigger: 'blur' },
          { type: 'number', min: 1, message: '表头行号必须大于0', trigger: 'blur' }
        ],
        startRow: [
          { required: true, message: '请输入数据起始行', trigger: 'blur' },
          { type: 'number', min: 1, message: '数据起始行必须大于0', trigger: 'blur' }
        ]
      },
      saveLoading: false,
      testLoading: false,
      clearLoading: false
    }
  },
  created() {
    this.checkAuthStatus()
    this.loadConfig()
  },
  methods: {
    /** 刷新配置 */
    refresh() {
      this.checkAuthStatus()
      this.loadConfig()
    },

    /** 检查授权状态 */
    async checkAuthStatus() {
      try {
        const response = await getWPS365TokenStatus(this.userId)
        if (response.code === 200) {
          this.isAuthorized = response.data.hasToken && response.data.isValid
          this.tokenInfo = response.data
          if (response.data.userId) {
            this.userId = response.data.userId
          }
        }
      } catch (error) {
        console.error('检查授权状态失败', error)
      }
    },

    /** 加载配置 */
    async loadConfig() {
      try {
        // TODO: 从后端加载配置
        // 暂时从localStorage读取
        const savedConfig = localStorage.getItem('wps365_auto_write_config')
        if (savedConfig) {
          const config = JSON.parse(savedConfig)
          this.form.fileId = config.fileId || ''
          this.form.headerRow = config.headerRow || 2
          this.form.startRow = config.startRow || 3
          this.config.isConfigured = !!(config.fileId)
        }
      } catch (error) {
        console.error('加载配置失败', error)
      }
    },

    /** 处理授权 */
    async handleAuthorize() {
      try {
        const response = await getWPS365AuthUrl()
        if (response.code === 200) {
          const width = 600
          const height = 700
          const left = (window.screen.width - width) / 2
          const top = (window.screen.height - height) / 2

          window.open(
            response.data,
            'WPS365授权',
            `width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
          )

          this.$message.success('授权页面已打开，请在新窗口中完成授权')

          const messageHandler = (event) => {
            if (event.data && event.data.type === 'wps365_oauth_callback') {
              window.removeEventListener('message', messageHandler)
              if (event.data.userId) {
                this.userId = event.data.userId
              }
              setTimeout(() => {
                this.checkAuthStatus()
                this.$message.success('授权完成')
              }, 500)
            }
          }
          window.addEventListener('message', messageHandler)

          setTimeout(() => {
            this.checkAuthStatus()
          }, 3000)
        }
      } catch (error) {
        this.$message.error('获取授权URL失败：' + (error.msg || error.message))
      }
    },

    /** 刷新授权状态 */
    async handleRefreshAuth() {
      await this.checkAuthStatus()
      this.$message.success('授权状态已刷新')
    },

    /** 测试读取 */
    async handleTestRead() {
      if (!this.isAuthorized || !this.userId) {
        this.$message.warning('请先完成授权')
        return
      }
      if (!this.form.fileId) {
        this.$message.warning('请输入文件ID')
        return
      }

      this.$message.info('正在测试读取...')
      try {
        const response = await readWPS365AirSheetCells({
          userId: this.userId,
          fileId: this.form.fileId,
          worksheetId: '0', // AirSheet中worksheetId通常是整数，0表示第一个工作表
          range: 'A1:B5'
        })
        if (response.code === 200) {
          this.$message.success('读取成功！文件ID正确。')
          console.log('读取结果:', response.data)
        } else {
          this.$message.warning('读取失败: ' + (response.msg || '未知错误'))
        }
      } catch (error) {
        this.$message.error('读取失败: ' + (error.msg || error.message))
        console.error('读取错误:', error)
      }
    },

    /** 保存配置 */
    async handleSave() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) {
          return false
        }
        if (!this.isAuthorized) {
          this.$message.warning('请先完成授权')
          return
        }

        this.saveLoading = true
        try {
          // TODO: 保存到后端
          // 暂时保存到localStorage
          const config = {
            fileId: this.form.fileId,
            headerRow: this.form.headerRow,
            startRow: this.form.startRow
          }
          localStorage.setItem('wps365_auto_write_config', JSON.stringify(config))
          this.config.isConfigured = true
          this.config.hint = 'H-TF订单将自动写入WPS365在线表格'
          this.$message.success('配置保存成功')
        } catch (error) {
          this.$message.error('保存配置失败: ' + (error.msg || error.message))
        } finally {
          this.saveLoading = false
        }
      })
    },

    /** 测试配置 */
    async handleTest() {
      if (!this.isAuthorized || !this.userId) {
        this.$message.warning('请先完成授权')
        return
      }
      this.$refs.form.validate(async (valid) => {
        if (!valid) {
          return false
        }

        this.testLoading = true
        try {
          // 测试读取
          const readResponse = await readWPS365AirSheetCells({
            userId: this.userId,
            fileId: this.form.fileId,
            worksheetId: '0', // AirSheet中worksheetId通常是整数，0表示第一个工作表
            range: 'A1:B5'
          })
          if (readResponse.code !== 200) {
            this.$message.error('读取测试失败: ' + (readResponse.msg || '未知错误'))
            return
          }

          // 测试写入（写入测试数据）
          const testRange = `A${this.form.startRow}:B${this.form.startRow}`
          const testValues = [['测试数据1', '测试数据2']]
          const writeResponse = await updateWPS365AirSheetCells({
            userId: this.userId,
            fileId: this.form.fileId,
            worksheetId: '0', // AirSheet中worksheetId通常是整数，0表示第一个工作表
            range: testRange,
            values: testValues
          })
          if (writeResponse.code === 200) {
            this.$message.success('配置测试成功！读写功能正常。')
          } else {
            this.$message.warning('写入测试失败: ' + (writeResponse.msg || '未知错误'))
          }
        } catch (error) {
          this.$message.error('配置测试失败: ' + (error.msg || error.message))
          console.error('测试错误:', error)
        } finally {
          this.testLoading = false
        }
      })
    },

    /** 清除配置 */
    async handleClear() {
      this.$confirm('确定要清除配置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearLoading = true
        try {
          // TODO: 清除后端配置
          localStorage.removeItem('wps365_auto_write_config')
          this.form.fileId = ''
          this.form.headerRow = 2
          this.form.startRow = 3
          this.config.isConfigured = false
          this.config.hint = ''
          this.$message.success('配置已清除')
        } catch (error) {
          this.$message.error('清除配置失败: ' + (error.msg || error.message))
        } finally {
          this.clearLoading = false
        }
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.wps365-config {
  padding: 0;
}

.config-container {
  display: flex;
  gap: 20px;
}

.config-left {
  flex: 1;
  min-width: 0;
}

.config-right {
  width: 300px;
  flex-shrink: 0;
}

.config-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.auth-status {
  display: flex;
  align-items: center;
}

.token-info {
  margin-top: 15px;
}

.status-card-wrapper {
  margin-bottom: 20px;
}

.status-card {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 4px;
}

.status-card.success {
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
}

.status-card.warning {
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
}

.status-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin-right: 15px;
}

.status-icon.success {
  background-color: #67c23a;
  color: white;
}

.status-icon.warning {
  background-color: #e6a23c;
  color: white;
}

.status-text {
  flex: 1;
}

.status-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.status-desc {
  font-size: 12px;
  color: #909399;
}

.help-card-wrapper {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.help-content {
  padding: 10px 0;
}

.help-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
  font-size: 13px;
  color: #606266;
}

.help-item i {
  color: #67c23a;
}
</style>
