<template>
	<div id = "inrecord" style="height:100%;">
			<div class="searchForm-header">
					<el-form :model="query" label-width="100px" inline="" class = "searchForm">
						<el-row>
							<el-form-item label="库房名称" style="margin-left: -25px">
								<el-select v-model="query.wareName" clearable size="small"  style="width:100px;margin-left: -8px" @change="changeWare">
									<el-option v-for="item in optionsWare" :key="item.id" :label="item.name" :value="item.name">
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item label="垛位名称" style="margin-left: -35px">
								<el-input v-model="query.stackName" size="small" style="width:100px;margin-left: -8px"></el-input>
							</el-form-item>
							<el-form-item label="物料名称" style="margin-left: -35px">
								<el-input v-model="query.materialName" size="small"  style="width:130px;margin-left: -8px">
									<el-button slot="append" icon="el-icon-search" @click="showMaterial"></el-button>
								</el-input>
							</el-form-item>
							<el-form-item label="钢种" style="margin-left: -35px">
								<el-input v-model="query.standard" size="small"  style="width:150px;margin-left: -8px">
									<el-button slot="append" icon="el-icon-search" @click="showMaterial"></el-button>
								</el-input>
							</el-form-item>
							<el-form-item label="客户名称" style="margin-left: -35px">
								<el-select v-model="query.customerName" filterable placeholder="请选择上游客户" clearable size="small" style="margin-left: 5px; width: 170px">
									<el-option v-for="item in optionsCust" :key="item.name" :label="item.name" :value="item.name" >
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item label="订单号" style="margin-left: -25px">
								<el-input v-model="query.ordNo" size="small"  style="width:120px;margin-left: -8px"  @input="getOrdList">
								</el-input>
							</el-form-item>
							<el-form-item label="车号" style="margin-left: -25px">
								<el-input v-model="query.carNo" size="small"  style="width:120px;margin-left: -8px">
								</el-input>
							</el-form-item>
						</el-row>
						<el-row>
							<el-form-item label="规格型号" style="margin-left: -25px;margin-top: -15px">
								<el-input v-model="query.model" size="small"  style="width:120px;margin-left: -8px">
								</el-input>
							</el-form-item>
							<el-form-item label="钢板号" style="margin-left: -35px;margin-top: -15px">
								<el-input v-model="query.plateNo" size="small"  style="width:120px;margin-left: -8px" @input="getPltList">
								</el-input>
							</el-form-item>
              <el-form-item label="合约号" style="margin-left: -35px;margin-top: -15px">
                <el-input v-model="query.contractNo" size="small"  style="width:120px;margin-left: -8px" @input="getConList">
                </el-input>
              </el-form-item>
							<el-form-item label="理货人员" style="margin-top: -15px">
								<el-select v-model="query.tallyPeople" size="small" style="margin-left: 10px;margin-top: -15px" clearable placeholder="理货人员">
									<el-option v-for="item in tallyPeopleOption" :key="item.id" :label="item.dicName" :value="item.dicCode">
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item label="入库时间" style="margin-left: -35px;margin-top: -15px">
								<el-date-picker size="small" v-model="query.inRecordDate"  style="width:330px;margin-left: -8px" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
							    </el-date-picker>
							</el-form-item>
							<el-form-item label="付款单位" style="margin-left: -35px;margin-top: -15px">
								<el-select v-model="query.fkComponyName" filterable placeholder="请选择上游客户" clearable size="small" style="margin-left: 5px; width: 170px">
									<el-option v-for="item in optionsCust" :key="item.name" :label="item.name" :value="item.name" >
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item label="垛位备注" style="margin-left: -35px;margin-top: -15px">
								<el-input v-model="query.remark1" size="small"  style="width:120px;margin-left: -8px" @input="getPltList">
								</el-input>
							</el-form-item>
              <el-form-item label="修改时间" style="margin-left: -35px;margin-top: -15px">
                <el-date-picker size="small" v-model="ChangeInDtm" type="datetime" placeholder="选择日期时间" style="width:200px;margin-left: -8px">
                </el-date-picker>
              </el-form-item>
							<el-form-item  label=" " style="margin-left: -35px;margin-top: -15px">
								<el-button size="small" @click="handleSearch" type="primary">查询</el-button>
								<!-- <el-button @click="handleSearch" type="primary" size="small">查询</el-button> -->
							</el-form-item>
							<el-form-item label="" style="margin-top: -15px">
								<el-upload class="upload-demo" action=""
									 ref="upload" :limit="1" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
									 :auto-upload="false"  >
									 <el-button plain slot="trigger"  type="success" v-show="false" style= "margin-left: 5px" size="small">询单导入</el-button>
									<el-button   type="success" @click="handleExport" style="margin-left: 2px" size="small">导出记录</el-button>
								</el-upload>
							</el-form-item>
							<el-form-item label="" style="margin-top: -15px">
							    <el-button type="primary" size="small"  @click="resetButton" :disabled="backAble">重置</el-button>
							</el-form-item>
							<!-- <el-form-item label="" style="margin-top: -15px">
							    <el-button type="danger" size="small"  @click="deleteRecord" :disabled="backAble">删除记录</el-button>
							</el-form-item> -->
							<el-form-item label="" style="margin-top: -15px">
								<el-dropdown placement="bottom" trigger="click" @command="batchOperate">
									<el-button type="danger" size="small"> 其他操作<i class="el-icon-arrow-down el-icon--right"></i></el-button>
									<el-dropdown-menu slot="dropdown">
										<el-dropdown-item command="deleteRecord" style="background-color: #f5f5f5;">删除记录</el-dropdown-item>
										<el-dropdown-item command="changeRecordInDtm" style="background-color: #f5f5f5;">修改时间</el-dropdown-item>
									</el-dropdown-menu>
								</el-dropdown>

							</el-form-item>

						</el-row>
					</el-form>
			<total-block ref="totalBlock" style="margin-left: -25px;font-size: 13px;margin-left: 5px" v-bind:childParam="childParam" v-bind:childUrl = 'childUrl'></total-block>
		</div>
		<div class="tabledata-grid">
			<el-table v-loading="loading"  :data="tableData" height="100%" stripe border style="width: 97%;font-size: 13px;margin-top: -50px;margin-left: 25px" @select="handleTableSelect" :header-cell-style="{'text-align':'center'}">
				<el-table-column type="selection" width="40" header-align="center" align="center"></el-table-column>
				<el-table-column prop="id" label="编号" min-width="10%" v-if="false">
				</el-table-column>
				<el-table-column prop="wareName" label="仓库名称" width="150px" show-overflow-tooltip header-align="center">
				</el-table-column>
				<el-table-column prop="stackName" label="垛位" width="60px" show-overflow-tooltip header-align="center" align="center">
				</el-table-column>
				<el-table-column prop="layer" label="层号" show-overflow-tooltip width="60px" header-align="center" align="center">
				</el-table-column>
				<el-table-column prop="materialName" label="货物品名" show-overflow-tooltip width="100px" header-align="center" align="center">
				</el-table-column>
        <el-table-column prop="contractNo" label="合约号" show-overflow-tooltip width="100px" header-align="center" align="center">
				</el-table-column>
				<el-table-column prop="ordNo" label="订单号" width="180px" show-overflow-tooltip align="left">
				</el-table-column>
				<el-table-column prop="model" label="规格" show-overflow-tooltip width="180px" align="center">
				</el-table-column>
				<el-table-column prop="standard" label="材质" show-overflow-tooltip width="80px" align="center">
				</el-table-column>
				<el-table-column prop="count" label="入库数量" width="100px" show-overflow-tooltip align="right">
				</el-table-column>
				<el-table-column prop="weight" label="入库重量" width="100px" show-overflow-tooltip align="right">
				</el-table-column>
				<el-table-column prop="plateNo" label="钢板号" width="200px" show-overflow-tooltip align="center">
				</el-table-column>
				<el-table-column prop="customerName" label="订货单位" width="200px" show-overflow-tooltip align="center">
				</el-table-column>   <!-- 原客户名称 -->
				<el-table-column prop="fkComponyName" label="客户单位" width="200px" show-overflow-tooltip align="center">
				</el-table-column>   <!-- 新增 -->
				<el-table-column prop="receiveAddress" label="收货地址" width="300" show-overflow-tooltip align="left">
				</el-table-column>
				<el-table-column prop="productionPlace" label="产地" width="250" show-overflow-tooltip header-align="center">
				</el-table-column>
				<el-table-column prop="carNo" label="入库车号" width="120px" show-overflow-tooltip align="left">
				</el-table-column>
				<el-table-column prop="tallyPeople" label="吊装工" width="250" show-overflow-tooltip header-align="center">
				</el-table-column>
				<el-table-column prop="addUser.userDesc" label="入库操作人" width="120px" show-overflow-tooltip align="left">
				</el-table-column>
				<el-table-column prop="addTime" label="入库时间" width="200px" show-overflow-tooltip align="left">
				</el-table-column>
				<el-table-column prop="remark" label="备注" width="100px" show-overflow-tooltip align="left">
				</el-table-column>
				<el-table-column prop="remark1" label="垛位备注" width="100px" show-overflow-tooltip align="left">
				</el-table-column>
				<el-table-column prop="recordType" label="类型" width="100px" show-overflow-tooltip align="center" :formatter="typeFormatter">
				</el-table-column>

			</el-table>
		</div>
		<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
		 :page-sizes="pageSizes" :page-size="pageSize" style="margin-left: 25px" layout="total, sizes, prev, pager, next, jumper" :total="totalRows">
		</el-pagination>

		<popup-material ref="PopupMaterial" @receviceFromChild="receviceFromMaterial"></popup-material>
		<popup-customer ref="PopupCustomer" @receviceFromChild="receviceFromCustomer"></popup-customer>
		<popup-customer ref="PopupFkCompony" @receviceFromChild="receviceFromFkCompony"></popup-customer>

		<!-- 导出Loading遮罩层 -->
		<div v-if="exportLoading" class="export-loading-mask">
			<div class="export-loading-content">
				<i class="el-icon-loading"></i>
				<p>正在导出，请稍候...</p>
			</div>
		</div>
	</div>
</template>

<style>
/* 导出Loading遮罩样式 */
.export-loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.export-loading-content {
  background-color: #fff;
  padding: 30px 50px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
}

.export-loading-content i {
  font-size: 40px;
  color: #409EFF;
  margin-bottom: 15px;
}

.export-loading-content p {
  font-size: 16px;
  color: #333;
  margin: 0;
}
</style>

<script>
	import axios from '@/axios'
	import PopupStack from '@/components/PopupStack.vue'
	import PopupMaterial from '@/components/PopupMaterial.vue'
	import PopupCustomer from '@/components/PopupCustomer.vue'
	import TotalBlock    from '@/components/TotalBlock.vue'
	import Export2Excel from '../../excel/Export2Excel.js'
	export default {
		components: {
			PopupStack,
			PopupMaterial,
			PopupCustomer,
			TotalBlock
		},
		data() {
			return {
				query: {
					wareName: '',
					stackName: '',
					model: '',
					materialName: '',
					standard: '',
					customerName: '',
					plateNo: '',
					inRecordDate:[],
					ordNo:'',
					carNo:'',
					tallyPeople:'',
					fkComponyName:'',
					remark1:'',
          contractNo:''
				},
				selectRows: [],
				loading: false,
			exportLoading: false,
				tableData: [],
				optionsWare: [],
				dialogVisible: false,
				labelPosition: 'right',

				//分页参数
				currentPage: 1,
				totalRows: 0,
				pageSizes: [50, 100, 200,500,1000],
				pageSize: 50,
				childParam:{
					page: '',
					rows: '',
					wareName: '',
					stackName: '',
					model: '',
					materialName: '',
					standard: '',
					customerName: '',
					plateNo: '',
					ord_no:'',
          contractNo:''
				},
				childUrl:'WareInRecord/queryTotal.do',
				tallyPeopleOption:[],
				optionsCust:[],
				ChangeInDtm: '',

			};
		},
		//页面加载完成渲染
		mounted() {
			this.getWare()
			this.getSearchItem();
			// this.getTableData()
			this.setSearchTime();
			this.getAllCustomer();

		},
		methods: {
			setSearchTime(){
				var now = new Date();
				this.query.inRecordDate = [new Date(now.getFullYear(), now.getMonth(), now.getDate()),new Date(now.getFullYear(), now.getMonth(), now.getDate()+1)];
			},
			getSearchItem(){
				var url = 'Common/querySelector.do'
				var param = {
					type: 'TALLY_PEOPLE',
				}
				axios.get(url, param).then(response => {
					this.tallyPeopleOption = response.data.data;
				});

			},
			getAllCustomer() {
				var url = 'MaintCustomer/queryByUserId.do'
				var param = {}
				axios.get(url, param).then(response => {
					this.optionsCust = response.data.data
				});
			},
			typeFormatter: function(row, column) {
				switch (row.recordType) {

					case "0":
						return "入库取消";
						break;
					default:
						return "入库";
						break;
				}
			},
			batchOperate(command) {
				switch (command) {
					case "deleteRecord":
						this.deleteRecord();
						break;
					case "changeRecordInDtm":
						this.changeRecordInDtm();
						break;
				}
			},

			handleTableSelect(selection, row) {  //第一个参数是目前所有选中的数据
				console.log(JSON.stringify(row))
				this.selectRows = selection
				this.setLayerColor()
			},
			showMaterial() {
				this.$refs.PopupMaterial.show()
			},
			receviceFromMaterial(material) {
				//console.log("receviceFromStack")
				this.query.materialName = material.name
				this.query.standard = material.standard
			},

			showCustomer() {
				this.$refs.PopupCustomer.show()
			},
			showFkCompony(){
				this.$refs.PopupFkCompony.show()
			},
			receviceFromCustomer(customer) {
				//console.log("receviceFromStack")
				this.query.customerName = customer.name

			},
			receviceFromFkCompony(customer) {
				this.query.fkComponyName = customer.name
			},
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageSize = val
				this.getTableData()
			},
			// 修改当前页事件
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.currentPage = val
				this.getTableData()
			},
			handleSearch() {
				this.currentPage = 1
				this.getTableData();
				//this.getTotalData();
			},
			resetButton(){      //查询条件重置
				this.query.wareName = '',
				this.query.stackName = '',
				this.query.model = '',
				this.query.materialName = '',
				this.query.standard = '',
				this.query.customerName = '',
				this.query.plateNo = '',
				this.query.wareId = '',
				this.query.ordNo = '',
				this.query.fkcustmerName = '',
				this.query.carNo = '',
				this.query.tallyPeople = '',
				this.query.fkComponyName = '',
				this.query.remark1 = '';
        this.query.contractNo = '';
				this.setSearchTime()
			},
			getWare() {
				var url = 'MaintWare/queryByUserId.do'
				var param = {}
				axios.get(url, param).then(response => {
					console.log(response)
					this.optionsWare = response.data.data
					if (response.data.data.length == 1) {
						this.wareName = response.data.data[0].name
						//	this.getStack()
					}
				});
			},
			getTableData() {
				var url = 'WareInRecord/query.do'
				if(this.query.inRecordDate == null){
					this.query.inRecordDate = [false,false];
				}
				this.loading = true
				var param = {
					page: this.currentPage,
					rows: this.pageSize,
					wareName: this.query.wareName,
					stackName: this.query.stackName,
					model: this.query.model,
					materialName: this.query.materialName,
					standard: this.query.standard,
					customerName: this.query.customerName,
					plateNo: this.query.plateNo.length == 0 ? '' : this.query.plateNo.join(','),
					fromDate:(!this.query.inRecordDate[0]) ? "1970-01-01 00:00:00" : this.query.inRecordDate[0].Format("yyyy-MM-dd HH:mm:ss"),		//date类型
					toDate  :(!this.query.inRecordDate[1]) ? new Date().Format("yyyy-MM-dd HH:mm:ss") :this.query.inRecordDate[1].Format("yyyy-MM-dd HH:mm:ss"),
					ordNo: this.query.ordNo == 0 ? '' : this.query.ordNo.join(','),
					carNo : this.query.carNo,
					tallyPeople:this.query.tallyPeople,
					fkComponyName:this.query.fkComponyName,
					remark1:this.query.remark1,
          contractNo:this.query.contractNo.length == 0 ? '' : this.query.contractNo.join(','),
				}

				this.childParam = param;
				axios.post(url, param).then(response => {
					if (response.data.code == 0) {
						this.tableData = response.data.data.list
						this.totalRows = response.data.data.total
						this.$refs.totalBlock.getTotalData();
					} else {
						this.$message({
							type: 'error',
							message: '操作失败；' + response.data.msg,
						});
					}
					this.loading = false
				});

			},
			changeWare(){

			},
			getPltList(){
				const replaceResult = this.query.plateNo.replace(/[；,，;\s\r\n]+/g, ",").split(",");
				this.query.plateNo = replaceResult;
			},
      getConList(){
        const replaceResult = this.query.contractNo.replace(/[；,，;\s\r\n]+/g, ",").split(",");
        this.query.contractNo = replaceResult;
      },
			getOrdList(){
				const replaceResult = this.query.ordNo.replace(/[；,，;\s\r\n]+/g, ",").split(",");
				this.query.ordNo = replaceResult;
			},
			handleExport() {
        // 显示加载动画
        this.exportLoading = true;

        var baseUrl = this.$store.state.app.serverName;
        var url = baseUrl + 'WareStore/inExportStoreExcel.do';
        let userId = localStorage.getItem("userId");
        let belongId = localStorage.getItem("belongId");
        let token = localStorage.getItem("token");
        console.log(userId, belongId, token);
				var param = {
					page: -1,
					rows: -1,
					wareName: this.query.wareName,
					stackName: this.query.stackName,
					model: this.query.model,
					materialName: this.query.materialName,
					standard: this.query.standard,
					customerName: this.query.customerName,
					plateNo: this.query.plateNo.length == 0 ? '' : this.query.plateNo.join(','),
					fromDate:(!this.query.inRecordDate[0]) ? "1970-01-01 00:00:00" : this.query.inRecordDate[0].Format("yyyy-MM-dd HH:mm:ss"),		//date类型
					toDate  :(!this.query.inRecordDate[1]) ? new Date().Format("yyyy-MM-dd HH:mm:ss") :this.query.inRecordDate[1].Format("yyyy-MM-dd HH:mm:ss"),
					ordNo: this.query.ordNo == 0 ? '' : this.query.ordNo.join(','),
					carNo : this.query.carNo,
					tallyPeople:this.query.tallyPeople,
					fkComponyName:this.query.fkComponyName,
					remark1:this.query.remark1,
          contractNo:this.query.contractNo.length == 0 ? '' : this.query.contractNo.join(','),
          userId: userId,
          belongId: belongId
				}

        var params = [];
        // 去掉 if(param\[key\]) 判断，空字符串也要传递给后端
        for (var key in param) {
          params.push(key + '=' + encodeURIComponent(param[key]));
        }
        var fullUrl = url + (params.length > 0 ? '?' + params.join('&') : '');

        // 使用 fetch + blob 方式，下载完成后关闭 loading
        fetch(fullUrl)
        .then(response => {
          if (!response.ok) {
            throw new Error('网络请求失败');
          }
          return response.blob();
        })
        .then(blob => {
          // 创建下载链接
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = '入库记录_' + new Date().toISOString().slice(0, 10) + '.xlsx';
          document.body.appendChild(link);
          link.click();
          // 浏览器开始下载后立即关闭 loading
          this.exportLoading = false;
          // 清理
          setTimeout(() => {
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
          }, 100);
        })
        .catch(error => {
          console.error('导出失败:', error);
          this.$message.error('导出失败：' + error.message);
          this.exportLoading = false;
        });

			},
			exportExcel(imptData) {
				// alert(JSON.stringify(imptData))
				const header = ["仓库名称"
								,"垛位"
								,"层号"
								,"品名"
								,"订单号"
								,"规格"
								,"钢种"
								,"入库数量"
								,"入库重量"
								,"钢板号"
								,"订货单位"
								,"客户单位"
								,"收货地址"
								,"计量方式"
								,"切边类型"
								,"产地"
								,"入库车号"
								,"入库理货人员"
								,"入库操作人"
								,"入库时间"
								,"垛位备注"
								,"类型"
								,"备注"
                ,"合约号"
				] // 导出的表头名
				const filterVal = [
						"wareName"
						,"stackName"
						,"layer"
						,"materialName"
						,"ordNo"
						,"model"
						,"standard"
						,"count"
						,"weight"
						,"plateNo"
						,"customerName"
						,"fkComponyName"
						,"receiveAddress"
						,"wgtDcnMtcCd"
						,"edgeTy"
						,"productionPlace"
						,"carNo"
						,"tallyPeople"
						,"addUserUserDesc"
						,"addTime"
						,"remark1"
						,"recordType"
						,"remark"
            ,"contractNo"
				]

				for(var i=0;i<imptData.length;i++){
					imptData[i]["addUserUserDesc"] = imptData[i].addUser.userDesc;
					imptData[i]["recordType"]      = imptData[i]["recordType"] == 0 ? "入库取消" : "入库";
				}
				const list = imptData
				const data = this.formatJson(filterVal, list)

				const filename = '入库单' + (new Date()).toLocaleDateString();
				Export2Excel.export_json_to_excel({
					header,
					data,
					filename
				})
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => {
					return v[j]
				}))
			},
			handleTableSelectionChange(val) {
				this.selectRows = val
				this.setLayerColor()
			},
			deleteRecord(){
				if (this.selectRows.length < 1) {
					this.$message({
						type: 'error',
						message: '至少选择一条数据！',
					});
					return
				}else{
					var url = 'WareInRecord/deleterecord.do'
					var param = {
						json: JSON.stringify(this.selectRows),
					}
					axios.post(url, param).then(response => {
						if (response.data.code == 0) {
							this.getTableData()
							this.stackDialogVisible = false
						} else {
							this.$message({
								type: 'error',
								message: '操作失败；' + response.data.msg,
							});
						}
					});
				}

			},
			changeRecordInDtm(){
				if (this.selectRows.length < 1) {
					this.$message({
						type: 'error',
						message: '至少选择一条数据！',
					});
					return
				}else{
					var url = 'WareInRecord/changeRecordInDtm.do'
					var param = {
						json: JSON.stringify(this.selectRows),
						ChangeInDtm: this.ChangeInDtm.Format("yyyy-MM-dd HH:mm:ss")
					}
					axios.post(url, param).then(response => {
						if (response.data.code == 0) {
							this.getTableData()
						} else {
							this.$message({
								type: 'error',
								message: '操作失败；' + response.data.msg,
							});
						}
					});
				}
			}

		},
	}
</script>

<style>
	.searchForm{
		background-color: #C6E2FF;
		border-top: 8px solid #C6E2FF;
		/*border:1px solid #C6E2FF;*/
		border-radius:8px 8px 8px 8px;
		/*border-collapse:separate;
		border-spacing:0px 2px;	*/			/*和border之间的距离*/
		margin-left: 30px;
	}
	.searchForm-header{
		height: auto;
		margin-left: 10px;
	}
	.tabledata-grid{
		font-size: 20px;
		height: calc(100% - 230px);
	}

</style>
