<template>
  <div class="app-container">
    <div class="card-change">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="60px">
        <el-form-item label="" prop="orderNumber">
          <el-input v-model="queryParams.orderNumber" placeholder="请输入盘点单号"/>
        </el-form-item>
        <el-form-item label="" v-model="queryParams.approvalStatus" prop="status">
          <el-select v-model="queryParams.approvalStatus" placeholder="请选择状态" style="" clearable>
            <el-option
              v-for="dict in dict.type.oilPurchasedStatus"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="beginTime"
            style="width: 160px"
            type="date"
            placeholder="开始日期">
          </el-date-picker>
          至
          <el-date-picker
            v-model="endTime"
            style="width: 160px"
            type="date"
            placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item style="float: right;margin-right: 0px">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          <el-button
            type="primary"
            @click="detailsAdd"
            v-hasPermi="['convenienceStore:inventory:index']"
          >新增库存盘点
          </el-button>
        </el-form-item>
      </el-form>

      <div style="height: 74vh;overflow: auto; scrollbar-width: none">
        <el-table ref="tables" border
                  v-loading="loading"
                  :data="inventoryList"
                  :default-sort="defaultSort">
          <el-table-column label="序号" align="center" type="index" width="60"></el-table-column>
          <el-table-column label="盘点单号" align="center" prop="orderNumber"></el-table-column>
          <el-table-column label="盘点数量" align="center" prop="inventoryQuantity">
            <template slot-scope="scope">
              <span>{{ scope.row.inventoryQuantity == null ? "-" : scope.row.inventoryQuantity }}</span>
            </template>
          </el-table-column>
          <el-table-column label="库存差异" align="center" prop="inventoryDiscrepancy">
            <template slot-scope="scope">
              <span>{{ scope.row.inventoryDiscrepancy == null ? "-" : scope.row.inventoryDiscrepancy }}</span>
            </template>
          </el-table-column>
          <el-table-column label="盈亏金额（元）" align="center" prop="profitLossAmount">
            <template slot-scope="scope">
              <span>{{ scope.row.profitLossAmount == null ? "-" : scope.row.profitLossAmount }}</span>
            </template>
          </el-table-column>

          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <div style="color: #FF9655" v-if="scope.row.approvalStatus == 'await'">待审核</div>
                <div style="color: #0DC291" v-if="scope.row.approvalStatus == 'qrts'" >已审核入库</div>
                <div style="color: #F44522" v-if="scope.row.approvalStatus == 'yzf'">已作废</div>
                <div style="color: #409EFF" v-if="scope.row.approvalStatus == 'ysh'" >已审核</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="制单人" align="center" prop="createByName" width="230px">
            <template slot-scope="scope">
              <span>{{ scope.row.createByName }}</span>
            </template>
          </el-table-column>

          <el-table-column label="审核人" align="center" prop="approverName">
            <template slot-scope="scope">
              <span>{{ scope.row.approverName == null ? "-" : scope.row.approverName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="入库人" align="center" prop="confirmerName">
            <template slot-scope="scope">
              <span>{{ scope.row.confirmerName == null ? "-" : scope.row.confirmerName }}</span>
            </template>
          </el-table-column>

          <el-table-column label="制单时间" align="center" prop="orderDate" >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.orderDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="审核时间" align="center" prop="examineTime" >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.examineTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="入库时间" align="center" prop="storageTime" >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.storageTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                v-if="scope.row.approvalStatus == 'await'"
                @click="dispose(scope.row)"
              >盘点审核
              </el-button>
              <el-button
                size="mini"
                type="text"
                v-else-if="scope.row.approvalStatus == 'ysh'"
                @click="dispose(scope.row)"
              >盘点入库
              </el-button>
              <el-button
                size="mini"
                type="text"
                v-else
                @click="dispose(scope.row)"
              >查看详情
              </el-button>
            </template>

          </el-table-column>
        </el-table>
      </div>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNo"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

  </div>
</template>

<script>
import {getInventoryPageApi, delInventoryApi, addInventoryApi} from "@/api/convenienceStore/inventory";
import {listSupplier} from "@/api/convenienceStore/supplier";

export default {
  name: "index",
  dicts: ['oilPurchasedStatus'],

  data() {
    return {
      inventoryList: [],
      // 供应商列表
      supplierList: [],
      // 弹出框标题
      title: '',
      // 显示搜索条件
      showSearch: true,
      disableInput: false, // 默认不禁用
      // 是否显示弹出层
      open: false,
      // 总条数
      total: 0,

      // 查询参数
      queryParams: {
        orderNumber: "",
        approvalStatus: "",
        status: '',
        supplierId: '',
        dateRange: '',
        pageNo: null,
        pageSize: null,
      },
      beginTime: "",
      endTime: "",
      // 新增批次
      inventoryForm: {
        orderNumber: null,
        approvalStatus: "",
        orderDate: new Date(),
      },
      // 遮罩层
      loading: false,
      // 默认排序
      defaultSort: {prop: 'createTime', order: 'descending'},
    }

  },
  async created() {
    await this.getList();
    this.getQueryList();

  },
  methods: {

    // 获取列表
    getList() {
      this.loading = true;
      let dateRange = []
      if (this.beginTime && this.endTime) {
        dateRange.push(this.beginTime.toLocaleDateString())
        dateRange.push(this.endTime.toLocaleDateString())
      }
      getInventoryPageApi(this.addDateRange(this.queryParams, dateRange)).then(response => {
        this.inventoryList = response.data.records;
        this.total = response.data.total;
      })
      this.loading = false;
    },
    // 查询搜索列表信息
    getQueryList() {
      listSupplier().then(response => {
        this.supplierList = response.data.records
      })
    },

    async detailsAdd() {
      try {
        await this.$confirm('您确定要新增盘点批次吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        this.inventoryForm.approvalStatus = 'await';
        this.refresh();
        this.inventoryForm.orderDate = this.parseTime(new Date())
        const res = await addInventoryApi(this.inventoryForm);

        if (res) {
          this.$modal.msgSuccess("新建批次成功");
          this.getList();
          this.dispose(res.data)
        } else {
          this.$modal.msgError("新建批次失败");
        }
      } catch (error) {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      }
    },

    // 生成盘点批次
    refresh() {
      let timestamp = new Date().getTime();
      let min = 100; // 最小的四位数是 1000
      let max = 999; // 最大的四位数是 9999
      let randomFourDigitNumber = Math.floor(Math.random() * (max - min + 1)) + min;
      this.inventoryForm.orderNumber = timestamp + randomFourDigitNumber.toString();
    },

    // 处理单据
    dispose(data) {
      this.$router.push({
        name: 'inventory-details',
        params: {
          PinventoryId: data.id,
          PorderNumber: data.orderNumber,
          PorderDate: data.orderDate,
          PapprovalStatus: data.approvalStatus,
          PcreataByName: data.createByName
        },

      });
    },

    // 重置
    resetQuery() {
      this.queryParams = {}
      this.getList();

    },
    // 删除
    handleDel(data) {
      delInventoryApi(data).then(response => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      })
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
  }


}
</script>

<style scoped lang="scss">
.app-container {
  width: 100%;
  height: 100%;
  background: #f6f8f9;
}

</style>
