<template>
  <div class="app-container">
    <el-card style="margin-bottom: 20px">
      <el-form
        v-show="showSearch"
        :model="queryParams"
        ref="queryForm"
        size="small"
        class="search-form"
        label-width="80px"
        @submit.native.prevent
      >
        <el-form-item label="申请人:" prop="createUser">
          <el-input
            v-model="queryParams.createUser"
            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"
          />
        </el-form-item>
        <el-form-item label="审批状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 240px">
            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <!-- 表单按钮 -->
        <el-form-item class="form-right">
          <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-card>

    <el-card style="margin-bottom: 20px">
      <el-row :gutter="10" class="mb8" style="display: flex; justify-content: flex-end">
        <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="handleAdd">新增</el-button>
          <el-button type="primary" size="mini" @click="batchSubmit">申请提交</el-button>
        </el-col>
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" /> -->
      </el-row>

      <el-table
        class="my-table"
        :data="tableList"
        highlight-current-row
        style="width: 100%"
        v-loading="isLoading"
        @selection-change="selectionChange"
      >
        <el-table-column type="selection" width="45" align="center" :selectable="selectable"/>
        <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 }">
            <span v-if="column.prop == 'status'">
              <el-tag v-if="row.status == 0" size="small" type="info">草稿</el-tag>
              <el-tag v-if="row.status == 1" size="small" type="warning">待审批</el-tag>
              <el-tag v-if="row.status == 2" size="small" type="success">审批通过</el-tag>
              <el-tag v-if="row.status == 3" size="small" type="danger">驳回</el-tag>
            </span>
            <span v-else>{{ row[column.prop] }}</span>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" align="center" width="150">
          <template v-slot="{ row }">
            <el-button v-if="row.status == 0 || row.status == 3" type="text" size="mini" @click="handleEdit(row)"
            >编辑
            </el-button
            >
            <el-button
              v-if="row.status == 0 || row.status == 3"
              type="text"
              style="color: red"
              size="mini"
              @click="handleDelete(row)"
            >删除
            </el-button
            >
            <el-button v-if="row.status == 0 || row.status == 3" type="text" size="mini" @click="submit(row)"
            >提交
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>

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

<script>
import { getWarehousingListApi, deleteByIdApi, batchSubmissionApi } from '@/api/EquipmentEntryApply'

export default {
  name: 'EntryApply',
  data() {
    return {
      isLoading: false,
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createUser: '', // 关键字
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        timeRange: [], // 创建日期范围
        status: ''
      },
      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: '录入单号', prop: 'code' },
        { label: '装备数量', prop: 'maNum' },
        { label: '工具数量', prop: 'toolNum' },
        { label: '申请人', prop: 'createUser' },
        { label: '申请时间', prop: 'createTime' },
        { label: '审批状态', prop: 'status' }
      ],
      // 表格数据
      tableList: [],
      statusList: [
        { label: '草稿', value: '0' },
        { label: '待审批', value: '1' },
        // { label: '审批通过', value: '2' },
        { label: '驳回', value: '3' }
      ],
      selectedRowKeys: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.$refs.queryForm.resetFields()
      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] : '',
          isStatus: '2'
        }
        delete params.timeRange
        console.log('🚀 ~ getList ~ params:', params)
        const res = await getWarehousingListApi(params)
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.rows || []
        this.total = res.total || 0
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
        this.tableList = []
        this.total = 0
      } finally {
        this.isLoading = false
      }
    },
    selectable(row) {
      return row.status != 2 && row.status !=1
    },
    selectionChange(val) {
      if (!val.length) this.selectedRowKeys = []
      this.selectedRowKeys = val.map((item) => item.id)
      console.log('🚀 ~ this.selectedRowKeys:', this.selectedRowKeys)
    },
    // 新增
    handleAdd() {
      this.$router
        .push({
          path: '/stockManagement/entryApply/apply',
          query: { isAddVisible: false, isApprovalVisible: false }
        })
        .then(() => {
          this.$tab.closePage({ path: '/stockManagement/entryApply' })
        })
    },
    // 编辑
    handleEdit(row) {
      this.$router
        .push({
          path: '/stockManagement/entryApply/apply',
          query: {
            id: row.id,
            orderId: row.orderId,
            applyId: row.applyId,
            isAddVisible: false,
            isApprovalVisible: false,
            isEdit: true
          }
        })
        .then(() => {
          this.$tab.closePage({ path: '/stockManagement/entryApply' })
        })
    },
    // 删除
    async handleDelete(row) {
      // 确认
      this.$modal.confirm('是否确认删除该数据项？').then(async() => {
        try {
          await deleteByIdApi({ id: row.id })
          this.$modal.msgSuccess('操作成功')
          this.getList()
        } catch (error) {
          console.log('🚀 ~ error:', error)
        }
      })
    },
    // 提交
    async submit(row) {
      console.log('🚀 ~ row:', row)
      // 确认
      this.$modal.confirm('是否确认提交？').then(async() => {
        try {
          await batchSubmissionApi(row.id)
          this.$modal.msgSuccess('操作成功')
          this.getList()
        } catch (error) {
          console.log('🚀 ~ error:', error)
        }
      })
    },
    // 批量提交
    async batchSubmit() {
      if (this.selectedRowKeys.length === 0) {
        this.$modal.msgError('请选择需要提交的数据')
        return
      }
      // 确认
      this.$modal.confirm('是否确认提交？').then(async() => {
        try {
          const params = this.selectedRowKeys.join(',')
          console.log('🚀 ~ params:', params)
          await batchSubmissionApi(params)
          this.$modal.msgSuccess('操作成功')
          this.getList()
        } catch (error) {
          console.log('🚀 ~ error:', error)
        }
      })
    }
  }
}
</script>

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