<template>
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline @submit.native.prevent>
      <el-form-item label="协议ID" prop="agreementId">
        <el-input
          v-model="queryParams.agreementId"
          placeholder="请输入协议ID"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="机具规格ID" prop="typeId">
        <el-input
          v-model="queryParams.typeId"
          placeholder="请输入机具规格ID"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="机具ID" prop="maId">
        <el-input
          v-model="queryParams.maId"
          placeholder="请输入机具ID"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px"
        />
      </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> -->
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="tableList" fit highlight-current-row style="width: 100%" @selection-change="selectionChange">
      <!-- 多选 -->
      <el-table-column type="selection" width="55" align="center" :selectable="isSelectable" />
      <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"
        :width="column.width"
        align="center"
      ></el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template slot-scope="{ row }">
          <el-button type="text" size="mini" icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" size="mini" icon="el-icon-delete" style="color: #f56c6c" @click="handleDelete(row)">
            删除
          </el-button>
        </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="60%">
      <el-form ref="dialogForm" :model="dialogForm" label-width="120px" :rules="dialogRules">
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="协议ID" prop="agreementId">
              <el-input v-model="dialogForm.agreementId" placeholder="请输入协议ID" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="机具规格ID" prop="typeId">
              <el-input v-model="dialogForm.typeId" placeholder="请输入机具规格ID" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="机具ID" prop="maId">
              <el-input v-model="dialogForm.maId" placeholder="请输入机具ID" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="领料数量" prop="num">
              <el-input v-model="dialogForm.num" type="number" :min="0" placeholder="请输入领料数量" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="领料时间" prop="outTime">
              <el-date-picker
                v-model="dialogForm.outTime"
                type="datetime"
                placeholder="请选择领料时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="退料时间" prop="backTime">
              <el-date-picker
                v-model="dialogForm.backTime"
                type="datetime"
                placeholder="请选择退料时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="状态" prop="status">
              <el-input v-model="dialogForm.status" placeholder="请输入状态" clearable />
            </el-form-item>
          </el-col>
          <!-- 领料ID -->
          <el-col :span="12" :offset="0">
            <el-form-item label="领料ID" prop="pickId">
              <el-input v-model="dialogForm.pickId" placeholder="请输入领料ID" clearable />
            </el-form-item>
          </el-col>
          <!-- 退料ID -->
          <el-col :span="12" :offset="0">
            <el-form-item label="退料ID" prop="backId">
              <el-input v-model="dialogForm.backId" placeholder="请输入退料ID" clearable />
            </el-form-item>
          </el-col>
          <!-- 租赁单价 -->
          <el-col :span="12" :offset="0">
            <el-form-item label="租赁单价" prop="leasePrice">
              <el-input v-model="dialogForm.leasePrice" type="number" :min="0" placeholder="请输入租赁单价" clearable />
            </el-form-item>
          </el-col>
          <!-- 是否结算 -->
          <el-col :span="12" :offset="0">
            <el-form-item label="是否结算" prop="isSlt">
              <el-input v-model="dialogForm.isSlt" placeholder="请输入是否结算" clearable />
            </el-form-item>
          </el-col>
          <!-- 结算时间 -->
          <el-col :span="12" :offset="0">
            <el-form-item label="结算时间" prop="sltTime">
              <el-date-picker
                v-model="dialogForm.sltTime"
                type="datetime"
                placeholder="请选择结算时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getListApi, getInfoApi, updateInfoApi } from '@/api/accountsInfoManagement'

export default {
  data() {
    return {
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        agreementId: '', // 协议ID
        typeId: '', // 机具型号ID
        maId: '' // 机具ID
      },
      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: 'ID', prop: 'id' },
        { label: '协议ID', prop: 'agreementId' },
        { label: '机具型号ID', prop: 'typeId' },
        { label: '机具ID', prop: 'maId' },
        { label: '领料数量', prop: 'num' },
        { label: '领料时间', prop: 'outTime', width: '120' },
        { label: '退料时间', prop: 'backTime', width: '120' },
        { label: '状态', prop: 'status' },
        { label: '租赁价格', prop: 'leasePrice' },
        { label: '是否结算', prop: 'isSlt' },
        { label: '结算日期', prop: 'sltTime', width: '120' }
      ],
      // 表格数据
      tableList: [],
      isEdit: false, // 是否编辑
      dialogTitle: '新增',
      dialogVisible: false,
      dialogForm: {
        pickId: null, // 领料ID
        backId: null, // 退料ID
        agreementId: null, // 协议ID
        typeId: null, // 机具规格ID
        maId: null, // 机具ID
        num: null, // 领料数量
        outTime: '', // 领料时间
        backTime: '', // 退料时间
        status: null, // 状态
        leasePrice: null, // 租赁价格
        isSlt: null, // 是否结算
        sltTime: '', // 结算时间
        optFlag: 'insert' // 操作标识
      },
      dialogRules: {},
      selectedRows: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.$refs.queryForm.resetFields()
      this.getList()
    },
    // 获取列表
    async getList() {
      console.log('列表-查询', this.queryParams)
      const loading = this.$loading({ text: '加载中...' })
      try {
        const params = { ...this.queryParams }
        const res = await getListApi(params)
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.rows
        this.total = res.total
        loading.close()
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
        this.tableList = []
        this.total = 0
        loading.close()
      }
    },
    // 多选
    selectionChange(val) {
      console.log('selectionChange', val)
      this.selectedRows = val
    },
    isSelectable(row, index) {
      // 如果已经有选中的行，并且当前行不是已选中的，则禁用
      return this.selectedRows.length === 0 || this.selectedRows.some(selected => selected.id === row.id)
    },
    handleAdd() {
      console.log('新增')
      this.dialogTitle = '新增'
      this.dialogVisible = true
      this.isEdit = false
      setTimeout(() => {
        this.$refs.dialogForm.resetFields()
        if (this.selectedRows.length > 0) {
          this.dialogForm = { ...this.selectedRows[0] }
        }
      }, 100)
    },
    // 编辑
    handleEdit(row) {
      console.log('编辑', row)
      this.dialogTitle = '编辑'
      this.dialogVisible = true
      this.isEdit = true
      setTimeout(() => {
        this.$refs.dialogForm.resetFields()
        this.getInfoDetails(row.id)
      }, 100)
    },
    // 获取详情
    async getInfoDetails(id) {
      const loading = this.$loading({ text: '加载中...' })
      try {
        const res = await getInfoApi({ id })
        console.log('🚀 ~ 获取详情 ~ res:', res)
        this.dialogForm = { ...res.data }
      } catch (error) {
        console.log('🚀 ~ 获取详情 ~ error:', error)
      } finally {
        loading.close()
      }
    },
    // 删除
    handleDelete(row) {
      console.log('删除', row)
      const optFlag = 'delete'
      this.$confirm('是否删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const loading = this.$loading({ text: '加载中...' })
        try {
          const res = await updateInfoApi({ id: row.id, optFlag })
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        } catch (error) {
          console.log('删除失败', error)
        } finally {
          loading.close()
        }
      })
    },
    // 导出数据
    formatTime(dater) {
      let date = dater || new 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()}.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)
      }
    },
    // 弹框确认
    dialogConfirm() {
      console.log('dialogConfirm')
      this.$refs.dialogForm.validate(async valid => {
        if (valid) {
          const loading = this.$loading({ text: '加载中...' })
          try {
            if (this.isEdit) {
              this.dialogForm.optFlag = 'update'
            } else {
              this.dialogForm.optFlag = 'insert'
              delete this.dialogForm.id
            }
            const params = { ...this.dialogForm }
            console.log('🚀 ~ dialogConfirm ~ params:', params)
            const res = await updateInfoApi(params)
            this.dialogVisible = false
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getList()
          } catch (error) {
            console.log('🚀 ~ dialogConfirm ~ error:', error)
          } finally {
            loading.close()
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

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