<template>
  <!-- 添加销售订单排车 -->
  <div class="addSalePlan">
    <page-title>新增销售订单排车</page-title>
    <!-- 销售订单表的数据 -->
    <div class="saleOrder">
      <dilTable v-bind.sync="option" @selection-change="selectionChange">
      </dilTable>
    </div>

    <div class="button-box">
      <el-button type="primary" @click="arragne">确定排车</el-button>
    </div>

    <!-- 车序号表格 -->
    <div class="switch" v-if="selectionList.length > 0">
      <el-tooltip placement="top">
        <div slot="content">下面表格已有数据,不能进行更改!!!</div>
        <el-switch
          v-model="value"
          active-text="件数"
          inactive-text="重量"
          disabled
        >
        </el-switch>
      </el-tooltip>
    </div>
    <div class="switch" v-else>
      <el-tooltip placement="top">
        <div slot="content">当下面表格有数据之后,将不能进行更改!!!</div>
        <el-switch v-model="value" active-text="件数" inactive-text="重量">
        </el-switch>
      </el-tooltip>
    </div>

    <!-- 排车表格 -->
    <div class="selectionTable from">
      <el-table
        :data="selectionList"
        border
        style="width: 100%"
        highlight-current-row
      >
        <el-table-column type="index" label="序号" width="50">
        </el-table-column>
        <el-table-column
          v-for="(item, i) in tableTop"
          :key="i"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          align="center"
          show-overflow-tooltip
        >
          <template slot="scope" v-if="item.label !== '重量'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '车序号'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '收货地址'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '运输单价'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '截止日期'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '收货姓名'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '收货方电话'">
            <span>{{ item.label }}</span>
          </template>
          <!-- 插入输入框 -->
          <template slot-scope="scope">
            <template v-if="item.slot">
              <!-- 物资件数 -->
              <template v-if="item.prop == 'orderPlanWeight'">
                <el-input
                  class="textinput"
                  placeholder="(必填)"
                  v-model.number="scope.row.orderPlanWeight"
                ></el-input>
              </template>
              <!-- 车序号 -->
              <template v-if="item.prop == 'cxh'">
                <el-input
                  class="textinput1"
                  placeholder="(必填)"
                  v-model.number="scope.row.cxh"
                  @change="updateArragneCxh(scope.row.cxh)"
                ></el-input>
              </template>
              <!-- 收货地址 -->
              <template v-if="item.prop == 'saleShipperAddressName'" >
                <el-input
                  style="width: 200px"
                  v-model="scope.row.saleShipperAddressName"
                  disabled
                >
                </el-input>
                <el-button
                  type="primary"
                  placeholder="()"
                  @click="select(scope.$index,1)"
                  >浏览</el-button
                >
              </template>
              <!-- 运输单价id -->
              <template v-if="item.prop == 'priceValue'" >
                <el-input
                  style="width: 200px"
                  v-model="scope.row.priceValue"
                  disabled
                >
                </el-input>
                <el-button
                  type="primary"
                  placeholder="()"
                  @click="select(scope.$index,2)"
                  >浏览</el-button
                >
              </template>
              <!-- 截止日期 -->
              <template v-if="item.prop == 'saleDateOfReceipt'">
                 <el-date-picker
                  class="textinput3"
                  type="date"
                  v-model.number="scope.row.saleDateOfReceipt"
                ></el-date-picker>
              </template>
              <!-- 收货客户 -->
              <template v-if="item.prop == 'saleOrderConsignee'">
                <el-input
                  class="textinput4"
                  placeholder="(非必填)"
                  v-model.number="scope.row.saleOrderConsignee"
                ></el-input>
              </template>
              <!-- 收货客户电话号码 -->
              <template v-if="item.prop == 'saleOrderConsigneeTel'">
                <el-input
                  class="textinput5"
                  placeholder="(非必填)"
                  v-model.number="scope.row.saleOrderConsigneeTel"
                ></el-input>
              </template>
              <!-- 排车数 -->
            <template v-if="item.prop == 'arragneCount'">
                <el-input
                  class="textinput6"
                  v-model.number="scope.row.arragneCount"
                ></el-input>
              </template>
            </template>
            <template v-else>
              <span>{{ scope.row[item.prop] }}</span>
            </template>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            
                
            <el-button
              @click="copyRow(scope.$index,scope.row)"
              type="text"
              size="big"
            >
              复制
            </el-button>

            <el-input
            style="width: 50px;"
              v-model.number="scope.row.arragneCount"
            ></el-input>

            <el-button
              @click="deleteRow(scope.$index,scope.row)"
              type="text"
              icon="el-icon-close"
              size="big"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 运输单价(地址对应)的模态框 -->
    <el-drawer 
      :visible.sync="addressDrawer" 
      :destroy-on-close="false"
      direction="rtl"
      size="40%"
      :wrapperClosable="false"
      modal
      close-on-press-escape
    
    >
      <el-input placeholder="请输入内容" v-model="addressText" style="margin-top: 10px; margin-left: 20px; width: 250px" clearable>
      </el-input>
      <el-button type="primary" class="btn" @click="selectAddressClick" style="margin-left: 5px">
         <i class="el-icon-search"></i>查询
      </el-button>

      <!-- 已选中 省市(区)县 -->
         <el-form :inline="true" style="margin-top: 0.5rem;">
          <el-form-item>
          <label class="el-form-item__label" style="width: auto;">已选中省市县(区):</label>
          </el-form-item>
          <el-form-item>
              <el-input class="el-form-item__content" v-model="address" placeholder="请输入内容" :disabled="true"></el-input>
          </el-form-item>
         </el-form>
         <!-- 具体收货地址 -->
         <div v-if="address != null">
          <el-form :inline="true" style="margin-top: 0.5rem;" >

          <el-form-item label="具体收货地址:">
            <el-autocomplete
              class="inline-input"
              v-model="place"
              :fetch-suggestions="querySearch1"
              placeholder="请输入具体收货地址"
              :trigger-on-focus="false"
              @select="handleSelect1"
            >
            </el-autocomplete>
          </el-form-item> 

          <el-button type="primary" @click="addAddressClick">确定</el-button>
        </el-form>
        </div>

      <div class="tablecls">
        <!-- 查询所有的运输单价 -->
        <dilTable
          v-bind.sync="Address"
          @radio-change="currentRadioChange2"
        ></dilTable>
      </div>
    </el-drawer>

    <div class="button-box">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="makeSure">确定</el-button>
    </div>
  </div>
</template>
<script>
import PageTitle from "@/components/Page/Title";
import { sjTime,isNumber } from "@/utils/sharedJsFile";
export default {
  components: { PageTitle },
  data() {
    return {
      //已选中 省市县(区)
      address:null,
      //具体收货地址
      place:null,
      //收货地址id
      addressId:null,
      //当前是哪一个浏览按钮触发
      browseButton:null,
      textInput: "",
      input: "",
      //排车数默认
      arragneCount: 1,
      //初始化车序号
      arragneCxh: 1,
      //是否自提
      saleOrderIsselfMention:'',
      //单价已选数量
      choosePriceCount: 0,
      option: {
        // 表格请求数据的地址
        requestUrl: "/api/v1/ams/getSaleOrderAndMaterialById?apiId=410&saleOrderId=" + this.$route.params.saleOrderId,
        // 控制显示多选列
        selectionType: "select",
      },
      //是否打开收货地址的模态框
      addressDrawer:false,
      //地址的框计算输入的值
      addressText:null,
      //收货地址的表格
      Address: {
        requestUrl: "/api/v1/ams/getAddressDeliveryAddress?apiId=255",
        selectionType: "radio",
      },
      //原运输单价的表格
      // Price: {
      //   requestUrl: "/api/v1/ams/getAmsContractTransportPrice1?apiId=109&deleted=0",
      //   selectionType: "radio",
      // },
      table: false,
      selectionList: [],
      selectionList1: [],
      drawer: false,
      direction: "rtl",
      form1: {},
      value: false,
      frist: {
        requestUrl: "/api/v1/ams/getAddressDeliveryAddress?apiId=255",
        selectionType: "radio",
        mapList: [],
      },
      options: [
        {
          values: "yes",
          label: "是",
        },
        {
          values: "no",
          label: "否",
        },
      ],
      values: "yes",
      tableTop: [
        {
          prop: "cxh",
          label: "车序号",
          width: "80",
          slot: true,
        },
        {
          prop: "materialName",
          label: "物资名称",
          width: "140",
        },
        {
          prop: "Specification",
          label: "规格型号",
          width: "140",
        },
        {
          prop: "orderPlanWeight",
          label: "重量",
          width: "80",
          slot: true,
        },
        {
          prop: "saleDateOfReceipt",
          label: "截止日期",
          width: "230",
          slot: true,
        },
        {
          prop: "saleShipperAddressName",
          label: "收货地址",
          width: "300",
          slot: true,
        },
        {
          prop: "priceValue",
          label: "运输单价",
          width: "300",
          slot: true,
        },
        {
          prop: "saleOrderConsignee",
          label: "收货客户",
          width: "150",
          slot: true,
        },
        {
          prop: "saleOrderConsigneeTel",
          label: "收货客户电话号码",
          width: "150",
          slot: true,
        },
        {
          prop: "arragneCount",
          label: "复制数",
          width: "80",
          slot: true,
        },
      ],
      row: {},
      //缓存当前选中的运输单价
      priceMap:{},
    };
  },
  // mounted() {
  //   this.dianji();
  // },
  watch: {
    value() {
      if (this.value) {
        this.tableTop[3]={
          prop: "orderPlanWeight",
          label: "件数",
          slot: true,
        };
      } else {
        this.tableTop[3]={
          prop: "orderPlanWeight",
          label: "重量",
          slot: true,
        };
      }
    },
  },
  methods: {
    //点击浏览事件
    ondrawer(row,index) {
      this.row = row;
      this.row.index = index;
      this.drawer = true;
    },
    //收货地址弹出层
    handleSelect1(item) {
        console.log("获取所有下拉值!");
    },
    //收货地址模态窗口的框计算
    selectAddressClick(){
      if(this.addressText){
        this.Address.requestUrl = "/api/v1/ams/getAddressDeliveryAddress?apiId=255&con="+this.addressText;
      }else{
        this.Address.requestUrl = "/api/v1/ams/getAddressDeliveryAddress?apiId=255&i=" + new Date();
      }
    },
    //以下是收货地址边输边查搜索
    querySearch1(queryString, cb){
      this.axios
        .post("/api/v1/ams/getRealAddressByLike?addressId="+this.addressId + "&index=" + queryString)
        .then((res) => {
          if (res.data.code == "200") {
            // console.log(res.data.data);
            var restaurants = res.data.data;
            // console.log(restaurants, "restaurants");
            var results = queryString
              ? restaurants.filter(this.createFilter1(queryString))
              : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
          }
        });
    },
    createFilter1(queryString) {
      return (restaurants) => {
        return (
          restaurants.value.toLowerCase().indexOf(queryString.toLowerCase()) >
          -1
        );
      };
    },
    //以上是收货地址边输边查搜索

    //修改输入框中的车序号，自动获取车序号最大值
    updateArragneCxh(cxh){
      if(this.arragneCxh<cxh){
          this.arragneCxh = ++cxh;
      }
    },
    //复制多条的方法
    copyRow(index,row){
      let arr = [];
      for(var i = 0 ;i<this.selectionList.length; i++){
        if(i == index){
          arr.push(this.selectionList[i]);
          //车序号自增
          var cxhStart = row.cxh;
          for(var j = 0;j<this.selectionList[i].arragneCount; j++){
            arr.push({
            Specification:row.Specification,
            arragneCount:this.arragneCount,
            cxh:++cxhStart,
            materialName:row.materialName,
            orderPlanWeight:row.orderPlanWeight,
            saleDateOfReceipt:row.saleDateOfReceipt,
            saleMaterialId:row.saleMaterialId,
            saleOrderConsignee:row.saleOrderConsignee,
            saleOrderConsigneeTel:row.saleOrderConsigneeTel,
            priceValue:row.priceValue,
            priceId:row.priceId,
            saleShipperAddressId:row.saleShipperAddressId,
            place:row.place,
            saleShipperAddressName:row.saleShipperAddressName,
          })

          }
          //确定车序号最大值并赋值给初始化车序号
          if(this.arragneCxh<cxhStart){
            this.arragneCxh = ++cxhStart;
          }
        }else{
          arr.push(this.selectionList[i]);
        }
      }
      this.selectionList = [];
      this.selectionList = arr;
    },
    //点击删除按钮删除当前点击的对象
    deleteRow(index,row){
      //统计与当前最大车序号相等的车序号
      var equalArragneCxh = 0;
      //若为最后一个删除对象，初始化this.arragneCxh的值
      if(this.selectionList.length==1){
        this.arragneCxh = 1;
      }else{
        for(var i = 0 ;i<this.selectionList.length; i++){
          if(this.selectionList[i].cxh==this.arragneCxh){
            equalArragneCxh++;
          }
        }
        //判断是否要减小最大车序号数
        if(equalArragneCxh==0){
          if((this.arragneCxh-1)==row.cxh){
          this.arragneCxh=row.cxh;
          }
        }
      }
      
      //删除当前点击的对象
      this.selectionList.splice(index,1);
    },
    //监听模态框点击事件
    currentRadioChange1(radioList) {
      this.selectionList[this.row.index].saleShipperAddressId = radioList.addressId;
      this.selectionList[this.row.index].saleShipperAddressName = radioList.address;
    },
    //运输单价模态窗口的点击事件
    addAddressClick(){
      //priceMap
      // this.selectionList[this.addressIndex].priceValue = this.priceMap.priceValue
      // this.selectionList[this.addressIndex].priceId = this.priceMap.priceId
      //获取运输单价和运输单价ID
      let map = {
        place: this.place,
        addressId: this.addressId
      }
      this.axios.post('/api/v1/ams/getPriceMap',map)
      .then((res)=>{
          if(res.data.data.priceId==-1){
            if(this.browseButton==1){
              this.selectionList[this.addressIndex].saleShipperAddressName = this.address+this.place;
              this.selectionList[this.addressIndex].saleShipperAddressId = this.addressId;
              this.selectionList[this.addressIndex].place = this.place;
            }
            this.selectionList[this.addressIndex].priceValue = '该区域尚未录入任何单价!';
            this.selectionList[this.addressIndex].priceId = 0;
            this.addAddressClickNext();
          }else{
            //赋值运输单价和运输单价ID
            if(this.browseButton==1){
              this.selectionList[this.addressIndex].saleShipperAddressName = this.address+this.place;
              this.selectionList[this.addressIndex].saleShipperAddressId = this.addressId;
              this.selectionList[this.addressIndex].place = this.place;
            }
            this.selectionList[this.addressIndex].priceValue = res.data.data.priceValue;//this.priceMap.priceValue
            this.selectionList[this.addressIndex].priceId = res.data.data.priceId;//this.priceMap.priceId
            this.addAddressClickNext();
          }
      });
    },
    //运输单价模态窗口的点击事件接续执行方法
    addAddressClickNext(){
      this.addressDrawer = false;
      let arr = this.selectionList;
      this.selectionList = [];
      //统计被选中的运输单价数量
      var count = 0;
      arr.forEach((e)=>{
        if(e.priceValue){
          count++;
        }
        this.selectionList.push({
          //销售订单与物资表主键
            Specification:e.Specification,
            arragneCount:e.arragneCount,
            cxh:e.cxh,
            materialName:e.materialName,
            orderPlanWeight:e.orderPlanWeight,
            saleDateOfReceipt:e.saleDateOfReceipt,
            saleMaterialId:e.saleMaterialId,
            saleOrderConsignee:e.saleOrderConsignee,
            saleOrderConsigneeTel:e.saleOrderConsigneeTel,
            priceValue:e.priceValue,
            priceId:e.priceId,
            saleShipperAddressId:e.saleShipperAddressId,
            place:e.place,
            saleShipperAddressName:e.saleShipperAddressName,
        })
      })
      //赋值单价已选数量
      this.choosePriceCount = count;
      //缩小运价省市县的范围
      if(this.browseButton==1){
        this.Address.requestUrl = "/api/v1/ams/getAddressDeliveryAddress?apiId=255&con="+this.address;
      }
    },

    //收货地址点击浏览的事件---------------------修改点
    select(index,type){
      this.browseButton = type;
      this.addressDrawer = true;
      this.addressIndex = index ; 
    },
    //收货地址模态框单选选中的事件----------------------------修改点
    currentRadioChange2(val){
      //若具体地址有值，清空值
      if(this.place!=null){
        this.place=null;
      }
      this.address = val.address;
      this.addressId = val.addressId;
      // this.priceMap = {};
      // this.priceMap = val;
    },
    // 框计算
    onclick() {
      this.option.requestUrl =
      "/api/v1/ams/getSaleOrderAndMaterialById?apiId=410&saleOrderId=" + this.$route.params.saleOrderId;
        //"/api/v1/uc/queryMaterialByLike?apiId=244&index=" + this.input;
    },
    open() {
      if (this.selectionList1.length != 0) {
        this.$confirm("取消会将已选择的数据清空, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.selectionList1 = [];
            this.table = false;
          })
          .catch(() => {});
      } else {
        this.table = false;
      }
    },
    // 进行排车
    arragne() {
      this.selectionList1.forEach((e) => {
        var addmap = {
          // materialCode: e.materialCode,
          cxh: this.arragneCxh,
          materialName: e.materialName,
          Specification: e.specificationModel,
          orderPlanWeight: null,
          saleShipperAddressId: null,
          saleShipperAddressName:null,
          saleDateOfReceipt: null,
          saleOrderConsignee: null,
          saleOrderConsigneeTel: null,
          saleMaterialId: e.saleMaterialId,
          priceValue:e.priceValue,
          priceId:e.priceId,
          // materialTheoreticalWeight: e.materialTheoreticalWeight,
          arragneCount : this.arragneCount,
        };
        this.selectionList.push(addmap);
      });
      //获取是否自提判断
      this.saleOrderIsselfMention = this.selectionList1[0].saleOrderIsselfMention;
      this.selectionList1 = [];
      this.table = false;
      //重置销售订单信息
      this.option.requestUrl = "/api/v1/ams/getSaleOrderAndMaterialById?apiId=410&saleOrderId=" + this.$route.params.saleOrderId + "&i=" + new Date();
    },
    // 返回选中的物资信息
    selectionChange(selection) {
      this.selectionList1 = [];
      this.selectionList1 = selection;
    },
    // 确定
    makeSure() {
        //初始化maplist
      var mapList = [];
      this.selectionList.forEach((item) => {
        //初始化mapItem
        var mapItem={
                //销售订单id
                saleOrderId : 0,
                //车序号    
                truckNo : "",
                //省市县id
                shippingAddressId : 0,
                //具体地址
                place :null,
                //截止日期
                dateOfReceipt :null,
                //收货方姓名   
                orderConsignee :"",
                //收货方电话 
                orderConsigneeTel :"",
                //车序号物资ID
                saleMaterialId : 0,
                //物资数量
                materialNumber : 0,
                //运输单价ID
                priceId: 0,
            };
        mapItem.saleOrderId=this.$route.params.saleOrderId;
        mapItem.truckNo=item.cxh;
        mapItem.shippingAddressId=item.saleShipperAddressId;
        mapItem.place=item.place;
        mapItem.dateOfReceipt=sjTime(item.saleDateOfReceipt);
        mapItem.orderConsignee=item.saleOrderConsignee;
        mapItem.orderConsigneeTel=item.saleOrderConsigneeTel;
        mapItem.saleMaterialId=item.saleMaterialId;
        mapItem.materialNumber=item.orderPlanWeight;
        mapItem.priceId=item.priceId;
        mapList.push(mapItem);
      });
      //校验是否自提，是自提，则运输单价必选，非自提，运输单价为空
      if(this.saleOrderIsselfMention=='是'){
        mapList.forEach((e)=>{
            e.priceId = null;
        })
        //发送请求
        this.axios.post("/api/v1/ams/addTruckNo", mapList).then((res) => {
        if (res.data.code == "200") {
          this.$router.go(-1);
        }
        this.$message({
          type: "success",
          message: "新增车序号成功!",
        });
        });  
      }else{
        //判断是否全部完成运输单价的选择
          if(this.choosePriceCount==this.selectionList.length){
            //发送请求
            this.axios.post("/api/v1/ams/addTruckNo", mapList).then((res) => {
            if (res.data.code == "200") {
              this.$router.go(-1);
            }
            this.$message({
              type: "success",
              message: "新增车序号成功!",
            });
            });
          }else{
            this.$message.warning('还有运输单价未被选定!')
          }
      }
          
    },
    // 取消
    cancel() {
      this.$router.go(-1);
    },
    //关闭事件
    handleClose(done) {
      this.$confirm("确认关闭?")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    CloseClick() {},
  },
};
</script>
<style lang='scss' scoped>
.addSalePlan{
  width: 100%;
}
.switch{
  margin-left: 60rem;
}
.form-box,
.from {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 5px;
  margin-bottom: 20px;
}
.button-box{
  display: flex;
  text-align: center;
  align-items: center;
  justify-content: center;
  margin-top: 0.3125rem;
  margin-bottom: 1.25rem;
}
.select {
  margin-left: -10rem;
}
.demo-form-inline {
  margin-left: 2rem;
}
.table_form {
  margin-left: -16rem;
}
.textinput {
  width: 70px;
}
.textinput1 {
  width: 70px;
  text-align: center;
  size: small;
}
.textinput2 {
  width: 50px;
  margin-right: 30px;
}
.textinput3 {
  width: 240px;
}
.textinput4 {
  width: 120px;
}
.textinput5 {
  width: 120px;
}
.textinput6{
  width: 70px;
}
</style>