<template>
  <div class="app-container">
    <!-- 机具供应展示 -->
    <el-form v-show="showSearch" size="small" :model="queryParams" ref="queryFormRef" inline @submit.native.prevent>
      <el-row>
        <el-col :span="6">
          <el-form-item>
            <el-date-picker
              v-model="queryDate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
        <el-form-item prop="keyWord">
          <el-input
            v-model="queryParams.keyWord"
            placeholder="请输入关键词检索"
            clearable
            style="width: 250px"
            @keyup.enter.native="onHandleSearch"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onHandleSearch">查询</el-button>
          <el-button icon="el-icon-refresh" @click="onHandleReset">重置</el-button>
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出数据</el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <div class="card-box">
      <div class="card-box-content">
        <div v-for="(card, index) in cardList_2" :key="index">
          <CardModel :state="card" />
        </div>
      </div>
    </div>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="tableList" fit highlight-current-row style="width: 100%">
      <!-- 多选 -->
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuation(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column
        v-for="(column, index) in tableColumns"
        show-overflow-tooltip
        :key="index"
        :label="column.label"
        :prop="column.prop"
        :width="column.width"
        align="center"
      ></el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { getRepairHomeTotalListApi, getRepairHomeListApi } from '@/api/home/maintain-balance'
import CardModel from './components/card-model' // 卡片组件

export default {
  components: {
    CardModel
  },
  data() {
    return {
      showSearch: true,
      total: 0,
      // 表单查询条件
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startTime: '',
        endTime: '',
        keyWord: ''
      },
      // 日期查询条件
      queryDate: [], // 默认时间范围
      cardList_2: [
        {
          title: '总接收量',
          theme: '#5ad55a',
          icon: 'In_the_library',
          isIncrease: true,
          increase: 0,
          count: 0
        },
        {
          title: '已修数量',
          theme: '#0099ff',
          icon: 'In_use',
          isIncrease: true,
          increase: 0,
          count: 0
        },
        {
          title: '在修数量',
          theme: '#8167f5',
          icon: 'In_repair',
          isIncrease: true,
          increase: 0,
          count: 0
        },
        {
          title: '报废数量',
          theme: '#bfbf00',
          icon: 'scrapped',
          isIncrease: true,
          increase: 0,
          count: 0
        },
        {
          title: '试验数量',
          theme: '#b8741a',
          icon: 'repair_store',
          isIncrease: true,
          increase: 0,
          count: 0
        }
      ],
      pickerOptions: {
        // disabledDate 禁用日期
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      tableList: [],
      tableColumns: [
        { label: '类型名称', prop: 'typeName' },
        { label: '规格型号', prop: 'typeModelName' },
        { label: '维修单号', prop: 'repairCode', width: '150' },
        { label: '单位', prop: 'unitName' },
        { label: '总接收数量', prop: 'backNum' },
        { label: '已修数量', prop: 'repairedNum' },
        { label: '在修数量', prop: 'repairingNum' },
        { label: '报废数量', prop: 'scrapNum' },
        { label: '试验数量', prop: 'testNum' },
        { label: '更换配件量', prop: 'changePartNum' },
        { label: '收费配件金额(元)', prop: 'amountPartPrice' },
        { label: '不收费配件金额(元)', prop: 'noAmountPartPrice' }
      ]
    }
  },
  created() {
    this.queryDate = this.getDefaultDateRange()
    this.getList()
  },
  methods: {
    async getList() {
      if (this.queryDate) {
        this.queryParams.startTime = this.queryDate[0]
        this.queryParams.endTime = this.queryDate[1]
      } else {
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }
      const loading = this.$loading({ text: '加载中...' })
      // console.log('🚀 ~ getList ~ this.queryParams:', this.queryParams)
      try {
        const res = await getRepairHomeListApi(this.queryParams)
        // console.log('🚀 ~ getList ~ res:', res)
        this.tableList = res.data.rows
        this.total = res.data.total
        const res2 = await getRepairHomeTotalListApi(this.queryParams)
        if (res2.code === 200 && res2.data) {
          res2.data.forEach((item, index) => {
            this.cardList_2[index].increase = item.increase
            this.cardList_2[index].isIncrease = item.isIncrease
            if (index === 0) {
              this.cardList_2[0].count = item.backNum
            } else if (index === 1) {
              this.cardList_2[1].count = item.repairedNum
            } else if (index === 2) {
              this.cardList_2[2].count = item.repairingNum
            } else if (index === 3) {
              this.cardList_2[3].count = item.scrapNum
            } else if (index === 4) {
              this.cardList_2[4].count = item.testNum
            }
          })
        }
        loading.close()
      } catch (error) {
        console.log('🚀 ~ getList ~ error:', error)
        loading.close()
      }
    },
    // 查询
    onHandleSearch() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    onHandleReset() {
      this.queryDate = this.getDefaultDateRange()
      this.$refs.queryFormRef.resetFields()
      this.getList()
    },
    // 默认日期范围
    getDefaultDateRange() {
      const today = new Date()

      // 获取上个月的同一天
      const lastMonth = new Date(today)
      lastMonth.setMonth(today.getMonth() - 1)

      // 处理日期溢出问题
      if (lastMonth.getDate() !== today.getDate()) {
        lastMonth.setDate(0) // 设置为上个月的最后一天
      }

      const formatDate = date => {
        const y = date.getFullYear()
        const m = String(date.getMonth() + 1).padStart(2, '0')
        const d = String(date.getDate()).padStart(2, '0')
        return `${y}-${m}-${d}`
      }

      return [formatDate(lastMonth), formatDate(today)]
    },
    // 导出数据
    handleExport() {
      if (this.queryDate) {
        this.queryParams.startTime = this.queryDate[0]
        this.queryParams.endTime = this.queryDate[1]
      } else {
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }
      try {
        let fileName = `修试平衡表_${new Date().getTime()}.xLsx`
        let url = '/material/repair_audit_details/exportRepairHomeList'
        const params = { ...this.queryParams }
        console.log('🚀 ~ 导出 ~ params:', params)
        this.download(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    }
  }
}
</script>

<style scoped lang="scss">
// 卡片区样式
.card-box {
  display: flex;
  height: 110px;

  .card-box-content {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 12px;
    margin-right: -12px;
  }
}
</style>
