<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;">市级调节储备粮进销存汇总表</div>
   <div class="flexBox">
      <div style="flex: 1;">上报单位：{{formInline.orgName}}</div>
      <div style="flex: 1;text-align: center;">填报期数：{{formInline.period}}</div>
      <div style="flex: 1;text-align: right;" >
        <span>单位：吨</span>
      </div>
    </div> -->
      <table id="summaryData">
        <thead>
			<tr>
				<th colspan='9' style="border: none;">
				    <div style="text-align: center;font-size: 20px;font-weight: 600;margin-bottom: 20px;">市级调节储备粮进销存汇总表</div>	
				</th>
			</tr>
			<tr>
				<th colspan='3' style="border: none;">
					   <div style="text-align: left;">上报单位：{{formInline.orgName}}</div>
				</th>
				<th colspan="3" style="border: none;">
					<div style="text-align: left;">填报期数：{{formInline.period}}</div>
				</th>
				<th colspan="1" style="border: none;">
				</th>
				<th colspan="1" style="border: none;">
				</th>
				<th colspan="1" style="border: none;">
					<div style="text-align: right;" >
					  <span>单位：吨</span>
					</div>
				</th>
			</tr>
          <tr>
            <th rowspan="2">
              品名
            </th> 
            <th rowspan="2">期初库存</th>
            <th rowspan="1" colspan="3">收入
             </th>
           <th rowspan="1" colspan="3">支出
            </th>
            <th rowspan="2">期末库存</th>
          </tr>
          <tr>
          <td>合计</td>
          <td>采购</td>
          <td>其它</td>
          <td colspan='1'>合计</td>
          <td colspan='1'>销售</td>
          <!-- <td colspan='1'>损耗</td> -->
          <td colspan='1'>其它</td>
          </tr>
        </thead>
       <tbody>
          <tr v-for="(item,index) in formInline.detailList">
            <td style="width: 130px;">
              {{item.pzmc}}
            <td>
              <span>
              {{String(item.initial).indexOf(".") > -1
                ? Number(item.initial).toFixed(3)
                : item.initial}}</span>
            </td>
            <td>
              <!-- <span v-if="type == 'ck'|| index ==0 || index ==1 || index ==2 || index ==3 || index ==8 || index ==13 || index ==16 || index ==19 || index ==21">{{item.incomeTotal}}</span> -->
              <span>{{String(item.incomeTotal).indexOf(".") > -1
                ? Number(item.incomeTotal).toFixed(3)
                : item.incomeTotal}}</span>
            <td>
              <span>{{String(item.purchase).indexOf(".") > -1
                ? Number(item.purchase).toFixed(3)
                : item.purchase}}</span>
            </td>
            <td>
              <span>{{String(item.otherIncome).indexOf(".") > -1
                ? Number(item.otherIncome).toFixed(3)
                : item.otherIncome}}</span>
            </td>
            <td>
				<span>{{String(item.expenseTotal).indexOf(".") > -1
                ? Number(item.expenseTotal).toFixed(3)
                : item.expenseTotal}}</span>
              
            </td>
            <td>
              <span>{{String(item.sale).indexOf(".") > -1
                ? Number(item.sale).toFixed(3)
                : item.sale}}</span>
            </td>
            <td>
              <span>{{String(item.otherExpense).indexOf(".") > -1
                ? Number(item.otherExpense).toFixed(3)
                : item.otherExpense}}</span>
            </td>
            <td>
              {{String(item.ending).indexOf(".") > -1
                ? Number(item.ending).toFixed(3)
                : item.ending}}
            </td>
          </tr>
		  <div v-if="type == 'ck'" style="margin-top: 20px;"></div>
          <tr v-if="type == 'ck' && formInline.remark">
			  <td colspan="1" style="border: none;text-align: center;">
				  <div>备注</div>
			  </td>
			  <td colspan="8" style="border: none;text-align: left;">
				  <div class="textarap"
				  style="white-space: pre-wrap" v-html="formInline.remark">
				   </div>
			  </td>
		  </tr>
		  <div v-if="type != 'xg'" style="margin-top: 20px;"></div>
		  <tr v-if="type != 'xg'">
			  <td colspan="1" style="border: none;text-align: left;">
				<div style="text-align: right;margin-right: 10px;">
					制表
				 </div>
			  </td>
			  <td colspan="1" style="border: none;text-align: left;width: 130px;">
				<div class="inputText"
				style="white-space: pre-wrap" v-html="formInline.tabulator">
				 </div>
			  </td>
			  <td colspan="1" style="border: none;text-align: left;width: 150px;">
				<div class="inputText"
				style="white-space: pre-wrap;margin-left: 5px;" v-html="formInline.tabulatorDate">
				 </div>
			  </td>
			  <td colspan="1" style="border: none;text-align: left;">
			  </td>
			  <td colspan="1" style="border: none;text-align: left;">
				<div style="text-align: right;margin-right: 10px;">
					复核
				 </div>
			  </td>
			  <td colspan="1" style="border: none;text-align: left;width: 130px;">
				<div class="inputText"
				style="white-space: pre-wrap" v-html="formInline.recevier">
				 </div>
			  </td>
			  <td colspan="1" style="border: none;text-align: left;width: 150px;">
				<div class="inputText"
				style="white-space: pre-wrap;margin-left: 5px;" v-html="formInline.recevieDate">
				 </div>
			  </td>
			  <td colspan="1" style="border: none;text-align: left;">
			  </td>
			  <td colspan="1" style="border: none;text-align: left;">
			  </td>
		  </tr>
        </tbody>
      </table>
	  <div v-if="type != 'ck'">
		<div style="margin-top: 20px;"></div>
		<div class="areawidth" v-if="type != 'xg' && formInline.remark">
		   <el-form-item label="备注" label-width="80px">
		   <el-input :readonly="type != 'xg'" type="textarea" :rows="2" clearable v-model="formInline.remark" placeholder="请输入"></el-input>
		   </el-form-item>
		 </div> 
		 <div class="areawidth" v-if="type == 'xg'">
		    <el-form-item label="备注" label-width="80px">
		    <el-input :readonly="type != 'xg'" type="textarea" :rows="2" clearable v-model="formInline.remark" placeholder="请输入"></el-input>
		    </el-form-item>
		  </div>
		 <el-row>
		  <el-col :span="12">
			  <el-form-item label="制表">
				<el-input readonly v-model="formInline.tabulator" placeholder=""></el-input>
			  </el-form-item>  
			  <el-form-item label-width="0">
				  <el-date-picker
				  :readonly="type != 'xg'"
				   v-model="formInline.tabulatorDate"
				   type="date"
				   placeholder="选择时间"
				   format="yyyy-MM-dd"
				   value-format="yyyy-MM-dd">
				  </el-date-picker>
			  </el-form-item>
		  </el-col>
		<el-col :span="12">
			  <el-form-item label="复核">
				<el-input readonly v-model="formInline.recevier" placeholder=""></el-input>
			  </el-form-item>  
			  <el-form-item label-width="0">
				  <el-date-picker
				  :readonly="type != 'fh'"
				   v-model="formInline.recevieDate"
				   type="date"
				   placeholder="选择时间"
				   format="yyyy-MM-dd"
				   value-format="yyyy-MM-dd">
				  </el-date-picker>
			  </el-form-item>
		</el-col>
		</el-row>  
	  </div>
      <div style="text-align: center; margin-top: 20px">
        <el-button  v-if="type != 'ck' && type == 'xg' " type="primary"
          icon="iconfont iconbaocun" @click="saveZc('0','formInline','1','91000290','待提交')">保存</el-button>
       <el-button v-if="type != 'ck'&& type == 'xg'" type="primary"
          icon="iconfont icontijiao" @click="saveZc('1','formInline','1','91000300','待复核')">提交</el-button>
       <el-button type="primary" :loading="stateLoading" @click="saveZc('2','formInline','3','91000600','审批完成')" size="small" class="iconfont icongaizhang"
       	v-if="type != 'ck' && (formInline.status == '91000202' || formInline.status == '91000300')">复核</el-button>
		<el-button type="primary" :loading="stateLoading" @click="saveZc('2','formInline','3','91000290','待提交')" size="small" class="iconfont iconbohui"
			v-if="type != 'ck' && (formInline.status == '91000202' || formInline.status == '91000300')">驳回</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 {
	purchaseStockgenerate,
	purchaseStockSummarySave,
	purchaseStocksummaryInfo,
	purchaseStockSummaryUpdate
  } from "@/api/cwbb/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:{
		  receiveOpinion:'',//接收意见
		  receiveStatus:'1',//是否接收
          dataType:1,
          leader:'',
          recevier:'',
		  recevieDate:'',
          tabulator:'',
		  tabulatorDate:'',
          reportDate:'',
          orgCode:sessionStorage.getItem("orgCode"),
          period:'',
          sskdbm:sessionStorage.getItem("tyshxydm")+'001',
          orgName:sessionStorage.getItem("orgName"),
          operationType:'',
		  summaryStatus:1,
          detailList:[
            {
              pzmc:'粮食合计',
              pzbm:'',
              initial:null,
              incomeTotal:null,
              purchase:null,
              otherIncome:null,
              expenseTotal:null,
              sale:null,
              loss:null,
              otherExpense:null,
              ending:null,
            },
            {
              pzmc:'(一)小麦',
              pzbm:'1110000',
              initial:null,
              incomeTotal:null,
              purchase:null,
              otherIncome:null,
              expenseTotal:null,
              sale:null,
              loss:null,
              otherExpense:null,
              ending:null,
            },
            {
              pzmc:'其中：硬白麦',
              pzbm:'1111006',
              initial:null,
              incomeTotal:null,
              purchase:null,
              otherIncome:null,
              expenseTotal:null,
              sale:null,
              loss:null,
              otherExpense:null,
              ending:null,
            },
            {
              pzmc:'软白麦',
              pzbm:'1111009',
              initial:null,
              incomeTotal:null,
              purchase:null,
              otherIncome:null,
              expenseTotal:null,
              sale:null,
              loss:null,
              otherExpense:null,
              ending:null,
            },
            {
              pzmc:'硬红麦',
              pzbm:'1111007',
              initial:null,
              incomeTotal:null,
              purchase:null,
              otherIncome:null,
              expenseTotal:null,
              sale:null,
              loss:null,
              otherExpense:null,
              ending:null,
            },
            {
              pzmc:'软红麦',
              pzbm:'1111010',
              initial:null,
              incomeTotal:null,
              purchase:null,
              otherIncome:null,
              expenseTotal:null,
              sale:null,
              loss:null,
              otherExpense:null,
              ending:null,
            },
            {
              pzmc:'(二)稻谷',
              pzbm:'1130000',
              initial:null,
              incomeTotal:null,
              purchase:null,
              otherIncome:null,
              expenseTotal:null,
              sale:null,
              loss:null,
              otherExpense:null,
              ending:null,
            },
            {
              pzmc:'其中:粳稻谷',
              pzbm:'1132000',
              initial:null,
              incomeTotal:null,
              purchase:null,
              otherIncome:null,
              expenseTotal:null,
              sale:null,
              loss:null,
              otherExpense:null,
              ending:null,
            },
          ],
        }
      }

    },
    created(){
		this.getJxcInfo()
		
		// this.formInline.receiveDate=this.dateFormat()
    },
    methods:{
      cancelClick(){
        this.$router.push({
          name: "arSummary",
        });
      },

      saveZc(type,formName,shtype,status,statusName){
        console.log('66555-==============')
        this.shtype=shtype
		// if(status){
		// 	this.formInline.status=status
		// 	this.formInline.status=status
		// }
		
        if(status){
          // this.formInline.status=status
          	// this.formInline.statusName=statusName
			this.formInline.operationType=type
        }else{
          this.formInline.operationType=type
        }
		this.formInline.summaryStatus=1
		var datas={
			...this.formInline,
			status:status ? status : undefined,
			statusName:statusName ? statusName : undefined
		}
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.$route.query.id){
              // console.log(this.formInline,'ooiyy7778-----')
              purchaseStockSummaryUpdate(datas,this.shtype).then(res =>{
                if(res.infoCode == 200){
                  this.$message({
                    message: "提交成功",
                    type: "success",
                  });
                  this.$router.push({
                    name: "arSummary",
                  });
                }else{
					this.formInline.status=''
					this.formInline.statusName=''
                  this.$message.error(res.msg);
                }
              })
            }else{
              // console.log(this.formInline,'ooiyy7778----+++++++++++++-')
              purchaseStockSummarySave(datas).then(res =>{
                if(res.infoCode == 200){
                  this.$message({
                    message: "保存成功",
                    type: "success",
                  });
                  this.$router.push({
                    name: "arSummary",
                  });
                }else{
                  this.$message.error(res.msg);
                }
              })
            }
          }
        })

      },
      getJxcInfo(){
		  console.log(dateFormat(new Date()),'9976577-----------')
		if(this.$route.query.id){
			
			var data={
				period:this.$route.query.period,
				dataType:1,
			  // psId:this.$route.query.id
			}
			purchaseStocksummaryInfo(data).then(res =>{
			  if(res.infoCode == 200){
				  if(res.data){
					  // this.formInline.reporter=sessionStorage.getItem("userName")
					  this.formInline=res.data
					  // this.formInline.reporter='储备粮11'
					  if(this.type == 'fh'){
					  	this.formInline.recevier=this.formInline.recevier ? this.formInline.recevier :sessionStorage.getItem("userName")
						this.formInline.recevieDate=dateFormat(new Date())
					  }else if(this.type == 'xg'){
					  	this.formInline.tabulator=this.formInline.tabulator ? this.formInline.tabulator :sessionStorage.getItem("userName")
						this.formInline.recevier=''
						this.formInline.recevieDate=''
					  }
				  }
			  }
			})
		}else{
			var data={
				// period:'2023年01月',
				dataType:1,
			  // psId:this.$route.query.id
			}
			purchaseStockgenerate(data).then(res =>{
			  if(res.infoCode == 200){
			    this.formInline=res.data
				this.formInline.orgCode=this.formInline.orgCode ? this.formInline.orgCode :sessionStorage.getItem("orgCode")
				this.formInline.sskdbm=this.formInline.sskdbm ? this.formInline.sskdbm :sessionStorage.getItem("tyshxydm") + '001'
				this.formInline.orgName= this.formInline.orgName ? this.formInline.orgName :sessionStorage.getItem("orgName")
				if(this.type == 'fh'){
					this.formInline.recevier=this.formInline.recevier ? this.formInline.recevier :sessionStorage.getItem("userName")
				    this.formInline.receiveDate=dateFormat(new Date())
				}else if(this.type == 'xg'){
					this.formInline.tabulator=this.formInline.tabulator ? this.formInline.tabulator :sessionStorage.getItem("userName")
					this.formInline.tabulatorDate=dateFormat(new Date())
					this.formInline.recevier=''
				}
			  }
			})
		}
        
      },
	  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++) {
	      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;
   text-align: left;
 }
 .areawidth /deep/ .el-form-item__content{
   width: 93%!important;
 }
 .textarap {
   border: 1px solid #dcdfe6;
   background-color: #ffffff;
   line-height: 1.5;
   padding: 5px 15px;
   border-radius: 4px;
   color: #606266;
   font-size: 12px;
   min-height: 40px;
 }
 .inputText {
   border: 1px solid #dcdfe6;
   background-color: #ffffff;
   line-height: 40px;
   height: 40px;
   padding: 0 15px;
   border-radius: 4px;
   color: #606266;
   font-size: 12px;
   // width: 120px;
 }
</style>
<style>

</style>
