<template>
  <div class="modern-page-container">
    <div class="page-wrapper">
      <!-- 查询条件 -->
      <el-card v-show="showSearch" class="search-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon class="title-icon"><Search /></el-icon>
              查询条件
            </span>
          </div>
        </template>
        <el-form :model="searchForm" ref="searchFormRef" :inline="true" @keyup.enter="handleSearch" class="search-form">
          <el-form-item label="有效金额" prop="effectiveMoney">
            <el-input-number 
              v-model="searchForm.effectiveMoney" 
              placeholder="请输入有效金额"
              :precision="2"
              :min="0"
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="是否住人" prop="isLiveNum">
            <el-select 
              v-model="searchForm.isLiveNum" 
              placeholder="请选择" 
              clearable
              style="width: 200px">
              <el-option label="等于0" :value="true" />
              <el-option label="不等于0" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item label="楼号" prop="buildNo">
            <el-select 
              v-model="searchForm.buildNo" 
              placeholder="请选择楼号" 
              clearable
              filterable 
              style="width: 200px">
              <el-option
                v-for="item in buildingList"
                :key="item.buildingNo"
                :label="item.buildingNo"
                :value="item.buildingNo">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房间号" prop="roomNo">
            <el-input 
              v-model="searchForm.roomNo" 
              placeholder="请输入房间号" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain icon="Search" @click="handleSearch">查询</el-button>
            <el-button icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 数据列表 -->
      <el-card class="content-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon class="title-icon"><Document /></el-icon>
              水费明细列表
            </span>
            <div class="header-actions">
              <el-button
                icon="FolderAdd"
                type="primary"
                @click="formDialogRef.openDialog()">
                新增明细
              </el-button>
              <el-button
                icon="DataAnalysis"
                type="warning"
                class="ml10"
                @click="handleStats">
                统计分析
              </el-button>
              <el-button
                icon="Download"
                type="success"
                class="ml10"
                @click="handleExport">
                导出数据
              </el-button>
              <el-button
                icon="Setting"
                type="info"
                class="ml10"
                @click="handleInitWaterOrder">
                批量初始化订单
              </el-button>
              <right-toolbar  
                v-model:showSearch="showSearch" 
                class="ml10"
                @queryTable="getDataList">
                <TableColumnControl
                  ref="columnControlRef"
                  :columns="tableColumns"
                  v-model="visibleColumns"
                  trigger-type="default"
                  trigger-circle
                  @change="handleColumnChange"
                  @order-change="handleColumnOrderChange"
                >
                  <template #trigger>
                    <el-tooltip class="item" effect="dark" content="列设置" placement="top">
                      <el-button circle style="margin-left: 0;">
                        <el-icon><Menu /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </template>
                </TableColumnControl>
              </right-toolbar>
            </div>
          </div>
        </template>

        <!-- 表格 -->
        <el-table 
          :data="state.dataList" 
          v-loading="state.loading" 
          stripe
          :cell-style="tableStyle.cellStyle" 
          :header-cell-style="tableStyle.headerCellStyle"
          class="modern-table"
          @sort-change="sortChangeHandle">
          <el-table-column type="index" label="序号" width="70" align="center">
            <template #header>
              <el-icon><List /></el-icon>
            </template>
            <template #default="{ $index }">
              {{ $index + 1 + ((state.pagination?.current || 1) - 1) * (state.pagination?.size || 10) }}
            </template>
          </el-table-column>
          <template v-for="col in visibleColumnsSorted" :key="col.prop || col.label">
            <el-table-column 
              v-if="checkColumnVisible(col.prop || '') && col.prop !== '序号'"
              :prop="col.prop" 
            :label="col.label" 
            show-overflow-tooltip
            align="center"
            :min-width="col.minWidth"
            :width="col.width">
            <template #header>
              <el-icon><component :is="columnConfigMap[col.prop]?.icon || Money" /></el-icon>
              <span style="margin-left: 4px">{{ col.label }}</span>
            </template>
            <!-- 床位号格式化 -->
            <template v-if="col.prop === 'bedNum'" #default="scope">
              <el-tag v-if="scope.row.bedNum" size="small" type="info" effect="plain">
                {{ scope.row.bedNum }}号床
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 住人数量格式化-->
            <template v-else-if="col.prop === 'liveNum'" #default="scope">
              <el-tag v-if="scope.row.liveNum !== undefined && scope.row.liveNum !== null" size="small" type="success" effect="plain">
                {{ scope.row.liveNum }}
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 期初余额格式化-->
            <template v-else-if="col.prop === 'oddbMoney'" #default="scope">
              <el-tag v-if="scope.row.oddbMoney" size="small" type="success" effect="plain">
                ¥{{ Number(scope.row.oddbMoney).toFixed(2) }}
              </el-tag>
              <span v-else>¥0.00</span>
            </template>
            <!-- 充值金额格式化 -->
            <template v-else-if="col.prop === 'rechargeMoney'" #default="scope">
              <el-tag v-if="scope.row.rechargeMoney" size="small" type="primary" effect="plain">
                ¥{{ Number(scope.row.rechargeMoney).toFixed(2) }}
              </el-tag>
              <span v-else>¥0.00</span>
            </template>
            <!-- 消费金额格式化-->
            <template v-else-if="col.prop === 'costMoney'" #default="scope">
              <el-tag v-if="scope.row.costMoney" size="small" type="warning" effect="plain">
                ¥{{ Number(scope.row.costMoney).toFixed(2) }}
              </el-tag>
              <span v-else>¥0.00</span>
            </template>
            <!-- 有效金额格式化-->
            <template v-else-if="col.prop === 'effectiveMoney'" #default="scope">
              <el-tag size="small" :type="Number(scope.row.effectiveMoney) < 0 ? 'danger' : 'success'" effect="plain">
                ¥{{ scope.row.effectiveMoney ? Number(scope.row.effectiveMoney).toFixed(2) : '0.00' }}
              </el-tag>
            </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" width="200" align="center" fixed="right">
            <template #header>
              <el-icon><Setting /></el-icon>
              <span style="margin-left: 4px">操作</span>
            </template>
            <template #default="scope">
              <el-button 
                icon="Edit" 
                link 
                type="primary" 
                @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button 
                icon="View" 
                link 
                type="info" 
                @click="handleViewDetail(scope.row)">
                详情
              </el-button>
              <el-button 
                icon="Delete" 
                link 
                type="danger" 
                @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <pagination 
            @size-change="sizeChangeHandle" 
            @current-change="currentChangeHandle" 
            v-bind="state.pagination" />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑对话框 -->
    <FormDialog ref="formDialogRef" @refresh="getDataList()" />

    <!-- 详情对话框 -->
    <DetailDialog ref="detailDialogRef" />

    <!-- 统计分析对话框 -->
    <StatsDialog ref="statsDialogRef" />

    <!-- 批量初始化对话框-->
    <el-dialog v-model="initDialogVisible" title="批量初始化订单" :width="500" :close-on-click-modal="false" draggable>
      <el-form ref="initFormRef" :model="initForm" :rules="initRules" label-width="120px">
        <el-form-item label="消费金额" prop="costMoney">
          <el-input-number 
            v-model="initForm.costMoney" 
            :precision="2"
            :min="0"
            placeholder="请输入消费金额"
            style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="initDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmInit" :loading="initLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="WaterDetail">
import { reactive, ref, onMounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs, initWaterOrder } from "/@/api/stuwork/waterdetail";
import { getBuildingList } from "/@/api/stuwork/dormbuilding";
import { useMessage, useMessageBox } from "/@/hooks/message";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import FormDialog from './form.vue';
import DetailDialog from './detail.vue';
import StatsDialog from './stats.vue';
import { List, OfficeBuilding, House, UserFilled, Money, Setting, Menu, Search, Document, DataAnalysis } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'


// 定义变量
const route = useRoute()
const router = useRouter()
const searchFormRef = ref()
const columnControlRef = ref<any>()
const formDialogRef = ref()
const detailDialogRef = ref()
const statsDialogRef = ref()
const initFormRef = ref()
const showSearch = ref(true)
const buildingList = ref<any[]>([])
const initDialogVisible = ref(false)
const initLoading = ref(false)

// 表格列配置
const tableColumns = [
  { prop: 'buildNo', label: '楼号' },
  { prop: 'roomNo', label: '房间号' },
  { prop: 'bedNum', label: '床位号' },
  { prop: 'liveNum', label: '住人数量' },
  { prop: 'oddbMoney', label: '期初余额' },
  { prop: 'rechargeMoney', label: '充值金额' },
  { prop: 'costMoney', label: '消费金额' },
  { prop: 'effectiveMoney', label: '有效金额' }
]

// 列配置映射
const columnConfigMap: Record<string, { icon: any }> = {
  buildNo: { icon: OfficeBuilding },
  roomNo: { icon: House },
  bedNum: { icon: UserFilled },
  liveNum: { icon: UserFilled },
  oddbMoney: { icon: Money },
  rechargeMoney: { icon: Money },
  costMoney: { icon: Money },
  effectiveMoney: { icon: Money }
}

// 表格列控制hook
const {
  visibleColumns,
  visibleColumnsSorted,
  checkColumnVisible,
  handleColumnChange,
  handleColumnOrderChange
} = useTableColumnControl(tableColumns)

// 搜索表单
const searchForm = reactive({
  effectiveMoney: undefined as number | undefined,
  isLiveNum: undefined as boolean | undefined,
  buildNo: '',
  roomNo: ''
})

// 初始化表单
const initForm = reactive({
  costMoney: 0
})

// 初始化表单规则
const initRules = {
  costMoney: [
    { required: true, message: '请输入消费金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '消费金额必须大于等于0', trigger: 'blur' }
  ]
}

// 使用 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: searchForm,
  pageList: fetchList,
  props: {
    item: 'records',
    totalCount: 'total'
  },
  createdIsNeed: true
})

// table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  tableStyle
} = useTable(state)

// 查询
const handleSearch = () => {
  getDataList()
}

// 重置
const handleReset = () => {
  searchFormRef.value?.formRef?.resetFields()
  searchForm.effectiveMoney = undefined
  searchForm.isLiveNum = undefined
  searchForm.buildNo = ''
  searchForm.roomNo = ''
  getDataList()
}

// 编辑
const handleEdit = (row: any) => {
  formDialogRef.value.openDialog('edit', row)
}

// 查看详情
const handleViewDetail = (row: any) => {
  detailDialogRef.value.openDialog(row.roomNo)
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await useMessageBox().confirm('确定要删除该记录吗？')
    await delObjs([row.id])
    useMessage().success('删除成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '删除失败')
    }
  }
}

// 导出
const handleExport = () => {
  // TODO: 实现导出
  useMessage().warning('功能开发中')
}

// 统计分析
const handleStats = () => {
  statsDialogRef.value.openDialog()
}

// 批量初始化订单
const handleInitWaterOrder = () => {
  initDialogVisible.value = true
  initForm.costMoney = 0
}

// 确认初始化
const confirmInit = async () => {
  if (!initFormRef.value) return
  
  await initFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    initLoading.value = true
    try {
      await initWaterOrder({ costMoney: initForm.costMoney })
      useMessage().success('初始化成功')
      initDialogVisible.value = false
      getDataList()
    } catch (err: any) {
      useMessage().error(err.msg || '初始化失败')
    } finally {
      initLoading.value = false
    }
  })
}

// 获取楼号列表
const getBuildingListData = async () => {
  try {
    const res = await getBuildingList()
    if (res.data) {
      buildingList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    buildingList.value = []
  }
}

// 初始化
onMounted(() => {
  getBuildingListData()
  nextTick(() => {
    if (visibleColumns.value.length === 0) {
    }
  })
})
</script>

<style scoped lang="scss">
@import '/@/assets/styles/modern-page.scss';
</style>
