<template>
	<el-container>
		<el-header>
			<div class="left-panel">
				<el-button
					type="primary"
					:disabled = 'dLoading'
					icon="el-icon-download"
					@click="exportList"
				>导出</el-button>
			</div>
			<div class="right-panel">
				<el-input
					v-model="query.search"
					placeholder="物料名"
					clearable
					style="margin-right: 5px"
				></el-input>
				<el-button
					type="primary"
					icon="el-icon-search"
					@click="handleQuery"
				></el-button>
			</div>
		</el-header>
		<el-main class="nopadding">
			<scTable
				ref="table"
				:apiObj="apiObj"
				row-key="id"
				stripe
				:params="params"
				v-if="project_code=='gx'"
			>
				<el-table-column type="index" width="50" />
				<el-table-column label="日期" prop="update_time" sortable>
				</el-table-column>
				<el-table-column label="物料编号">
					<template #default="scope">
						<span v-if="scope.row.material_&&scope.row.material_.number">{{ scope.row.material_.number }}</span>
					</template>
				</el-table-column>
				<el-table-column label="物料名称">
					<template #default="scope">
						<span v-if="scope.row.material_&&scope.row.material_.name">{{ scope.row.material_.name }}</span>
					</template>
				</el-table-column>
				<el-table-column label="货位号">
					<template #default="scope">
						<span v-if="scope.row.material_&&scope.row.material_.bin_number_main">{{ scope.row.material_.bin_number_main }}</span>
					</template>
				</el-table-column>
				<el-table-column label="规格">
					<template #default="scope">
						<span v-if="scope.row.material_&&scope.row.material_.specification">{{ scope.row.material_.specification }}</span>
					</template>
				</el-table-column>
				<el-table-column label="品牌型号">
					<template #default="scope">
						<span v-if="scope.row.material_&&scope.row.material_.model">{{ scope.row.material_.model }}</span>
					</template>
				</el-table-column>
				<!-- 
					:filters="unitFilters"
					:filter-method="filterUnitDate"
					filter-placement="bottom-end"
				 -->
				<el-table-column label="单位">
					<template #default="scope">
						<span v-if="scope.row.material_&&scope.row.material_.unit">{{ scope.row.material_.unit }}</span>
					</template>
				</el-table-column>
				<el-table-column label="安全库存" sortable>
					<template #default="scope">
						<span v-if="scope.row.material_&&scope.row.material_.count_safe">{{ scope.row.material_.count_safe }}</span>
					</template>
				</el-table-column>
				<el-table-column label="数量" prop="count" sortable>
				</el-table-column>
				<el-table-column label="单价" sortable>
					<template #default="scope">
						<span v-if="scope.row.material_&&scope.row.material_.unit_price">{{ scope.row.material_.unit_price }}</span>
					</template>
				</el-table-column>
				<el-table-column label="总金额" prop="expiration_date" sortable>
					<template #default="scope">
						<span v-if="scope.row.material_&&scope.row.material_.unit_price">{{  Number(scope.row.material_.unit_price)*Number(scope.row.count) }}</span>
					</template>
				</el-table-column>
			</scTable>
			<scTable
				ref="table"
				:apiObj="apiObj"
				row-key="id"
				stripe
				:params="params"
				v-else
			>
				<el-table-column type="index" width="50" />
				<el-table-column label="物料批次" prop="batch">
				</el-table-column>
				<el-table-column label="物料名称" prop="material_name">
				</el-table-column>
				<el-table-column label="规格型号">
					<template #default="scope">
						{{ scope.row.specification }} {{ scope.row.model }}
					</template>
				</el-table-column>
				<el-table-column label="仓库" prop="warehouse_name">
				</el-table-column>
				<el-table-column label="物料存量" prop="count">
				</el-table-column>
				<el-table-column label="有效期" prop="expiration_date">
				</el-table-column>
				<el-table-column label="更新时间" prop="update_time">
				</el-table-column>
			</scTable>
		</el-main>
		<print-dialog
			v-if="print_m"
			ref="printmaterial"
			:mId="wmId"
			:mtype="wmtype"
			:apiObj="apiObjPrint"
		></print-dialog>
	</el-container>
</template>
<script>

import * as XLSX2 from "xlsx";
import * as XLSX from "xlsx-style";
import printDialog from "./../template/printmaterial.vue";
export default {
	name: "materials",
	components: {
		printDialog
	},
	data() {
		return {
			apiObj: this.$API.inm.warehouse.batch,
			params: { count__gte: 1, material__type__in: "40" },
			selection: [],
			unitFilters:[],
			query: {},
			warehouseOptions: [],
			wmtype:0,
			ElLoading:null,
			dLoading:false,
			print_m:false,
			materialsVisible:false,
			apiObjPrint:this.$API.cm.labelmat.fromMb,
			wmId:'',
			project_code:this.$TOOL.data.get("BASE_INFO").base.base_code
		};
	},
	mounted() {
		let that = this;
		this.getWarehouse();
		this.$nextTick(() => {
		    let datas = this.$refs.table.tableData;
			that.unitFilters = [];
			datas.forEach(item => {
				let unit = item.material_.unit;
				console.log(unit);
				if(that.unitFilters.indexOf(unit) >-1){}else{
					that.unitFilters.push(unit)
				}
			});
			console.log(that.unitFilters);
		})
	},
	methods: {
		getWarehouse() {
			this.$API.inm.warehouse.list.req({ page: 0 }).then((res) => {
				this.warehouseOptions = res;
			});
		},
		filterUnitDate(value, row) {
			return row.单位 === value;
        },
		handleQuery() {
			this.$refs.table.queryData(this.query);
		},
		resetQuery() {
			this.query = {};
		},
		//打印物料标签
		printMaterial(row){
			let that = this;
			that.wmId = row.id;
			that.wmtype = row.material_.type;
			that.print_m = true;
			this.$nextTick(() => {
			    this.$refs.printmaterial.open();
			})
		},
		exportList(){
			let that = this;
        	that.dLoading = true;
			let chartName = '辅料表';
			let titleData = ['辅料表'];
			let tipsData = ['日期','物料编号','物料名称','货位号','规格','品牌型号','单位','安全库存','数量','单价','总金额'];
			let tableData = [];
			tableData.push(titleData)
        	tableData.push(tipsData)
			that.ElLoading = this.$loading({
				lock: true,
				text: '数据请求中，请稍后...',
				background: 'rgba(0, 0, 0, 0)',
			})
			that.$API.inm.warehouse.batch.req({ page: 0, count__gte: 1, material__type__in: "40" }).then((res) => {
				res.forEach(item => {
					let data0 = [];
					let total = Number(item.material_.unit_price)*Number(item.count);
					data0.push(item.update_time);
					data0.push(item.material_.number);
					data0.push(item.material_.name);
					data0.push(item.material_.bin_number_main);
					data0.push(item.material_.specification);
					data0.push(item.material_.model);
					data0.push(item.material_.unit);
					data0.push(item.material_.count_safe);
					data0.push(item.count);
					data0.push(item.material_.unit_price);
					data0.push(total);
					tableData.push(data0);
			   })
			    let ws = XLSX2.utils.aoa_to_sheet(tableData);
              	let wb = XLSX2.utils.book_new();
				 XLSX2.utils.book_append_sheet(wb, ws, chartName);
				var wopts = {
					bookType: 'xlsx', 
					bookSST: false, 
					type: 'binary'
				};
              var wbout = XLSX.write(wb, wopts);
              var blob = new Blob([this.s2ab(wbout)], {
                  type: "application/octet-stream"
              });
              this.openDownloadDialog(blob, chartName+`.xlsx`);
              that.dLoading = false;
              that.ElLoading.close();
			}).catch(res=>{
				that.dLoading = false;
				that.ElLoading.close();
			})
		},
		s2ab(s) {
          var buf = new ArrayBuffer(s.length);
          var view = new Uint8Array(buf);
          for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
          return buf;
      },
	  openDownloadDialog(url, saveName) {
          if (typeof url == 'object' && url instanceof Blob) {
              url = URL.createObjectURL(url); // 创建blob地址
          }
          var aLink = document.createElement('a');
          aLink.href = url;
          aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
          var event;
          if (window.MouseEvent) event = new MouseEvent('click');
          else {
              event = document.createEvent('MouseEvents');
              event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
          }
          aLink.dispatchEvent(event);
      },
	},
};
</script>
