<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>报销申请管理</h2>
        <p class="page-desc">管理报销申请，包括待办审批、所有申请列表等</p>
      </div>
      <div class="header-right">
        <el-button 
          icon="el-icon-refresh" 
          @click="getList"
          :loading="listLoading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 标签页切换 -->
    <div class="tabs-container">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="所有待办" name="allPending">
          <template slot="label">
            <span><i class="el-icon-s-order"></i> 所有待办</span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="我的待办" name="myPending">
          <template slot="label">
            <span><i class="el-icon-user"></i> 我的待办</span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="所有申请" name="all">
          <template slot="label">
            <span><i class="el-icon-document"></i> 所有申请</span>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px" label-position="right">
        <el-form-item label="申请门店ID" prop="applicationStoreId">
          <el-input 
            v-model="queryParams.applicationStoreId" 
            placeholder="请输入申请门店ID" 
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <template v-if="activeTab === 'all'">
          <el-form-item label="申请编号" prop="id">
            <el-input 
              v-model="queryParams.id" 
              placeholder="请输入申请编号" 
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="申请人编号" prop="applicationUserId">
            <el-input 
              v-model="queryParams.applicationUserId" 
              placeholder="请输入申请人编号" 
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="申请人姓名" prop="applicationUserName">
            <el-input 
              v-model="queryParams.applicationUserName" 
              placeholder="请输入申请人姓名" 
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="申请时间" prop="applicationTime">
            <el-date-picker
              v-model="queryParams.applicationTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="金额" prop="amount">
            <el-input 
              v-model="queryParams.amount" 
              placeholder="请输入金额" 
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="审批状态" prop="approveStatus">
            <el-select 
              v-model="queryParams.approveStatus" 
              placeholder="请选择审批状态"
              clearable
              style="width: 200px"
            >
              <el-option label="待审批" value="待审批" />
              <el-option label="审批中" value="审批中" />
              <el-option label="已通过" value="已通过" />
              <el-option label="未通过" value="未通过" />
              <el-option label="已退回" value="已退回" />
            </el-select>
          </el-form-item>
          <el-form-item label="购买记录编号" prop="purchaseRecordsId">
            <el-input 
              v-model="queryParams.purchaseRecordsId" 
              placeholder="请输入购买记录编号" 
              clearable
              style="width: 200px"
            />
          </el-form-item>
        </template>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <NCC-table 
        v-loading="listLoading" 
        :data="list" 
        border 
        stripe
        height="calc(100vh - 500px)"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <!-- 申请编号 -->
        <el-table-column label="申请编号" width="180" align="center">
          <template slot-scope="scope">
            <div class="id-item">
              <i class="el-icon-document id-icon"></i>
              <span>{{ scope.row.id || '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 申请人 -->
        <el-table-column label="申请人" width="140" align="center">
          <template slot-scope="scope">
            <div class="user-item">
              <i class="el-icon-user user-icon"></i>
              <span>{{ scope.row.applicationUserName || '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 申请门店ID -->
        <el-table-column label="申请门店ID" width="160" align="center">
          <template slot-scope="scope">
            <div class="store-item">
              <i class="el-icon-shop store-icon"></i>
              <span>{{ scope.row.applicationStoreId || '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 申请时间 -->
        <el-table-column label="申请时间" width="180" align="center">
          <template slot-scope="scope">
            <div class="time-item">
              <i class="el-icon-time time-icon"></i>
              <span>{{ formatDateTime(scope.row.applicationTime) || '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 金额 -->
        <el-table-column label="金额" width="140" align="center">
          <template slot-scope="scope">
            <div class="amount-item">
              <i class="el-icon-money amount-icon"></i>
              <span class="amount-value">{{ formatMoney(scope.row.amount) || '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 审批状态 -->
        <el-table-column label="审批状态" width="120" align="center">
          <template slot-scope="scope">
            <el-tag 
              :type="getStatusType(scope.row.approveStatus)"
              size="small"
            >
              {{ scope.row.approveStatus || '无' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 当前审批人 -->
        <el-table-column label="当前审批人" width="160" align="center" v-if="activeTab !== 'all'">
          <template slot-scope="scope">
            <div class="approver-item">
              <i class="el-icon-user-solid approver-icon"></i>
              <span>{{ scope.row.currentApprovers || '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 当前节点 -->
        <el-table-column label="当前节点" width="120" align="center" v-if="activeTab !== 'all'">
          <template slot-scope="scope">
            <div class="node-item">
              <i class="el-icon-s-order node-icon"></i>
              <span>{{ scope.row.currentNodeOrder ? `第${scope.row.currentNodeOrder}节点` : '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 节点总数 -->
        <el-table-column label="节点总数" width="100" align="center" v-if="activeTab !== 'all'">
          <template slot-scope="scope">
            <div class="node-count-item">
              <i class="el-icon-s-data node-count-icon"></i>
              <span>{{ scope.row.nodeCount || '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="200" align="left" fixed="right">
          <template slot-scope="scope">
            <div class="action-buttons">
              <el-button 
                type="text" 
                icon="el-icon-view" 
                @click="handleView(scope.row)"
                size="small"
                class="view-btn"
              >
                查看
              </el-button>
              <el-button 
                type="text" 
                icon="el-icon-time" 
                @click="handleViewHistory(scope.row)"
                size="small"
                class="history-btn"
              >
                审批历史
              </el-button>
            </div>
          </template>
        </el-table-column>
      </NCC-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 详情/审批弹窗 -->
    <detail-dialog 
      v-if="detailVisible"
      ref="DetailDialog"
      @refresh="getList"
    />

    <!-- 审批历史弹窗 -->
    <approval-history-dialog 
      v-if="historyVisible"
      ref="ApprovalHistoryDialog"
    />
  </div>
</template>

<script>
import request from '@/utils/request'
import DetailDialog from './detail-dialog.vue'
import ApprovalHistoryDialog from './approval-history-dialog.vue'

export default {
  name: 'LqReimbursementApplication',
  components: {
    DetailDialog,
    ApprovalHistoryDialog
  },
  data() {
    return {
      activeTab: 'allPending', // 当前激活的标签页
      listLoading: false,
      list: [],
      total: 0,
      detailVisible: false,
      historyVisible: false,
      queryParams: {
        applicationStoreId: '',
        id: '',
        applicationUserId: '',
        applicationUserName: '',
        applicationTime: null,
        amount: '',
        approveStatus: '',
        purchaseRecordsId: ''
      },
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sidx: 'applicationTime',
        sort: 'desc'
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    async getList() {
      this.listLoading = true
      try {
        let url = '/api/Extend/LqReimbursementApplication'
        
        // 根据标签页选择不同的接口
        if (this.activeTab === 'allPending') {
          url = '/api/Extend/LqReimbursementApplication/Actions/AllPendingApproval'
        } else if (this.activeTab === 'myPending') {
          url = '/api/Extend/LqReimbursementApplication/Actions/PendingApproval'
        }

        const params = {
          currentPage: this.listQuery.currentPage,
          pageSize: this.listQuery.pageSize,
          sidx: this.listQuery.sidx,
          sort: this.listQuery.sort
        }

        // 添加查询参数
        if (this.queryParams.applicationStoreId) {
          params.applicationStoreId = this.queryParams.applicationStoreId
        }

        // 只有"所有申请"标签页才添加这些查询参数
        if (this.activeTab === 'all') {
          if (this.queryParams.id) {
            params.id = this.queryParams.id
          }
          if (this.queryParams.applicationUserId) {
            params.applicationUserId = this.queryParams.applicationUserId
          }
          if (this.queryParams.applicationUserName) {
            params.applicationUserName = this.queryParams.applicationUserName
          }
          if (this.queryParams.applicationTime && this.queryParams.applicationTime.length === 2) {
            params.applicationTime = `${this.queryParams.applicationTime[0]},${this.queryParams.applicationTime[1]}`
          }
          if (this.queryParams.amount) {
            params.amount = this.queryParams.amount
          }
          if (this.queryParams.approveStatus) {
            params.approveStatus = this.queryParams.approveStatus
          }
          if (this.queryParams.purchaseRecordsId) {
            params.purchaseRecordsId = this.queryParams.purchaseRecordsId
          }
        }

        const response = await request({
          url: url,
          method: 'GET',
          data: params
        })

        if (response.code === 200) {
          this.list = response.data.list || []
          this.total = (response.data.pagination && response.data.pagination.Total) || 0
        } else {
          this.$message.error(response.msg || '获取列表失败')
          this.list = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取列表失败:', error)
        this.$message.error('获取列表失败')
        this.list = []
        this.total = 0
      } finally {
        this.listLoading = false
      }
    },

    // 标签页切换
    handleTabChange() {
      this.listQuery.currentPage = 1
      this.resetQuery()
    },

    // 搜索
    handleQuery() {
      this.listQuery.currentPage = 1
      this.getList()
    },

    // 重置搜索
    resetQuery() {
      this.queryParams = {
        applicationStoreId: '',
        id: '',
        applicationUserId: '',
        applicationUserName: '',
        applicationTime: null,
        amount: '',
        approveStatus: '',
        purchaseRecordsId: ''
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sidx: 'applicationTime',
        sort: 'desc'
      }
      this.getList()
    },

    // 查看详情/审批
    handleView(row) {
      this.detailVisible = true
      this.$nextTick(() => {
        this.$refs.DetailDialog.init(row.id)
      })
    },

    // 查看审批历史
    handleViewHistory(row) {
      this.historyVisible = true
      this.$nextTick(() => {
        this.$refs.ApprovalHistoryDialog.init(row.id)
      })
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.listQuery.currentPage = val
      this.getList()
    },

    // 格式化金额
    formatMoney(amount) {
      if (!amount) return '无'
      return `¥${Number(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })}`
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '无'
      const date = new Date(dateTime)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        '待审批': 'info',
        '审批中': 'warning',
        '已通过': 'success',
        '未通过': 'danger',
        '已退回': 'warning'
      }
      return statusMap[status] || ''
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background: #f5f5f5;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .header-left {
    h2 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 20px;
      font-weight: 600;
    }

    .page-desc {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .header-right {
    display: flex;
    gap: 12px;
  }
}

.tabs-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

// 表格项样式
.id-item,
.user-item,
.store-item,
.time-item,
.amount-item,
.approver-item,
.node-item,
.node-count-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  
  .id-icon {
    color: #409EFF;
    font-size: 16px;
  }
  
  .user-icon {
    color: #67C23A;
    font-size: 16px;
  }
  
  .store-icon {
    color: #67C23A;
    font-size: 16px;
  }
  
  .time-icon {
    color: #909399;
    font-size: 16px;
  }
  
  .amount-icon {
    color: #F56C6C;
    font-size: 16px;
  }
  
  .approver-icon {
    color: #409EFF;
    font-size: 16px;
  }
  
  .node-icon {
    color: #909399;
    font-size: 16px;
  }
  
  .node-count-icon {
    color: #909399;
    font-size: 16px;
  }
  
  span {
    color: #606266;
  }
}

.amount-value {
  font-weight: 600;
  color: #F56C6C;
}

// 操作按钮样式
.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .view-btn {
    color: #409EFF;
    
    &:hover {
      color: #66b1ff;
    }
  }
  
  .history-btn {
    color: #909399;
    
    &:hover {
      color: #606266;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
