<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="运输类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shipType">
              <j-dict-select-tag v-model="model.shipType" dictCode="ship_type" placeholder="请选择运输类型" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="8">
            <a-form-model-item label="料号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pn">
              <a-auto-complete v-model="model.pn" placeholder="请输入料号"  @select="pnSelect" @change="pnChange" :dataSource="pnList"></a-auto-complete>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="规格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="spec">
              <a-input v-model="model.spec" placeholder="请输入规格" disabled ></a-input>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="8">
            <a-form-model-item label="发货数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shipNumber">
              <a-input-number v-model="model.shipNumber" :min="0" placeholder="请输入发货数量" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="托盘数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="palletsNum">
              <a-input-number v-model="model.palletsNum" placeholder="请输入预估托盘数" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="8">
            <a-form-model-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unit">
              <j-dict-select-tag placeholder="请选择单位" v-model="model.unit" dictCode="unit"></j-dict-select-tag>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="8">
            <a-form-model-item label="发货日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shipDate">
              <j-date placeholder="请选择发货日期"  v-model="model.shipDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="取货地点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pickUpHub">
              <!-- <j-dict-select-tag placeholder="请选择取货仓库" v-model="model.pickUpHub" dictCode="tms_logistics_route,start_city,start_city"></j-dict-select-tag> -->
              <a-auto-complete v-model="model.pickUpHub" placeholder="请输入取货地点"  @select="pickUpHubSelect" @change="pickUpHubChange" :dataSource="pickUpHubList"></a-auto-complete>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="送货地点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryAddress">
              <!-- <j-dict-select-tag placeholder="请选择送货地点" v-model="model.deliveryAddress" dictCode="tms_logistics_route,target_city,target_city"></j-dict-select-tag> -->
              <a-input v-model="model.deliveryAddress" placeholder="请输入送货地点" disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="到货日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryDate">
              <j-date placeholder="请选择到货日期"  v-model="model.deliveryDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <!-- 
          <a-col :span="8">
            <a-form-model-item label="销售人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesperson">
              <a-input v-model="model.salesperson" placeholder="请输入销售人员"  ></a-input>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="8">
            <a-form-model-item label="作业备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workNotes">
              <a-input v-model="model.workNotes" placeholder="请输入作业备注"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="model.id">
            <a-form-model-item label="当前状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currentStatus">
              <j-dict-select-tag placeholder="请选择当前状态" v-model="model.currentStatus" dictCode="current_status" ></j-dict-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="发货单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invoice">
              <a-select placeholder="发货单" v-model="model.invoice" showSearch @change="changeInvoice">
                <a-select-option  v-for="item in invoiceList"
                  :key="item" :value="item" :label="item">
                  {{item}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <table style="width: 100%;">
      <thead>
        <tr align="center">
          <th style="width: 5%;"></th>
          <th style="width: 15%;">发货单</th>
          <th style="width: 15%;">发货仓库</th>
          <th style="width: 15%;">料号</th>
          <th style="width: 15%;">品名</th>
          <th style="width: 15%;">规格</th>
          <th style="width: 10%;">数量</th>
          <th style="width: 5%;">单位</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item,index) in deliveryDetailList" align="center" :key="index">
          <a-checkbox v-model="item.selected"></a-checkbox>
          <td style="width: 15%;">{{ item.invoice }}</td>
          <td style="width: 15%;">{{ item.pickUpHub }}</td>
          <td style="width: 15%;">{{ item.pn }}</td>
          <td style="width: 15%;">{{ item.productName }}</td>
          <td style="width: 15%;">{{ item.specName }}</td>
          <td style="width: 10%;"><a-input-number v-model="item.shipNumber" :min="0"  style="width: 100%;" @change="changeQty"/></td>
          <td style="width: 5%;">{{ item.unit }}</td>
        </tr>
      </tbody>
    </table>
    <div align="center" style="margin-top: 20px;">
      <!-- <a-button @click="addLine" type="primary">新增</a-button> -->
      <a-button @click="batchDel" type="danger">删除选中</a-button>
    </div>
  </a-spin>
</template>

<script>

  import { httpAction, getAction,postAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
import { off } from 'codemirror'
import { h } from 'vue'
import { min } from 'xe-utils/methods'

  export default {
    name: 'DeliveryDemandForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        cityList:[],
        pickUpHubList:[],
        pnSpecList:[],
        pnList:[],
        invoiceList:[],
        deliveryDetailList:[],
        model:{
          shipNumber: 0,
          palletsNum: 0
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          shipType :[{required: true, message: '请选择发货类型!'}],
          pn :[{required: true, message: '请输入料号!'}],
          shipNumber :[{required: true, message: '请输入发货数量!'}],
          shipDate :[{required: true, message: '请选择发货日期!'}],
          deliveryDate :[{required: true, message: '请选择到货日期!'}],
          deliveryAddress :[{required: true, message: '请选择送货地点!'}],
          pickUpHub :[{required: true, message: '请选择取货仓库!'}],
          spec: [{required: true, message: '请输入规格!'}],
          palletsNum: [{required: true, message: '请输入预估托盘数!'}],
        },
        url: {
          add: "/deliverydemand/deliveryDemand/add",
          edit: "/deliverydemand/deliveryDemand/edit",
          queryById: "/deliverydemand/deliveryDemand/queryById",
          getPalletsNum: "/deliverydemand/deliveryDemand/getPalletsNum",
          getCity: "/logisticsroute/logisticsRoute/getCity",
          getPnSpecList: "/vehicleproduct/tmsVehicleProduct/getPnSpecList",
          getShip: "/deliverydemand/deliveryDemand/getShip",
          getShipDetail: "/deliverydemand/deliveryDemand/getShipDetail",
          queryByDeliveryDemandId: "/deliverydemanddetail/deliveryDemandDetail/queryByDeliveryDemandId"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.getCity();
      this.getPnSpecList();
      this.getShip();
    },
    methods: {
      // 计算托盘数
      changeGetpalletsNum() {
        // if (!this.model.pn || !this.model.spec || !this.model.shipNumber) {
        //   return
        // }
        postAction(this.url.getPalletsNum, this.deliveryDetailList).then(res => {
          if (res.success) {
            this.model.palletsNum = res.result
          }
        })
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.model = Object.assign({}, record);
        this.visible = true;
        this.queryByDeliveryDemandId();
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            this.model.deliveryDemandDetailList = this.deliveryDetailList
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },

      getCity(){
        getAction(this.url.getCity).then(res => {
          if (res.success) {
            this.cityList = res.result;
            this.pickUpHubList = res.result;
          }
        })
      },
      pickUpHubSelect(){
        let pickUpHub = this.pickUpHubList.filter(x=>x.includes(this.model.pickUpHub))[0].split('&-')[0]
        let deliveryAddress = this.pickUpHubList.filter(x=>x.includes(this.model.pickUpHub))[0].split('&-')[1]
        this.model.pickUpHub = pickUpHub
        this.model.deliveryAddress = deliveryAddress
      },
      pickUpHubChange(val){
        this.pickUpHubList = this.cityList.filter(x => x.includes(val));
      },

      getPnSpecList(){
        getAction(this.url.getPnSpecList).then(res => {
          if (res.success) {
            this.pnSpecList = res.result;
            this.pnList = res.result;
          }
        })
      },
      pnSelect(){
        let pn = this.pnList.filter(x=>x.includes(this.model.pn))[0].split('&-')[0]
        let spec = this.pnList.filter(x=>x.includes(this.model.pn))[0].split('&-')[1]
        this.model.pn = pn
        this.model.spec = spec
      },
      pnChange(val){
        this.pnList = this.pnSpecList.filter(x => x.includes(val));
      },
      getShip(){
        getAction(this.url.getShip).then(res => {
          if (res.success) {
            this.invoiceList = res.result
          }
        })
      },
      addLine(){
        this.deliveryDetailList.push({selected: false,shipNumber: 0})
      },
      batchDel(){
        this.deliveryDetailList = this.deliveryDetailList.filter(x => x.selected===false)
        this.changeQty()
      },
      // 计算发货数量
      changeQty(){
        this.model.shipNumber = parseFloat(this.deliveryDetailList.reduce((sum, current) => sum + current.shipNumber, 0).toFixed(4));
        console.log(this.model.shipNumber);
        console.log(typeof this.model.shipNumber);
        
        this.changeGetpalletsNum()
      },
      changeInvoice(value){
        console.log(value);
        let hasEven = this.deliveryDetailList.some((item) => {
          return item.invoice == value;
        });
        if(hasEven){
          this.$message.warning("列表中已存在"+value);
          return;
        }
        getAction(this.url.getShipDetail, {invoice: value}).then(res => {
          if(res.success){
            this.deliveryDetailList.push(...res.result)
            this.changeQty()
          }
        })
      },
      queryByDeliveryDemandId(){
        getAction(this.url.queryByDeliveryDemandId, {deliveryDemandId: this.model.id}).then(res => {
          if(res.success){
            this.deliveryDetailList = res.result
          }
        })
      }
      
    }
  }
</script>