<template>
  <!-- 新增预托书 -->
  <div id="addPreBookDrawer">
    <a-drawer
      :title="(defultMethod == 'add')?'新增预托书':'编辑预托书'"
      width="89%"
      placement="right"
      :closable="true"
      :visible="visible"
      @close="handleCancel"
    >
      <!-- 主表信息 -->
      <a-card :bordered="true">
        <div class="table-page-search-wrapper">
          <!-- :rules="validatorRules" -->
          <a-form-model layout="inline" ref="form" :model="addPreBook" :rules="validatorRules">
            <a-row :gutter="24">
              

              <a-col :md="6" :sm="8">
                <a-form-model-item label="预托书号" prop="depositaryReceiptNo">
                  <a-input placeholder="请填写预托书号" v-model="addPreBook.depositaryReceiptNo"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="8">
                <a-form-model-item label="托书日期" prop="shippingOrderDate">
                  <a-date-picker
                    placeholder="请选择托书日期"
                    style="width:100%;"
                    :format="dateFormat"
                    v-model="addPreBook.shippingOrderDate"
                  />
                </a-form-model-item>
              </a-col>

              <!-- <a-col :md="12" :sm="16">
                <a-form-model-item label="外销发票号码" prop="exportInvoiceNo">
                  <a-input placeholder="请输入外销发票号码" v-model="addPreBook.exportInvoiceNo"></a-input>
                </a-form-model-item>
              </a-col> -->

              <a-col :md="6" :sm="8">
                <a-form-model-item label="经营单位" prop="unitInOperation">
                 <j-search-select-tag
                    placeholder="请选择收货人"
                    v-model="addPreBook.unitInOperation"
                    @change="unitInOperationChange"
                    dict="test-200">
                  </j-search-select-tag>
                </a-form-model-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <a-form-model-item label="经营单位地址" prop="unitInOperationAddress">
                  <a-input placeholder="根据经营单位自动带出" v-model="addPreBook.unitInOperationAddress"></a-input>
                </a-form-model-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <a-form-model-item label="进仓/装柜日期" prop="latestDateOfShipment">
                  <a-date-picker
                    placeholder="请选择进仓/装柜日期"
                    style="width:100%;"
                    :format="dateFormat"
                    v-model="addPreBook.latestDateOfShipment"
                  />
                </a-form-model-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <a-form-model-item label="最终船期" prop="theFinalShippingDate">
                  <a-date-picker placeholder="请输入最终船期" style="width:100%;" v-model="addPreBook.theFinalShippingDate"/>
                </a-form-model-item>
              </a-col>

               <a-col :md="6" :sm="8">
                <a-form-model-item label="贸易国别" prop="tradeCountry">
                  <j-search-select-tag
                    placeholder="请选择贸易国别"
                    v-model="addPreBook.tradeCountry"
                    dict="trade_country">
                  </j-search-select-tag>
                  <!-- <a-input placeholder="请输入贸易国别" v-model="addPreBook.tradeCountry"></a-input> -->
                </a-form-model-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <a-form-model-item label="运抵国别" prop="arriveInCountry">
                    <j-search-select-tag
                    placeholder="请选择运抵国别"
                    v-model="addPreBook.arriveInCountry"
                    dict="country_of_arrival">
                  </j-search-select-tag>
                  <!-- <a-input placeholder="请输入运抵国别" v-model="addPreBook.arriveInCountry"></a-input> -->
                </a-form-model-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <a-form-model-item label="收货人" prop="consignee">
                  <!-- <j-dict-select-tag 
                   style="width:100%;margin-bottom: 10px;"  v-model="addPreBook.consigneeAll" 
                  dictCode="sys_dict_item,item_text,description,dict_id in(select id from sys_dict where dict_code='receiving_goods_info')"
                  @change="consigneeSelectChange"/> -->
                  <j-search-select-tag
                    placeholder="请选择收货人"
                    v-model="addPreBook.consignee"
                    @change="consigneeSelectChange"
                    dict="receiving_goods_info">
                  </j-search-select-tag>
                </a-form-model-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <a-form-model-item label="收货人地址" prop="consigneeAddress">
                  <a-input placeholder="根据收货人自动带出" v-model="addPreBook.consigneeAddress" ></a-input>
                </a-form-model-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <a-form-model-item label="通知方" prop="notifyParty">
                  <a-input placeholder="根据收货人自动带出" v-model="addPreBook.notifyParty" ></a-input>
                </a-form-model-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <a-form-model-item label="通知方地址" prop="notifyPartyAddress">
                  <a-input placeholder="根据收货人自动带出" v-model="addPreBook.notifyPartyAddress" ></a-input>
                </a-form-model-item>
              </a-col>

             
              <a-col :md="6" :sm="8">
                <a-form-model-item label="出口口岸" prop="exportPort">
                   <j-search-select-tag
                    placeholder="请选择出口口岸"
                    v-model="addPreBook.exportPort"
                    dict="export_port">
                  </j-search-select-tag>
                  <!-- <a-input placeholder="请输入出口口岸" v-model="addPreBook.exportPort"></a-input> -->
                </a-form-model-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <a-form-model-item label="目的港" prop="destinationPort">
                    <j-search-select-tag
                    placeholder="请选择目的港"
                    v-model="addPreBook.destinationPort"
                    dict="port_of_destination">
                  </j-search-select-tag>
                  <!-- <a-input placeholder="请输入目的港" v-model="addPreBook.destinationPort"></a-input> -->
                </a-form-model-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <a-form-model-item label="收汇方式" prop="exchangeEarningsValue">
                  <j-search-select-tag
                    placeholder="请选择收汇方式"
                    v-model="addPreBook.exchangeEarningsValue"
                    dict="collection_method">
                  </j-search-select-tag>
                  <!-- <a-input placeholder="请输入收汇方式" v-model="addPreBook.exchangeEarningsValue"></a-input> -->
                </a-form-model-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <a-form-model-item label="成交方式" prop="termsOfDeliveryvalue">
                   <j-search-select-tag
                    placeholder="请选择成交方式"
                    v-model="addPreBook.termsOfDeliveryvalue"
                    dict="transaction_method"
                    change>
                  </j-search-select-tag>
                  <!-- <a-input placeholder="请输入成交方式" v-model="addPreBook.termsOfDeliveryvalue"></a-input> -->
                </a-form-model-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <a-form-model-item label="金额" prop="money">
                  <a-input placeholder="请输入金额" v-model="addPreBook.money"></a-input>
                </a-form-model-item>
              </a-col>

            </a-row>
          </a-form-model>
        </div>
      </a-card>

      <!--操作按钮区域 参照预装箱单  増行-->
      <a-card :bordered="true" style="margin:10px 0 60px 0;">
        

        <!-- table-->
        <a-spin :spinning="confirmLoading">
          <!-- :rules="validatorRules" -->
          <j-vxe-table
            ref="vTable"
            toolbar
            row-number
            row-selection
            drag-sort
            keep-source
            :height="350"
            :loading="loading"
            :dataSource="addPreBook.syLetterDepositItemList"
            :columns="addPerBookColumns"
            :alwaysEdit=true
            :bordered=true
            :toolbarConfig="toolbarConfig"
            @valueChange="handleValueChange"
          >

            <template v-slot:toolbarSuffix>
              <a-button @click="referadvancePackingList" type="primary" icon="ordered-list">参照预装箱单</a-button>
            </template>

            <template v-slot:action="props">
              <a-popconfirm title="确定删除吗？" @confirm="handleDelete(props)">
                <a>删除</a>
              </a-popconfirm>
            </template>

          </j-vxe-table>
        </a-spin>

      </a-card>

      <!-- 页面底部保存取消 -->
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 999
        }"
      >
        <a-popconfirm title="确定放弃新增？" @confirm="handleCancel" okText="确定" cancelText="取消">
          <a-button :style="{ marginRight: '8px' }">取消</a-button>
        </a-popconfirm>
        <a-button type="primary" @click="myHandSave">
          保存
        </a-button>
        <!-- <a-button type="primary" @click="myHandSubmit" style="margin-left: 8px">
          保存并提交
        </a-button> -->
      </div>
    </a-drawer>
    <!-- 参照预装箱单 -->
    <advancePackingList-modal ref="advancePackingListModal" :father="aa"  @callback="referCallback" @ok="modalFormOk"></advancePackingList-modal>
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JEllipsis from '@/components/jeecg/JEllipsis'
import moment from 'moment'
import AdvancePackingListModal from '@views/pre-book/advancePackingListModal.vue'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { addPreBook, editById } from '@api/document/pre-book.js'

export default {
  name: 'AddPreBookDrawer', // 新增预托书
  computed: {},
  mixins: [JeecgListMixin],
  components: { AdvancePackingListModal, JEllipsis, moment }, // 参照预装箱单 弹框
  data() {
    return {
      // 表头
      addPerBookColumns: [
        // {
        //   title: '英文名称',
        //   key: 'englishName',
        //   width: 120,
        //   fixed: 'left',
        //   className: 'replacecolor'
        // },
        {
          title: '款号',
          key: 'itemNumber',
          width: 120,
          // fixed: 'left',
          className: 'replacecolor'
        },
        {
          title: '小po',
          key: 'smallPo',
          width: 120,
          className: 'replacecolor'
        },
        {
          title: '数量',
          key: 'total',
          width: 120,
          className: 'replacecolor'
        },
        {
          title: '箱数',
          key: 'boxNumber',
          width: 90,

          className: 'replacecolor'
        },

        {
          title: '毛重',
          key: 'totalGrossWeight',
          width: 120,

          className: 'replacecolor'
        },
        {
          title: '净重',
          key: 'totalNetWeight',
          width: 120,

          className: 'replacecolor'
        },
        {
          title: '体积',
          key: 'totalVolume',
          width: 160,

          className: 'replacecolor'
        },
        {
          title: '分销点',
          key: 'distributionPoint',
          width: 120,

          className: 'replacecolor'
        },
        {
          title: '集装箱代号',
          key: 'containerCode',
          width: 120,
          type:JVXETypes.inputNumber,
          className: 'replacecolor',
        },

        {
          title: '集装箱号',
          key: 'containerNumber',
          width: 120,
          type:JVXETypes.input,
          className: 'replacecolor',
        },
        {
          title: '单价',
          key: 'unitPrice',
          width: 120,

          className: 'replacecolor'
        },
        {
          title: '金额',
          key: 'totalPrice',
          width: 120,

          className: 'replacecolor'
        },
        //         {
        //   title: '创建时间',
        //   dataIndex: 'createTime',
        //   align: 'center',
        //   sorter: true,
        //   customRender: text => {
        //     return moment(text).format('YYYY-MM-DD')
        //   }
        // },
        {
          title: '预发货日期',
          key: 'preDeliveryDate',
          width: 120,

          className: 'replacecolor'
        },
        {
          title: '业务员',
          key: 'salesman',
          width: 120,

          className: 'replacecolor'
        },

        {
          title: '业务部门',
          key: 'salesDepartment',
          width: 120,

          className: 'replacecolor'
        },
        {
          title: '采购/委外订单号',
          key: 'spurOrSubOrder',
          width: 160,

          className: 'replacecolor'
        },

        {
          title: '采购/委外工厂',
          key: 'supplier',
          width: 160,

          className: 'replacecolor'
        },

        {
          title: '操作',
          key: 'action',
          type: JVXETypes.slot,
          width: 100,
          align: 'center',
          fixed: 'right',
          slotName: 'action',
        }
      ],
      addPerBookData: [],


      msgFormSon: 'test', // 子组件传来数据的变量
      loading: false, // 表格加载
      addPreBook: {}, //主表信息
      confirmLoading: false,
      visible: false,
      defultMethod:'add',
      dateFormat: 'YYYY-MM-DD',
      toolbarConfig: {
          btn: []
      },
      validatorRules:{
          shippingOrderDate:[{required: true, message: '托书日期不能为空!'}],
          consignee:[{required: true, message: '收货人不能为空!'}],
          depositaryReceiptNo:[{required: true, message: '预托书号不能为空!'}],
          unitInOperation:[{required: true, message: '经营单位不能为空!'}],
          unitInOperationAddress:[{required: true, message: '经营单位地址不能为空!'}],
          tradeCountry:[{required: true, message: '贸易国别不能为空!'}],
          arriveInCountry:[{required: true, message: '运抵国别不能为空!'}],
          exportPort:[{required: true, message: '出口口岸不能为空!'}],
          destinationPort:[{required: true, message: '目的港不能为空!'}],
      },
    }
  },
  created() {},
  methods: {
    moment,
    // 参照预装箱单
    referadvancePackingList() {
      //子表中有数据时，传值给参照数据组件
      if(this.addPreBook.syLetterDepositItemList.length !== 0){
        this.$refs.advancePackingListModal.fatherData = this.addPreBook.syLetterDepositItemList
      }
      this.$refs.advancePackingListModal.advancePackingListModVis = true;
      this.$refs.advancePackingListModal.queryParam = {};
      this.$refs.advancePackingListModal.searchQuery();
    },
    // 増行
    handleAddColumn() {
      console.log('増行')

      const addrow = {
          id:"",
          syLetterDepositId:"",
          preDeliveryDate:"",
          clientAbbreviation:"",
          syPreAssembledPackingListId:"",
          syPreAssembledPackingListItemId:"",
          acSetNo:"",
          garmentFactory:"",
          // hod:"",
          styleNo:"",
          smallPo:"",
          itemCode:"",
          distributionPoint:"",
          size:"",
          startingBoxNumber:"",
          endCaseNumber:"",
          colour:"",
          piecesBox:"",
          boxNumber:"",
          total:"",
          netWeight:"",
          totalNetWeight:"",
          grossWeight:"",
          totalGrossWeight:"",
          outerBoxLength:0,
          outerBoxWidth:0,
          outerBoxHeight:0,
          totalVolume:"",
          netWeightToo:0,
          unitPrice:"",
          totalPrice:"",
          containerCode:"",
          containerNumber:"",
          custor:"",
          itemNumber:"",
          preAssembledPackingNo:"",
          salesman:"",
          salesDepartment:"",
          spurOrSubOrder:""
      }

      this.addPerBookData.push(addrow)
    },

    // ------------------------------------------
    // 操作 删除
    handleDelete(index) {
      var ret = this.addPreBook.syLetterDepositItemList.splice(index, 1);
      this.setHeadCalField();
      return ret;
      
    },
    // 抽屉 取消
    handleCancel() {
      this.close()
    },
    myHandSave(){
      this.addPreBook.theDocumentsState=0;
      this.saveAdd();

    },
    myHandSubmit(){
      this.addPreBook.theDocumentsState=1;
      this.saveAdd();
    },
    // 抽屉 提交
    saveAdd() {
      const that = this;
      var newObj = this.addPreBook;
      if (newObj.syLetterDepositItemList.length == 0){
        this.$message.error('当前记录没有子表记录，无法保存');
        return;
      }
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          //  for(var i =0;i<newObj.syLetterDepositItemList.length;i++){
          //    var row = newObj.syLetterDepositItemList[i]
          //    if(row.containerCode === '' || !row.containerCode){
          //       this.$message.error('第'+(i+1)+'行集装箱代号未填，无法保存！');
          //       return
          //     }
          //    if(row.containerNumber === '' || !row.containerNumber){
          //       this.$message.error('第'+(i+1)+'行集装箱号未填，无法保存！');
          //       return
          //     }
          //   }
          that.confirmLoading = true;
          if (newObj.id == undefined || newObj.id == "" || newObj.id == null){
            addPreBook(newObj).then(res => {
              that.confirmLoading = false;
              if (res.success) {
                this.$message.success('新增成功')
                this.close()
                //清空信息
                this.fatherList(); // 调用父组件 查询方法
                // this.msgFormSon = {}  清空子表信息
              }else{
                this.$message.error(res.message)
              }
            })
          }else{
            newObj.syLetterDepositItemList.map(item =>{
              item.hod = item.preDeliveryDate
               delete item.preDeliveryDate
            })
            editById(newObj).then(res => {
              that.confirmLoading = false;
              if (res.success) {
                this.$message.success('修改成功')
                this.close();
                this.fatherList() // 调用父组件 查询方法
                // this.msgFormSon = {}  清空子表信息
              }else{
                this.$message.error(res.message)
              }
            })
          }
        }
      })
      // this.getShipmentList() // 刷新发运明细列表
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.defultMethod = 'add'
      this.$refs.form.resetFields()
    },

    // ------------------------------------------
    modalFormOk() {},
    aa() {},
    // 参照回调
    referCallback(dataList){
      var subList = this.convertReferToSub(dataList);
        var filterList = subList.filter(newItem=>{
          return this.addPreBook.syLetterDepositItemList.filter(item=>{
            return item.syPreAssembledPackingListItemId === newItem.syPreAssembledPackingListItemId;
          }).length == 0;
        });
        this.addPreBook.syLetterDepositItemList = this.addPreBook.syLetterDepositItemList.concat(filterList);
        this.addPreBook.termsOfDeliveryvalue = 'FOB'
        this.addPreBook.exchangeEarningsValue = 'T/T'
        this.addPreBook.exportPort='宁波'
        var dd = moment(new Date()).format('YYYY-MM-DD')
         this.$set( this.addPreBook,'shippingOrderDate',dd)
        // this.addPreBook.shippingOrderDate = moment(new Date()).format('YYYY-MM-DD')
        this.setHeadCalField();
        
    },
    // 参照数据转换成子表
    convertReferToSub(dataList){
      var ret = [];
      for (var i=0; i<dataList.length; i++){
        var data = dataList[i];
        var sub = {
          id:"",
          syLetterDepositId:"",
          preDeliveryDate:data.preDeliveryDate,
          clientAbbreviation:data.customerAbbreviation,
          syPreAssembledPackingListId:data.id,
          syPreAssembledPackingListItemId:data.itemId,
          acSetNo:data.acSetNo,
          garmentFactory:"",
          // hod:"",
          styleNo:"",
          smallPo:data.smallPo,
          itemCode:"",
          distributionPoint:data.distributionPoint,
          size:data.size,
          startingBoxNumber:"",
          endCaseNumber:"",
          colour:data.colour,
          piecesBox:data.piecesBox,
          boxNumber:data.boxNumber,
          total:data.piecesBox*data.boxNumber,
          netWeight:data.totalNetWeight/data.boxNumber,
          totalNetWeight:data.totalNetWeight,
          grossWeight:data.totalGrossWeight/data.boxNumber,
          totalGrossWeight:data.totalGrossWeight,
          outerBoxLength:0,
          outerBoxWidth:0,
          outerBoxHeight:0,
          totalVolume:data.totalVolume,
          netWeightToo:0,
          unitPrice:data.unitPrice,
          totalPrice:data.totalPrice,
          containerCode:data.containerCode,
          containerNumber:data.containerNumber,
          custor:data.customer,
          itemNumber:data.itemNumber,
          preAssembledPackingNo:data.documentNo,
          salesman:data.salesman,
          salesDepartment:data.salesDepartment,
          spurOrSubOrder:data.spurOrSubOrder,
          supplier:data.supplier
        };
        ret.push(sub);
      }
      return ret;
    },
     handleValueChange(event) {
      },
      // 收货人下拉框
      consigneeSelectChange(value){
        if(value !=null && value !='' &&value != 'undefined'){
         var arr = value.split("+");
         this.addPreBook.consignee = arr[0]
         if(arr.length == 4){
           this.addPreBook.consigneeAddress = arr[1]
           this.addPreBook.notifyParty = arr[2]
           this.addPreBook.notifyPartyAddress = arr[3]
        }else{
           this.$message.error('收货信息维护有问题，请检查！')
        }
        }else{
          this.addPreBook.consigneeAddress = '';
          this.addPreBook.notifyParty = '';
          this.addPreBook.notifyPartyAddress = '';
        }
      },
      //经营单位下拉框
      unitInOperationChange(val){
      if(val !=null && val !='' &&val != 'undefined'){
          var valueArr = val.split("+")
          this.addPreBook.unitInOperation = valueArr[0]
          this.addPreBook.unitInOperationAddress = valueArr[3]
          this.addPreBook.customsCode = valueArr[1]
          this.addPreBook.dutyParagraph = valueArr[2]
        }else {
          this.addPreBook.unitInOperation = ''
          this.addPreBook.unitInOperationAddress = ''
          this.addPreBook.customsCode = ''
          this.addPreBook.dutyParagraph = ''
        }
        
      
    },
   
      // 设置表头计算字段
      setHeadCalField(){
        var money = 0
        for (var i=0; i<this.addPreBook.syLetterDepositItemList.length; i++){
          money += this.addPreBook.syLetterDepositItemList[i].totalPrice;
        }
        this.addPreBook.money = money.toFixed(2);
      }
    
  },

  mounted() {},
  // 接收父组件查询方法
  props: {
    fatherList: {
      type: Function,
      default: null
    }
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
@import '~@assets/less/overwriter.less';
/deep/ .ant-table-thead > tr > th {
  text-align: center;
  // font-weight: 700;
}
/deep/ .ant-table-tbody {
  text-align: center;
}
// /deep/ th.replacecolor {
//   background-color: #ccc;
// }

// 抽屉里的card样式
/deep/ .ant-drawer-content {
  background-color: #f0f2f5;
}
/deep/ .ant-drawer-body {
  padding: 10px;
}
</style>
