<template>
  <div>
    <div style="margin-bottom: 16px;">
      <el-button type="primary" @click="openCreateDialog">新增策略组</el-button>
    </div>

    <el-table :data="policyGroups" border>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="groupCode" label="策略组编码" />
      <el-table-column prop="groupName" label="策略组名称" />
      <el-table-column prop="channelType" label="渠道类型" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
          <el-tag v-else type="info">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button link type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.status === 1" link type="warning" @click="handleToggleStatus(scope.row, 0)">禁用</el-button>
          <el-button v-else link type="success" @click="handleToggleStatus(scope.row, 1)">启用</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑策略组' : '新增策略组'" width="600px">
      <el-form :model="dialogForm" label-width="100px">
        <el-form-item label="策略组编码">
          <el-input v-model="dialogForm.group_code" :disabled="isEdit" placeholder="唯一编码" />
        </el-form-item>
        <el-form-item label="策略组名称">
          <el-input v-model="dialogForm.group_name" placeholder="显示名称" />
        </el-form-item>
        <el-form-item label="渠道类型">
          <el-select v-model="dialogForm.channel_type" placeholder="选择渠道类型" style="width: 100%">
            <el-option label="企微" value="wecom" />
            <el-option label="个人微信" value="wechat_personal" />
            <el-option label="短信" value="sms" />
            <el-option label="IVR" value="ivr" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="dialogForm.status" placeholder="状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="策略配置">
          <el-input v-model="dialogForm.policies" type="textarea" :rows="10" placeholder='JSON 数组，例如：[{"rule":"channel_type","value":"wecom"}]' />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listPolicyGroups,
  createPolicyGroup,
  updatePolicyGroup,
  updatePolicyGroupStatus,
  deletePolicyGroup,
} from '@/api/sendPolicy'

const policyGroups = ref<any[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)

const dialogForm = reactive({
  group_code: '',
  group_name: '',
  channel_type: '',
  status: 1,
  policies: '[]',
})

async function loadPolicyGroups() {
  try {
    const res: any = await listPolicyGroups()
    policyGroups.value = res.data || []
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

function resetDialogForm() {
  dialogForm.group_code = ''
  dialogForm.group_name = ''
  dialogForm.channel_type = ''
  dialogForm.status = 1
  dialogForm.policies = '[]'
}

function openCreateDialog() {
  isEdit.value = false
  resetDialogForm()
  dialogVisible.value = true
}

function openEditDialog(row: any) {
  isEdit.value = true
  dialogForm.group_code = row.groupCode
  dialogForm.group_name = row.groupName
  dialogForm.channel_type = row.channelType
  dialogForm.status = row.status
  try {
    const policies = row.policies ? JSON.parse(row.policies) : []
    dialogForm.policies = JSON.stringify(policies, null, 2)
  } catch {
    dialogForm.policies = row.policies || '[]'
  }
  dialogVisible.value = true
}

function buildPayload() {
  let policies
  try {
    policies = JSON.parse(dialogForm.policies)
  } catch {
    throw new Error('策略配置不是有效的 JSON')
  }
  return {
    groupCode: dialogForm.group_code,
    groupName: dialogForm.group_name,
    channelType: dialogForm.channel_type,
    status: dialogForm.status,
    policies,
  }
}

async function handleSave() {
  try {
    const payload = buildPayload()
    if (isEdit.value) {
      await updatePolicyGroup(dialogForm.group_code, payload)
      ElMessage.success('更新成功')
    } else {
      await createPolicyGroup(payload)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    await loadPolicyGroups()
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleToggleStatus(row: any, status: number) {
  try {
    await updatePolicyGroupStatus(row.groupCode, status)
    ElMessage.success(status === 1 ? '已启用' : '已禁用')
    await loadPolicyGroups()
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm('确定删除该策略组吗？', '提示', { type: 'warning' })
    await deletePolicyGroup(row.groupCode)
    ElMessage.success('删除成功')
    await loadPolicyGroups()
  } catch (e: any) {
    if (e !== 'cancel') {
      ElMessage.error(e.message)
    }
  }
}

onMounted(() => {
  loadPolicyGroups()
})
</script>
