<template>
  <!-- 基础页面 -->
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline @submit.native.prevent>
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键字"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px"
        />
      </el-form-item>
      <!-- 日期范围 -->
      <el-form-item label="查询日期" prop="timeRange">
        <el-date-picker
          v-model="queryParams.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable
          unlink-panels
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          style="width: 240px"
          :picker-options="pickerOptions"
        />
      </el-form-item>

      <!-- 表单按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table :data="tableList" fit highlight-current-row style="width: 100%" v-loading="isLoading" :max-height="650">
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="index => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1"
      />
      <el-table-column
        v-for="(column, index) in tableColumns"
        show-overflow-tooltip
        :key="index"
        :label="column.label"
        :prop="column.prop"
        align="center"
      >
        <!-- 插槽 -->
        <template v-slot="{ row }" v-if="column.prop == 'outNum'">
          <span
            v-if="row.outNum > 0"
            style="color: #F56C6C; cursor: pointer; text-decoration: underline"
            @click="handleDialog(row, 'out')"
          >
            {{ row.outNum }}
          </span>
          <span v-else>{{ row.outNum }}</span>
        </template>
        <template v-slot="{ row }" v-else-if="column.prop == 'inputNum'">
          <span
            v-if="row.inputNum > 0"
            style="color: #409eff; cursor: pointer; text-decoration: underline"
            @click="handleDialog(row, 'in')"
          >
            {{ row.inputNum }}
          </span>
          <span v-else>{{ row.inputNum }}</span>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%">
      <el-form ref="dialogForm" :model="dialogForm" label-width="" size="small" inline @submit.native.prevent>
        <el-form-item label="关键字" prop="keyword">
          <el-input v-model="dialogForm.keyword" placeholder="请输入关键字" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleDialogQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="handleDialogReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="dialogList"
        fit
        highlight-current-row
        style="width: 100%"
        v-loading="isLoading"
        :max-height="500"
      >
        <el-table-column
          type="index"
          width="55"
          label="序号"
          align="center"
          :index="index => (dialogForm.pageNum - 1) * dialogForm.pageSize + index + 1"
        />
        <el-table-column
          v-for="(column, index) in dialogColumns"
          show-overflow-tooltip
          :key="index"
          :label="column.label"
          :prop="column.prop"
          align="center"
        >
          <!-- 插槽 -->
          <template v-slot="{ row }" v-if="column.prop == 'num'">
            <span v-if="isOut">{{ row.outNum }}</span>
            <span v-else>{{ row.inputNum }}</span>
          </template>
          <template v-slot="{ row }" v-else-if="column.prop == 'maCode'">
            <span>{{ row.maCode || '-' }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="dlgTotal > 0"
        :total="dlgTotal"
        :page.sync="dialogForm.pageNum"
        :limit.sync="dialogForm.pageSize"
        @pagination="getDialogList"
      />

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getInventoryLogListApi, getInventoryLogDetailsApi } from '@/api/operationsManagement'

export default {
  data() {
    return {
      isLoading: false,
      showSearch: true,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: '', // 关键字
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        timeRange: [] // 创建日期范围
      },
      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: '物品种类', prop: 'constructionType' },
        { label: '物品类型', prop: 'materialType' },
        { label: '设备类型', prop: 'typeName' },
        { label: '规格型号', prop: 'typeModelName' },
        { label: '昨日库存', prop: 'preStoreNum' },
        { label: '出库数', prop: 'outNum' },
        { label: '入库数', prop: 'inputNum' },
        { label: '当前库存', prop: 'afterStoreNum' }
      ],
      // 表格数据
      tableList: [],
      isOut: false, // 是否出库
      dialogTitle: '详情',
      dialogVisible: false,
      dialogForm: {
        keyword: '',
        pageNum: 1,
        pageSize: 10
      },
      dlgTotal: 0, // 弹框总条数
      dialogColumns: [
        { label: '设备类型', prop: 'typeName' },
        { label: '规格型号', prop: 'typeModelName' },
        { label: '设备编码', prop: 'maCode' },
        { label: '数量', prop: 'num' },
        { label: '操作人', prop: 'nickName' },
        { label: '操作时间', prop: 'createTime' },
        { label: '任务单号', prop: 'code' }
      ],
      dialogList: []
    }
  },
  created() {
    const date = new Date()
    this.queryParams.timeRange = [this.format(date), this.format(date)]
    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}`
    },
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.$refs.queryForm.resetFields()
      const date = new Date()
      this.queryParams.timeRange = [this.format(date), this.format(date)]
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getList()
    },
    // 获取列表
    async getList() {
      console.log('列表-查询', this.queryParams)
      this.isLoading = true
      try {
        const params = {
          ...this.queryParams,
          startTime: this.queryParams.timeRange ? this.queryParams.timeRange[0] : '',
          endTime: this.queryParams.timeRange ? this.queryParams.timeRange[1] : ''
        }
        delete params.timeRange
        console.log('🚀 ~ getList ~ params:', params)
        const res = await getInventoryLogListApi(params)
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.data.rows || []
        this.total = res.data.total || 0
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
        this.tableList = []
        this.total = 0
      } finally {
        this.isLoading = false
      }
    },

    handleDialog(row, type) {
      console.log('🚀 ~ handleDialog ~ row:', row)
      this.dialogTitle = type == 'out' ? '出库详情' : '入库详情'
      this.isOut = type == 'out' ? true : false
      this.dialogVisible = true
      this.dialogList = []
      setTimeout(() => {
        this.$refs.dialogForm.resetFields()
        this.dialogForm.typeId = row.typeId
        this.dialogForm.startTime = this.queryParams.timeRange ? this.queryParams.timeRange[0] : ''
        this.dialogForm.endTime = this.queryParams.timeRange ? this.queryParams.timeRange[1] : ''
        this.getDialogList()
      }, 100)
    },
    // 弹框查询
    handleDialogQuery() {
      this.dialogForm.pageNum = 1
      this.getDialogList()
    },
    // 重置
    handleDialogReset() {
      this.dialogForm.keyword = ''
      this.dialogForm.pageNum = 1
      this.dialogForm.pageSize = 10
      this.getDialogList()
    },
    // 获取弹框列表
    async getDialogList() {
      try {
        this.isLoading = true
        const params = { ...this.dialogForm }
        console.log('🚀 ~ getDialogList ~ params:', params)
        const res = await getInventoryLogDetailsApi(params)
        console.log('🚀 ~ 获取弹框列表 ~ res:', res)
        this.dialogList = res.data.rows || []
        this.dlgTotal = res.data.total || 0
      } catch (error) {
        console.log('🚀 ~ 获取弹框列表 ~ error:', error)
      } finally {
        this.isLoading = false
      }
    },
    // 导出数据
    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}`
    },
    // 导出数据
    handleExport() {
      // 提示
      this.$message({
        type: 'warning',
        message: '导出功能开发中，敬请期待！'
      })
      try {
        let fileName = `导出_${this.formatTime(new Date())}.xLsx`
        let url = '/material/backstage/costPush/exportPushCheck'
        const params = { ...this.queryParams }
        console.log('🚀 ~ 导出 ~ params:', params)
        // this.derive(url, params, fileName)
        // this.download(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
