<template>
  <!-- 万州港-达州新增装车1 -->
  <div class="addWagonLoad">
    <page-title>返回</page-title>
    <div class="tempTable">
      <div class="search" style="display:flex;margin: 10px;">
        <el-input
          placeholder="请输入车皮号或外轮船名"
          v-model="input"
          style="margin: 10px; width:38%"
          clearable
        ></el-input>
        <el-button
          type="primary"
          class="btn"
          @click="findWagon()"
          style="margin: 10px;"
        >
          <i class="el-icon-search"></i>查询
        </el-button>
         <el-upload style="margin: 10px;"
          class="upload-excel"
          action=""
          :on-change="importExcel"
          :show-file-list="false"
          accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :auto-upload="false">
          <el-button  type="primary">
            <i class="el-icon-search"></i>导入查询</el-button>
            <span >查询结果数量：{{tableDataReal.length}}</span>
      </el-upload>
      </div>
      <!-- 临时表已导入配单的车皮 -->
      <div class="tempTable" style="height:300px;overflow:scroll;float:left;margin-left:5px">
        <el-table
          ref="tempTable"
          empty-text="请先查询，再查看数据"
          highlight-current-row
          @selection-change="handleSelectionChange"
          @row-click="rowClick"
          :data="tableDataReal"
          :row-style="{height:'40px'}"
          style="width: 100%;font-size: 18px"
          id="domesticTable">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
          type="index"
          width="50"
          prop="tempResultId"
          label="编号"
          align="center"
          fixed="left"
          :resizable="false">
          </el-table-column>
          <el-table-column
          align="center"
            prop="materialName"
            label="物资名"
            width="240px">
          </el-table-column>
          <el-table-column
          align="center"
            prop="foreignShipName"
            label="外轮船名"
            width="100px">
          </el-table-column>
          <el-table-column
          align="center"
            prop="wagonNo"
            label="车号"
            width="180px">
          </el-table-column>
          <el-table-column
          align="center"
          width="100px"
            prop="resultBillableTonnage"
            label="标重">
          </el-table-column>
          <el-table-column
          align="center"
            prop="updateTime"
            label="出库时间"
            width="200px">
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="right" 
    style="margin-top:10px
           float:right;">
        <div class="form">
          <div class="form_box" style="">
            <el-form>
               <div class="preview-group">
                  <el-form-item label="发站:">
                    <el-autocomplete
                      disabled
                      class="inline-input"
                      v-model="sendStation"
                      :fetch-suggestions="querySearchSendStation"
                      placeholder="请输入发站名称"
                      :trigger-on-focus="false"
                      @select="handleSelectSendStation"
                    >
                      <template slot-scope="{ item }">
                        <div class="name">{{ item.arrivalName }}</div>
                      </template>
                    </el-autocomplete>
                  </el-form-item>
                  <el-form-item label="到站:">
                    <el-select filterable  v-model="arrivalStationId">
                        <el-option v-for="item in arrivalStations" :value="item.arrivalId" :key="item.arrivalId" :label="item.arrivalName"></el-option>
                    </el-select>
                  </el-form-item>
               </div>
          </el-form>
            <dil-form :formId="387" v-model="form1" ref="from1"></dil-form>
          </div>
        </div>
        <div class="button-box">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" :loading="isLoading" :disabled="!isSend" @click="makeSure">确定</el-button>
        </div>
    </div>
  </div>
</template>

<script>
import PageTitle from "@/components/Page/Title";
import { sjTime } from "@/utils/sharedJsFile";
import {getCookie} from "@/utils/util.js";
export default {
  components: { PageTitle },
  data() {
    return {
      isSend:false,
      isLoading:false,
      list: [],
      form1: {
        resultLoadingDate:new Date()
      },
      tableData:[],
      tableDataReal:[],
      selectionRow:[],
      input: "",
      value: undefined,
      //船名
      remark: null,
      //采购订单id
      purchaseOrderId: null,
      //物资名称
      materialName: null,
      //发货单位名称
      supplierName: null,
      //发货单位id
      supplierId: null,
      //物资id
      materialId: null,
      //是否需要打开模态窗口
      drawer: false,
      //卸货点id
      unloadPointId: null,
      //卸货点名称
      unloadPointName: null,
      //查询
      search1:null,
      search2:null,
      a: 1,
      direction: "rtl",
      inputText: "",
      sendStationId: 4,//发站id和到站id都写死了，并且赋了港口名，如果数据库id变化，要注意
      sendStation:"万州港",
      arrivalStationId:1,
      arrivalStations:[]
    };
  },
  mounted(){
    this.form1.resultLoadingDate=new Date();
    this.getArrivalStation();
    this.searchLoadTemp();
  },
  methods: {
    findWagon(){
      this.tableDataReal=[];
      this.isSend=true;
      this.tableData.forEach((item)=>{
        if(item.foreignShipName.includes(this.input) || item.wagonNo.includes(this.input)){
          this.tableDataReal.push(item);
        }
      });
      if(this.tableDataReal.length<=0){
        this.$message.warning("查询不到记录!");
      }
      console.log("serachResult:",this.tableDataReal);
    },
    //发站弹出层
    handleSelectSendStation(item) {
      this.sendStationId = item.arrivalId;
      this.sendStation = item.arrivalName;
    },
    //以下是发站边输边查搜索
    querySearchSendStation(queryString, cb) {
      this.axios
        .get("/api/v1/uc/getArrivalByLike?index=" + this.sendStation)
        .then((res) => {
          if (res.data.code == "200") {
            var restaurantsSupplier = res.data.data;
            console.log(restaurantsSupplier)
            var results = queryString
              ? restaurantsSupplier.filter(
                  this.createFilterSendStation(queryString)
                )
              : restaurantsSupplier;
            // 调用 callback 返回建议列表的数据
            cb(results);
          }
        });
    },
    //发站
    createFilterSendStation(queryString) {
      return (restaurantsSupplier) => {
        return (
          restaurantsSupplier.arrivalName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) > -1
        );
      };
    },
    //到站弹出层
    handleSelectToTheStation(item) {
      this.toTheStationId = item.arrivalId;
      this.toTheStation = item.arrivalName;
    },
    //以下是到站边输边查搜索
    querySearchToTheStation(queryString, cb) {
      this.axios
        .get("/api/v1/uc/getArrivalByLike?index=" + this.toTheStation)
        .then((res) => {
          if (res.data.code == "200") {
            var restaurantsSupplier = res.data.data;
            console.log(restaurantsSupplier)
            var results = queryString
              ? restaurantsSupplier.filter(
                  this.createFilterToTheStation(queryString)
                )
              : restaurantsSupplier;
            // 调用 callback 返回建议列表的数据
            cb(results);
          }
        });
    },
    //到站
    createFilterToTheStation(queryString) {
      return (restaurantsSupplier) => {
        return (
          restaurantsSupplier.arrivalName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) > -1
        );
      };
    },
    // 确定
    makeSure() {
      this.isLoading=true;
      if (this.selectionRow.length <= 0  || 
          !this.sendStationId ||
          !this.arrivalStationId ||
          !this.form1.resultLoadingDate){
        if (this.selectionRow.length <= 0) {
          this.$message({
            type: "warning",
            message: "请选择车皮号！",
          });
          this.isLoading=false;
           return;
        }else{
          this.$message({
            type: "warning",
            message: "除备注外皆为必填！",
          });
          this.isLoading=false;
          return;
        }
      }
      let date=this.form1.resultLoadingDate;
      let month=(date.getMonth()+1);
      let day=date.getDate();
      if(month>=1 && month <=9){
        month="0"+month;
      }
      if(day>=1 && day<=9){
        day="0"+day;
      }
      let dateStr=date.getFullYear()+"年"+month+"月"+day+"日";
      this.selectionRow.forEach((item)=>{
        if(!item.sendDate || !item.arrivalDate){
          item.sendDate=dateStr;
          item.arrivalDate=dateStr;
        }
      });
      let map = {
        wagonList:this.selectionRow,
        sendStationId: this.sendStationId,
        arrivalStationId: this.arrivalStationId,
        resultLoadingDate: sjTime(this.form1.resultLoadingDate),
        remarks: this.form1.resultRemarks,
        userId:getCookie("userId"),
        resultType:1,
      }
      console.log(map);
      this.axios.post('/api/v1/tms/addShipLoadResult',map).then((res)=>{
        console.log(res);
        if(res.data.code == "200"){
          this.$message({
            type: "success",
            message: "操作成功",
          });
          this.searchLoadTemp();
        }else {
          this.$message({
              type: "error", 
              message: res.data.data,
          });
        }
      }).then(()=>{
        this.isLoading=false;
      });
    },
    // 取消
    cancel() {
      this.$router.go(-1);
    },
    // 导入excel
    importExcel(file) {
      let that=this;
      if (!file) {
        that.$message({
          message: "文件错误!",
          type: "warning",
        });
        return
      }
      let importData=[];
      var reader = new FileReader();
      var data=null;
      var workbook=null;
      //设置读取操作
      reader.onload = function (e) {
        console.log(e);
        data = e.target.result;
        workbook= XLSX.read(data, {
            type: 'binary'
        });
        console.log(workbook);
        let rows= XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);//只取第一页
        let index=1;
        for(index=1;index<rows.length;index++){
          if(typeof workbook.Sheets[workbook.SheetNames[0]]['A'+index] !='undefined'){
            index++;
            break;
           }
        }
        console.log('表头行数:'+index);
        if(index>=rows.length){
          that.$message({
            message: "文件错误!",
            type: "warning",
          });
          return
        }
        //校验表头
        if( workbook.Sheets[workbook.SheetNames[0]]['A'+index].v!='序号'
        || workbook.Sheets[workbook.SheetNames[0]]['B'+index].v!='发站'
        || workbook.Sheets[workbook.SheetNames[0]]['C'+index].v!='到站'
        || workbook.Sheets[workbook.SheetNames[0]]['D'+index].v!='发货日期'
        || workbook.Sheets[workbook.SheetNames[0]]['E'+index].v!='到货日期'
        || workbook.Sheets[workbook.SheetNames[0]]['F'+index].v!='卸货地点'
        || workbook.Sheets[workbook.SheetNames[0]]['G'+index].v!='品名'
        || (workbook.Sheets[workbook.SheetNames[0]]['I'+index].v!='计费\n吨位'
        && workbook.Sheets[workbook.SheetNames[0]]['I'+index].v!='计费吨位'
        && workbook.Sheets[workbook.SheetNames[0]]['I'+index].v!='计费&#10;吨位')
        || workbook.Sheets[workbook.SheetNames[0]]['J'+index].v!='车号'
        || workbook.Sheets[workbook.SheetNames[0]]['K'+index].v!='计量吨位'
        || workbook.Sheets[workbook.SheetNames[0]]['L'+index].v!='计费吨位合计'){
          if(workbook.Sheets[workbook.SheetNames[0]]['A'+index].v!='序号'){
             that.$message({
                message: "表格格式错误:序号错误",
                type: "warning",
            });
          }else if(workbook.Sheets[workbook.SheetNames[0]]['B'+index].v!='发站'){
             that.$message({
                message: "表格格式错误:发站错误",
                type: "warning",
            });
          }else if(workbook.Sheets[workbook.SheetNames[0]]['C'+index].v!='到站'){
             that.$message({
                message: "表格格式错误:到站错误",
                type: "warning",
            });
          }else if(workbook.Sheets[workbook.SheetNames[0]]['D'+index].v!='发货日期'){
             that.$message({
                message: "表格格式错误:发货日期错误",
                type: "warning",
            });
          }else if(workbook.Sheets[workbook.SheetNames[0]]['E'+index].v!='到货日期'){
             that.$message({
                message: "表格格式错误:到货日期错误",
                type: "warning",
            });
          }else if(workbook.Sheets[workbook.SheetNames[0]]['F'+index].v!='卸货地点'){
             that.$message({
                message: "表格格式错误:卸货地点错误",
                type: "warning",
            });
          }else if(workbook.Sheets[workbook.SheetNames[0]]['G'+index].v!='品名'){
             that.$message({
                message: "表格格式错误:品名错误",
                type: "warning",
            });
          }else if(workbook.Sheets[workbook.SheetNames[0]]['I'+index].v!='计费\n吨位' 
          && workbook.Sheets[workbook.SheetNames[0]]['I'+index].v!='计费吨位'
          && workbook.Sheets[workbook.SheetNames[0]]['I'+index].v!='计费&#10;吨位'){
             that.$message({
                message: "表格格式错误:计费吨位错误",
                type: "warning",
            });
          }else if(workbook.Sheets[workbook.SheetNames[0]]['J'+index].v!='车号'){
             that.$message({
                message: "表格格式错误:车号错误",
                type: "warning",
            });
          }else if(workbook.Sheets[workbook.SheetNames[0]]['K'+index].v!='计量吨位'){
             that.$message({
                message: "表格格式错误:计量吨位错误",
                type: "warning",
            });
          }else if(workbook.Sheets[workbook.SheetNames[0]]['L'+index].v!='计费吨位合计'){
             that.$message({
                message: "表格格式错误:计费吨位合计错误",
                type: "warning",
            });
          }
          return;
        }
        let groupNo=1;
        let isLoading=true;
        //读取表格
        for(let i=index+1;i<=rows.length+1;i++){
          let row=workbook.Sheets[workbook.SheetNames[0]]['A'+i];
          if(row && typeof row.v == "number" && isLoading==false){
            isLoading=true;
            groupNo++;
          }else if(!row || typeof row.v != "number" && isLoading==true){
            isLoading=false;
          }
          if(row!='undefined' && row!=null && typeof row.v=='number' 
              && workbook.Sheets[workbook.SheetNames[0]]['B'+i]!='undefined'
            && workbook.Sheets[workbook.SheetNames[0]]['B'+i]!=null
              && workbook.Sheets[workbook.SheetNames[0]]['C'+i]!='undefined'
            && workbook.Sheets[workbook.SheetNames[0]]['C'+i]!=null
              && workbook.Sheets[workbook.SheetNames[0]]['D'+i]!='undefined'
            && workbook.Sheets[workbook.SheetNames[0]]['D'+i]!=null
              && workbook.Sheets[workbook.SheetNames[0]]['E'+i]!='undefined'
            && workbook.Sheets[workbook.SheetNames[0]]['E'+i]!=null
              && workbook.Sheets[workbook.SheetNames[0]]['F'+i]!='undefined'
            && workbook.Sheets[workbook.SheetNames[0]]['F'+i]!=null
              && workbook.Sheets[workbook.SheetNames[0]]['G'+i]!='undefined'
            && workbook.Sheets[workbook.SheetNames[0]]['G'+i]!=null
              && workbook.Sheets[workbook.SheetNames[0]]['J'+i]!='undefined'
            && workbook.Sheets[workbook.SheetNames[0]]['J'+i]!=null){
            let tableRow={
              sendStation:workbook.Sheets[workbook.SheetNames[0]]['B'+i].v,
              arrivalStation:workbook.Sheets[workbook.SheetNames[0]]['C'+i].v,
              sendDate: that.formatDate(workbook.Sheets[workbook.SheetNames[0]]["D" + i].v),
              arrivalDate: that.formatDate(workbook.Sheets[workbook.SheetNames[0]]["E" + i].v),
              unloadPoint:workbook.Sheets[workbook.SheetNames[0]]['F'+i].v,
              productName:workbook.Sheets[workbook.SheetNames[0]]['G'+i].v,
              wagonNo:workbook.Sheets[workbook.SheetNames[0]]['J'+i].v,
              weight:workbook.Sheets[workbook.SheetNames[0]]['I'+i].v,
              mineral:workbook.Sheets[workbook.SheetNames[0]]['H'+i].v,
              groupNo:groupNo
            }
            if((tableRow.wagonNo+"").length!=7){
              that.$message({
                message: "存在车皮号长度不等于7:"+tableRow.wagonNo,
                type: "warning",
              });
              continue;
            }
            importData.push(tableRow);
          }
        }
        console.log("importData",importData);
        if(importData.length<=0){
          that.$message({
            message:"Excel没有可用数据",
            type:"warning"
          });
          return;
        }else if(that.tableData.length<=0){
          that.$message({
            message:"数据库没有可用数据",
            type:"warning "
          })
          return;
        }
        //批量查询
        let tableData=[];
        importData.forEach((row)=>{
          let temp=that.tableData.find(item=>item.wagonNo==row.wagonNo 
          && row.productName.includes(item.foreignShipName));
          if(temp){
            temp.sendDate=row.sendDate;
            temp.arrivalDate=row.arrivalDate;
            temp.groupNo=row.groupNo;

            tableData.push(temp);
          }
        });
        that.tableDataReal=tableData;
        if(tableData.length<=0){
          that.$confirm('查询不到相关车皮!可能是没有出库，请联系万州港相关人员!')
          .then(_ => {
            that.isSend=false;
            done();
          });
        }else if(tableData.length<importData.length){
           that.$confirm("共"+(importData.length-tableData.length)+"条车皮查询失败!可能是没有出库，请联系万州港相关人员!")
          .then(_ => {
            that.isSend=false;
            done();
          });
        }else{
          that.isSend=true;
          that.$message({
            message: "查询成功!",
            type: "success",
          });
        }
      };
      reader.readAsBinaryString(file.raw); //以二进制方式读取
    },
    //采购订单表格选中
    orderChange(selection){
      console.log(selection);
      this.purchaseOrderId=selection.purchaseOrderId;
      this.form1 = { 
        purchaseOrderNo: selection.purchaseOrderNo,
        resultLoadingDate:new Date() 
        };
      this.materialId=selection.materialId;
      this.materialName=selection.materialName;
      this.supplierId=selection.supplierId;
      this.supplierName=selection.supplierName;
    },
    //查询临时表
    searchLoadTemp(){
      this.tableDataReal=[];
      this.axios.post('/api/v1/tms/getResultType?apiId=58&resultType=1&con='+this.input).then((res)=>{
        console.log("temp:",res.data.data);
        if(res.data.code == "200"){
          this.tableData=res.data.data;
        }else {
          this.$message({
              type: "error", 
              message: res.data.data,
          });
        }
      })
    },
    //查询到站
    getArrivalStation(){
      this.axios.get("/api/v1/uc/getArrivalByLike?index="+this.input).then((res)=>{
        if(res.data.code == "200"){
          this.arrivalStations=res.data.data;
        }else {
          this.$message({
              type: "error", 
              message: res.data.data,
          });
        }
        console.log("到站列表：",this.arrivalStations);
      })
    },
    //点击行勾选
    rowClick(row, column, event) {
       let tempTable = this.$refs.tempTable; // 获取表格对象
       //判断是否已存在
       let findRow = this.selectionRow.find(item => item.wagonNo == row.wagonNo);
       if (findRow) {
          tempTable.toggleRowSelection(row, false);
       }else{
          tempTable.toggleRowSelection(row);
       }
       //赋值
       this.selectionRow=this.$refs.tempTable.selection;
    },
    handleSelectionChange(rows) {
      this.selectionRow = rows //保存已选择行
      console.log(this.selectionRow);
    },
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + '年' + (month < 10 ? '0' + month : month)+ '月' + (date < 10 ? '0' + date : date) + '日'
    },
  },
};
</script>
<style lang='scss'>
.addWagonLoad {
  color: #606266;
  font-size: 0.675rem;
  font-weight: 500;
  .cp {
    width: 49%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding-top: 0.625rem;
    padding-bottom: 0.625rem;
    margin-left: 364px;
    .cp_title {
      .cp_top {
        width: 3.125rem;
        padding-right: 1.55rem;
      }
    }
  }
  .cpList {
    display: flex;
    justify-content: center;
    width: 100%;
    height: 10rem;
    .list {
      width: 45%;
      border: #000 0.0625rem solid;
      padding: 0.625rem;
      display: flex;
      flex-wrap: wrap;
      .cpList1 {
        background-color: #c9c7c7;
        height: 1.875rem;
        margin-right: 0.5rem;
        padding: 0.625rem;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        .itu {
          position: absolute;
          top: -0.125rem;
          right: 0.0625rem;
          width: 0.625rem;
          height: 0.625rem;
        }
      }
    }
  }
  .matching {
    width: 100%;
    height: 3.125rem;
    display: flex;
    justify-content: center;
    align-items: center;
    .text {
      width: 8.75rem;
    }
    .span {
      display: inline-block;
      width: 310px;
      height: 0.0625rem;
    }
  }
  .material {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 3.75rem;
    margin-left: 27rem;
    width: 20rem;
    .text {
      text-align: right;
      width: 8.125rem;
    }
  }
  .forwardingUnit {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 3.75rem;
    margin-left: 27rem;
    width: 20rem;
    .text {
      text-align: right;
      width: 8.125rem;
    }
  }
  .remark {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 3.75rem;
    .text {
      text-align: right;
      width: 5.625rem;
    }
    .span {
      display: inline-block;
      width: 1.875rem;
      height: 1.25rem;
    }
    .el-input{
      width: 13.5rem;
      margin-right: 2.375rem;
    }
  }
  .purchaseOrder {
    display: flex;
    justify-content: center;
    align-items: center;
    .span {
      display: inline-block;
      width: 1.875rem;
      height: 0.0625rem;
    }
  }
  .form {
   display: flex;
    .form_box {
      width: 340px;
      margin-left: 30px;
      margin-right: 20px;
      .el-form {
        .preview-group {
          .el-form-item {
            .el-form-item__label {
              display: inline-block;
              width: 70px !important;
            }
            .el-form-item__content {
              .el-select {
                width: 250px;
              }
              .el-input {
                width: 250px;
              }
              .el-textarea{
                .el-textarea__inner{
                  width: 225px;     
                  margin-top: 0.03rem;
                }
              }
            }
          }
        }
      }
    }
  }
  .button-box {
    display: flex;
    justify-content: center;
    padding-top: 10px;
  }
  .formOther  .el-input__inner{
    width: 250px;
  }
}
</style>

