<template>
  <div class="holidays-container table_form-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form inline :model="searchForm">
        <el-form-item label="节假日名称">
          <el-input v-model="searchForm.name" placeholder="请输入节假日名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" v-auth="'contractVariety_addHoliday'"
            :loading="loading">搜索</el-button>
          <el-button @click="handleReset" :loading="loading">重置</el-button>
        <el-button type="primary" :loading="syncLoading" @click="handleSyncRiskControl()" v-auth="'riskControl_editRiskControlSetting'">
          同步
        </el-button>
        </el-form-item>
      </el-form>
      <div class="search-right">
        <el-button type="primary" @click="handleAdd" v-auth="'contractVariety_addHoliday'">添加节假日</el-button>
      </div>
    </div>

    <!-- 列表区域：使用公共 Table 组件 -->
    <Table ref="tableRef" :table-data="tableData" :columns="tableColumns" row-key="id" :loading="loading">
      <!-- 操作列插槽 -->
      <template #action="{ row }">
        <el-button type="primary" size="small" @click="handleEdit(row)"
          v-auth="'contractVariety_addHoliday'">编辑</el-button>
        <el-button type="danger" size="small" @click="handleDel(row)"
          v-auth="'contractVariety_addHoliday'">删除</el-button>    
      </template>
    </Table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :destroy-on-close="true"
      @close="handleDialogClose">
      <Form ref="formRef" :form-data="formData" :form-rules="formRules" :form-items="formItems"
        :options-map="optionsMap">
        <!-- 休市市场多选插槽 -->
        <template #marketSelect>
          <el-select v-model="formData.groupId" multiple placeholder="请选择休市市场" style="width: 100%" clearable>
            <el-option v-for="market in marketList" :key="market.value" :label="market.label" :value="market.value" />
          </el-select>
        </template>
      </Form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { getGroupListApi } from '@/api/modules/trade/group'
import { getHolidayList, addHoliday, editHoliday, delHoliday } from '@/api/modules/trade/time'
import { ElMessage, ElMessageBox } from 'element-plus'
import { usePageLoading } from '@/composables/useLoading'
import Table from '@/components/common/Table.vue'
import Form from '@/components/common/Form.vue'
import {  syncRiskControlApi } from '@/api/modules/risk'

defineOptions({
  name: 'Holidays'
})

// 类型定义
interface HolidayItem {
  id: string
  name: string
  start_time: string
  end_time: string
  group_id: string[]
  description: string
}

interface TableRow {
  id: string
  name: string
  startTime: string
  endTime: string
  marketNames: string
  groupId: string[]
  description: string
}

// 按钮 loading
const { loading, startLoading, stopLoading } = usePageLoading()
const submitLoading = ref(false)

// 市场列表
const marketList = ref<{ label: string; value: string }[]>([])

// 表格列配置
const tableColumns = [
  { prop: 'name', label: '节假日名称', width: 150 },
  { prop: 'startTime', label: '休市开始时间', width: 180 },
  { prop: 'endTime', label: '休市结束时间', width: 180 },
  { prop: 'marketNames', label: '休市市场', width: 200 },
  { prop: 'description', label: '备注' },
  { prop: 'action', label: '操作', width: 180, slotName: 'action' },
]

// 表格数据
const tableData = ref<TableRow[]>([])
const tableRef = ref()

// 搜索表单
const searchForm = reactive({
  name: '',
})

// 弹窗状态
const dialogVisible = ref(false)
const dialogTitle = computed(() => (isEdit.value ? '编辑节假日' : '添加节假日'))
const isEdit = ref(false)
const currentId = ref<string | null>(null)

// 表单数据
const formData = reactive({
  name: '',
  datePicker: [] as string[],
  groupId: [] as string[],
  description: '',
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入节假日名称', trigger: 'blur' }],
  datePicker: [{ required: true, message: '请选择休市时间', trigger: 'change' }],
  groupId: [{ required: true, message: '请选择休市市场', trigger: 'blur' }],
  description: [{ required: true, message: '请输入备注', trigger: 'change' }],
}

// 表单配置
const formItems: Array<{
  type: 'input' | 'date' | 'slot' | 'textarea'
  label: string
  prop: string
  placeholder?: string
  required?: boolean
  dateType?: 'datetimerange'
  rangeSeparator?: string
  startPlaceholder?: string
  endPlaceholder?: string
  valueFormat?: string
  slotName?: string
}> = [
    { type: 'input', label: '节假日名称', prop: 'name', placeholder: '请输入节假日名称', required: true },
    {
      type: 'date',
      label: '休市时间',
      prop: 'datePicker',
      dateType: 'datetimerange',
      rangeSeparator: '至',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      required: true,
    },
    { type: 'slot', label: '休市市场', prop: 'groupId', slotName: 'marketSelect' },
    { type: 'textarea', label: '备注', prop: 'description', placeholder: '请输入备注' },
  ]

// 市场选项 Map（仅保留给非 slot 类型字段使用）
const optionsMap = computed(() => ({}))

// 表单引用
const formRef = ref()

/**
 * @description: 获取市场列表
 */
const getMarketList = async () => {
  const res = await getGroupListApi()
  console.log('res:', res);
  marketList.value = res.map((item: { name: string; id: number }) => ({
    label: item.name,
    value: String(item.id),
  }))
  console.log('marketList.value:', marketList.value);
}

/**
 * @description: 获取节假日列表
 */
const getList = async () => {
  startLoading()
  try {
    const res = await getHolidayList()
    // 前端过滤：按节假日名称搜索
    const filteredData = res.filter((item: HolidayItem) => {
      if (searchForm.name && !item.name.includes(searchForm.name)) {
        return false
      }
      return true
    })
    tableData.value = filteredData.map((item: HolidayItem) => {
      const groupIds = item.group_id ? String(item.group_id).split(',').filter(Boolean) : []
      const marketNames = groupIds
        .map((id) => marketList.value.find((m) => m.value === id)?.label || '')
        .filter(Boolean)
        .join(',')
      return {
        id: String(item.id),
        name: item.name,
        startTime: item.start_time,
        endTime: item.end_time,
        marketNames,
        groupId: groupIds,
        description: item.description,
      }
    })
  } finally {
    stopLoading()
  }
}

// 同步风控模板
const syncLoading = ref(false)
const handleSyncRiskControl = async () => {
  syncLoading.value = true
  try {
    await syncRiskControlApi() 
  } finally {
    syncLoading.value = false
  }
}
/**
 * @description: 搜索
 */
const handleSearch = async () => {
  await getList()
}

/**
 * @description: 重置
 */
const handleReset = () => {
  searchForm.name = ''
  getList()
}

/**
 * @description: 打开添加弹窗
 */
const handleAdd = () => {
  isEdit.value = false
  currentId.value = null
  resetForm()
  dialogVisible.value = true
}

/**
 * @description: 打开编辑弹窗
 */
const handleEdit = (row: TableRow) => {
  isEdit.value = true
  currentId.value = row.id
  formData.name = row.name
  formData.datePicker = [row.startTime, row.endTime]
  // 直接使用 groupId（已保存为字符串数组）
  formData.groupId = row.groupId
  formData.description = row.description
  dialogVisible.value = true
}

/**
 * @description: 删除
 */
const handleDel = async (row: TableRow) => {
  try {
    await ElMessageBox.confirm('确认删除该节假日吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await delHoliday({ id: row.id })
    ElMessage.success('删除成功')
    await getList()
  } catch {
    // 用户取消
  }
}

/**
 * @description: 重置表单
 */
const resetForm = () => {
  formData.name = ''
  formData.datePicker = []
  formData.groupId = []
  formData.description = ''
}

/**
 * @description: 弹窗关闭
 */
const handleDialogClose = () => {
  resetForm()
  formRef.value?.resetFields()
}

/**
 * @description: 提交表单
 */
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
  } catch {
    return
  }

  submitLoading.value = true
  try {
    const submitData = {
      name: formData.name,
      start_time: formData.datePicker[0],
      end_time: formData.datePicker[1],
      group_id: formData.groupId.join(','),
      description: formData.description,
    }

    if (isEdit.value && currentId.value) {
      await editHoliday({ id: currentId.value, ...submitData })
      ElMessage.success('编辑成功')
    } else {
      await addHoliday(submitData)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    await getList()
  } finally {
    submitLoading.value = false
  }
}

/**
 * @description: 页面初始化
 */
onMounted(async () => {
  await getList()
  await getMarketList()
})
</script>

<style scoped lang="scss">
.holidays-container {
  :deep(.search-container) {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    flex-wrap: wrap;
    gap: 16px;

    .el-form {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
    }

    .search-right {
      flex-shrink: 0;
    }
  }
}
</style>
