<template>
  <!-- 添加车皮装车实绩 -->
  <div class="addWagonLoad">
    <page-title>返回</page-title>
    <div class="cp">
      <span >车皮号:</span>
      <el-upload style="margin: 8px;"
          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">导入</el-button>
      </el-upload>
      <span >当前导入数量：{{tableData.length}}</span>
    </div>
    <div class="table item">
      <el-table
        stripe
        :data="tableData"
        style="width: 100%">
        <el-table-column
        type="index"
        width="50"
        prop="number"
        label="序号"
        align="center"
        fixed="left"
        :resizable="false">
        </el-table-column>
        <el-table-column
        align="center"
          prop="materialName"
          label="物资"
          width="180px">
        </el-table-column>
        <el-table-column
        align="center"
          prop="supplierName"
          label="发货单位"
          width="180px">
        </el-table-column>
        <el-table-column
        align="center"
          prop="wagonNo"
          label="车号"
          width="180px">
        </el-table-column>
        <el-table-column
        align="center"
          prop="sendDate"
          label="发货日期"
          width="180px">
        </el-table-column>
        <el-table-column
        align="center"
          prop="sendStation"
          label="火车发站"
          width="180px">
        </el-table-column>
        <el-table-column
        align="center"
        width="180px"
          prop="arrivalStation"
          label="火车到站">
        </el-table-column>
         <el-table-column
         align="center"
        width="180px"
          prop="weight"
          label="标重">
        </el-table-column>
        <!-- <el-table-column
        align="center"
        width="100px"
          fixed="right"
          label="操作">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
            <el-button type="text" size="small">编辑</el-button>
          </template>
        </el-table-column> -->
      </el-table>
    </div>
    <!-- <div class="matching item">
          <span class="text">是否知道采购订单号:</span>
          <el-switch
            v-model="matching"
            active-color="#27d452"
            inactive-color="#e1e3e6"
          >
          </el-switch>
    </div>
    <div class="material item">
      <span class="text">物资：</span>
      <el-input v-model="materialName" disabled> </el-input>
      <el-button type="primary" @click="ondrawer(1)">浏览</el-button>
    </div>

    <div class="forwardingUnit item">
      <span class="text">发货单位：</span>
      <el-input v-model="supplierName" disabled> </el-input>
      <el-button type="primary" @click="ondrawer(2)">浏览</el-button>
    </div>
    <div class="forwardingUnit item" v-if="matching">
      <span class="text">卸货点：</span>
      <el-input v-model="unloadPointName" disabled> </el-input>
      <el-button type="primary" @click="ondrawer(3)">浏览</el-button>
    </div> -->
    <div class="fromOther">
      <!-- <el-form :inline="true" class="demo-form-inline" label-width="80px" style="margin-left:500px;">
        <el-form-item label="发站:">
          <el-autocomplete
            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> -->
      
    </div>
    <!-- <div class="remark from" v-if="matching">
      <span class="text">船名/备注：</span>
      <el-input
        v-model="remark"
        @blur="onBlur"
        placeholder="可输入船名\备注重新匹配采购订单"
      >
      </el-input>
      <span class="span"></span>
    </div>
    <div class="purchaseOrder from" v-if="matching" >
      <span class="text" style="width:140px">采购订单号：</span>
      <el-input
        v-model="purchaseOrderNo"
        placeholder="请选择物资和发货单位"
        disabled
      >
      </el-input>
      <span class="span"></span>
    </div> -->
    <div class="form">
      <div class="form_box" style="margin-right: 10rem;margin-top:20px">
        <el-form>
          <div class="preview-group">
              <el-form-item label="到站:">
                <el-autocomplete
                  class="inline-input"
                  v-model="toTheStation"
                  :fetch-suggestions="querySearchToTheStation"
                  placeholder="请输入到站名称"
                  :trigger-on-focus="false"
                  @select="handleSelectToTheStation"
                >
                  <template slot-scope="{ item }">
                    <div class="name">{{ item.arrivalName }}</div>
                  </template>
                </el-autocomplete>
              </el-form-item>
          </div>
        </el-form>
        <dil-form :formId="364" v-model="form1" ref="from1"></dil-form>
      </div>
    </div>

    <div class="button_box">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" :disabled="disable"  @click="makeSure">确定</el-button>
    </div>
    <!-- 模态窗口 -->
    <el-drawer :visible.sync="drawer" :direction="direction" size="30%">
      <el-input
        placeholder="请输入内容"
        v-model="inputText"
        style="margin-top: 0rem; margin-right: 0.1rem; width: 230px"
        clearable
      ></el-input>
      <el-button
        type="primary"
        class="btn"
        @click="onClick(a)"
        style="margin-bottom: 0.9375rem"
      >
        <i class="el-icon-search"></i>查询
      </el-button>
      <div v-show="a == 1">
        <dilTable
          v-bind.sync="frist"
          @radio-change="currentRadioChange1"
        ></dilTable>
      </div>
      <div v-show="a == 2">
        <dilTable
          v-bind.sync="secend"
          @radio-change="currentRadioChange2"
        ></dilTable>
      </div>
       <div v-show="a == 3">
        <dilTable
          v-bind.sync="unloadPoint"
          @radio-change="currentRadioChange3"
        ></dilTable>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import PageTitle from "@/components/Page/Title";
import { sjTime, isNumber } from "@/utils/sharedJsFile";
export default {
  components: { PageTitle },
  data() {
    return {
      disable:true,
      file:null,
      list: [],
      form1: {},
      input: "",
      //是否匹配采购订单号
      matching: false,
      value: undefined,
      //船名
      remark: null,
      //采购订单id
      purchaseOrderId: null,
      //采购订单号
      purchaseOrderNo: null,
      //物资名称
      materialName: null,
      //发货单位名称
      supplierName: null,
      //发货单位id
      supplierId: null,
      //物资id
      materialId: null,
      //表格数据
      tableData:[],
      unloadPointName:null,
      //物资集合和供应商映射，相当于本地缓存，减少请求次数
      materialMap:new Map(),
      supplierMap:new Map(),
      materials:[],
      suppliers:[],
      unloadPointId:null,
      //是否需要打开模态窗口
      drawer: false,
      a: 1,
      direction: "rtl",
      inputText: "",
      frist: {
        requestUrl: "/api/v1/uc/queryAPOMaterialByLike?apiId=244&startNum=050",
        selectionType: "radio",
        mapList1: [],
      },
      secend: {
        requestUrl:
          "/api/v1/uc/getSupplierMesByMaterialId?apiId=247&materialId=",
        selectionType: "radio",
        mapList2: [],
      },
      unloadPoint: {
        requestUrl: "/api/v1/uc/getUnloadingMesByLike?apiId=374",
        selectionType: "radio",
      },
      sendStationId:null,
      toTheStationId:1,
      sendStation:null,
      toTheStation:"老区轨道衡"
    };
  },
  watch: {
    matching(val) {
      if (val) {
        this.getPurchaseOrderNo();
      }
    },
  },
  created() {
    this.form1 = {
      arrivalStationId: 1,
    };
  },
  mounted(){
    this.form1.resultLoadingDate=new Date();
  },
  methods: {
    currentRadioChange1(selection) {
      this.input = null;
      this.materialName = selection.materialName;
      this.materialId = selection.materialId;
      if (this.matching) {
        this.getPurchaseOrderNo();
      }
    },
    currentRadioChange2(selection) {
      this.supplierName = selection.supplierName;
      this.supplierId = selection.supplierId;
      if (this.matching) {
        this.getPurchaseOrderNo();
      }
    },
    currentRadioChange3(selection) {
      this.unloadPointId = selection.warehouseId;
      this.unloadPointName = selection.warehouseName;
    },
    ondrawer(num) {
      this.drawer = true;
      this.a = num;
      if (num == 2) {
        this.secend.requestUrl =
          "/api/v1/uc/getSupplierMesByMaterialId?apiId=247&materialId=" +
          this.materialId;
      }
    },
    onBlur() {
      if (this.matching) {
        this.getPurchaseOrderNo();
      }
    },
    getPurchaseOrderNo() {
      console.log(this.matching);
      let map = {
        materialId: this.materialId,
        supplierId: this.supplierId,
      };
      if (this.remark) {
        map.remark = this.remark;
      }
      console.log(this.map);
      if (this.materialId && this.supplierId) {
        this.axios.post("/api/v1/oms/selectNewOrderId", map).then((res) => {
          console.log(res);
          if (res.data.code == "200") {
            if (res.data.data == null) {
              this.$message({
                message: "没有匹配的采购订单号!",
                type: "warning",
              });
              this.form1 = [];
            } else {
              this.remark = res.data.data.remark;
              this.purchaseOrderId = res.data.data.purchaseOrderId;
              this.purchaseOrderNo = res.data.data.purchaseOrderNo;
            }
          } else {
            this.$message.error("请求失败");
          }
        });
      }
    },
    //发站弹出层
    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
        );
      };
    },
    onClick(a) {
      if (a == 1) {
        this.frist.requestUrl =
          "/api/v1/uc/queryAPOMaterialByLike?apiId=244&startNum=050&index=" +
          this.inputText;
      } else if (a == 2) {
        this.secend.requestUrl =
          "/api/v1/uc/getSupplierMesByMaterialId?apiId=247&materialId=" +
          this.materialId +
          "&index=" +
          this.inputText;
      } else if (a == 3) {
        this.unloadPoint.requestUrl =
          "/api/v1/uc/getUnloadingMesByLike?apiId=374&index=" + this.inputText;
      }
    },
    onchang() {
      var state = false;
      var cptop = this.input.substring(0, 2);
      var cptop1 = this.input.substring(0, 3);
      if (
        cptop == "45" ||
        cptop == "46" ||
        cptop == "42" ||
        cptop == "47" ||
        cptop == "15" ||
        cptop == "16" ||
        cptop == "17" ||
        cptop == "18"
      ) {
        state = true;
      } else if (
        cptop1 == "140" ||
        cptop1 == "141" ||
        cptop1 == "142" ||
        cptop1 == "143" ||
        cptop1 == "145"
      ) {
        state = true;
      } else {
        this.$message({
          type: "warning",
          message: "车皮号格式不对，请重新输入！",
        });
      }
      if (state) {
        if (this.input.length == 7) {
          this.list.push(this.input);
          this.input = "";
        } else if (this.input.length < 7) {
          this.$message({
            type: "warning",
            message: "车皮号长度不足7位数，请重新输入！",
          });
        } else if (this.input.length > 7) {
          this.$message({
            type: "warning",
            message: "车皮号长度超过7位数，请重新输入！",
          });
        }
      }
    },
    onclick(index) {
      this.list.splice(index, 1);
    },
    // 确定
    makeSure() {
      this.disable=true;
      let that=this;
      if (this.tableData.length <= 0  || !this.toTheStationId || this.form1.resultLoadingDate){
        if (this.tableData.length <= 0) {
          this.$message({
            type: "warning",
            message: "请导入数据！",
          });
        } else {
            this.disable=false;
            if (this.toTheStationId) {
              if (this.form1.resultLoadingDate) {
              } else {
                this.$message({
                  type: "warning",
                  message: "请选择装车时间！",
                });
              }
            } else {
              this.$message({
                type: "warning",
                message: "请选择到站！",
              });
            }
        }
      }
      //绑定通用字段
      this.tableData.forEach((row)=>{
        row.resultType=3;//装车类型为国产矿
        row.arrivalStationId=that.form1.arrivalStationId;//到站id,默认老区轨道衡
        row.resultLoadingDate=sjTime(that.form1.resultLoadingDate);//装车日期
        row.resultRemarks=that.form1.resultRemarks;//备注
      })
      console.log(that.tableData);
      //请求添加
      this.axios
        .post("/api/v1/tms/addDomesticLoadResult", that.tableData)
        .then((res) => {
          console.log(res);
          if (res.data.code == "200") {
            this.$message({
              type: "success",
              message: "新增成功",
            });
            this.$router.push("/wagonLoadMine");
          }
        });
      
    },
    cancel() {
      this.$router.push("/wagonLoadMine");
    },
    // 导入excel
    importExcel(file) {
      let that=this;
      if (!file) {
        that.$message({
          message: "文件错误!",
          type: "warning",
        });
        return
        }
        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]]);//只取第一页
          console.log(rows);
          //清空
          if(rows.length>0){
            that.disable=false;
            that.tableData=[];
            if((typeof rows[0]['车号'])=='undefined'){
              that.$message({
                message: "导入Excel格式错误!",
                type: "warning",
              });
              return;
            }
          }
          //绑定数据
          rows.forEach((row,index) => {
            let carNumber=row['车号'];
            if((typeof carNumber)!="undefined" && carNumber.length == 7){
              //表格数据
              let temp={
                number:row['序号'],
                materialName:row['品  名'],
                supplierName:row['发货单位'],
                sendDate:row['发货日期'],
                sendStation:row['发站'],
                arrivalStation:row['到站'],
                wagonNo:row['车号'],
                weight:row['标重']
              }
              that.tableData.push(temp);
            }
            else{
              console.log("车号"+carNumber+"不是7位数!");
            }
        });
        };
        reader.readAsBinaryString(file.raw); //以二进制方式读取
    }
  },
};
</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;
      overflow:auto;
      .cpList1 {
        background-color: #c9c7c7;
        height: 1.875rem;
        margin: 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: 20rem;
    height: 3.125rem;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 24rem;
    .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: 24rem;
    width: 20rem;
    .text {
      text-align: right;
      width: 8.125rem;
    }
  }
  .forwardingUnit {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 3.75rem;
    margin-left: 24rem;
    width: 20rem;
    .text {
      text-align: right;
      width: 8.125rem;
    }
  }
  .remark {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 3.75rem;
    margin-left: 24rem;
    width: 22rem;
    .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;
    margin-left: 24rem;
    width: 22rem;
    margin-bottom: 15px;
    .span {
      display: inline-block;
      width: 1.875rem;
      height: 0.0625rem;
    }
  }
  .form {
    display: flex;
    width: 340px;
    margin-left:37.5%; 
    margin-right: 20px;
    .form_box {
      
      .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: 250px;
                
                  margin-top: 0.03rem;
                }
              }
            }
          }
        }
      }
    }
  }
  .button_box {
    display: flex;
    justify-content: center;
    margin-top: 30px;
    margin-bottom: 30px;
  }
   .fromOther  .el-input__inner{
    width: 250px;
  }
 
}
</style>

