<template>
  <div class="app-container">
    <!--    搜索框-->
    <el-card >
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="" prop="oilNumber">
          <el-select v-model="queryParams.numberId" placeholder="油品" style="width:100%" @change="chooseOilNumber()"             clearable
>
            <el-option
              v-for="option in selectOilTypeByPrice"
              :key="option.numberId"
              :label="option.oilType +' '+option.oilName"
              :value="option.numberId"
            ></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="" prop="tankName">
          <el-input
            v-model="queryParams.tankName"
            placeholder="油罐名称"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label-width="120px" label="" v-model="queryParams.inventoryStatistics" prop="inventoryStatistics" clearable>
          <el-select v-model="queryParams.inventoryStatistics" placeholder="" style="width:100%">
            <el-option label="库存统计状态" value=""></el-option>
            <el-option
              v-for="dict in dict.type.zhzt"
              :key="dict.label"
              :label="dict.label"
              :value="dict.label"
            ></el-option>
          </el-select>
        </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="exportExcelTank()"
                     v-hasPermi="['oilConfig:oilStatistics:list:ex']"
          >导出</el-button>
        </el-form-item>
      </el-form>

      <el-table key="2" ref="tables"
                v-loading="loading"
                :data="statisticsList"
                border
                :default-sort="defaultSort">
        <el-table-column align="center" type="index" label="序号"></el-table-column>
        <el-table-column label="油罐名称" align="center" prop="tankName"/>
        <el-table-column label="油品名称" align="center" prop="oilNumber" />
        <el-table-column label="油罐容量L" align="center" prop="tankVolume" />
        <el-table-column label="油品密度(g/ml)" align="center" prop="oilDensity" />
        <el-table-column label="当前剩余油量（L）" align="center" prop="storedQuantity" />
        <el-table-column label="当前成本价（元/L）" align="center" prop="discountedPrice" />
        <el-table-column label="成本金额(元)" align="center" prop="totalPrice" />
        <el-table-column label="状态" align="center" prop="inventoryStatistics">
          <template slot-scope="scope">
            <div slot="reference" class="name-wrapper">
              <el-tag v-if ="scope.row.inventoryStatistics == '启用'" size="success">启用</el-tag>
              <el-tag v-if ="scope.row.inventoryStatistics == '禁用'" type="danger" size="medium">禁用</el-tag>
            </div>
          </template>
<!--          <template slot-scope="scope">-->
<!--            <el-switch-->
<!--              v-model="scope.row.status"-->
<!--              active-value="启用"-->
<!--              inactive-value="禁用"-->
<!--              @change="changeStatus(scope.row)"-->
<!--              active-color="#13ce66"-->
<!--              inactive-color="#ff4949">-->
<!--            </el-switch>-->

<!--          </template>-->
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" width="200">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</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"
              icon="el-icon-edit"
              @click="trace(scope.row)"
            >库存跟踪记录</el-button>
            <!--            v-hasPermi="['']"-->

          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>


    <el-drawer
      title="库存跟踪记录"
      :visible.sync="drawer"
      direction="rtl"
      size="40%"
      :before-close="handleClose">

      <div style="display: grid; place-items: center;">
        <div class="box-card" style="">
          <div style="display: flex; justify-content: space-between;margin-bottom: 10px">
            <span>油罐名称：{{statisticsForm.tankName}}</span>
            <span>油品油号:{{  statisticsForm.oilNumber }}</span>
            <span>库存数量:{{statisticsForm.storedQuantity}}{{statisticsForm.unit}}</span>
            <span>更新时间:{{ statisticsForm.updateTime }}</span>
          </div>
          <el-table ref="tables"
                  v-loading="loading"
                  :data="trackList"
                  :default-sort="defaultSort"
                    border
          key="1">
            <el-table-column align="center" type="index" label="序号"></el-table-column>
            <el-table-column label="单据" align="center" prop="document" />
            <el-table-column label="单号" align="center" prop="orderNumber" />
            <el-table-column label="变动数量（L）" align="center" prop="quantityChange" />

            <el-table-column label="库存更新时间" align="center" prop="updateTime" width="200">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime) }}</span>
            </template>
          </el-table-column>
        </el-table>
          <pagination
            v-show="total2>0"
            :total="total2"
            :page.sync="queryParams2.page"
            :limit.sync="queryParams2.pageSize"
            @pagination="getTrackingList"
          />
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {exportExcelTankApi, getTankApi} from "@/api/oilConfig/oilTank";
import {getTrackingApi} from "@/api/oilConfig/oilStatistics";
import {getOilNameListApi} from "@/api/oilPrice";

export default {
  name: "oilStatistics",
  dicts: ['zhzt'],

  data() {
    return {
      statisticsList: [],
      trackList: [],
      selectOilTypeByPrice: [],

      // 总条数
      total: 0,
      total2: 0,
      statisticsForm: {
        tankName:'',
        oilNumber:'',
        storedQuantity:'',
        updateTime:'',
        unit:''
      },

      // 查询参数
      queryParams: {
        numberId:'',
        status:'启用',
        inventoryStatistics:'',
        tankName: '',
        page:null,
        pageSize:null
      },

      queryParams2: {
        page:null,
        pageSize:null
      },
      drawer: false,

      // 遮罩层
      loading: false,
      // 默认排序
      defaultSort: {prop: 'createTime', order: 'descending'},
    }
  },
  async created() {
    let this_ = this
    await this_.getList()
    this_.getOilNameList()
  },
  methods: {

    exportExcelTank() {
      exportExcelTankApi().then(res=>{
        console.log("res",res)
        // this.downloadFile(res);
        const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

        this.$download.saveAs(blob,'库存统计.xLsx')
      })
    },

    downloadFile(blobData) {
      this.$down()
      // 创建一个 Blob 对象，并创建一个 URL，用于下载文件
      const blob = new Blob([blobData], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;

      // 设置下载文件的名称
      link.setAttribute('download', 'exportedFile.xlsx');

      // 模拟点击链接进行下载
      link.click();
    },


    getList() {
      getTankApi(this.queryParams).then(res=>{
        this.statisticsList = res.data.records
        this.total = res.data.total;

      })
    },
    getTrackingList(data) {
      // this.queryParams2.tankId = data.id
      getTrackingApi(this.queryParams2).then(res=>{
        this.trackList = res.data.records
        this.total2 = res.data.total;
      })
    },
    // 库存跟踪
    trace(data) {
      let this_ = this
      this_.statisticsForm = {},
      this_.statisticsForm.tankName = data.tankName,
      this_.statisticsForm.oilNumber = data.oilNumber,
      this_.statisticsForm.storedQuantity = data.storedQuantity,
      this_.statisticsForm.updateTime = data.updateTime,
      this_.statisticsForm.unit = data.unit,
      this_.queryParams2.tankId = data.id
      this.trackList = []
      this_.getTrackingList(data)
      this.drawer=true
    },

    // 搜索框重置
    resetQuery() {
      this.res()

      this.getList()
    },

    res() {
      // 查询参数
      this.queryParams= {
        numberId:'',
        status:'启用',
        inventoryStatistics:'',
        tankName: '',
        page:null,
        pageSize:null
      }
    },


    handleClose(done) {
      done();
      // this.$confirm('确认关闭？')
      //   .then(_ => {
      //     done();
      //   })
      //   .catch(_ => {});
    },

    // 选择油品号
    getOilNameList() {
      var this_=this
      getOilNameListApi().then( response => {
        var list = response.data
        this_.selectOilTypeByPrice = list
      });
    },

    // 搜索按钮操作
    handleQuery() {

      this.queryParams.page = 1;
      this.getList();
    },
  }
}
</script>

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

  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 90%;
  }
  .el-form--inline .el-form-item {
    margin-right: 44px;
  }

</style>
