<template>
  <my-layout>
    <el-card class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
      <el-form :inline="true" label-width="auto" :label-position="'left'" @submit.stop.prevent>
        <el-form-item label="原因描述" prop="revokeReason">
          <el-input v-model="state.filter.keyWord" placeholder="请输入原因描述" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="原因类型" prop="revokeType">
          <el-select v-model="state.filter.revokeType" placeholder="请选择原因类型" clearable style="width: 200px">
            <el-option v-for="item in state.revokeTypeOptions" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker v-model="state.filter.startTime" type="datetime" placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 180px" />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker v-model="state.filter.endTime" type="datetime" placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 180px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="ele-Search" @click="handleQuery">查询</el-button>
          <el-button v-auth="'api:admin:revoke-reason:add'" type="primary" icon="ele-Plus"
            @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="my-fill mt8" shadow="never">
      <el-table v-loading="loading" :data="state.revokeReasonList" row-key="id" style="width: 100%" border>
        <el-table-column label="原因类型" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getRevokeTypeName(row.revokeType) }}
          </template>
        </el-table-column>
        <el-table-column prop="revokeReason" label="原因描述" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right" header-align="center" align="center">
          <template #default="{ row }">
            <el-button v-auth="'api:admin:revoke-reason:update'" icon="ele-EditPen" size="small" text type="primary"
              @click="handleEdit(row)">编辑</el-button>
            <el-button v-auth="'api:admin:revoke-reason:soft-delete'" icon="ele-Delete" size="small" text type="danger"
              @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="my-flex my-flex-end" style="margin-top: 10px">
        <el-pagination v-model:current-page="state.pageInput.currentPage" v-model:page-size="state.pageInput.pageSize"
          :total="state.total" :page-sizes="[10, 20, 50, 100]" size="small" background @size-change="handleSizeChange"
          @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" />
      </div>
    </el-card>

    <uspreason-form ref="formRef" :title="state.formTitle" @ok="getList" />
  </my-layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeMount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { RevokeReasonApi } from '/@/api/admin/revoke-reason'
import eventBus from '/@/utils/mitt'
import type {
  RevokeReasonPageInput,
  RevokeReasonOutput,
  RevokeReasonPageDto,
  RevokeTypeEnumItem
} from '/@/api/types/RevokeType'

import UspreasonForm from './components/uspreason-form.vue'

const loading = ref(false)
const formRef = ref()

const state = reactive({
  loading: false,
  formTitle: '',
  total: 0,
  filter: {
    keyWord: "",
    revokeType: "",
    isDown: false,
    startTime: "",
    endTime: ""
  },
  pageInput: {
    currentPage: 1,
    pageSize: 20,
  } as RevokeReasonPageInput,
  revokeReasonList: [] as Array<RevokeReasonPageDto>,
  revokeTypeOptions: [] as RevokeTypeEnumItem[]
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  state.pageInput.filter = state.filter
  try {
    const res = await new RevokeReasonApi().getPage(state.pageInput)
    state.revokeReasonList = res.data?.list || []
    state.total = res.data?.total || 0
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

/** 获取撤销类型枚举列表 */
const getRevokeTypeOptions = async () => {
  try {
    const res = await new RevokeReasonApi().getRevokeTypeEnumList()
    state.revokeTypeOptions = res.data ?? []
  } catch (error) {
    console.error('获取撤销类型枚举列表失败:', error)
  }
}

const getRevokeTypeName = (revokeType: string) => {
  const item = state.revokeTypeOptions.find(item => item.value === Number(revokeType))
  return item?.label || ''
}


/** 搜索按钮操作 */
const handleQuery = () => {
  state.pageInput.currentPage = 1
  getList()
}

/** 新增按钮操作 */
const handleAdd = () => {
  state.formTitle = '新增原因'
  formRef.value?.open()
}

/** 修改按钮操作 */
const handleEdit = (row: RevokeReasonOutput) => {
  state.formTitle = '编辑原因'
  formRef.value?.open(row)
}

/** 删除按钮操作 */
const handleDelete = (id: number) => {
  ElMessageBox.confirm('确认要删除该记录吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await new RevokeReasonApi().softDelete({ id: id })
      if (res.success) {
        ElMessage.success('删除成功')
        getList()
      }
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

/** 每页条数改变 */
const handleSizeChange = (val: number) => {
  state.pageInput.pageSize = val
  getList()
}

/** 当前页改变 */
const handleCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  getList()
}

onMounted(() => {
  getRevokeTypeOptions()
  getList()
  eventBus.on('refreshUspReason', getList)
})

onBeforeMount(() => {
  eventBus.off('refreshUspReason')
})
</script>

<style lang="scss" scoped>
.my-query-box {
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }
}

.my-fill {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.my-flex {
  display: flex;
}

.my-flex-end {
  justify-content: flex-end;
}

.mt8 {
  margin-top: 8px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
