<template>
  <a-modal
    title="参照订单数据"
    v-model="referOrderDataModVis"
    :confirmLoading="confirmLoading"
    @ok="onSubmit"
    @cancel="handleCancel"
    width="90%"
  >
    <!-- tabel 加载 -->
    <a-spin :spinning="confirmLoading">
      <!-- 查询  -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :md="5" :sm="8">
              <a-form-item label="账套">
                <j-search-select-tag
                  placeholder="请选择账套"
                  v-model="queryParam.account"
                  dict="view_account,account,account">
                </j-search-select-tag>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="8">
              <a-form-item label="款号">
                <a-input placeholder="请输入款号" v-model="queryParam.itemNumber"></a-input>
              </a-form-item>
            </a-col>

             <a-col :md="5" :sm="8">
                <a-form-model-item label="类型">
                  <a-select v-model="queryParam.flourOrGarment">
                    <a-select-option value="">请选择</a-select-option>
                    <a-select-option value="1">成衣</a-select-option>
                    <a-select-option value="0">面辅料</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="5" :sm="8">
               <a-form-item label="预发货日期">
                  <a-range-picker
                    style="width: 100%"
                    :mode="rangeMode"
                    :placeholder="['开始日期', '结束日期']"
                    :value="range"
                    format = "YYYY-MM-DD"
                    @change="rangeSelectChange"
                  />
                </a-form-item>
              </a-col>
            <template v-if="toggleSearchStatus">
              <a-col :md="5" :sm="8">
                <a-form-item label="业务员">
                  <a-input placeholder="请输入业务员" v-model="queryParam.salesman"></a-input>
                </a-form-item>
              </a-col>
              <!-- <a-col :md="5" :sm="8">
                <a-form-item label="客户">
                  <j-search-select-tag
                    placeholder="请选择客户"
                    v-model="queryParam.customerName"
                    dict="view_customer,customerfullname,customerfullname">
                  </j-search-select-tag>
                </a-form-item>              
              </a-col> -->
              <a-col :md="5" :sm="8">
                <a-form-item label="小po">
                  <a-input placeholder="请输入小po" v-model="queryParam.smallPo"></a-input>
                </a-form-item>              
              </a-col>

               <a-col :md="5" :sm="8">
                <a-form-model-item label="是否被参照">
                  <a-select v-model="queryParam.refer">
                    <a-select-option value="1">是</a-select-option>
                    <a-select-option value="0">否</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>

              <a-col :md="5" :sm="8">
                <a-form-item label="订单日期">
                  <a-range-picker
                    style="width: 100%"
                    :mode="dataRangeMode"
                    :placeholder="['开始日期', '结束日期']"
                    :value="dateRange"
                    format = "YYYY-MM-DD"
                    @change="dateRangeSelectChange"
                  />
                </a-form-item>
              </a-col>
            </template>


            <a-col :md="4" :sm="8">
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                <a @click="handleToggleSearch" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 勾选表  :row-key="record => record.id" { pageSize: 50 } , y: 800  -->
      <a-table
        bordered
        size="small"
        rowKey="id"
        v-if="orderListData"
        :columns="referOerderColumns"
        :data-source="orderListData"
        :loading="loading"
        :pagination="false"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
        :scroll="{ x: 1500, y:450 }"
      >
      </a-table>
    </a-spin>
  </a-modal>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JEllipsis from '@/components/jeecg/JEllipsis'
import moment from 'moment'
import { randomUUID } from '@/utils/util'
import { queryOrderData, confimOrderData,addShipmentList } from '@api/document/shipmentList'

export default {
  name: 'ReferOrderDataModal', // 参照订单数据弹框
  mixins: [JeecgListMixin],
  components: { JEllipsis, moment },

  data() {
    let ellipsis = (v, l = 20) => <j-ellipsis value={v} length={l} /> // 省略

    return {
      selectedRowKeys: [],
      selectedRows: {}, // 勾选项
      loading: false, // 表格加载
      fatherData:[],
      // 表头
      referOerderColumns: [
        {
          title: '订单号',
          dataIndex: 'orderNumber',
          width: 180,
          // fixed: 'left',
          ellipsis: true,
          className: 'replacecolor'
        },
        {
          title: '款号',
          dataIndex: 'itemNumber',
          width: 150,
          // fixed: 'left',
          ellipsis: true,
          className: 'replacecolor'
        },
        {
          title: '预发货日期',
          dataIndex: 'preDeliveryDate',
          width: 120,
          ellipsis: true,
          className: 'replacecolor'
        },
      
          {
          title: '小po',
          dataIndex: 'smallPo',
          width: 100,
          ellipsis: true,
          className: 'replacecolor'
        },
        //    账套替换
        // {
        //   title: '账套',
        //   dataIndex: 'account',
        //   width: 80,
        //   className: 'replacecolor'
        // },
       
         
     
        //  {
        //   title: '预完工日期',
        //   dataIndex: 'preCompletionDate',
        //   width: 120,
        //   className: 'replacecolor'
        // },
        {
          title: 'packId',
          dataIndex: 'packId',
          width: 120,
          ellipsis: true,
          className: 'replacecolor'
        },
        {
          title: '分销点',
          dataIndex: 'distributionPoint',
          width: 120,
          ellipsis: true,
          className: 'replacecolor'
        },
        {
          title: '存货编码',
          dataIndex: 'inventoryCode',
          width: 120,
          ellipsis: true,
          className: 'replacecolor'
        },
         {
          title: '存货名称',
          dataIndex: 'inventoryName',
          ellipsis: true,
          width: 250,
          className: 'replacecolor'
        },

        
       
        {
          title: '颜色',
          dataIndex: 'colour',
          width: 160,
          ellipsis: true,
          className: 'replacecolor'
        },
        // {
        //   title: '尺码',
        //   dataIndex: 'size',
        //   width: 100,
        //   className: 'replacecolor'
        // },
        {
          title: '配码规格',
          dataIndex: 'codingRules',
          width: 180,
          ellipsis: true,
          className: 'replacecolor'
        },
        {
          title: '箱数',
          dataIndex: 'boxNumber',
          width: 100,
          ellipsis: true,
          className: 'replacecolor'
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 100,
          ellipsis: true,
          className: 'replacecolor'
        },
        {
          title: '订单剩余数量',
          dataIndex: 'surplusNum',
          width: 120,
          ellipsis: true,
          className: 'replacecolor'
        },
        // {
        //   title: '含税单价',
        //   dataIndex: 'unitPriceIncludingTax',
        //   width: 100,
        //   className: 'replacecolor'
        // },
         {
          title: '成衣工厂',
          dataIndex: 'garmentFactory',
          width: 100,
          ellipsis: true,
          className: 'replacecolor'
        },
        // {
        //   title: '成衣件数',
        //   dataIndex: 'garmentNmb',
        //   width: 100,
        //   className: 'replacecolor'
        // },
        // {
        //   title: '业务类型',
        //   dataIndex: 'businessTypeText',
        //   width: 100,
        //   className: 'replacecolor'
        // },
        // {
        //   title: '客户订单',
        //   dataIndex: 'customerOrderNumber',
        //   width: 100,
        //   className: 'replacecolor'
        // },
        // {
        //   title: '销售类型',
        //   dataIndex: 'salesTypeText',
        //   width: 100,
        //   className: 'replacecolor'
        // },

        {
          title: '客户简称',
          dataIndex: 'customerAbbreviation',
          width: 220,
          align: 'left',
          ellipsis: true,
          className: 'replacecolor'
        },
       
        //  {
        //   title: '供应商编码',
        //   dataIndex: 'supplierCode',
        //   width: 100,
        //   className: 'replacecolor'
        // },
        {
          title: '供应商',
          dataIndex: 'supplier',
          width: 120,
          ellipsis: true,
          className: 'replacecolor'
        },
        // {
        //   title: '汇率',
        //   dataIndex: 'exchangeRate',
        //   width: 100,
        //   className: 'replacecolor'
        // },
        // {
        //   title: '整单合计',
        //   dataIndex: 'wholeOrderTotal',
        //   width: 100,
        //   className: 'replacecolor'
        // },

        // {
        //   title: '销售部门',
        //   dataIndex: 'salesDepartment',
        //   width: 120,
        //   className: 'replacecolor'
        // },
        // {
        //   title: '业务员',
        //   dataIndex: 'salesman',
        //   width: 120,
        //   className: 'replacecolor'
        // },
        // {
        //   title: '币种',
        //   dataIndex: 'currencyText',
        //   width: 100,
        //   className: 'replacecolor'
        // },

        // {
        //   title: '品牌方',
        //   dataIndex: 'brandSide',
        //   width: 120,
        //   className: 'replacecolor'
        // },
        // {
        //   title: '第三方',
        //   dataIndex: 'thirdParty',
        //   width: 220,
        //   align: 'left',
        //   className: 'replacecolor'
        // },
        // {
        //   title: '定金比例(%)',
        //   dataIndex: 'depositRatio',
        //   width: 100,
        //   className: 'replacecolor'
        // },
        // {
        //   title: '定金',
        //   dataIndex: 'deposit',
        //   width: 100,
        //   className: 'replacecolor'
        // },
        // {
        //   title: '协同路线',
        //   dataIndex: 'collaborativeRoute',
        //   width: 100,
        //   className: 'replacecolor'
        // },
        // {
        //   title: '付款条件',
        //   dataIndex: 'termOfPayment',
        //   width: 120,
        //   customRender: t => ellipsis(t),
        //   className: 'replacecolor'
        // },
        // {
        //   title: '最终客户',
        //   dataIndex: 'endCustomer',
        //   width: 120,
        //   className: 'replacecolor'
        // },
        // {
        //   title: '订单备注',
        //   dataIndex: 'orderRemarks',
        //   width: 280,
        //   customRender: t => ellipsis(t),
        //   className: 'replacecolor'
        // },
        // {
        //   title: '价格备注',
        //   dataIndex: 'priceRemarks',
        //   width: 280,
        //   customRender: t => ellipsis(t),
        //   className: 'replacecolor'
        // },
        // {
        //   title: '订单变更说明',
        //   dataIndex: 'orderChangeDescription',
        //   width: 220,
        //   customRender: t => ellipsis(t),
        //   className: 'replacecolor'
        // },
        //  {
        //   title: '订单日期',
        //   dataIndex: 'orderDate',
        //   width: 120,
        //   className: 'replacecolor'
        // },
        // {
        //   title: '订单主表ID',
        //   dataIndex: 'syOrderDataId',
        //   width: 120,
        //   // fixed: 'right',
        //   className: 'replacecolor1'
        // },
        // {
        //   title: '订单子表ID',
        //   dataIndex: 'syOrderDataItemId',
        //   width: 450,
        //   // fixed: 'right',
        //   className: 'replacecolor'
        // }
      ],
      orderListData: [], //订单数据
      confirmLoading: false,
      referOrderDataModVis: false,
      error:'', // 选中数据不符合的字段名
      errorIdentical:[],//选中多行数据客户、分销点不同字段
      errorFather: '', //选中数据与已有数据不同集合

      // 查询条件
      queryParam: {
        refer:'0'
        // itemNumber: '', // 订单号
        // smallPo:'',//小po
        // account: '', //账套
        // pageSize:100,
        // preDeliveryDateS:'', //预发货开始日期
        // preDeliveryDateE:'', //预发货结束日期
        // flourOrGarment:'', //类型
        // startDeliveryDate :'',
        // endDeliveryDate : ''
        // pageNo: '', // 初始页
        // pageSize: '-1' // 每页显示条数
      },
      // 分页
      pagination: {},
      confimList: [], //勾选的订单数组
      propList: [], //需要给新增页的数据
      dateRange:[],
      range:[],//预发货日期数组
      dataRangeMode:['date','date'],
      rangeMode:['date','date'],
    }
  },
  // 接收父组件 方法
  // props: {},

  created() {
    // this.getOrderList()  	
    // this.defalutDate()
  },
  methods: {
    moment,
    // 参照订单数据 查询
    getOrderList() {
      this.confirmLoading = true;
      // if (this.queryParam.preDeliveryDate != ""){
      //   this.queryParam.preDeliveryDate = this.queryParam.preDeliveryDate.format('YYYY-MM-DD');
      // }
      this.$nextTick(() => {
        queryOrderData(this.queryParam).then(res => {
          this.confirmLoading = false;
          if (res.success) {
            for (var i=0; i<res.result.records.length;i++){
              res.result.records[i].id = randomUUID();
            }
            this.orderListData = res.result.records
            this.orderListData.map(item =>{
              item.boxNumber = Number(item.boxNumber).toFixed(0)
            })
            this.pagination = {
              total: res.result.total,
              current: res.result.current,
              pageSize: res.result.size
            }
          }
        })
      })
    },

    // 弹框确定
    onSubmit() {
      this.dataSet( this.selectedRows)
      var vv = this.selectedRows[0]
      // if(this.fatherData.length !== 0){
      //   this.fatherDataSet(this.fatherData,vv)
      // }
      if (this.selectedRowKeys.length == 0) {
        this.$message.error('请勾选订单数据')
      } else if(this.selectedRows !== 1 && this.error !==''){
          this.$message.error(this.error+'至少一项不相同！');
          this.error = ''
      }else{
        var garment = ''
        if(this.queryParam.flourOrGarment == 1){
          garment = '成衣'
        }else {
           garment = '面料'
        }
         this.loading = true
        addShipmentList({itemId:this.confimList,readyFabric:garment}).then(res => {
         if (res.success) {
         this.loading = false
          // this.referOrderDataModVis = false;
          this.close()
          this.selectedRowKeys = [];
          this.selectedRows = [];
           this.$message.success('添加成功')
          }else {
           this.$message.error('res.message')
          }
        })
      }
    },

    //参照数据选择多条时
    dataSet(){
       this.confimList = []
       var orderTest = [],
       poTest = [],
       preDeliveryTest = [],
       preCompletionTest = [],
       itemNumberTest = [],
       inventoryCodeTest = [],
       inventoryNameTest = [],
       colourTest = [],
       sizeTest = [],
       custorTest = [],
       distributionPointTest = []
       this.selectedRows.map(item=>{
         this.confimList.push(item.syOrderDataItemId);
         orderTest.push(item.orderNumber)
         poTest.push(item.smallPo)
         preDeliveryTest.push(item.preDeliveryDate)
         preCompletionTest.push(item.preCompletionDate)
         itemNumberTest.push(item.itemNumber)
         inventoryCodeTest.push(item.inventoryCode)
         inventoryNameTest.push(item.inventoryName)
         colourTest.push(item.colour)
         sizeTest.push(item.size)
         custorTest.push(item.customerName)
         distributionPointTest.push(item.distributionPoint)
      })
      if([...new Set(orderTest)].length == 1 && [...new Set(poTest)].length == 1 &&[...new Set(preDeliveryTest)].length == 1&&
      [...new Set(preCompletionTest)].length == 1 && [...new Set(itemNumberTest)].length == 1 &&[...new Set(inventoryCodeTest)].length !== 1&&
      [...new Set(inventoryNameTest)].length == 1 && [...new Set(colourTest)].length == 1 &&[...new Set(sizeTest)].length == 1){
        this.error = '订单号,小po,预发货日期,预完工日期,款号,存货编码,存货名称,颜色,尺码'
      }
      if([...new Set(custorTest)].length !== 1){this.errorIdentical.push('客户名称不相同')}
      if([...new Set(distributionPointTest)].length !== 1){this.errorIdentical.push('分销点')}
    },

    //已有参考列表
    // fatherDataSet(fathers,sons){
    //   var father = fathers[0]
    //   if(father.orderNumber === sons.orderNumber && father.smallPo === sons.smallPo && father.preDeliveryDate === sons.preDeliveryDate &&
    //   father.preCompletionDate === sons.preCompletionDate && father.itemNumber === sons.itemNumber && father.inventoryCode === sons.inventoryCode &&
    //   father.inventoryName === sons.inventoryName && father.colour === sons.colour && father.size === sons.size) {
    //     this.errorFather = '订单号,小po,预发货日期,预完工日期,款号,存货编码,存货名称,颜色,尺码'
    //   }
    //   // if(father.orderNumber !== sons.orderNumber){this.errorFather.push('订单号')}
    //   // if(father.smallPo !== sons.smallPo){this.errorFather.push('小po')}
    //   // if(father.preDeliveryDate !== sons.preDeliveryDate){this.errorFather.push('预发货日期')}
    //   // if(father.preCompletionDate !== sons.preCompletionDate){this.errorFather.push('预完工日期')}
    //   // if(father.itemNumber !== sons.itemNumber){this.errorFather.push('款号')}
    //   // if(father.inventoryCode !== sons.inventoryCode){this.errorFather.push('存货编码')}
    //   // if(father.inventoryName !== sons.inventoryName){this.errorFather.push('存货名称')}
    //   // if(father.colour !== sons.colour){this.errorFather.push('颜色')}
    //   // if(father.size !== sons.size){this.errorFather.push('尺码')}
    // },

    handleTableChange(pagination, filters, sorter) {
      this.queryParam.pageNo = pagination.current;
      this.getOrderList();
    },

    searchQuery() {
      this.toggleSearchStatus = false
      if(this.queryParam.flourOrGarment === '' || !this.queryParam.hasOwnProperty('flourOrGarment')){
        this.$message.error('请选择查询类型！');
      }else if(this.queryParam.account === '' || !this.queryParam.hasOwnProperty('account')){
        this.$message.error('请选择账套号！');
      }else{
         if(this.range.length == 2){
           var separator = "-"; //日期分隔符  
           var startDates = this.queryParam.preDeliveryDateS.split(separator);  
           var endDates = this.queryParam.preDeliveryDateE.split(separator);  
           var startDate = new Date(startDates[0], startDates[1]-1, startDates[2]);  
           var endDate = new Date(endDates[0], endDates[1]-1, endDates[2]);  
           var timeInterval= parseInt(Math.abs(endDate - startDate ) / 1000 / 60 / 60 /24) + 1;
           if(timeInterval > 31 ){
             this.$message.error('预发货时间区间超过31天，请重新选择！');
             this.range = []
             this.queryParam.preDeliveryDateS = ''
             this.queryParam.preDeliveryDateE = ''
           }else{
             this.queryParam.pageNo = '';
             this.getOrderList();
           }
         }else {
           this.queryParam.pageNo = ''
           this.getOrderList();
         }
         
      }
    },

    // 重置
    searchReset() {
      this.queryParam = {}
      // this.queryParam.customerName = '';
      this.dateRange = [];
      this.range = [];
      this.orderListData = []
      this.selectedRowKeys = [];
      this.selectedRows = [];
      // this.$emit('default-reset')
    },
    // 选中行
    onSelectChange(keys, rows) {
      this.selectedRowKeys = keys;
      this.selectedRows = rows;
    },

    close() {
      this.referOrderDataModVis = false;
      this.queryParam = {
        refer:'0'
      }
       this.$emit('close')
      this.searchReset();
    },
    handleCancel() {
      this.close();
    },
    // 时间发生变化的回调，发生在用户选择时间时
    dateRangeSelectChange(value) {
      this.dateRange = value;
      if (value.length == 0){
        this.queryParam.startDeliveryDate = "";
        this.queryParam.endDeliveryDate = "";
      }else{
        this.queryParam.startDeliveryDate = value[0].format('YYYY-MM-DD');
        this.queryParam.endDeliveryDate  = value[1].format('YYYY-MM-DD');
      }
    },

    rangeSelectChange(value) {
      this.range = value
        if (value.length == 0){
        this.queryParam.preDeliveryDateS = "";
        this.queryParam.preDeliveryDateE = "";
      }else{
        this.queryParam.preDeliveryDateS = value[0].format('YYYY-MM-DD');
        this.queryParam.preDeliveryDateE  = value[1].format('YYYY-MM-DD');
      }
    }
  },
  computed: {
    // 选中项
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
        },
        getCheckboxProps: record => ({
          props: {
            disabled: record.title === 'Disabled User',
            // Column configuration not to be checked
            title: record.title
          }
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
/deep/ .ant-table-thead > tr > th {
  text-align: center;
  // font-weight: 700;
}
/deep/ .ant-table-tbody {
  text-align: center;
}
/deep/ .ant-table-fixed-left table, .ant-table-fixed-right table{
width: min-content;
}
// /deep/ th.replacecolor1 {
// display: none;
// }
</style>
