<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">  
        <el-form-item label="所属区域" prop="areaId">
            <el-cascader v-model="queryParams.areaId"
            :options="treeAreaOptions" :filterable="true" style="width: 100%;" :show-all-levels="false"
            :props="{  
                emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
                checkStrictly: false,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
                value:'id',label:'label'
            }" clearable @change="handleAreaChange">
            </el-cascader>
        </el-form-item>
        <el-form-item label="货品仓库" prop="warehouseId">
            <el-select v-model="queryParams.warehouseId" clearable placeholder="请选择货品仓库" style="width: 100%;">
                <el-option v-for="item in wareHouseOptions"
                    :key="item.warehouseId"
                    :label="item.warehouseName"
                    :value="item.warehouseId"
                ></el-option>
            </el-select> 
        </el-form-item>  
        <el-form-item label="货品名称" prop="materialName">
            <el-input v-model="queryParams.materialName" placeholder="请输入货品名称" maxlength="30" clearable style="width: 240px"/>
        </el-form-item> 
        <el-form-item label="批次号" prop="intoCode">
            <el-input v-model="queryParams.intoCode" placeholder="请输入批次号" maxlength="30" clearable style="width: 240px"/>
        </el-form-item> 
        <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
    </el-form> 
    <el-row :gutter="10" class="mb8"> 
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableListData" height="800">
        <el-table-column label="序号" align="center" width="80" type="index">
            <template slot-scope="scope">
            <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
            </template>
        </el-table-column>
        <el-table-column label="货品编码" align="center" prop="materialCode" :show-overflow-tooltip="true" /> 
        <el-table-column label="货品名称" align="center" prop="materialName" :show-overflow-tooltip="true" /> 
        <el-table-column label="货品类别" align="center" prop="materialTypeName" :show-overflow-tooltip="true" /> 
        <el-table-column label="计量单位" align="center" prop="unitName" :show-overflow-tooltip="true" /> 
        <el-table-column label="货品规格" align="center" prop="size" :show-overflow-tooltip="true"></el-table-column> 
        <el-table-column label="单价（元）" align="center" prop="unitPrice" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                <span>{{ (scope.row.unitPrice/100).toFixed(2) }}</span>
            </template>
        </el-table-column>  
        <el-table-column label="所属区域" align="center" prop="areaName" :show-overflow-tooltip="true"/>
        <el-table-column label="货品仓库" align="center" prop="warehouseName" :show-overflow-tooltip="true" />  
        <el-table-column label="数据来源" align="center" prop="dataForm" :show-overflow-tooltip="true" /> 
        <el-table-column label="批次号" align="center" prop="intoCode" :show-overflow-tooltip="true" /> 
        <el-table-column label="当前批次库存数" align="center" prop="inventoryNum" :show-overflow-tooltip="true" /> 
        <el-table-column label="当前批次总金额（元）" align="center" prop="totalMoney" :show-overflow-tooltip="true" /> 
        <el-table-column label="供应商" align="center" prop="supplierName" :show-overflow-tooltip="true" /> 
        <el-table-column label="保质期" align="center" prop="expireTime" :show-overflow-tooltip="true" />   
        <el-table-column label="过期状态" align="center" prop="expireState" :show-overflow-tooltip="true" width="120">
            <template slot-scope="scope">
                <span v-if="scope.row.expireState==1">过期</span>
                <span v-if="scope.row.expireState==2">保质期内</span> 
            </template>
        </el-table-column> 
        <el-table-column label="剩余天数" align="center" prop="expireDay" :show-overflow-tooltip="true" width="120"/>
    </el-table> 

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

<script>
import { systemAreaTreeApi } from "@/api/base/stall";  
import { drpWareHousePageApi } from "@/api/foodManage/stockManage";
import { stockExpireWarningPageApi } from "@/api/foodManage/stockReport";  
export default {
    name: "",
    dicts: [],
    data() {
        return {
            // 遮罩层
            loading: true,
            loadingBtn: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            //表格数据
            tableListData: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false, 
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10, 
            },
            treeAreaOptions:[],//区域树
            wareHouseOptions:[],//仓库下拉选
            dateRange:this.defaultDateRange(),
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                    const start = new Date();
                    const end = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
                    picker.$emit('pick', [start, end]);
                    }
                },{
                    text: '最近一个月',
                    onClick(picker) {
                    const start = new Date();
                    const end = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    picker.$emit('pick', [start, end]);
                    }
                },{
                    text: '最近三个月',
                    onClick(picker) {
                    const start = new Date();
                    const end = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 91);
                    picker.$emit('pick', [start, end]);
                    }
                }]
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
            //   canteenName: [
            //     { required: true, message: "字典名称不能为空", trigger: "blur" }
            //   ],
            //   dictType: [
            //     { required: true, message: "字典类型不能为空", trigger: "blur" }
            //   ]
            }
        };
    },
    created() { 
      this.getAreaTreeData(); 
      this.getWareHouseData()
      this.getList();
    },
    methods: {
        //区域树
        getAreaTreeData() {
            systemAreaTreeApi({}).then((response) => {
            this.treeAreaOptions = response.data; 
            });
        },
        handleAreaChange(e){
           this.getWareHouseData()
        }, 
        /** 查询货品下拉结构 */
        getWareHouseData() { 
            drpWareHousePageApi({ areaId:this.queryParams.areaId }).then((response) => {
                this.wareHouseOptions = response.rows||[];
                this.$set(this.queryParams,'warehouseId',null)  
            }); 
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() { 
            this.dateRange = this.defaultDateRange()
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 查询列表 */
        getList() {
            this.loading = true;
            let param = {
                "pageNum": this.queryParams.pageNum, 
                "pageSize": this.queryParams.pageSize,   
                "areaId": this.queryParams.areaId,  
                "warehouseId": this.queryParams.warehouseId,   
                "materialName": this.queryParams.materialName,   
                "intoCode": this.queryParams.intoCode,   
            } 
            stockExpireWarningPageApi(param).then(response => {
                this.tableListData = response.rows;
                this.total = Number(response.total);
                this.loading = false;
            });
        },   
        defaultDateRange() {
          const end = new Date(new Date().toLocaleDateString());
          end.setTime(end.getTime() + 24 * 60 * 60 * 1000 -1);
          const start = new Date((new Date().toLocaleDateString()));
          start.setTime(start.getTime() - 30 * 24 * 60 * 60 * 1000); 
          this.start = parseInt(start.getTime() / 1000)
          this.end = parseInt(end.getTime() / 1000)
          return [start, end]
        }, 
        //日期
        formatDate(date) {
            // 格式化为 YYYY-MM-DD
            date = new Date(date)
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        //日期时间
        formatDateTime(date) {
            // 格式化为 YYYY-MM-DD
            date = new Date(date)
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
            const day = String(date.getDate()).padStart(2, '0');
            const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
            const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
            const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        } 
    }
};
</script>
