<!-- 提取移库开票 -->
<template>
  <div class="extractMove">
    <p-modal
      title="提取"
      :visible="visible_extract"
      destroyOnClose
      :draggable="true"
      :enlargeable="true"
      width="90%"
      @ok="handleOk_extract"
      @cancel="handleCancel"
    >
      <!-- 提取 -->
      <p-table
        ref="table3"
        :columns="columns3"
        :data-source.sync="data3"
        rowKey="billId"
        dragle
        auto-width
        hasRowSelectCheck
        :remoteUrl="remoteUrl"
        :remoteBefore="remoteBefore"
        :row-select-type="1"
        @checkRow="checkRow3"
        bordered
      >
      </p-table>
    </p-modal>
    <p-modal
      :title="'拆分总数量' + totalNum"
      :visible="visible_split"
      destroyOnClose
      :draggable="true"
      :enlargeable="true"
      width="80%"
      :footer="null"
      @cancel="handleCancel"
    >
      <!-- 拆分弹窗 -->
      <split_modal ref="splitModal" :objData="objData" :totalNum="totalNum" @handleOk="handleOk"></split_modal>
    </p-modal>
    <p-card title="提取移库开票">
      <template slot="extra">
        <p-button type="primary" icon="to-top" @click="extract" style="margin-right: 15px">提取</p-button>
        <p-button type="primary" icon="column-height" @click="merge" style="margin-right: 15px">合并拆分</p-button>
        <!-- <p-button type="primary" icon="plus" @click="addRow"  style="margin-right:15px;">新增</p-button>
			<p-button type="primary" icon="delete" @click="delShow" style="margin-right:15px;">删除</p-button> -->
        <p-button type="primary" icon="save" @click="hanlderSubmit">保存</p-button>
      </template>
      <div class="plg-inner-form-mb">
        <p-grid-form ref="search" :items="items" @submit="hanlderSubmit" />
      </div>
      <p-table-edit-pro
        ref="table"
        hasRepairDataSource
        dragle
        auto-width
        :scroll="{ x: true }"
        :columns="columns"
        :data-source.sync="data"
        rowKey="key"
        :row-select-type="2"
        @checkRow="checkRow"
        @change="changePagination"
        :pagination="pagination"
        :loading="loading"
        bordered
      >
        <!-- <template slot="inStockStatus" slot-scope="text,rows,index">
				{{	common_stockstatus.find(item =>{
						if(text == item.dictId ){
							return  item.dictName;
						} else {
							return '';
						}
					})
				}}
				</template>
				<template slot="outStockStatus" slot-scope="text,rows,index">
				{{	common_stockstatus.find(item =>{
						if(text == item.dictId ){
							return  item.dictName;
						} else {
							return '';
						}
					})
				}}
			</template> -->

        <template slot="opertion" slot-scope="text, rows, index">
          <a @click="modal_split(rows, index)">拆分</a>
        </template>
      </p-table-edit-pro>
    </p-card>
  </div>
</template>

<script>
// 拆分弹窗
import split_modal from './components/split_modal.vue'
// 设置默认仓库
import { setwarehouse } from '@/views/kzyWMS/SearchModal/mixins_warehouse.js'
import { items, columns, columns3 } from './config/extractMove.js'
import { move_erp_list, move_erp_add, dict_listbytype } from '../api/api.js'
import { upcloud_base_wh_operate } from '@/config/serviceSettings'
import { getCargoOwner } from '../../utils/index'
// import store  from '@/store';
export default {
  mixins: [setwarehouse],
  components: { split_modal },
  data() {
    return {
      items,
      columns: columns(this),
      columns3: columns3(this),
      data3: [],
      data: [],
      objData: {},
      selectId: [],
      selectData: [],
      common_stockstatus: [],
      totalNum: 0, //零散数合计(可拆总数量)
      caseQuantity: 0, //整件数合计
      // index:null,	//插入下标
      indexArr: [], //合并拆分下标
      selectedRows3: [], //主表选择记录
      loading: false,
      visible_split: false, //拆分弹窗
      visible_extract: false, //提取弹窗
      lineId: '', //ERP明细ID
      pagination: {
        total: 0,
        pageSize: 10, //每页中显示10条数据
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ['10', '15', '20'], //每页中显示的数据
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
      remoteUrl: {
        url: upcloud_base_wh_operate + '/move/v1/erp-head-list',
        method: 'get',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        params: {},
      },
    }
  },
  methods: {
    remoteBefore(res, remoteParams) {
      console.log(this.$refs['search'].form.getFieldsValue().warehouseId)
      remoteParams.params = {
        ...remoteParams.params,
        warehouseId: this.$refs['search'].form.getFieldsValue().warehouseId,
      }
      return remoteParams
    },
    async getAuthBycargoOwner() {
      await getCargoOwner().then((res) => {
        if (res.success) {
          this.$nextTick(() => {
            this.$refs.search.form.setFieldsValue({
              cargoOwnerId: res.data.list[0].companyId,
              cargoOwnerName: res.data.list[0].companyName,
              cargoOwnerCode: res.data.list[0].companyCode,
            })
          })
        }
        if (!res.success) {
          this.$exception(res)
          return
        }
      })
    },
    getData(params) {
      ;(params = {
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize,
        ...params,
      }),
        (this.loading = true)
      move_erp_list(params)
        .then((res) => {
          if (res.success) {
            this.loading = false
            res.data.list.forEach((t) => {
              t.oddPieceQuantity = 0
              t.caseQuantity = 0
            })
            this.data = res.data.list
            this.pagination.total = Number(res.data.totalCount)
          } else {
            this.loading = false
            this.$exception(res)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 保存 提交
    hanlderSubmit(event) {
      event.preventDefault()
      // this.$refs.table.validateFields((err, values) => {
      //        if (!err) {
      if (this.data.length) {
        this.loading = true
        move_erp_add(this.data)
          .then((res) => {
            if (res.success) {
              this.$message.success('保存成功！')
              this.loading = false
              this.data = []
              this.selectedRows3 = []
              // this.getData({ billId: this.selectedRows3[0].billId, billNo: this.selectedRows3[0].billNo })
            } else {
              this.loading = false
              this.$exception(res)
            }
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        this.$message.warning('无数据！')
      }
      //   }
      // });
    },
    changePagination(pagination, filters, sorter) {
      // 分页变化
      console.log(pagination, filters, sorter, '分页变化分页变化')
      this.pagination = pagination
      this.getData({ billId: this.selectedRows3[0].billId, billNo: this.selectedRows3[0].billNo }) //分页查询所有列表
    },
    // 合并拆分
    merge() {
      if (this.selectData.length < 1) return this.$message.warning('请选择数据！')
      // if (this.selectData.length >= 1) {
      let temp = this.selectData.find((item) => item.lineId != this.selectData[0].lineId)
      if (temp) {
        this.$message.warning('存在不同的ERP移库单！')
      } else {
        // 整件数合计
        let caseQuantity = 0
        for (let index in this.selectData) {
          caseQuantity += +this.selectData[index].caseQuantity
        }
        // this.caseQuantity = caseQuantity;
        // 零散数合计
        let totalNum = 0
        for (let index in this.selectData) {
          totalNum += +this.selectData[index].oddPieceQuantity
        }
        // this.totalNum = totalNum;

        // js数组转为对象
        let objA = {}
        for (let key in this.selectData[0]) {
          //这里key索引
          objA[key] = this.selectData[0][key]
        }

        // case 0:'整散合一';	case 1: '整散分离';
        /* if(this.selectData[0].isCaseOrPiece){
							this.totalNum = totalNum + caseQuantity * this.selectData[0].isCaseOrPiece;
							this.objData  = Object.assign(objA,{oddPieceQuantity:totalNum,caseQuantity:caseQuantity},
													{key: 'key'+parseInt(Math.random()*10000) } );
						} else { */
        this.totalNum = totalNum + caseQuantity * objA.caseConvertionRate
        this.objData = Object.assign(
          objA,
          { oddPieceQuantity: totalNum, caseQuantity: caseQuantity * objA.caseConvertionRate },
          { key: 'key' + parseInt(Math.random() * 10000) }
        )
        // }
        this.visible_split = true
      }
      // } else {
      //   this.$message.warning('请选择数据！')
      // }
    },
    checkRow(selectId, selectRows) {
      console.log(arguments, 'argumentsargumentsarguments')
      // 求最大 index
      // this.indexArr = Math.max(...arguments[0]);

      // 根据key找出选中索引数组
      this.indexArr.length = 0 //清空数组
      selectRows.forEach((rows, index) => {
        let ind = this.data.findIndex((item) => item.key == rows.key)
        this.indexArr.push(ind)
      })
      console.log('checkRow下标数组', this.indexArr)

      this.selectId = [...selectId]
      this.selectData = [...selectRows]
      console.log('selectId,selectRows：', selectId, selectRows)
    },
    colChange({ name, value, index, label, record, modalRowData, config, vNode, options, moment, event }) {
      console.log('改变单元格数据：', name, value, index, label, record, modalRowData)
      this.data[index].pieceQuantity = value
      console.log('行修改后：', this.data)
    },
    // 重置
    resetRow() {
      this.$emit('update:dataSource', [])
      this.$refs.table.dataSource[0].cargoOwnerId = ''
      this.$refs.table.dataSource[0].cargoOwnerName = ''
      console.log('this.$refs.table:', this.$refs.table.dataSource, this.data)
    },
    // 增加行
    addRow() {
      this.$refs.search.form.validateFields((err, values) => {
        if (!err) {
          this.$refs['search'].form.disableItem()
          // 手动单号、部门、备注不禁用
          this.$refs['search'].form.enableItem(['warehouseName2', 'departmentName', 'comments'])
          this.$refs.table.createRow()
        } else {
          this.$message.warning('有必填数据！')
        }
      })
    },
    // 仅前台显示删除，后台不做删除
    delShow() {
      console.log('this.selectId:', this.selectId)
      if (this.selectId.length) {
        this.$refs.table.removeRow(this.selectId)
        this.selectId = []
      } else {
        this.$message.warning('请选择数据！')
      }
    },
    // 拆分弹窗
    modal_split(rows, index) {
      this.$nextTick(() => {
        this.indexArr = [index] //最大下标
        console.log('准备拆分下标：', index)

        this.objData = { ...rows, key: 'key' + parseInt(Math.random() * 10000) }
        // 0整散合一   1整散分离
        // 总数量 判断对象中的key是否存在
        // if(rows.isCaseOrPiece){
        //  ('key' in rows)?this.totalNum=rows.oddPieceQuantity+rows.caseQuantity*rows.caseConvertionRate : this.totalNum=rows.erpPlanQuantity;
        // } else {
        'key' in rows
          ? (this.totalNum = +(rows.oddPieceQuantity + rows.caseQuantity * rows.caseConvertionRate))
          : (this.totalNum = +rows.erpPlanQuantity)
        // }
        // this.totalNum = +this.objData.erpPlanQuantity;

        this.visible_split = true
        // this.objData = this.$refs.table.getCurrentRow().obj;
        console.log('拆分弹窗：', this.objData)
      })
    },
    handleOk(val) {
      this.visible_split = false

      console.log('接收到的数据：', val)

      // 循环插入数据
      val.forEach((item, ind) => {
        // console.log("删除最大下标：", Math.max(...this.indexArr) );
        if (this.indexArr.length > 1) {
          this.data.splice(Math.max(...this.indexArr) + 1, 0, item)
          console.log('插入最大下标：', Math.max(...this.indexArr) + 1)
        } else {
          this.data.splice(this.indexArr[0] + 1, 0, item)
          console.log('插入下标：', this.indexArr[0] + 1)
        }
      })
      // 删除,  删除前先从大到小排序，先删除最底下最大的索引
      this.indexArr.sort(function (a, b) {
        return b - a
      })
      this.indexArr.forEach((item, index) => {
        this.data.splice(this.indexArr[index], 1)
        console.log('正在删除下标：', this.indexArr[index])
      })
      // 删除完成将索引数组清0
      this.indexArr.length = 0
      console.log('this.data', this.data, this.indexArr)
    },

    handleCancel(e) {
      this.visible_split = false //关闭拆分弹窗
      this.visible_extract = false //关闭提取弹窗
    },
    checkRow3(selectedRowKeys, selectedRows3) {
      console.log(selectedRowKeys, selectedRows3)
      this.selectedRows3 = [...selectedRows3]
      // this.lineId = selectedRowKeys[0];
    },
    // 提取
    extract() {
      let _this = this
      this.$nextTick(() => {
        _this.visible_extract = true
      })
    },
    // 提取确认
    handleOk_extract() {
      if (this.selectedRows3.length) {
        this.$refs.search.form.setFieldsValue({
          cargoOwnerId: this.selectedRows3[0].cargoOwnerId,
          cargoOwnerName: this.selectedRows3[0].cargoOwnerName,
          billId: this.selectedRows3[0].billId, //ERP移库单ID
          billNo: this.selectedRows3[0].billNo, //ERP移库单号
          iarDate: this.selectedRows3[0].iarDate,
        })

        this.$refs['search'].form.disableItem()
        // 手动单号、部门、备注不禁用
        this.$refs['search'].form.enableItem(['departmentName', 'comments'])
        this.visible_extract = false

        this.getData({ billId: this.selectedRows3[0].billId, billNo: this.selectedRows3[0].billNo })
      } else {
        this.$message.warning('请选择数据！')
      }
    },
  }, // methods
  mounted() {
    this.getAuthBycargoOwner()
    /* dict_listbytype({dicttypeCodes:'common_stockstatus'}).then(res=>{
				if(res.success){
					this.common_stockstatus = res.data;	
					//dictId: "1000000229"  dictName: "初始"
				}
			}) */
  },
}
</script>

<style lang="less" scoped>
::v-deep {
  .p-table-edit .ant-table-body {
    min-height: auto;
  }
  .ant-table-wrapper.p-table.p-checkbox.p-table-edit {
    min-height: 200px;
    .ant-table-placeholder {
      min-height: 160px;
    }
  }
}
</style>
