<template>
  <div>
    <p-card v-if='isShow == 1' title='订单挂起'>
      <div slot='extra'>
        <p-button icon='filter' @click='toggleFormTag = !toggleFormTag'>{{ toggleFormTag ? '隐藏' : '显示' }}</p-button>
      </div>
      <p-grid-form ref='formTarget' v-show='toggleFormTag' :span='8' :label-col='{ span: 9 }' :items='queryFormItems'
                   @submit='hanlderSubmit' />
      <p-table
        ref='logTable'
        :rowSelectType='tableOne.rowSelectType'
        :columns='tableOne.columns'
        :remoteUrl='params.url'
        :remoteData='params.params'
        :remoteParams='params.params'
        :rowKey='tableOne.rowKey'
        :expandedRowKeys='expandedRowKeys'
        @expand='expandedRowRender'
        @expandedRowsChange='expandedRowsChange'
        @clickRow='clickRow'
      >
        <template slot='action' slot-scope='text, record'>
          <span>
              <a v-if="record.status !== '已经取消'" @click.stop="actionClick(record, 'cancel')">订单还原</a>
              <a class='ml-10' v-action:issue @click.stop='issue(record)'>强制下发</a>
          </span>
        </template>
        <p-table
          slot='expandedRowRender'
          :columns='goodsColumnsConfig'
          :scroll='{ x: true }'
          :rowSelectType='false'
          :loading='loading'
          :showHeader='true'
          :hasRowCount='false'
          :colorTransformRow='false'
          :hasRowSelectCheck='true'
          :data-source='innerData'
          :pagination='false'
        >
          <div slot='action' slot-scope='text'>
            <a style='margin: 0 5px' @click.stop='itemDet(text)'>详情</a>
            <a style='margin: 0 5px' @click.stop='orderModify(text)'>指定库位</a>
          </div>
        </p-table>
      </p-table>
    </p-card>
    <itemDetail ref='detailItem' :itemId='itemId' />
    <detailspilt v-if='isShow == 3' ref='tablelog' @clickEvent='clickEvent' :orderModifyData='orderModifyData'
                 :num='itemNum' />

    <p-modal title='红冲' width='80%' :visible='visible' :enlargeable='true' :draggable='true' @ok='handleOk'
             @cancel='handleCancel'>
      <p-table-edit-pro ref='hcTable' style='padding: 30px' :scroll='{ x: true }'
                        :columns='HCgoodsColumnsConfig'
                        :data-source='HCinnerData'
                        @clickRow='clickRow'
                        :hasRepairDataSource='true'
                        :rowSelectType='false'
                        rowKey='_row_count'
      />
    </p-modal>
  </div>
</template>

<script>
import { queryFormItems } from './js/queryConfig'
import { tableOne, goodsColumnsConfig, HCgoodsColumnsConfig } from './js/tableConfig'
import { getWaveItemList, cencelWaveList, getAuthByUser, postbillDPrePosition, postdistributeList } from './api'
import { forSelectText } from '@/views/kzyWMS/utils/index.js'
import itemDetail from '@/views/kzyWMS/components/itemDetail'
import { upcloud_base_wh_outbound } from '@/config/serviceSettings'
import detailspilt from '@/views/kzyWMS/outBound/schedule/execute/modules/detailspilt.vue'

export default {
  name: 'Paused',
  components: { itemDetail, detailspilt },
  data() {
    return {
      itemId: '',
      queryFormItems: queryFormItems(this),
      tableOne: tableOne(this),
      goodsColumnsConfig,
      HCgoodsColumnsConfig,
      data: [
        {
          num: '2112'
        }
      ],
      params: {
        url: upcloud_base_wh_outbound + '/wave/bill/query',
        params: {
          pageNum: 1,
          pageSize: 10
        },
        timeout: 30000,
        method: 'get'
      },
      innerData: [],
      HCinnerData: [],
      expandedRowKeys: [],
      loading: false,
      toggleFormTag: true,
      isShow: 1,
      orderModifyData: {},
      itemNum: 0,
      computedNum: 0,
      rowRecord: {},
      visible: false,
      row: {},
      type: ''
    }
  },
  created() {
    forSelectText([goodsColumnsConfig]).then((res) => {
      console.log('子组件', res)
    })
    this.getAuthByUser()
    this.params.params.warehouseId = this.$store.getters.warehouse.warehouseId
    this.params.params.warehouseName = this.$store.getters.warehouse.warehouseName
  },
  mounted() {
    let warehouseName = this.$store.getters.warehouse.warehouseName
    let warehouseId = this.$store.getters.warehouse.warehouseId
    this.$refs.formTarget.form.setFieldsValue({ warehouseName: warehouseName, warehouseId: warehouseId })
  },
  methods: {
    hanlderSubmit(event, form) {
      event.preventDefault()
      this.$refs.formTarget.form.validateFields((error, values) => {
        if (!error) {
          values.withStockQty = 1
          this.params.params = values
        }
      })
      this.$emit('Query', event, form)
    },
    btEven(event) {
      console.log(event)
      this.$emit('btEven', event)
    },
    async getAuthByUser() {
      await getAuthByUser().then((res) => {
        if (res.success) {
          this.params.params.cargoOwnerId = res.data.list[0].companyId
          this.params.params.cargoOwnerName = res.data.list[0].companyName
          console.log(res.data.list[0].companyId, 'res.data.list[0].companyId')
          console.log(this.$refs.formTarget.form.getFieldsValue())
          this.$nextTick(() => {
            this.$refs.formTarget.form.setFieldsValue({
              consignorid: res.data.list[0].companyId,
              consignorname: res.data.list[0].companyName
            })
          })
        }
        if (!res.success) {
          this.$exception(res)
          return
        }
      })
      this.$refs.logTable.reload()
    },
    itemDet(data) {
      this.itemId = data.itemId
      this.$refs.detailItem.open()
    },
    actionClick(data, event) {
      if (event === 'cancel') {
        const params = { billId: data.billId }
        cencelWaveList(params).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$refs.logTable.reload()
          } else {
            this.$message.error(res.message)
          }
        })
      }
      this.$emit('actClick', data, event)
    },
    async clickRow(selectedRowKeys, record, row) {
      this.$emit('clickRow', record)
    },
    expandedRowsChange(expandedRowKeys) {
      console.log(expandedRowKeys)
    },
    expandedRowRender(expanded, record) {
      this.loading = true
      this.rowRecord = record
      console.log(expanded, record)
      if (expanded) {
        this.expandedRowKeys = [record.billId]
        const params = {
          // billId:record.billId,
          withStockQty: 1
        }
        getWaveItemList(record.billId, params).then((res) => {
          console.log(res)
          this.innerData = res.data.items
          this.type = res.data.type
          this.loading = false
        })
      } else {
        this.expandedRowKeys = this.expandedRowKeys.filter((item) => {
          return item !== record.billId
        })
      }
    },
    issue(data) {
      this.row = data
      const params = {
        // billId:record.billId,
        withStockQty: 1
      }

      getWaveItemList(data.billId, params).then((res) => {
        if (res.success) {
          this.HCinnerData = res.data.items
          this.HCinnerData = this.HCinnerData.filter(item => {
            let stockQty = item.stockQty ? item.stockQty : 0
            return stockQty < item.pieceQty
          })
          if (this.HCinnerData.length > 0) {
            this.visible = true
          } else {
            const params = { wavesIds: [this.row.waveId], billId: this.row.billId, redDTOs: [] }
            this.postdistributeList(params)
          }
        }
      })
    },
    orderModify(data) {
      console.log(data)
      this.isShow = 3
      this.itemNum = data.pieceQty
      this.computedNum = data.pieceQty
      console.log(this.type, 'this.rowRecord.typethis.rowRecord.type')
      const params = {
        warehouseId: this.rowRecord.warehouseId,
        cargoOwnerId: this.rowRecord.consignorId,
        billId: data.billId,
        billDId: data.billDId,
        itemId: data.itemId,
        manufacturerLotNum: data.manufacturerLotNum,
        status: data.stockStatus ? data.stockStatus : '',
        subStatus: this.type == '7' ? '3' : ''
      }
      this.orderModifyData = params
    },
    handleCancel() {
      this.visible = false
    },
    handleOk() {
      let status = this.HCinnerData.every(item => {
        return item.redReason
      })
      if (status) {
        console.log(this.$store)
        this.HCinnerData.forEach(item => {
          let stockQty = item.stockQty ? item.stockQty : 0
          item.qty = item.pieceQty - stockQty
          item.billDId = item.id
          item.employeeNo = this.$store.getters.userInfo.employeeNo
          item.username = this.$store.getters.userInfo.username
          item.userId = this.$store.getters.userInfo.userId
        })
        const params = { wavesIds: [this.row.waveId], billId: this.row.billId, redDTOs: this.HCinnerData }
        console.log(params, 'paramsparamsparamsparams')
        this.postdistributeList(params)
      } else {
        this.$message.error('请输入红冲原因')
      }
    },
    postdistributeList(params) {
      postdistributeList(params).then((res) => {
        if (res.success) {
          this.visible = false
          this.$refs.logTable.reload()
          this.$message.success(res.message)
        } else {
          this.$exception(res)
        }
      })
    },

    clickEvent(data) {
      if (data == 'handleOkreplenishment') {
        let status = this.$refs.tablelog.chekTableData()
        if (!status) {
          console.log(this.selectedRows1)
          const data = this.$refs.tablelog.innerData
          console.log(this.orderModifyData)
          let params = []
          data.forEach((item) => {
            if (item.qty > 0) {
              const obj = {
                areaCategory: item.warehouseAreaCategory,
                areaCode: item.warehouseAreaCode,
                areaId: item.warehouseAreaId,
                batchId: item.batchId,
                billDId: this.orderModifyData.billDId,
                billId: this.orderModifyData.billDId,
                conversionRate: item.caseConversionRate,
                // creator: item.enterpriseId,
                // creatorName: item,
                // gmtCreate: item,
                // gmtModified: item.gmtModified,
                // id: item,
                itemId: item.itemId,
                locationId: item.locatorId,
                locationType: item.locatorType,
                manufacturerLotNum: item.manufacturerLotNum,
                status: item.status,
                // modifier: item,
                // modifierName: item,
                qty: item.qty
                // waveId: item
              }
              params.push(obj)
            }
          })
          postbillDPrePosition(params).then((res) => {
            if (res.success) {
              this.$refs.tablelog.queryReplenishment()
              this.$message.success(res.message)
              // this.$refs.logTable.reload()
            } else {
              this.$exception(res)
            }
          })
        }
      } else if (data == 'back') {
        this.isShow = 1
      }
    }
  }
}
</script>
