<template>
  <div class="db-config-management">
    <!-- 查询条件区域 -->
    <el-card class="filter">
      <el-form class="demo-form-inline" :inline="true" :model="searchForm">
        <el-form-item label="店铺ID">
          <el-select v-model="searchForm.storeId" placeholder="请选择店铺ID">
            <el-option
              v-for="item in storeIdOptions"
              :key="item.store_id"
              :label="item.store_name"
              :value="item.store_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="是否有外网访问">
          <el-select v-model="searchForm.hasInternet" placeholder="请选择">
            <el-option label="有" value="1" />
            <el-option label="无" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="是否启用">
          <el-select v-model="searchForm.hasStart" placeholder="请选择">
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据列表区域 -->
    <el-card class="list">
      <div slot="header" class="tool">
        <el-button type="primary" @click="openAddDrawer">新增</el-button>
      </div>

      <el-table border :data="dbConfigList" stripe>
        <el-table-column label="店铺ID" prop="storeId" />
        <el-table-column label="数据库IP地址" prop="dbIp" />
        <el-table-column label="数据库类型" prop="dbType" />
        <el-table-column label="数据库名称" prop="dbName" />
        <el-table-column label="数据库端口" prop="dbPort" />
        <el-table-column label="数据库用户名" prop="dbUsername" />
        <el-table-column label="数据库密码" prop="dbPassword" />
        <el-table-column label="外网访问" prop="hasInternet">
          <template slot-scope="scope">
            <el-tag :type="scope.row.hasInternet === '1' ? 'success' : 'info'">
              {{ scope.row.hasInternet === '1' ? '有' : '无' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="同步模式" prop="syncMode">
          <template slot-scope="scope">
            {{ scope.row.syncMode === '1' ? '定时同步' : '间隔同步' }}
          </template>
        </el-table-column>
        <el-table-column label="是否启用" prop="hasStart">
          <template slot-scope="scope">
            <el-tag :type="scope.row.hasStart === '1' ? 'success' : 'danger'">
              {{ scope.row.hasStart === '1' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="同步表达式" prop="cronExpression" />
        <el-table-column label="备注信息" prop="remark" />
        <el-table-column label="刷新时间" prop="refreshTime" />
        <el-table-column label="是否双向同步" prop="isTowSync">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isTowSync === '1' ? 'success' : 'info'">
              {{ scope.row.isTowSync === '1' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="openEditDrawer(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <el-button
              size="mini"
              type="warning"
              @click="generateKey(scope.row)"
            >
              密钥生成
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        :current-page="pagination.pageNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 新增/编辑抽屉组件 -->
    <db-config-form
      ref="storeConfDrawerRef"
      :form-data="currentFormData"
      :is-edit="isEditMode"
      :store-id-options="storeIdOptions"
      @save="handleSave"
    />

    <!-- 密钥生成弹窗 -->
    <el-dialog title="生成密钥结果" :visible="keyDialogVisible" width="30%">
      <div>
        <p>您的密钥为：</p>
        <el-input v-model="generatedKey" readonly />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="keyDialogVisible = false">
            好的
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import DbConfigForm from './DbConfigForm.vue'
  import StoreConfApi from '@/api/storeConf'
  import GoodsToolApi from '@/api/goodsTool'
  import { omit } from 'lodash'

  export default {
    components: {
      DbConfigForm,
    },
    data() {
      return {
        searchForm: {
          storeId: '',
          hasInternet: '',
          hasStart: '',
        },
        storeIdOptions: [],
        dbConfigList: [],
        pagination: {
          pageNum: 1,
          pageSize: 10,
          total: 0,
        },
        total: 0,
        drawerVisible: false,
        currentFormData: {},
        isEditMode: false,
        keyDialogVisible: false,
        generatedKey: '',
      }
    },
    created() {
      this.getShopList()
      this.fetchDbConfigList()
    },
    methods: {
      async getShopList() {
        let res = await GoodsToolApi.getShopList()
        if (res.status == 200) {
          this.storeIdOptions = res.data.items
        }
      },

      // 获取数据库配置列表
      async fetchDbConfigList() {
        const params = {
          ...this.searchForm,
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize,
        }
        let res = {}

        res = await StoreConfApi.geConfList(params)

        if (res.status == 200) {
          this.dbConfigList = res.data.items
          this.pagination.total = res.data.records
        }
      },

      // 搜索
      handleSearch() {
        this.pagination.pageNum = 1
        this.pagination.pageSize = 10
        this.fetchDbConfigList()
      },

      // 重置搜索条件
      resetSearch() {
        this.searchForm = {
          storeId: '',
          hasInternet: '',
          hasStart: '',
        }
        this.pagination.pageNum = 1
        this.pagination.pageSize = 10
        this.handleSearch()
      },

      // 分页相关
      handleSizeChange(newSize) {
        this.pagination.pageSize = newSize
        this.fetchDbConfigList()
      },

      handleCurrentChange(newPage) {
        this.pagination.pageNum = newPage
        this.fetchDbConfigList()
      },

      // 打开新增抽屉
      openAddDrawer() {
        this.isEditMode = false
        this.currentFormData = {}
        this.$refs.storeConfDrawerRef.open()
      },

      // 打开编辑抽屉
      openEditDrawer(row) {
        this.isEditMode = true
        this.currentFormData = { ...row } // 深拷贝避免直接修改原数据
        this.$refs.storeConfDrawerRef.open()
      },

      // 处理保存
      async handleSave(data) {
        let res = null
        if (this.isEditMode) {
          res = await StoreConfApi.updateConfList({
            ...omit(data, ['refreshTime', 'isTowSync']),
          })
        } else {
          res = await StoreConfApi.createConfList(data)
        }

        if (res.status == 200) {
          this.$message.success('操作成功')
          this.fetchDbConfigList()
        }
        this.drawerVisible = false
      },

      // 处理删除
      handleDelete(row) {
        this.$confirm('确定要删除该配置吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(async () => {
          let res = await StoreConfApi.deleteConfList(row)

          if (res.status == 200) {
            this.$message.success('删除成功')
            this.fetchDbConfigList()
          } else {
            this.$message.error(res?.msg)
          }
        })
      },

      // 生成密钥
      generateKey(row) {
        this.$confirm('确定要生成新的密钥吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(async () => {
          let res = await StoreConfApi.createConfSecretkKey(row)

          if (res.status == 200) {
            this.generatedKey = res.data
            this.keyDialogVisible = true
          } else {
            this.$message.error(res?.msg)
          }
        })
      },
    },
  }
</script>

<style scoped>
  .filter {
    margin-bottom: 15px;
  }
  .list {
    .tool {
      display: flex;
      gap: 10px;
      ::v-deep .el-button {
        margin-left: 0 !important;
      }
    }
  }
</style>
