<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, watch } from 'vue'

import {
  emptyListingSalePriceConfig,
  mergeListingSalePriceConfig,
  type PublishSalePriceConfig,
} from '@/features/listings/api/listingOptions'
import { updateSystemConfig, type SystemConfig } from '@/features/admin/api/systemConfigs'
import { safeParseJSON } from '@/utils/json'

const props = defineProps<{
  modelValue: boolean
  config: SystemConfig
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', val: boolean): void
  (e: 'saved'): void
}>()

const submitting = ref(false)
const description = ref('')
const salePriceConfigDraft = ref<PublishSalePriceConfig>(cloneSalePriceConfig(emptyListingSalePriceConfig))

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      salePriceConfigDraft.value = parseSalePriceConfig(props.config.value)
      description.value = props.config.description || ''
    }
  },
  { immediate: true }
)

function parseSalePriceConfig(raw: string) {
  const parsed = safeParseJSON(raw, emptyListingSalePriceConfig)
  return cloneSalePriceConfig(mergeListingSalePriceConfig(parsed))
}

function cloneSalePriceConfig(config: PublishSalePriceConfig) {
  return JSON.parse(JSON.stringify(config)) as PublishSalePriceConfig
}

function addSaleFixedMarkupRule() {
  salePriceConfigDraft.value.fixed_markup_rules.push({
    min_m: 0,
    max_m: 0,
    markup_amount: 0,
  })
}

function removeSaleFixedMarkupRule(index: number) {
  salePriceConfigDraft.value.fixed_markup_rules.splice(index, 1)
}

function addSaleRatioAdjustmentRule() {
  salePriceConfigDraft.value.ratio_adjustment_rules.push({
    min_m: 0,
    max_m: 0,
    ratio_subtract: 0,
  })
}

function removeSaleRatioAdjustmentRule(index: number) {
  salePriceConfigDraft.value.ratio_adjustment_rules.splice(index, 1)
}

async function handleSave() {
  submitting.value = true
  try {
    const value = JSON.stringify(salePriceConfigDraft.value, null, 2)
    await updateSystemConfig(props.config.key, {
      value,
      description: description.value,
    })
    ElMessage.success('配置已更新')
    emit('saved')
    emit('update:modelValue', false)
  } catch (error) {
    ElMessage.error(readError(error, '保存失败'))
  } finally {
    submitting.value = false
  }
}

function readError(error: unknown, fallback: string) {
  if (typeof error === 'object' && error && 'response' in error) {
    const response = (error as { response?: { data?: { message?: string } } }).response
    return response?.data?.message || fallback
  }
  return fallback
}
</script>

<template>
  <el-dialog
    :model-value="modelValue"
    title="编辑出售定价配置"
    width="920px"
    @update:model-value="emit('update:modelValue', $event)"
  >
    <div class="dialog-body">
      <p class="config-key-label"><strong>{{ config.key }}</strong></p>

      <div class="publish-options-editor">
        <div class="editor-toolbar">
          <span>内部出售定价规则</span>
        </div>

        <div class="editor-block">
          <div class="editor-block-title subtle-title">
            <span>90M 及以下固定加价：出售价格 = 回收价格 + 固定加价</span>
            <el-button size="small" @click="addSaleFixedMarkupRule">添加固定加价</el-button>
          </div>
          <el-table :data="salePriceConfigDraft.fixed_markup_rules" size="small" border>
            <el-table-column label="最小 M" min-width="120">
              <template #default="{ row }"><el-input-number v-model="row.min_m" :min="0" :step="10" /></template>
            </el-table-column>
            <el-table-column label="最大 M" min-width="120">
              <template #default="{ row }"><el-input-number v-model="row.max_m" :min="0" :step="10" /></template>
            </el-table-column>
            <el-table-column label="加价金额/元" min-width="140">
              <template #default="{ row }"><el-input-number v-model="row.markup_amount" :min="0" :step="1" /></template>
            </el-table-column>
            <el-table-column label="操作" width="90">
              <template #default="{ $index }">
                <el-button size="small" type="danger" plain @click="removeSaleFixedMarkupRule($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="editor-block-title subtle-title">
            <span>90M 以上比例修正：出售比例 = 回收比例 - 比例修正；最大 M 为 0 表示无上限</span>
            <el-button size="small" @click="addSaleRatioAdjustmentRule">添加比例修正</el-button>
          </div>
          <el-table :data="salePriceConfigDraft.ratio_adjustment_rules" size="small" border>
            <el-table-column label="最小 M" min-width="120">
              <template #default="{ row }"><el-input-number v-model="row.min_m" :min="0" :step="10" /></template>
            </el-table-column>
            <el-table-column label="最大 M" min-width="120">
              <template #default="{ row }"><el-input-number v-model="row.max_m" :min="0" :step="10" /></template>
            </el-table-column>
            <el-table-column label="比例修正" min-width="130">
              <template #default="{ row }"><el-input-number v-model="row.ratio_subtract" :min="0" :step="0.5" /></template>
            </el-table-column>
            <el-table-column label="操作" width="90">
              <template #default="{ $index }">
                <el-button size="small" type="danger" plain @click="removeSaleRatioAdjustmentRule($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <el-form-item label="配置说明" class="desc-item">
        <el-input v-model="description" type="textarea" :rows="3" placeholder="配置说明" />
      </el-form-item>
    </div>
    <template #footer>
      <el-button @click="emit('update:modelValue', false)">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-body {
  display: grid;
  gap: 16px;
  max-height: 65vh;
  overflow-y: auto;
  padding-right: 8px;
}

.config-key-label {
  margin: 0;
  color: #374151;
}

.publish-options-editor {
  display: grid;
  gap: 16px;
}

.editor-toolbar,
.editor-block-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.editor-toolbar span {
  color: #30343a;
  font-weight: 700;
}

.editor-block {
  display: grid;
  gap: 10px;
}

.subtle-title {
  margin-top: 6px;
  color: #4b5563;
  font-size: 13px;
}

.desc-item {
  margin-top: 14px;
  margin-bottom: 0;
}
</style>
