<!--补打柱护板-->
<template>
  <div class="cr-body-content">
    <div ref="box">
      <flexbox class="content-header">
        <el-form
          :model="listQuery"
          ref="queryForm"
          v-show="showSearch"
          :inline="true"
        >
          <el-form-item label="大众顺序号">
            <el-col :span="11">
              <el-form-item prop="beginHostSN">
                <el-input
                  v-model="listQuery.beginHostSN"
                  placeholder=""
                  clearable
                  size="small"
                  style="width: 170px"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col class="line" :span="2" style="width: 12px; text-align: center">-</el-col>
            <el-col :span="11">
              <el-form-item prop="endHostSN">
                <el-input
                  v-model="listQuery.endHostSN"
                  placeholder=""
                  clearable
                  size="small"
                  style="width: 170px"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item label="底盘号码">
            <el-col :span="11">
              <el-form-item prop="beginVin">
                <el-input
                  v-model="listQuery.beginVin"
                  placeholder=""
                  clearable
                  size="small"
                  style="width: 140px"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col class="line" :span="2" style="width: 12px; text-align: center">-</el-col>
            <el-col :span="11">
              <el-form-item prop="endVin">
                <el-input
                  v-model="listQuery.endVin"
                  placeholder=""
                  clearable
                  size="small"
                  style="width: 140px"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
          </el-form-item>
					
					<el-form-item label="上线日期">
					  <el-date-picker
					    v-model="listQuery.onlineTimeValue"
					    size="small"
					    style="width: 380px"
					    value-format="yyyy-MM-dd HH:mm:ss"
					    type="datetimerange"
					    :default-time="['00:00:00', '23:59:59']"
					    range-separator="-"
					    start-placeholder="开始日期"
					    end-placeholder="结束日期"
					  ></el-date-picker>
					</el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleFilter"
              >搜索</el-button
            >
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetQuery('queryForm')"
              >重置</el-button
            >
            <el-button
              class="filter-item"
              size="mini"
              type="success"
              icon="el-icon-s-shop"
              @click="handleReplenishPrint()"
              >补打(支持多选)</el-button
            >

          </el-form-item>
        </el-form>
      </flexbox>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        element-loading-text="拼命加载中..."
        element-loading-spinner="el-icon-loading"
        class="cr-table"
        :data="list"
        :height="tableHeightZHB"
        :cell-style="cellStyle"
        :header-cell-style="headerRowStyle"
        size="small"
        stripe
        border
        highlight-current-row
        style="width: 100%; margin-top: -25px"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        :row-key="getRowKeys"
        :expand-row-keys="expands"
        @expand-change="exChange"
      >
        <el-table-column type="selection" width="44px" sortable="false"></el-table-column>
        <el-table-column
          v-for="(item, index) in getDefaultField"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :min-width="item.width"
          :formatter="fieldFormatter"

          show-overflow-tooltip
          :gutter="0"
        >
          <template slot="header" slot-scope="scope">
            {{ scope.column.label }}
          </template>
        </el-table-column>
      </el-table>
      <div class="table-footer">
        <!-- 分页控件 style="margin-top: -25px;margin-bottom:-25px;float:right;"-->
        <pagination
          v-show="totalCount > 0"
          :total="totalCount"
          style="margin-bottom: -5px; float: right"
          :page.sync="page"
          :limit.sync="listQuery.MaxResultCount"
          @pagination="getList"
        />
      </div>
    </div>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import permission from "@/directive/permission/index.js";
import CRMTableHead from "../../components/CRMTableHead";
import importExcel from "@/components/ImportExcel-vw";
import Lockr from "lockr";
import { mapGetters } from "vuex";
import moment from "moment";
import Detail from "./detail.vue";
import { downloadFile } from "@/utils/crmindex.js";
import qs from "qs";

export default {
  name: "M100Online-budaZHB",
  components: { Pagination, CRMTableHead, importExcel, Detail },
  directives: { permission },
  filters: {
    IsCustomerSignFilter(status) {
      //翻译是否签字
      const statusMap = {
        true: "是",
        false: "否",
      };
      return statusMap[status];
    },
  },
  props: {
    customerInfosZHB: {
      type: Array,
      default: () => {

        return [];
      },
    },
  },
  data() {

    return {
      crmType: "M100Online-ZHB",
      getRowKeys: (row) => {
        return row.id; //这里看这一行中需要根据哪个属性值是id
      },
      expands: [], //只展开一行放入当前行id
      PrintTimeValue: [],
      activeNames: ["1"],
      multipleSelection: [],
      valueSelect: "",
      customerInfos: [],
      dialogOptions: [],
      versionValue: "",
      searchContent: "", // 输入内容
      showExcelImport: false,
      form: {},
      drawer: false,
      list: null,
      totalCount: 0,
      listLoading: true,
      customerInfo: {
        printType: "",
        productLine: "",
        fwStation: ""
      },
      // 高级搜索
      filterObj: {
        type: Object,
        default: () => {
          return {};
        },
      },
      listQuery: {
        SkipCount: 0,
        MaxResultCount: 15,
        beginVin: undefined,
        endVin: undefined,
        beginHostSN: undefined,
        endHostSN: undefined,
        OnlineTimeBegin: undefined,
        OnlineTimeEnd: undefined,
      },
      listPLQuery: {
        BillType: 2,
        //UserId: this.userinfo.UserId,
      },
      hostSNQuery: {
        productLine: undefined,
      },
      hostCheckQuery: {
        printType: undefined, //0:打印;1:重打;2:补打;
        productLine: undefined,
        beginHostSN: undefined,
        endHostSN: undefined,
        beginVin: undefined,
        endVin: undefined,
      },
      hostPrintQuery: {
        printType: undefined, //0:打印;1:重打;2:补打;
        productLine: undefined,
        beginHostSN: undefined,
        endHostSN: undefined,
        beginVin: undefined,
        endVin: undefined,
      },
      fileQuery: {
        dataname: undefined,
      },
      form: {
        details: [],
      },
      page: 1,
      // 显示搜索条件
      showSearch: true,
      drawer: false,
      dialogFormVisible: false,
      formTitle: "",
      isEdit: false,
      formLoading: false,
      tableHeight: document.documentElement.clientHeight - 335,
      tableHeightZHB: document.documentElement.clientHeight - 300,
      detailTableHeight: 250,
      details: [], //修改子表数据源
      PLList: [], //产线下拉
      isShowHostSN: false,
      isShowVin: false,
      isShowState: true,
    };
  },
  mounted() {
    this.$nextTick(() => {
      var offsetHei = document.documentElement.clientHeight;
      //console.log(offsetHei);
      let boxH = this.$refs.box.offsetHeight;
      this.tableHeight = offsetHei - boxH - 57 - 79; //57为footer高度，79为页面上部标签高度
      //this.tableHeight = offsetHei -260
    });
  },
  created() {
    this.getList();
  },
  watch: {
    customerInfosZHB: {
      handler(newVal) {
				debugger
        console.log("柱护板-接收的父组件的值：" + JSON.stringify(newVal));
        if (newVal == "" || newVal == "undefined") {
          //TODO
        } else {
          newVal.forEach((element) => {
            this.customerInfo.printType = 2; //2时补打
            this.customerInfo.productLine = element.ProductLine;
			this.customerInfo.fwStation = element.fwStation;
          });
          if (this.customerInfo.productLine != "") {
            this.getList();
          }
        }
      },
      immediate: true,
    },
  },
  computed: {
    getDefaultField() {
      var tempsTabs = [];
      tempsTabs.push({ label: "大众顺序号", prop: "hostSN", width: 80 });
      tempsTabs.push({
        label: "底盘号",
        prop: "vin",
        width: 160,

      });
      tempsTabs.push({
        label: "KNR",
        prop: "knr",
        width: 100,

      });
      tempsTabs.push({
        label: "M100上线时间",
        prop: "onlineTime",
        width: 150,

      });
      tempsTabs.push({
        label: "M100接收时间",
        prop: "receiveTime",
        width: 150,

      });
      tempsTabs.push({
        label: "车型代码",
        prop: "vehicleModelCode",
        width: 100,

      });
      tempsTabs.push({
        label: "版本",
        prop: "version",
        width: 100,

      });

      tempsTabs.push({
        label: "产线",
        prop: "productLine",
        width: 80,

      });
      tempsTabs.push({
        label: "柱护板状态",
        prop: "printBillNum",
        width: 110,

      });

      tempsTabs.push({
        label: "备注",
        prop: "remark",
        width: 80,

      });
			tempsTabs.push({
			  label: "R100上线时间",
			  prop: "r100OnlineTime",
			  width: 150,
			
			});
			tempsTabs.push({
			  label: "R100接收时间",
			  prop: "r100ReceiveTime",
			  width: 150,
			
			});
      return tempsTabs;
    },


    ...mapGetters(["userInfo"]), //获取当前用户信息
  },
  methods: {
    //base64转化成流，dataurl是后台返回的base64
    dataURLtoBlob(dataurl) {
      var bstr = atob(dataurl.substring(dataurl.indexOf(",") + 1));
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: "application/pdf" });
    },
    doPrint(val) {
      var ordonnance = document.getElementById(val).contentWindow;
      setTimeout(() => {
        // window.print()
        ordonnance.print();
        this.pdfLoading = false;
      }, 100);
    },
    printpdf(dataResult) {
      //打印功能，dataResult是后台返回的base64
      let blob = this.dataURLtoBlob(dataResult);
      var date = new Date().getTime();
      var ifr = document.createElement("iframe");
      ifr.style.frameborder = "no";
      ifr.style.display = "none";
      ifr.style.pageBreakBefore = "always";
      ifr.setAttribute("id", "printPdf" + date);
      ifr.setAttribute("name", "printPdf" + date);
      ifr.src = window.URL.createObjectURL(blob);
      document.body.appendChild(ifr);
      this.doPrint("printPdf" + date);
      window.URL.revokeObjectURL(ifr.src); // 释放URL 对象
      this.dialogFormVisible = false;
    },
		
		/**
		 * DataGrid只展开当前行
		 * @param {Object} row
		 * @param {Object} rowList
		 */
    exChange(row, rowList) {
      //this.listLoading = true;

      var that = this;
      if (rowList.length) {
        that.expands = [];
        if (row) {
          that.expands.push(row.id); // 只展开当前行id
        }
      } else {
        that.expands = [];
      }
    },
		
    /**
		 * 取列表数据
		 * @param {Object} data
		 */
    getList(data) {
			//debugger
      this.listLoading = true;
			let inputParam = {};
      if (data != undefined) {
        inputParam.SkipCount = (this.page - 1) * data.limit;
      } else {
        inputParam.SkipCount = (this.page - 1) * 15;
      }
      inputParam.vinBegin = this.listQuery.beginVin;
      inputParam.vinEnd = this.listQuery.endVin;
      inputParam.hostSNBegin = this.listQuery.beginHostSN;
      inputParam.hostSNEnd = this.listQuery.endHostSN;
			
			if (this.listQuery.onlineTimeValue !== undefined) {
			  inputParam.onlineTimeBegin = this.listQuery.onlineTimeValue[0];
			  inputParam.onlineTimeEnd = this.listQuery.onlineTimeValue[1];
			}

      if (this.customerInfo.productLine != "") {
        inputParam.productLine = this.customerInfo.productLine;
      }
      if (this.customerInfo.fwStation != "") {
        inputParam.fwStation = this.customerInfo.fwStation;
      }

      console.log('取柱护板补打列表replenish-print-zhb-list方法输入参数：' + JSON.stringify(this.listQuery));
      this.$axios
        .gets(
          "/api/newjit/bill-m100/replenish-print-zhb-list",
          inputParam
        )
        .then((response) => {
          this.list = response.items;
          this.totalCount = response.totalCount;
          setTimeout(() => {
            //大数据量加载时
            this.listLoading = false;
          }, 500);
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    //补打-柱护板
    handleReplenishPrint() {
			debugger
      this.isEdit = true;
      if (this.multipleSelection == null || this.multipleSelection.length == 0) {
        this.$message({
          message: "请选择要补打的单据！",
          type: "warning",
        });
        return;
      } else {
        //补打方法
        let beginVin1 = this.multipleSelection[0].vin;
        let endVin1 = this.multipleSelection[this.multipleSelection.length -1].vin;
        var params = {
          printType: 2,
          productLine: this.customerInfo.productLine,
		  fwStation: this.customerInfo.fwStation,
          beginVin: beginVin1,
          endVin: endVin1,
					m100IdList: []
        };
				this.multipleSelection.forEach(itm => {
					params.m100IdList.push(itm.id);
				});
				
        console.log("柱护板补打输入参数：" + JSON.stringify(params));
       //  this.$axios
       //    .posts("/api/newjit/bill-m100/print-zhuhuban-packing-list", params)
       //    .then((response) => {

       //      if (response.status === false) {
       //        this.$message({
       //          message: response.message,
       //          type: "error",
       //        });
       //        return;
       //      } else if (response.status === true) {
       //        this.fileQuery.dataname = JSON.stringify(response.item);
							
       //        console.log(
       //          "柱护板-调用Handlers/Handler1.ashx?report=zhuhuban传的值：" +
       //            JSON.stringify(this.fileQuery.dataname)
       //        );
							
       //        this.$axios
       //          .posts(
       //            "/Handlers/Handler1.ashx?report=zhuhuban_" + this.customerInfo.productLine + '-' + this.customerInfo.fwStation,
       //            qs.stringify(this.fileQuery)
       //          )
       //          .then((response) => {
       //            this.printpdf(response); //打印我文件流
							// 		this.getList(); //刷新列表
       //          });
       //      }
       //    })
       //    .catch(() => {});
			 this.private_printZhuHuBan(params);
      }
    },

	/**
	 * 保存、加载、打印柱护板
	 */
	private_printZhuHuBan(input)
	{
		debugger
		//门板
		//传递大众顺序号起止
		let _this = this;
		this.$axios
		  .posts(
			"/api/newjit/bill-m100/save-zhuhuban-report",
			input
		  )
		  .then((response) => {
			console.log("保存柱护板报表");
			console.log(response);
			console.log(response.status);
			if (response.status === false) {
			  this.$message({
				message: response.message,
				type: "error",
			  });
			  return;
			} else if (response.status === true) {
				let loadInput = {};
				loadInput.dataResultType = "1"; //全部打印
				loadInput.reportIdList = response.item;
				
				// //--------------------------------------
				//门板
				//传递大众顺序号起止
				this.$axios
				  .posts(
					"/api/newjit/bill-m100/load-zhuhuban-report",
					loadInput
				  )
				  .then((response) => {
					console.log("加载柱护板报表");
					console.log(response);
					console.log(response.status);
					if (response.status === false) {
					  this.$message({
						message: response.message,
						type: "error",
					  });
					  return;
					} else if (response.status === true) {
							  //传给grid++接口json数据，得到返回的文件base64
							  //this.fileQuery.report = "menban";
							  this.fileQuery.dataname = JSON.stringify(
								response.item
							  );
								
							  //this.fileQuery.dataname = "";
							  console.log("打印json");
							  console.log(this.fileQuery.dataname);
							  this.$axios
								.posts(
								  //"/Handlers/Handler1.ashx?report=zhuhuban",
								  "/Handlers/Handler1.ashx?report=zhuhuban_" + _this.customerInfo.productLine + '-' + _this.customerInfo.fwStation,
								  qs.stringify(this.fileQuery)
								)
								.then((response) => {
								  console.log("获取文件base64编码");
								  console.log(response);
								  this.formLoading = false;
								  this.isDisable = false;
								  this.printpdf(response); //打印我文件流
								})
								.catch((error) => {
								  this.formLoading = false;
								  this.isDisable = false;
								});
					}
				  });
				//--------------------------------------
			}
		  });
	},
	

    /** 重置按钮操作 */
    resetQuery(refName) {
      this.$refs[refName].resetFields();
			this.listQuery.OnlineTimeValue = [];
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.listQuery.SkipCount = 1;
      //this.getList();
    },

    /** DataGrid格式化显示字段 */
    fieldFormatter(row, column) {
      if (column.property === "billStatus") {
        return { 1: "未匹配", 2: "未打印", 3: "已打印" }[row[column.property]];
      }
			if (column.property === "printBillNum") {
				
				if (row[column.property] != null && row[column.property].length > 0)
				{
					return "柱护板已打印"
				}
				else
				{
					return "柱护板未打印"
				}
			}	
			
      if (column.property == "printDate" || column.property == "receiveTime") {
        var date = row[column.property];
        if (date == undefined) {
          return "";
        }
        return moment(date).format("YYYY-MM-DD HH:mm:ss");
      }
      return row[column.property] || "--";
    },

    /**
		 * 搜索按钮单击事件
		 */
    handleFilter() {
      this.page = 1;
      this.getList();
    },

		/**
		 * DataGrid列排序事件（未使用）
		 * @param {Object} data
		 */
    sortChange(data) {
      const { prop, order } = data;
      if (!prop || !order) {
        this.handleFilter();
        return;
      }
      this.listQuery.Sorting = prop + " " + order;
      this.handleFilter();
    },
		
		/**
		 * DataGrid多选触发事件
		 * @param {Object} val
		 */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /** 
		 * DataGrid通过回调控制style 
		 */
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property === "qty") {
        return { textAlign: "right" };
      } else {
        return { textAlign: "left" };
      }
    },
    /** DataGrid通过回调控制表头style */
    headerRowStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property === "qty") {
        return { textAlign: "right", background: "#FAFAFA" };
      } else {
        return { textAlign: "left", background: "#FAFAFA" };
      }
    },
		
		/**
		 * DataGrid行单击事件
		 * @param {Object} row
		 * @param {Object} column
		 * @param {Object} event
		 */
    handleRowClick(row, column, event) {
      //this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row);
    },

    closeDialog() {},
  },
};
</script>



<style lang="scss" scoped>
@import "../../../pg-fis/styles/crmtable.scss";
.divider1 {
  margin: 0;
}
.divider2 {
  margin: 10px;
  margin-bottom: 20px;
  width: 95%;
}
.label1 {
  margin-left: 5px;
  margin-right: 5px;
}
</style>


