<template>
	<div id="protectedItems" class="content-main">
		<el-form :inline="true" ref="formInline" :model="formInline" class="demo-form-inline recordsDetailsTable">
			<el-row>
				<el-form-item label="上报单位:">
					<el-input clearable v-model="formInline.name" placeholder="请输入"></el-input>
				</el-form-item>
				<el-form-item>
					<div class="search-button">
						<span class="search-line"></span>
						<el-button type="primary" size="small" class="iconfont iconchaxun" @click="getDataName">查询</el-button>
						<el-button type="primary" size="small" class="iconfont iconzhongzhi" @click="doSearch">重置</el-button>
					</div>
				</el-form-item>
			</el-row>
			<!-- <div style="text-align: center;font-size: 20px;font-weight: 600;margin-bottom: 20px;">市级粮食调节储备补贴申请明细表</div> -->
			<div class="flexBox">
				<div style="flex: 1;text-align: right;">
					<span>汇总日期:{{formInline.summaryDay}}</span>
				</div>
			</div>
			<table id="summaryData">
				<thead>
					<tr>
						<!-- <th rowspan="3">
              序号
            </th> -->
						<th rowspan="3">
							上报单位
						</th>
						<th colspan="9">储备粮</th>
						<th colspan="5">储备油</th>
						<th rowspan='2'>地址</th>
						<th rowspan='2'>联系人</th>
						<th rowspan='2'>电话</th>
						<th rowspan='2'>更新日期</th>
					</tr>
					<tr>
						<!-- <th rowspan="3">
							全市规模总计
						</th> -->
						<th rowspan="2">折合原粮合计</th>
						<th rowspan="2">小麦</th>
						<th rowspan="2">稻谷</th>
						<th colspan="3">面粉</th>
						<th colspan="3">大米</th>
						<th rowspan="2">合计</th>
						<th rowspan="2">大豆原油</th>
						<th colspan="3">成品油</th>
					</tr>
					<tr>
						<th>小计</th>
						<th>小包装</th>
						<th>罐存</th>
						<th>小计</th>
						<th>小包装</th>
						<th>罐存</th>
						<th>合计</th>
						<th>小包装</th>
						<th>罐存</th>
						<th></th>
						<th></th>
						<th></th>
						<th></th>
					</tr>
				</thead>
				<tbody>
					<tr v-for="(item,index) in formData.reserveSizeSummaryDetailVOList">
						<!-- <td><span style="width: 60px;">{{index+1}}</span></td> -->
						<!-- <td style="width: 120px;">
              <span style="width: 120px;">{{item.kdmc}}</span>
            </td> -->
						<td style="max-width: 140px;">
							<!-- <el-form-item style="width: 120px;" :key="item.key" :prop="'reserveSizeSummaryDetailVOList.' + index + '.xm'"> -->
								{{item.kdmc}}
							<!-- </el-form-item> -->

						</td>
						<td>
							<span>
								{{String(item.cblhj).indexOf(".") > -1
                ? Number(item.cblhj).toFixed(3)
                : item.cblhj}}</span>
							<!-- <el-form-item v-else :key="item.key" :prop="'detailList.' + index + '.ncwb'" :rules="[
                   {
                     pattern:/^(-)?(0|[1-9]\d*)(\s|$|\.\d{1,3}\b)/,
                     message: '请输入数字,最多保留三位小数',
                     trigger: 'blur',
                   },
                 ]">
                <el-input clearable v-model="item.ncwb" @change="gcinputnum(index,'ncwb')" placeholder="请输入">
                </el-input>
              </el-form-item> -->
						</td>
						<td>
							<span>
								{{String(item.xm).indexOf(".") > -1
                ? Number(item.xm).toFixed(3)
                : item.xm}}</span>
						</td>
						<td>
							<span>
								{{String(item.dg).indexOf(".") > -1
                ? Number(item.dg).toFixed(3)
                : item.dg}}</span>
						</td>
						<td>
							<span>
								{{String(item.mfhj).indexOf(".") > -1
                ? Number(item.mfhj).toFixed(3)
                : item.mfhj}}</span>
							<!-- <el-form-item v-else :key="item.key" :prop="'detailList.' + index + '.mfxj'" :rules="[
                   {
                     pattern:/^(-)?(0|[1-9]\d*)(\s|$|\.\d{1,3}\b)/,
                     message: '请输入数字,最多保留三位小数',
                     trigger: 'blur',
                   },
                 ]">
                <el-input clearable v-model="item.mfxj" @change="gcinputnum(index,'mfxj')" placeholder="请输入">
                </el-input>
              </el-form-item> -->
						</td>
						<td>
							<span>
								{{String(item.mfXbz).indexOf(".") > -1
                ? Number(item.mfXbz).toFixed(3)
                : item.mfXbz}}</span>
						</td>
						<td>
							<span>
								{{String(item.mfGc).indexOf(".") > -1
                ? Number(item.mfGc).toFixed(3)
                : item.mfGc}}</span>
						</td>
						<td>
							<span>
								{{String(item.dmhj).indexOf(".") > -1
                ? Number(item.dmhj).toFixed(3)
                : item.dmhj}}</span>
							<!-- <el-form-item v-else :key="item.key" :prop="'detailList.' + index + '.qmwb'" :rules="[
                   {
                     pattern:/^(-)?(0|[1-9]\d*)(\s|$|\.\d{1,3}\b)/,
                     message: '请输入数字,最多保留三位小数',
                     trigger: 'blur',
                   },
                 ]">
                <el-input clearable v-model="item.qmwb" @change="gcinputnum(index,'qmwb')" placeholder="请输入">
                </el-input>
              </el-form-item> -->
						</td>
						<td>
							<span>
								{{String(item.dmXbz).indexOf(".") > -1
			    ? Number(item.dmXbz).toFixed(3)
			    : item.dmXbz}}</span>
						</td>
						<td>
							<span>
								{{String(item.dmGc).indexOf(".") > -1
			    ? Number(item.dmGc).toFixed(3)
			    : item.dmGc}}</span>
						</td>
						<td>
							<span>
								{{String(item.cbyhj).indexOf(".") > -1
			    ? Number(item.cbyhj).toFixed(3)
			    : item.cbyhj}}</span>
							<!-- <el-form-item v-else :key="item.key" :prop="'detailList.' + index + '.qmwb'" :rules="[
			       {
			         pattern:/^(-)?(0|[1-9]\d*)(\s|$|\.\d{1,3}\b)/,
			         message: '请输入数字,最多保留三位小数',
			         trigger: 'blur',
			       },
			     ]">
			    <el-input clearable v-model="item.qmwb" @change="gcinputnum(index,'qmwb')" placeholder="请输入">
			    </el-input>
			  </el-form-item> -->
						</td>
						<td>
							<span>
								{{String(item.ddyy).indexOf(".") > -1
			    ? Number(item.ddyy).toFixed(3)
			    : item.ddyy}}</span>
						</td>
						<td>
							<span>
								{{String(item.cpyhj).indexOf(".") > -1
			    ? Number(item.cpyhj).toFixed(3)
			    : item.cpyhj}}</span>
							<!-- <el-form-item v-else :key="item.key" :prop="'detailList.' + index + '.qmwb'" :rules="[
			       {
			         pattern:/^(-)?(0|[1-9]\d*)(\s|$|\.\d{1,3}\b)/,
			         message: '请输入数字,最多保留三位小数',
			         trigger: 'blur',
			       },
			     ]">
			    <el-input clearable v-model="item.qmwb" @change="gcinputnum(index,'qmwb')" placeholder="请输入">
			    </el-input>
			  </el-form-item> -->
						</td>
						<td>
							<span>
								{{String(item.cpyxbzhj).indexOf(".") > -1
			    ? Number(item.cpyxbzhj).toFixed(3)
			    : item.cpyxbzhj}}</span>
						</td>
						<td>
							<span>
								{{String(item.cpyGc).indexOf(".") > -1
			    ? Number(item.cpyGc).toFixed(3)
			    : item.cpyGc}}</span>
						</td>
						<td style="max-width: 160px;">
							<span>
								{{String(item.address).indexOf(".") > -1
			    ? Number(item.address).toFixed(3)
			    : item.address}}</span>
						</td>
						<td>
							<span>
								{{String(item.linkman).indexOf(".") > -1
			    ? Number(item.linkman).toFixed(3)
			    : item.linkman}}</span>
						</td>
						<td>
							<span>
								{{String(item.phone).indexOf(".") > -1
			    ? Number(item.phone).toFixed(3)
			    : item.phone}}</span>
						</td>
						<td>
							<span>
								{{String(item.updateTime).indexOf(".") > -1
			    ? Number(item.updateTime).toFixed(3)
			    : item.updateTime}}</span>
						</td>
					</tr>
				</tbody>
			</table>
			<!-- <div class="flexBox">
	    <div style="flex: 1;">上报单位：{{formInline.orgName}}</div>
	    <div style="flex: 1;text-align: right;">
	      <span>上报时间：{{formInline.reportDay}}</span>
	    </div>
	  </div> -->
			<div style="text-align: center; margin-top: 20px">
				<el-button type="primary" :loading="stateLoading" @click="saveZc('','formInline','1')" size="small" class="iconfont icongaizhang"
				 v-if="type == 'hz'">汇总</el-button>
				<el-button
				v-if="type == 'dc'"
				  type="primary"
				  class="iconfont icondaochu11"
				  @click="exportExcel"
				  >导出</el-button
				>
				<el-button @click="cancelClick" type="primary" icon="iconfont iconfanhui">返回</el-button>
			</div>
		</el-form>
	</div>
</template>

<script>
	import {
		rSSummaryGetAccepted,
		reserveSizeReport,
		reserveSizeAcceptId,
		rSSummaryId,
		rSizeSummarySummarize,
		rSSummaryNameId
	} from "@/api/reserveScaleReport/index";
	import * as XLSX from "xlsx";
	import * as XLSXS from "xlsx-style";
	import FileSaver from "file-saver";
	import {
		dateFormat
	} from '@/utils/index'
	export default {
		data() {
			return {
				stateLoading: false,
				type: this.$route.query.type,
				formData:{
					reserveSizeSummaryDetailVOList:[],
				},
				
				formInline: {
					orgCode: sessionStorage.getItem("orgCode"),
					sskdbm: sessionStorage.getItem("tyshxydm") + '001',
					orgName: sessionStorage.getItem("orgName"),
					name:'',
					reserveSizeSummaryDetailVOList: [{
						dg: 0,
						xm: 0,
					}],
				}
			}
		},
		created() {
			const now = new Date();
			const year = now.getFullYear(); // 年
			// const month = now.getMonth()+1
			const month = now.getMonth() < 9 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1; // 月
			this.formInline.period = `${year}-${month}`
			this.formInline.year = dateFormat(new Date())
			console.log(this.$route.query.id, 'uyu========')
			// this.getJxcInfo()
			if (this.$route.query.id) {
				this.getJxcInfo()
			} else {
				this.GetPeriod()
			}

		},
		methods: {
			getDataName(){
				var data={
					id:this.$route.query.id,
					name:this.formInline.name
				}
				var sjcbgmhj = {
					kdmc:'全市规模总计',
					address: null,
					cblhj: null,
					cbyhj: null,
					cpyGc: null,
					cpyhj: null,
					cpyxbzhj: null,
					ddyy: null,
					dg: null,
					dmGc: null,
					dmXbz: null,
					dmhj: null,
					id: null,
					kdLevel: null,
					kdbm: "",
					linkman: null,
					mfGc: null,
					mfXbz: null,
					mfhj: null,
					phone: null,
					reserveSizeSummaryId: null,
					updateTime: "2023-11-28",
					xm: null,
				}
				rSSummaryNameId(data).then(res =>{
					if (res.infoCode == 200) {
						this.formInline = res.data
						this.formInline.cityTotal.kdmc='市级合计'
						this.formInline.districtTotal.kdmc='区级合计'
						let arr1=[]
						let arr2=arr1.concat(this.formInline.cityTotal,this.formInline.cityLevelList,this.formInline.districtTotal,this.formInline.districtLevelList)
						console.log(arr2,'yyeete------++++++++++++')
						arr2.forEach((item) =>{
							if(item.kdmc == '市级合计' || item.kdmc =='区级合计'){
								sjcbgmhj.cblhj+=item.cblhj
								sjcbgmhj.xm+=item.xm
								sjcbgmhj.dg+=item.dg
								sjcbgmhj.mfGc+=item.mfGc
								sjcbgmhj.mfXbz+=item.mfXbz
								sjcbgmhj.mfhj+=item.mfhj
								sjcbgmhj.dmhj+=item.dmhj
								sjcbgmhj.dmGc+=item.dmGc
								sjcbgmhj.dmXbz+=item.dmXbz
								sjcbgmhj.cpyhj+=item.cpyhj
								sjcbgmhj.ddyy+=item.ddyy
								sjcbgmhj.cbyhj+=item.cbyhj
								sjcbgmhj.cpyGc+=item.cpyGc
								sjcbgmhj.cpyxbzhj+=item.cpyxbzhj
							}
						})
						this.formData.qscblhj=sjcbgmhj.cblhj
						 this.formData.qscbyhj=sjcbgmhj.cbyhj
						this.formData.reserveSizeSummaryDetailVOList=arr2
						this.formData.reserveSizeSummaryDetailVOList.unshift(sjcbgmhj)
					}
				})
			},
			doSearch(){
				this.formInline.name=''
				this.getDataName()
			},
			cancelClick() {
				this.$router.push({
					name: "summaryIndex"
				});
			},
			saveZc(type, formName, status, sussInfo, errInfo) {
				console.log('66555-==============')
				// this.shtype = shtype
				this.$refs[formName].validate((valid) => {
					if (valid) {
						// if (this.$route.query.id) {
							this.formData.reportMonth=this.formInline.reportMonth
							this.formData.reportYear=this.formInline.reportYear
							this.formData.summaryDay=this.formInline.summaryDay
							this.formInline.status = status
							this.formInline.id = this.$route.query.id
							console.log(this.formData, 'ooiyy7778-----')
							rSizeSummarySummarize(this.formData).then(res => {
								if (res.infoCode == 200) {
									this.$message({
										message: "提交成功",
										type: "success",
									});
									this.$router.push({
										name: "summaryIndex",
									});
								} else {
									this.$message.error(res.msg);
								}
							})
						// }
					}
				})

			},
			GetPeriod() {
				const now = new Date();
				const year = now.getFullYear(); // 年
				var data = {
					// month:'2023-11'
					year: year
				}
				console.log('6666===========')
				var sjcbgmhj = {
					kdmc:'全市规模总计',
					address: null,
					cblhj: null,
					cbyhj: null,
					cpyGc: null,
					cpyhj: null,
					cpyxbzhj: null,
					ddyy: null,
					dg: null,
					dmGc: null,
					dmXbz: null,
					dmhj: null,
					id: null,
					kdLevel: null,
					kdbm: "",
					linkman: null,
					mfGc: null,
					mfXbz: null,
					mfhj: null,
					phone: null,
					reserveSizeSummaryId: null,
					updateTime: "2023-11-28",
					xm: null,
				}
				rSSummaryGetAccepted(data).then(res => {
					if (res.infoCode == 200) {
						this.formInline = res.data
						this.formInline.cityTotal.kdmc='市级合计'
						this.formInline.districtTotal.kdmc='区级合计'
						let arr1=[]
						let arr2=arr1.concat(this.formInline.cityTotal,this.formInline.cityLevelList,this.formInline.districtTotal,this.formInline.districtLevelList)
						console.log(arr2,'yyeete------++++++++++++')
						arr2.forEach((item) =>{
							if(item.kdmc == '市级合计' || item.kdmc =='区级合计'){
								sjcbgmhj.cblhj+=item.cblhj
								sjcbgmhj.xm+=item.xm
								sjcbgmhj.dg+=item.dg
								sjcbgmhj.mfGc+=item.mfGc
								sjcbgmhj.mfXbz+=item.mfXbz
								sjcbgmhj.mfhj+=item.mfhj
								sjcbgmhj.dmhj+=item.dmhj
								sjcbgmhj.dmGc+=item.dmGc
								sjcbgmhj.dmXbz+=item.dmXbz
								sjcbgmhj.cpyhj+=item.cpyhj
								sjcbgmhj.ddyy+=item.ddyy
								sjcbgmhj.cbyhj+=item.cbyhj
								sjcbgmhj.cpyGc+=item.cpyGc
								sjcbgmhj.cpyxbzhj+=item.cpyxbzhj
							}
						})
						this.formData.qscblhj=sjcbgmhj.cblhj
						 this.formData.qscbyhj=sjcbgmhj.cbyhj
						this.formData.reserveSizeSummaryDetailVOList=arr2
						this.formData.reserveSizeSummaryDetailVOList.unshift(sjcbgmhj)
						// this.formInline.reserveSizeSummaryDetailList=arr2	
						// this.formInline.reserveSizeSummaryDetailList.unshift(sjcbgmhj)
					}
				})
			},
			getJxcInfo() {
				var data = {
					id: this.$route.query.id
				}
				var sjcbgmhj = {
					kdmc:'全市规模总计',
					address: null,
					cblhj: null,
					cbyhj: null,
					cpyGc: null,
					cpyhj: null,
					cpyxbzhj: null,
					ddyy: null,
					dg: null,
					dmGc: null,
					dmXbz: null,
					dmhj: null,
					id: null,
					kdLevel: null,
					kdbm: "",
					linkman: null,
					mfGc: null,
					mfXbz: null,
					mfhj: null,
					phone: null,
					reserveSizeSummaryId: null,
					updateTime: "2023-11-28",
					xm: null,
				}
				rSSummaryId(data).then(res => {
					if (res.infoCode == 200) {
						this.formInline = res.data
						this.formInline.cityTotal.kdmc='市级合计'
						this.formInline.districtTotal.kdmc='区级合计'
						let arr1=[]
						let arr2=arr1.concat(this.formInline.cityTotal,this.formInline.cityLevelList,this.formInline.districtTotal,this.formInline.districtLevelList)
						console.log(arr2,'yyeete------++++++++++++')
						arr2.forEach((item) =>{
							if(item.kdmc == '市级合计' || item.kdmc =='区级合计'){
								sjcbgmhj.cblhj+=item.cblhj
								sjcbgmhj.xm+=item.xm
								sjcbgmhj.dg+=item.dg
								sjcbgmhj.mfGc+=item.mfGc
								sjcbgmhj.mfXbz+=item.mfXbz
								sjcbgmhj.mfhj+=item.mfhj
								sjcbgmhj.dmhj+=item.dmhj
								sjcbgmhj.dmGc+=item.dmGc
								sjcbgmhj.dmXbz+=item.dmXbz
								sjcbgmhj.cpyhj+=item.cpyhj
								sjcbgmhj.ddyy+=item.ddyy
								sjcbgmhj.cbyhj+=item.cbyhj
								sjcbgmhj.cpyGc+=item.cpyGc
								sjcbgmhj.cpyxbzhj+=item.cpyxbzhj
							}
						})
						this.formData.qscblhj=sjcbgmhj.cblhj
						 this.formData.qscbyhj=sjcbgmhj.cbyhj
						this.formData.reserveSizeSummaryDetailVOList=arr2
						this.formData.reserveSizeSummaryDetailVOList.unshift(sjcbgmhj)
					}
				})
			},
			exportExcel() {
			  this.$confirm("是否下载Excel表？", "提示", {
			    closeOnClickModal: false,
			    closeOnPressEscape: false,
			    confirmButtonText: "确定",
			    cancelButtonText: "取消",
			    type: "warning",
			    customClass: "messageBox",
			  }).then(() => {
			    let wb = XLSX.utils.table_to_book(
			      document.getElementById("summaryData"),
			      { sheet: "存储费补贴汇总" }
			    );
			    this.setExlStyle(wb["Sheets"]["存储费补贴汇总"]);
			    //合并单元格边框补齐
			    this.addRangeBorder(
			      wb["Sheets"]["存储费补贴汇总"]["!merges"],
			      wb["Sheets"]["存储费补贴汇总"]
			    );
			    var ws = XLSXS.write(wb, {
			      type: "buffer",
			    });
			    try {
			      FileSaver.saveAs(
			        new Blob([ws], { type: "application/octet-stream" }),
			        `存储费补贴汇总.xlsx`
			      );
			    } catch (e) {
			      if (typeof console !== "undefined") console.log(e, ws);
			    }
			    return ws;
			  });
			},
			setExlStyle(data, type) {
			  let borderAll = {
			    //单元格外侧框线
			    top: {
			      style: "thin",
			    },
			    bottom: {
			      style: "thin",
			    },
			    left: {
			      style: "thin",
			    },
			    right: {
			      style: "thin",
			    },
			  };
			  data["!cols"] = [];
			  // if(type =='kc'){
			  // data['!cols'].push({wpx: 60},{wpx: 260});
			  for (let i = 0; i < 22; i++) {
				  if(i == 0){
					  data["!cols"].push({ wpx: 280 });
				  }else{
					data["!cols"].push({ wpx: 120 });  
				  }
			    
			  }
			  // }
			  // this.$nextTick(() =>{
			  for (let key in data) {
			    console.log(key, data[key], "datakey----------------");
			    if (data[key] instanceof Object) {
			      // data[key].t='s'
			      data[key].s = {
			        // item.NumberFormat = "@";
			        border: borderAll,
			        alignment: {
			          horizontal: "center", //水平居中对齐
			          vertical: "center",
			        },
			        font: {
			          sz: 11,
			        },
			        bold: true,
			        numFmt: 0,
			      };
			      // console.log(key,data[key],'datakey----------------')
			    }
			  }
			  this.$nextTick(() => {
			    return data;
			  });
			},
			addRangeBorder(range, ws) {
			  let cols = [
			    "A",
			    "B",
			    "C",
			    "D",
			    "E",
			    "F",
			    "G",
			    "H",
			    "I",
			    "J",
			    "K",
			    "L",
			    "M",
			    "N",
			    "O",
			    "P",
			    "Q",
			    "R",
			    "S",
			    "T",
			    "U",
			    "V",
			    "W",
			    "X",
			    "Y",
			    "Z",
			  ];
			  range.forEach((item) => {
			    console.log(item);
			    let style = {
			      s: {
			        border: {
			          top: { style: "thin" },
			          left: { style: "thin" },
			          bottom: { style: "thin" },
			          right: { style: "thin" },
			        },
			      },
			    };
			    // 处理合并行
			    for (let i = item.s.c; i <= item.e.c; i++) {
			      ws[`${cols[i]}${Number(item.e.r) + 1}`] =
			        ws[`${cols[i]}${Number(item.e.r) + 1}`] || style;
			      // 处理合并列
			      for (let k = item.s.r + 2; k <= item.e.r + 1; k++) {
			        ws[cols[i] + k] = ws[cols[k] + item.e.r] || style;
			      }
			    }
			  });
			  return ws;
			},
		}
	}
</script>

<style scoped lang="scss">
	.recordsDetailsTable {
		background-color: #fff;
		font-size: 14px;
		padding-bottom: 20px;

		table {
			width: 100%;
			margin-top: 10px;
			font-size: 14px;
		}

		.tdsize {
			font-size: 18px;
			font-weight: 700;
		}

		td,
		th {
			text-align: center;
			border: 1px solid #eaeaea;
			word-wrap: break-word;
			height: 40px;
		}

		span,
		.el-input,
		.el-textarea {
			font-size: 12px;
		}
	}

	.flexBox {
		display: flex;
		line-height: 40px;
		height: 40px;
		// text-align: center;
	}

	.areawidth {
		width: 100%;
	}

	.areawidth /deep/ .el-textarea__inner {
		width: 100% !important;
	}

	// .el-form--inline .el-form-item
	.areawidth /deep/.el-form-item {
		width: 100% !important;
	}

	.areawidth /deep/ .el-form-item__content {
		width: 93% !important;
	}
</style>
<style>

</style>
