<template>
  <!-- 万州港-达州港口出库 -->
  <div class="addWagonLoad">
    <page-title>返回</page-title>
    <div class="purchaseOrder_table">
      <div class="search" style="display:flex">
        <div style="margin-top: 18px;margin-left:10px">
          <el-label>物资名或订单号：</el-label>
        </div>
        <el-input
          placeholder="请输入"
          v-model="search1"
          style="margin: 10px; width:10%"
          clearable
        ></el-input>
        <div style="margin-top: 18px;margin-left:10px">
          <el-label>外轮船名：</el-label>
        </div>
        <el-input
          placeholder="请输入"
          v-model="search2"
          style="margin: 10px;width:10%"
          clearable
        ></el-input>
        <el-button
          type="primary"
          class="btn"
          @click="searchOrder()"
          style="margin: 10px;"
        >
          <i class="el-icon-search"></i>查询
        </el-button>
      </div>
      <!-- 采购订单号 -->
      <dilTable
        v-bind.sync="purchaseOption"
        @radio-change="orderChange"
      ></dilTable>
    </div>
    <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>
      <span style="color:red">导入数据中的 序号、车皮号 是必须的</span>
    </div>
    <div
      class="table item left"
      style="width:750px;
        height:300px;
        float:left;
        overflow:auto"
    >
      <el-table  ref="tempTable"
          highlight-current-row
          @row-click="rowClick"
          :data="tableData"
          :row-style="{height:'40px'}"
          style="width: 1000px;font-size: 18px">
        <el-table-column
          type="selection"
          width="40px">
        </el-table-column>
        <el-table-column
          type="index"
          width="50px"
          prop="number"
          label="序号"
          align="center"
          fixed="left"
          :resizable="false"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="makeDate"
          label="制票日期"
          width="120px"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="wagonNo"
          label="车皮号"
          width="120px"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="materialName"
          label="物资"
          width="180px"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="mineral"
          label="矿种"
          width="120px"
        >
        </el-table-column>
        <el-table-column align="center" width="80px" prop="wagonWeight" label="标重">
        </el-table-column>
      </el-table>
    </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
                  class="inline-input"
                  v-model="sendStation"
                  :fetch-suggestions="querySearchSendStation"
                  placeholder="请输入发站名称"
                  disabled
                  :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-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> -->
              <el-form-item label="有拼装:">
                <el-switch
                  v-model="isAssembly">
                </el-switch>
              </el-form-item>
            </div>
          </el-form>
          <dil-form :formId="102" 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" @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 {
      isLoading: false,
      list: [],
      form1: {},
      tableData: [],
      input: "",
      isAssembly:false,
      value: undefined,
      selection:[],
      //船名
      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: "",
      purchaseOption: {
        // 表格请求数据的地址
        requestUrl: "/api/v1/tms/findPurchaseOrderList?apiId=81",
        // 控制选择单列
        selectionType: "radio",
        pageSize: 5
      },
      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: 4,//发站id和到站id都写死了，并且赋了港口名，如果数据库id变化，要注意
      toTheStationId: 1,
      sendStation: "万州港",
      toTheStation: "老区轨道衡"
    };
  },
  mounted() {
    this.form1.resultLoadingDate = new Date();
  },
  methods: {
    currentRadioChange1(selection) {
      this.input = null;
      this.materialName = selection.materialName;
      this.materialId = selection.materialId;
      this.getPurchaseOrderNo();
    },
    currentRadioChange2(selection) {
      this.supplierName = selection.supplierName;
      this.supplierId = selection.supplierId;
      this.getPurchaseOrderNo();
    },
    currentRadioChange4(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() {
      this.getPurchaseOrderNo();
    },
    getPurchaseOrderNo() {
      let map = {
        materialId: this.materialId,
        supplierId: this.supplierId
      };
      if (this.remark) {
        map.remark = this.remark;
      }
      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.form1 = { purchaseOrderNo: res.data.data.purchaseOrderNo };
            }
          } else {
            this.$message.error("请求失败");
          }
        });
      }
    },
    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 == 4) {
        this.unloadPoint.requestUrl =
          "/api/v1/uc/getUnloadingMesByLike?apiId=374&index=" + this.inputText;
      }
    },
    //发站弹出层
    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
        );
      };
    },
    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 {
          this.$message({
            type: "warning",
            message: "车皮号长度不足7位数，请重新输入！"
          });
        }
      }
    },
    searchOrder() {
      //查询订单
      if (
        typeof this.search1 != "undefined" &&
        typeof this.search2 != "undefined"
      ) {
        let requestUrl = "/api/v1/tms/findPurchaseOrderList?apiId=81";
        if (this.search1 != null) {
          requestUrl += "&materialName=" + this.search1;
        }
        if (this.search2 != null) {
          requestUrl += "&resultForeignShipName=" + this.search2;
        }
        this.purchaseOption.requestUrl = requestUrl;
      } else {
        this.purchaseOption.requestUrl =
          "/api/v1/tms/findPurchaseOrderList?apiId=81";
      }
    },
    onclick(index) {
      this.list.splice(index, 1);
    },
    // 确定
    makeSure() {
      this.isLoading = true;
      let state = 0;
      if (
        this.$refs.tempTable.selection.length > 0 &&
        this.materialId &&
        this.supplierId &&
        this.purchaseOrderId &&
        this.form1.resultIsclear &&
        this.form1.resultClass &&
        this.sendStationId &&
        this.toTheStationId &&
        this.form1.resultLoadingDate
      ) {
        state = 1;
      } else {
        this.isLoading = false;
        console.log(this.list.length);
        if (this.list.length == 0) {
          this.$message({
            type: "warning",
            message: "请选择车皮号！"
          });
        } else {
          if (this.materialId) {
            if (this.purchaseOrderId) {
              if (this.form1.resultIsclear) {
                if (this.form1.resultClass) {
                  if (this.sendStationId) {
                    if (this.toTheStationId) {
                      if (this.form1.resultLoadingDate) {
                      } else {
                        this.$message({
                          type: "warning",
                          message: "请选择装车时间！"
                        });
                      }
                    } else {
                      this.$message({
                        type: "warning",
                        message: "请选择到站！"
                      });
                    }
                  } else {
                    this.$message({
                      type: "warning",
                      message: "请选择发站！"
                    });
                  }
                } else {
                  this.$message({
                    type: "warning",
                    message: "请选择班别！"
                  });
                }
              } else {
                this.$message({
                  type: "warning",
                  message: "请选择是否清场！"
                });
              }
            } else {
              this.$message({
                type: "warning",
                message: "请选择采购订单号！"
              });
            }
          } else {
            this.$message({
              type: "warning",
              message: "请选择采购订单号！"
            });
          }
        }
      }
      if (state == 1) {
        let map = {
          portName: this.sendStation,
          wagonList: this.$refs.tempTable.selection,
          // unloadingPointId:this.unloadPointId,
          purchaseOrderRailPlanId: this.purchaseOrderId,
          materialId: this.materialId,
          sendUnitId: this.supplierId,
          isClean: this.form1.resultIsclear,
          resultClass: this.form1.resultClass,
          sendStationId: this.sendStationId,
          arrivalStationId: this.toTheStationId,
          resultLoadingDate: sjTime(this.form1.resultLoadingDate),
          resultRemarks: this.form1.resultRemarks,
          userId: getCookie("userId"),
          resultType: 1,
          purchaseNo: this.form1.purchaseOrderNo,
          isAssembly:this.isAssembly
        };
        console.log(map);
        //校验拼装车的标重
        if(this.isAssembly){
          let flag=false;
          map.wagonList.forEach((item)=>{
            if(typeof item.wagonWeight !='undefined'){
              flag=true;
            }
          });
          if(!flag){
            this.$message.warning("拼装车的标重不存在！");
            this.isLoading = false;
            return ;
          }
        }
        this.axios
          .post("/api/v1/tms/addWarehouseOutResult", map)
          .then(res => {
            console.log(res);
            if (res.data.code == "200") {
              this.$message({
                type: "success",
                message: "新增成功"
              });
              this.cancel();
            } else {
              this.$message({
                type: "error",
                message: res.data.data
              });
            }
            this.isLoading = false;
          })
          .catch(() => {
            this.$message.error("请联系管理员");
            this.isLoading = false;
          });
      }
    },
    // 取消
    cancel() {
      this.$router.go(-1);
    },
    // 导入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.tableData = [];
          that.isLoading = false;
          if (typeof rows[0]["车皮号"] == "undefined") {
            that.$message({
              message: "车皮号不存在!请参考下方格式！",
              type: "warning"
            });
            return;
          }
        }
        //绑定数据
        rows.forEach((row, index) => {
          let carNumber = row["车皮号"];
          if (typeof carNumber != "undefined" && carNumber.length == 7) {
            //车皮号表
            let map = {};
            map.wagonNo = carNumber;
            //表格数据
            let temp = {
              number: row["序号"],
              makeDate: row["制票日期"],
              materialName: row["品名"],
              wagonNo: row["车皮号"],
              mineral: row["矿种"],
              wagonWeight: row["标重"]
            };
            that.tableData.push(temp);
          } else {
            let errorNumb = index + 1;
            console.log("第" + errorNumb + "行车皮号异常!");
            return;
          }
        });
      };
      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;
    },
    //点击行勾选
    rowClick(row, column, event) {
       let tempTable = this.$refs.tempTable; // 获取表格对象
       //判断是否已存在
       let findRow = this.$refs.tempTable.selection.find(item => item.number == row.number);
       if (findRow) {
          tempTable.toggleRowSelection(row, false);
       }else{
          tempTable.toggleRowSelection(row);
       }
    },
  }
};
</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: 20%;
      margin-right: 200px;
      .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: 10px;
  }
  .formOther .el-input__inner {
    width: 250px;
  }
}
</style>
