<template>
  <div id="protectedItems" class="content-main">
    <el-form :inline="true" ref="formInline" :model="formInline" class="demo-form-inline recordsDetailsTable">
    <!-- <div style="text-align: center;font-size: 20px;font-weight: 600;margin-bottom: 20px;">{{formInline.reportMonth}}末市储大米按生产时间划分明细表</div>
	<div class="flexBox">
      <div style="flex: 1;text-align: right;" >
        <span>单位：吨</span>
      </div>
    </div> -->
	    <table id="summaryData">
	      <tbody>
			  <tr>
			  	<th colspan='18' style="border: none;">
			  	    <div style="text-align: center;font-size: 20px;font-weight: 600;margin-bottom: 20px;">{{formInline.summaryMonth}}市储大米按生产时间划分明细表</div>	
			  	</th>
			  </tr>
			  <tr>
			  	<th colspan="17" style="border: none;">
			  	</th>
			  	<th colspan="1" style="border: none;">
			  		<div style="text-align: right;" >
			  		  <span>单位：吨</span>
			  		</div>
			  	</th>
			  </tr>
	        <tr>
			  <th>序号</th>
	          <th width="90px">单位</th>
			  <th>合计</th>
	          <th v-for="(item, index) in formInline.tempVOList[0].riceReportSummaryDetailDOS" :key="index">
	            <span>{{item.produceMonth}}</span>
	          </th>
	        </tr>
	        <tr v-for="(val, indexs) in formInline.tempVOList" :key="indexs">
				<td>{{formInline.tempVOList.length == indexs+1 ? '-' : indexs+1}}</td>
	          <td width="90px">
	            {{val.orgName}}
	          </td>
			  <td>{{String(val.qyhj).indexOf('.') > -1 ? Number(val.qyhj).toFixed(3) : val.qyhj}}</td>
	          <td v-for="(info, m) in val.riceReportSummaryDetailDOS" :key="m">
	            <span>{{String(info.stockNum).indexOf(".") > -1
                      ? Number(info.stockNum).toFixed(3)
                      : info.stockNum}}</span>
	          </td>
	        </tr>
	      </tbody>
	    </table>
	  <div style="margin-top: 20px;"></div>
		  <el-row>
		 		   <el-form-item label="制表" label-width="80px">
		 		     <el-input clearable readonly v-model="formInline.lister" placeholder="请输入"></el-input>
		 		   </el-form-item>
		 		   <el-form-item label="汇总时间" label-width="80px">
		 			   <el-date-picker
		 			   :readonly="type != 'sc'"
		 				 v-model="formInline.summaryDay"
		 				 type="date"
		 				 placeholder="选择时间"
		 				 format="yyyy-MM-dd"
		 				 value-format="yyyy-MM-dd">
		 				</el-date-picker>
		 		   </el-form-item>
		  </el-row> 
	  <!-- </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 == 'sc'">保存</el-button>
		<!-- <el-button type="primary" :loading="stateLoading" @click="saveZc('','formInline','2')" size="small" class="iconfont iconbohui"
			v-if="type != 'ck' && (formInline.status == '90100000' || formInline.status == '91000200')">驳回</el-button>
       <el-button type="primary" @click="saveZc('','formInline','4')" size="small" class="iconfont iconbohui"
       	v-if="type != 'ck' && formInline.status == '91000201' ">撤销</el-button> -->
        <el-button
          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 {
    riceReportSummaryId,riceReportSummarySC,riceReportSummarySave
  } from "@/api/riceMonthReport/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,
        formInline:{
          orgCode:sessionStorage.getItem("orgCode"),
          orgName: sessionStorage.getItem("orgName"),
		  tempVOList:[
			  {
				riceReportSummaryDetailDOS:[]  
			  }
			  
		  ],
        }
      }

    },
    created(){
      if(this.$route.query.id){
        this.getJxcInfo()
      }else{
        this.GetSummarySC()
      }

    },
    methods:{
      cancelClick(){
        this.$router.push({
          name: "riceSummaryIndex",
        });
      },
	  GetSummarySC(){
		  var data={
			  month:this.$route.query.reportMonth
		  }
		  riceReportSummarySC(data).then(res =>{
			  if(res.infoCode== 200){
				  
				  var sumHj={
					  orgName:'合计',
					qyhj:null,
					riceReportSummaryDetailDOS:[
						{
							stockNum:null,
						},
						{
							stockNum:null,
						},
						{
							stockNum:null,
						},
						{
							stockNum:null,
						},
						{
							stockNum:null,
						},
						{
							stockNum:null,
						},
						{
							stockNum:null,
						},
						{
							stockNum:null,
						},
						{
							stockNum:null,
						},
						{
							stockNum:null,
						},
						{
							stockNum:null,
						},
						{
							stockNum:null,
						},
						{
							stockNum:null,
						},
						{
							stockNum:null,
						},
						{
							stockNum:null,
						}
					]
				  }
				  this.formInline=res.data
				  this.formInline.tempVOList.forEach((item,index) =>{
					  var qyhj=0
					  item.riceReportSummaryDetailDOS.forEach((val,v) =>{
						  qyhj+=val.stockNum
						sumHj.riceReportSummaryDetailDOS[v].stockNum+=val.stockNum
						
					  })
					  item.qyhj=qyhj
					  sumHj.qyhj+=qyhj
				  })
				  this.formInline.tempVOList.push(sumHj)
				  this.formInline.totalStock=sumHj.qyhj
				  if(this.type == 'sc'){
				  	console.log(sessionStorage.getItem("userName"))
				  	this.formInline.summaryDay=dateFormat(new Date())
				  	this.formInline.lister=sessionStorage.getItem("userName")
				  }
				  this.formInline.summaryMonth=this.$route.query.reportMonth
				  // console.log(this.formInline)
			  }
		  })
	  },
      saveZc(type,formName,shtype,sussInfo,errInfo){
        console.log('66555-==============')
        this.$refs[formName].validate((valid) => {
          if (valid) {
			  riceReportSummarySave(this.formInline).then(res =>{
			    if(res.infoCode == 200){
			      this.$message({
			        message: "保存成功",
			        type: "success",
			      });
			      this.$router.push({
			        name: "riceSummaryIndex",
			      });
			    }else{
			      this.$message.error(res.msg);
			    }
			  })
          }
        })

      },
	    getJxcInfo() {
	      var data = {
	        id:this.$route.query.id,
	      };
	      riceReportSummaryId(data).then((res) => {
	        if (res.infoCode == 200) {
	          // this.formInline.id=this.$route.query.id
			  var qyhj=null
	          var qyhjsum=null
	          this.formInline = res.data;
			  if(this.type == 'sc'){
				  console.log(sessionStorage.getItem("userName"))
			  	this.formInline.summaryDay=dateFormat(new Date())
			  	this.formInline.lister=sessionStorage.getItem("userName")
			  }
			  this.formInline.tempVOList.forEach((item,index) =>{
				  var qyhj=0
				  item.riceReportSummaryDetailDOS.forEach((val,v) =>{
					  qyhj+=val.stockNum
				  })
				  item.qyhj=qyhj
				  // qyhjsum+=qyhj
				  if(index == this.formInline.tempVOList.length-1){
					  console.log(index,this.formInline.tempVOList.length-1,'ueyyyeuw=======')
					 item.qyhj=qyhjsum
				  }else{
					 qyhjsum+=qyhj 
				  }
			  })
			  // this.formInline.tempVOList[this.formInline.tempVOList.length].push({qyhj:qyhjsum})
			  // this.formInline.tempVOList[this.formInline.tempVOList.length].qyhj=qyhjsum
			  this.formInline.riceReportId=this.$route.query.id
			  this.formInline.status=this.$route.query.status
			  this.formInline.summaryMonth=this.$route.query.reportMonth
	        }
	      });
	    },
		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: 60 });  
			  }else if(i == 1){
				  data["!cols"].push({ wpx: 220 });
			  }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;
    }
}
.title-name{
    text-align: center;
    font-size: 22px;
    font-weight: 600;
  }
  .line-box{
    display: flex;
  }
  .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>
  #riceMonthReport {
    position: relative !important;
  }

  #riceMonthReport > div {
    left: 0px !important;
    top: -40px !important;
  }
</style>
