<template>
  <div class="app-container" id="">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="开始日期"
          @change="() => queryParams.endTime = ''"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item>-</el-form-item>
      <el-form-item prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="结束日期"
          :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item prop="proName">
        <el-input
          v-model="queryParams.proName"
          placeholder="请输入工程名称"
          clearable
          :maxlength="20"
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item prop="jijuType">
        <el-select v-model="queryParams.jijuType" placeholder="请选择机具类型" style="width: 240px">
          <el-option label="施工机具" value="1"></el-option>
          <el-option label="安全工器具" value="2"></el-option>
        </el-select>
      </el-form-item>

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

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <div style="font-weight: bolder">
          统计日期：
          <span v-if="queryParams.startTime && queryParams.endTime">{{ queryParams.startTime }} 至 {{ queryParams.endTime }}</span>
        </div>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="tableList" :max-height="650">
      <el-table-column
        label="序号"
        align="center"
        width="80"
        type="index"
        :index="indexContinuation(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column label="分公司" align="center" prop="impUnitName" min-width="160"/>
      <el-table-column label="工程名称" align="center" prop="proName" min-width="160">
        <template slot-scope="scope">
          <span  class="clickText" @click="openDeviceRecords(scope.row)">
            {{ scope.row.proName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="机具类型" align="center" prop="jijuType" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.jijuType == '施工机具'" effect="plain">施工机具</el-tag>
          <el-tag type="warning" v-if="scope.row.jijuType == '安全工器具'" effect="plain">安全工器具</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="需求数量" align="center" prop="needNum" :show-overflow-tooltip="true" />
      <el-table-column label="已供数量（累计）" align="center" prop="supplyNum" :show-overflow-tooltip="true" />
      <el-table-column label="差值（已供G-需求F）" align="center" prop="diffNum" :show-overflow-tooltip="true" />
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      @pagination="getList"
    />

    <!-- 二级弹窗-->
    <el-dialog :title="titleDevice" :visible.sync="openDeviceRecord" width="1200px" append-to-body>
      <el-form :model="dialogDeviceQuery" ref="dialogDeviceQuery" size="small" :inline="true" label-width="80px">
        <el-form-item label="关键字" prop="keyWord">
          <el-input
            v-model="dialogDeviceQuery.keyWord"
            placeholder="请输入关键字"
            clearable
            :maxlength="20"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDialogDeviceQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-download" size="mini" @click="handleDialogDeviceExport">导出</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loadingDevice" :data="deviceRecordList" :max-height="650">
        <el-table-column
          label="序号"
          align="center"
          width="80"
          type="index"
          :index="indexContinuation(dialogDeviceQuery.pageNum, dialogDeviceQuery.pageSize)"
        ></el-table-column>
      <!-- <el-table-column label="工程名称" align="center" prop="proName" min-width="160"/> -->
      <el-table-column label="物资名称" align="center" prop="typeName" :show-overflow-tooltip="true"/>
      <el-table-column label="规格型号" align="center" prop="typeModelName" :show-overflow-tooltip="true" />
      <el-table-column label="单位" align="center" prop="unit" :show-overflow-tooltip="true" />
      <el-table-column label="需求数量" align="center" prop="needNum" :show-overflow-tooltip="true" />
      <el-table-column label="已供数量" align="center" prop="supplyNum" :show-overflow-tooltip="true" />
      <el-table-column label="差值（已供G-需求F）" align="center" prop="diffNum" :show-overflow-tooltip="true" />      
      <el-table-column label="在用数量" align="center" prop="usNum" :show-overflow-tooltip="true" />
      <el-table-column label="库存数量" align="center" prop="storeNum" :show-overflow-tooltip="true" />
      <el-table-column label="在修数量" align="center" prop="repairNum" :show-overflow-tooltip="true" />
      <el-table-column label="待入库数量" align="center" prop="inputNum" :show-overflow-tooltip="true" />
      <el-table-column label="总保有量" align="center" prop="allNum" :show-overflow-tooltip="true" />
      <el-table-column label="总在用工程明细" align="center" prop="allUsNum" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.allUsNum > 0" class="clickText" @click="openUserRecords(scope.row)">
            {{ scope.row.allUsNum }}
          </span>
          <!-- 否则，直接显示数字 -->
          <span v-else>
            {{ scope.row.allUsNum }}
          </span>
        </template>
      </el-table-column>>
      </el-table>

      <pagination
        v-show="dialogDeviceTotal > 0"
        :total="dialogDeviceTotal"
        :page.sync="dialogDeviceQuery.pageNum"
        :limit.sync="dialogDeviceQuery.pageSize"
        @pagination="getDeviceRecords"
      />
    </el-dialog>    

    <!-- 在用编码设备弹窗-->
    <el-dialog :title="title" :visible.sync="openUseRecord" width="1200px" append-to-body>
      <el-form :model="dialogUseQuery" ref="dialogUseQuery" size="small" :inline="true" label-width="80px">
        <el-form-item label="关键字" prop="keyWord">
          <el-input
            v-model="dialogUseQuery.keyWord"
            placeholder="请输入关键字"
            clearable
            :maxlength="20"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDialogUseQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-download" size="mini" @click="handleDialogUserExport">导出</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading2" :data="useRecordList" :max-height="650">
        <el-table-column
          label="序号"
          align="center"
          width="80"
          type="index"
          :index="indexContinuation(dialogUseQuery.pageNum, dialogUseQuery.pageSize)"
        ></el-table-column>
        <el-table-column label="工程名称" align="center" prop="proName" width="200" />
        <el-table-column label="物资名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
        <el-table-column label="规格型号" align="center" prop="typeModelName" :show-overflow-tooltip="true" />
        <el-table-column label="在用数量" align="center" prop="usNum" :show-overflow-tooltip="true" />
      </el-table>

      <pagination
        v-show="dialogUserTotal > 0"
        :total="dialogUserTotal"
        :page.sync="dialogUseQuery.pageNum"
        :limit.sync="dialogUseQuery.pageSize"
        @pagination="getUserRecords"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getStatisticsListApi, getAllUsDetailsApi,getAllDeviceDetailsApi } from '@/api/stquery/stquery'
export default {
  name: 'DeviceStatusRecord',
  dicts: [],
  data() {
    return {
      // 遮罩层
      loading: false,
      loading2: false,
      // 选中数组
      ids: [],
      // 弹出层标题
      title: '查看在用明细',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 主表格数据
      tableList: [],
      // 查询参数
      queryParams: {
        time: [],
        pageNum: 1,
        pageSize: 10,
        jijuType: null,
        proName: null,
        startTime: null,
        endTime: null
      },
      //在用弹窗
      openUseRecord: false,
      dialogUseQuery: {
        pageNum: 1,
        pageSize: 10,
        keyWord: undefined,
        typeId: undefined
      },
      useRecordList: [], //在用设备列表
      dialogUserTotal: 0,

      // 二级弹窗参数
      openDeviceRecord: false, // 二级弹窗
      dialogDeviceQuery: { // 二级查询参数
        pageNum: 1,
        pageSize: 10,
        keyWord: undefined,
        proId: undefined,
        jijuType: undefined,
        startTime: undefined,
        endTime: undefined
      },
      deviceRecordList: [], // 二级列表数据
      dialogDeviceTotal: 0, // 二级总条数
      titleDevice: '查看', // 二级标题
      loadingDevice: false, // 二级加载
    }
  },
  created() {
    const end = new Date()
    let start = new Date()
    start.setMonth(start.getMonth() - 1)
    this.queryParams.startTime = this.format(start)
    this.queryParams.endTime = this.format(end)
    this.getList()
  },
  methods: {
    format(date) {
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${y}-${m}-${day}`
    },
    // 获取列表
    async getList() {
      try {
        this.loading = true
        const params = {
          jijuType: this.queryParams.jijuType,
          proName: this.queryParams.proName,
          pageSize: this.queryParams.pageSize,
          pageNum: this.queryParams.pageNum,
          startTime: this.queryParams.startTime,
          endTime: this.queryParams.endTime
        }
        const res = await getStatisticsListApi(params)
        if (res.data.rows.length > 0) {
          this.tableList = res.data.rows
        } else {
          this.tableList = []
        }
        this.total = res.data.total
      } catch (error) {
        console.log('🚀 ~ getList ~ error:', error)
      } finally {
        this.loading = false
      }
    },
    indexContinuationForTable(num, size) {
      let number = (num - 1) * size
      console.log(number)
      if (number == 0) {
        return '合计'
      } else {
        return number
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      const end = new Date()
      let start = new Date()
      start.setMonth(start.getMonth() - 1)
      this.queryParams.startTime = this.format(start)
      this.queryParams.endTime = this.format(end)
      this.handleQuery()
    },
    /** 导出按钮操作 */
    handleExport() {
      const formatTime = date => {
        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')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}${month}${day}_${hours}${minutes}${seconds}`
      }

      const currentTime = formatTime(new Date())
      this.download(
        'material/complex_query/exportStatisticsList',
        {
          ...this.queryParams,
          // startTime: this.queryParams.time ? this.queryParams.time[0] : '',
          // endTime: this.queryParams.time ? this.queryParams.time[1] : '',
        },
        `供应统计报表_${currentTime}.xlsx`
      )
    },
    // ------------------
    //查看二级列表
    openDeviceRecords(row) {
      this.openDeviceRecord = true
      this.dialogDeviceQuery.proId = row.proId
      this.dialogDeviceQuery.jijuType = row.jijuType === '施工机具' ? 1 : 2
      this.dialogDeviceQuery.keyWord = ''
      this.dialogDeviceQuery.pageNum = 1
      this.dialogDeviceQuery.pageSize = 10
      this.dialogDeviceQuery.startTime = this.queryParams.startTime
      this.dialogDeviceQuery.endTime = this.queryParams.endTime
      this.deviceRecordList = []
      this.getDeviceRecords()
    },

    /** 查询二级弹窗设备列表 */
    getDeviceRecords() {
      this.loadingDevice = true
      getAllDeviceDetailsApi(this.dialogDeviceQuery)
        .then(response => {
          this.deviceRecordList = response.data.rows
          this.dialogDeviceTotal = response.data.total
        })
        .catch(() => {
          this.deviceRecordList = []
          this.dialogDeviceTotal = 0
        })
        .finally(() => {
          this.loadingDevice = false
        })
    },

    /** 二级弹窗搜索按钮操作 */
    handleDialogDeviceQuery() {
      this.dialogDeviceQuery.pageNum = 1
      this.getDeviceRecords()
    },

    /** 二级弹窗导出按钮操作 */
    handleDialogDeviceExport() {
      const formatTime = date => {
        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')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}${month}${day}_${hours}${minutes}${seconds}`
      }

      const currentTime = formatTime(new Date())
      this.download(
        'material/complex_query/exportSecondStatisticsList',
        {
          ...this.dialogDeviceQuery,
          // startTime: this.queryParams.time ? this.queryParams.time[0] : '',
          // endTime: this.queryParams.time ? this.queryParams.time[1] : '',
        },
        `供应统计报表_明细_${currentTime}.xlsx`
      )
    },

    //查看在用设备
    openUserRecords(row) {
      this.openUseRecord = true
      this.dialogUseQuery.typeId = row.typeId
      this.dialogUseQuery.keyWord = ''
      this.dialogUseQuery.pageNum = 1
      this.dialogUseQuery.pageSize = 10
      this.useRecordList = []
      this.getUserRecords()
    },

    /** 查询在用设备列表 */
    getUserRecords() {
      this.loading2 = true
      getAllUsDetailsApi(this.dialogUseQuery)
        .then(response => {
          this.useRecordList = response.data.rows
          this.dialogUserTotal = response.data.total
        })
        .catch(() => {
          this.useRecordList = []
          this.dialogUserTotal = 0
        })
        .finally(() => {
          this.loading2 = false
        })
    },
    /** 搜索在用按钮操作 */
    handleDialogUseQuery() {
      this.dialogUseQuery.pageNum = 1
      this.getUserRecords()
    },
    handleDialogUserExport() {
      const formatTime = date => {
        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')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}${month}${day}_${hours}${minutes}${seconds}`
      }

      const currentTime = formatTime(new Date())
      this.download(
        'material/complex_query/exportAllUsDetails',
        { ...this.dialogUseQuery },
        `供应统计报表_在用设备_${currentTime}.xlsx`
      )
    }
    // ------------------
  }
}
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
  width: 60px !important;
  margin-bottom: 10px;
}
.clickText {
  color: #02a7f0;
  cursor: pointer;
}
</style>
