<template>
  <div class="customer-css">
    <!-- 查询条件 -->
    <el-form :inline="true" label-position="top" class="search-form-inline">
      <div class="search-row">
        <el-form-item label="费用单号" class="search-item">
          <el-input v-model="searchData.feeNo" style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>

        <el-form-item label="申请人" class="search-item" >
          <el-input v-model="searchData.applyUser" style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>

        <el-form-item label="费用日期" class="search-item">
          <el-date-picker
            v-model="searchData.feeDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            style="width: 100%;">
          </el-date-picker>
        </el-form-item>

        <el-form-item label=" " class="search-item search-btn-item">
          <el-button type="primary" @click="getMainData" style="">查询</el-button>
          <el-button @click="handleAdd" type="primary" style="margin-left: 2px">新增</el-button>
        </el-form-item>
      </div>
    </el-form>

    <el-table
      :height="height"
      :data="mainDataList"
      border
      ref="mainTable"
      highlight-current-row
      @row-click="changeData"
      v-loading="dataListLoading"
      style="width: 100%;">
      <el-table-column
        v-for="(item,index) in columnArray1" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed==''?false:item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span v-if="!item.columnHidden">{{ scope.row[item.columnProp] }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-link type="primary" style="cursor: pointer; margin-right: 10px;" @click="handleEdit(scope.row)">编辑</el-link>
          <el-link type="danger" style="cursor: pointer;" @click="handleDelete(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页插件 -->
    <el-pagination style="margin-top: 0px"
                   @size-change="sizeChangeHandle"
                   @current-change="currentChangeHandle"
                   :current-page="pageIndex"
                   :page-sizes="[20, 50, 100, 200, 500]"
                   :page-size="pageSize"
                   :total="totalPage"
                   layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 详情页签 -->
    <el-tabs v-model="activeTab" style="margin-top: 0px; width: 99%;" @tab-click="handleTabClick" class="customer-tab" type="border-card">
      <!-- 费用明细 -->
      <el-tab-pane label="费用明细" name="detail">
        <fee-detail-tab ref="feeDetailTab" :fee-data="currentRow" :table-height="detailHeight" />
      </el-tab-pane>
      <!-- 申请单清单 -->
      <el-tab-pane label="申请单清单" name="request">
        <request-fee-tab ref="requestFeeTab" :fee-data="currentRow" :table-height="detailHeight" />
      </el-tab-pane>
    </el-tabs>

    <!-- 新增弹窗 -->
    <el-dialog
      title="新增费用记录"
      :visible.sync="addDialogVisible"
      width="30%"
      top="10vh"
      :close-on-click-modal="false">
      <el-form :model="addFormData" :rules="addRules" ref="addFormData" label-width="100px" size="small" label-position="top">
        <el-form-item label="费用日期" prop="feeDate" >
          <el-date-picker
            v-model="addFormData.feeDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            style="width: 50%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请人" prop="applyUser">
          <el-input v-model="addFormData.applyUser" placeholder="请输入申请人"  style="width: 50%"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            v-model="addFormData.remark"
            :autosize="{ minRows: 3, maxRows: 6 }"
            placeholder="请输入备注">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSaveAdd">保存</el-button>
        <el-button @click="addDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { searchFeeHeaderList, createFeeHeader, updateFeeHeader, deleteFeeRecord } from '@/api/inspection/srmFee.js'
import FeeDetailTab from './com_feeDetailTab.vue'
import RequestFeeTab from './com_requestFeeTab.vue'

export default {
  name: 'SrmFeeList',
  components: {
    FeeDetailTab,
    RequestFeeTab
  },
  data() {
    return {
      functionId: this.$route.meta.menuId,
      height: 400,
      detailHeight: 400,
      currentRow: {},
      activeTab: 'detail',
      addDialogVisible: false,
      addFormData: {
        feeDate: '',
        applyUser: '',
        remark: ''
      },
      addRules: {
        feeDate: [
          { required: true, message: '请选择费用日期', trigger: 'change' }
        ],
        applyUser: [
          { required: true, message: '请输入申请人', trigger: 'blur' }
        ]
      },
      searchData: {
        feeNo: '',
        applyUser: '',
        feeDate: '',
        site: this.$store.state.user.site,
        page: 1,
        limit: 50
      },
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      mainDataList: [],
      dataListLoading: false,
      columnArray1: [
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'FeeTable1FeeNo',
          tableId: 'FeeTable1',
          tableName: '费用管理',
          columnProp: 'feeNo',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '费用单号',
          columnWidth: '150',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'FeeTable1FeeDate',
          tableId: 'FeeTable1',
          tableName: '费用管理',
          columnProp: 'feeDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '费用日期',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'FeeTable1TotalAmount',
          tableId: 'FeeTable1',
          tableName: '费用管理',
          columnProp: 'totalAmount',
          headerAlign: 'center',
          align: 'right',
          columnLabel: '总金额',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'FeeTable1ApplyUser',
          tableId: 'FeeTable1',
          tableName: '费用管理',
          columnProp: 'applyUser',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '申请人',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'FeeTable1CreatedBy',
          tableId: 'FeeTable1',
          tableName: '费用管理',
          columnProp: 'createdBy',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '创建人',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'FeeTable1CreatedDate',
          tableId: 'FeeTable1',
          tableName: '费用管理',
          columnProp: 'createdDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '创建时间',
          columnWidth: '160',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'FeeTable1Remark',
          tableId: 'FeeTable1',
          tableName: '费用管理',
          columnProp: 'remark',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '备注',
          columnWidth: '200',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        }
      ]
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.height = (window.innerHeight - 220) / 2
      this.detailHeight = (window.innerHeight - 220) / 2
      this.getMainData()
    })
  },
  methods: {
    // 查询数据
    getMainData() {
      console.log('开始查询费用列表...')
      this.searchData.limit = this.pageSize
      this.searchData.page = this.pageIndex

      this.dataListLoading = true
      console.log('设置 loading 为 true')

      searchFeeHeaderList(this.searchData).then(({ data }) => {
        console.log('接口返回数据:', data)
        if (data && data.code === 0) {
          this.mainDataList = data.page.list || []

          this.pageIndex = data.page.currPage
          this.pageSize = data.page.pageSize
          this.totalPage = data.page.totalCount

          this.$nextTick(() => {
            if (this.$refs.mainTable) {
              this.$refs.mainTable.clearSelection()
            }
          })

          // 判断是否有数据
          if (this.mainDataList.length > 0) {
            this.$refs.mainTable.setCurrentRow(this.mainDataList[0])
            this.changeData(this.mainDataList[0])
          } else {
            this.changeData(null)
          }
        } else {
          console.error('查询失败:', data)
          this.$message.error((data && data.msg) || '查询失败')
        }
        this.dataListLoading = false
        console.log('设置 loading 为 false')
      }).catch((error) => {
        console.error('查询费用列表异常:', error)
        this.$message.error('查询失败，请稍后重试')
        this.dataListLoading = false
        console.log('异常处理，设置 loading 为 false')
      })
    },

    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getMainData()
    },

    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getMainData()
    },

    // 行点击事件
    changeData(row) {
      this.currentRow = row ? JSON.parse(JSON.stringify(row)) : {}
    },

    // 页签点击事件
    handleTabClick(tab) {
      if (tab.name === 'detail') {
        this.$nextTick(() => {
          if (this.$refs.feeDetailTab) {
            this.$refs.feeDetailTab.loadDetailList()
          }
        })
      } else if (tab.name === 'request') {
        this.$nextTick(() => {
          if (this.$refs.requestFeeTab) {
            this.$refs.requestFeeTab.loadRequestFeeList()
          }
        })
      }
    },

    // 新增
    handleAdd() {
      this.addDialogVisible = true
      this.addFormData = {
        feeDate: '',
        applyUser: '',
        remark: ''
      }
      if (this.$refs.addFormData) {
        this.$refs.addFormData.clearValidate()
      }
    },

    // 保存新增
    handleSaveAdd() {
      this.$refs.addFormData.validate((valid) => {
        if (valid) {
          const params = {
            site: this.$store.state.user.site,
            feeDate: this.addFormData.feeDate,
            applyUser: this.addFormData.applyUser,
            remark: this.addFormData.remark,
            createdBy: this.$store.state.user.name,
            updateBy: this.$store.state.user.name
          }

          createFeeHeader(params).then(({ data }) => {
            if (data.code === 0) {
              this.$message.success('创建成功')
              this.addDialogVisible = false
              this.getMainData()
            } else {
              this.$message.error(data.msg || '创建失败')
            }
          }).catch(() => {
            this.$message.error('创建失败')
          })
        }
      })
    },

    // 编辑（切换到费用明细页签）
    handleEdit(row) {
      this.changeData(row)
      this.activeTab = 'detail'
      this.$nextTick(() => {
        if (this.$refs.feeDetailTab) {
          this.$refs.feeDetailTab.loadDetailList()
        }
      })
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除该费用记录吗？删除后将同时删除明细和关联申请单。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          site: row.site,
          feeNo: row.feeNo
        }

        deleteFeeRecord(params).then(({ data }) => {
          if (data.code === 0) {
            this.$message.success('删除成功')
            this.getMainData()
          } else {
            this.$message.error(data.msg || '删除失败')
          }
        }).catch(() => {
          this.$message.error('删除失败')
        })
      }).catch(() => {})
    }
  },
  created() {
    this.getMainData()
  }
}
</script>

<style scoped lang="scss">

.search-form-inline {
  background: #fff;
  padding: 0;
  margin-bottom: 0;
}

.search-row {
  display: flex;
  align-items: flex-end;
  flex-wrap: wrap;
  gap: 0;
  margin-bottom: 0;
}

.search-item {
  flex: none;
  margin-bottom: 0;
  margin-right: 12px;
}

.search-item /deep/ .el-form-item__label {
  font-size: 14px;
  padding-bottom: 0;
  line-height: 1.2;
}

.search-btn-item {
  flex: none;
  margin-bottom: 0;
  margin-right: 0;
}

.search-btn-item /deep/ .el-form-item__content {
  line-height: normal;
}

.search-item /deep/ .el-form-item__label {
  font-size: 13px;
  color: #606266;
  padding-bottom: 5px;
  line-height: 1;
  height: auto;
}

.search-item /deep/ .el-form-item__content {
  line-height: normal;
}

/deep/ .customer-tab .el-tabs__content {
  padding: 5px !important;
}

// 按钮样式（与 inspectionRequestList 保持一致）
.customer-bun-min {
  padding: 7px 12px;
  font-size: 12px;
  border-radius: 3px;
}


</style>
