<template>
  <div>
    <p-card title='特殊订单下发' v-show='isShow == 1'>
      <template slot='extra'>
        <p-button icon='filter' @click='toggleFormTag = !toggleFormTag'>{{ toggleFormTag ? '隐藏' : '显示' }}</p-button>
        <p-button type='primary' class='ml-10' icon='plus' :loading='loading' :disabled='selectedRowKeys.length === 0'
                  @clickSync='planWave'>单据下发
        </p-button>
      </template>
      <p-grid-form v-show='toggleFormTag' ref='modelForm' :span='8' :label-col='{ span: 9 }' :items='items'
                   @submit='handlerSubmit'
      />
      <p-table
        dragle
        :columns='columns'
        :remoteUrl='orderPageUrl_TS'
        :remoteData='main_remoteData'
        :autoLoad='false'
        rowKey='billid'
        ref='logTable'
        :scroll='{ x: true,y:590 }'
        @clickRow='clickRow'
        rowSelectFixed
        :rowSelectType='2'
        @selectChange='selectChange'
        @select='checkSelect'
        :getCheckboxProps='getCheckboxProps'
        bordered
      >
        <template slot='isEnable' slot-scope='text'>{{ text ? '启用' : '禁用' }}</template>
        <template slot='action' slot-scope='text, record'>
          <!-- <a style='margin: 0 5px' @click.stop='HcOrder(record)' v-action:redOrder :disabled='record.isCancelled == 1'>红冲</a> -->
        </template>
      </p-table>
      <p-card title='订单行信息'>
        <p-table-edit size='small' dragle :scroll='{ x: true }'
                      :loading='spinning'
                      :columns='singleColumns'
                      :dataSource.sync='singleData' :rowSelectType='false' rowKey='lineid' :pagination='false' bordered>
          <a-table-column data-index='sysCarrierCode' title='系统承运商编码' />

          <template slot='action' slot-scope='text, record'>
            <!-- <a style="margin: 0 5px" @click.stop="saveItemDet(record)">保存</a> -->
            <a v-action:view @click.stop='itemDet(record)'>商品详情</a>
            <a class='ml-10' @click.stop='orderModify(record)'>指定库位</a>
          </template>
        </p-table-edit>
      </p-card>
    </p-card>
    <!-- 红冲弹窗 -->
    <HCdetailDialog v-if='isShow == 2' :billid='billid' :singleData='singleData' @clickEvent='clickEvent' />
    <!-- 明细弹窗 -->
    <itemDetail ref='detailItem' :itemId='itemId' />
    <!-- 解锁弹窗 -->
    <workerLogin :loginVisible='loginVisible' :isSupervisedData='isSupervisedData'
                 @loginResult='loginResult'
                 @handleCancel='handleCancel'
    />
    <detailspilt v-if='isShow == 3' ref='tablelog' @clickEvent='clickEvent2' :orderModifyData='orderModifyData'
                 :TS="'TS'" :num='itemNum' />

  </div>
</template>

<script>
import { itemfun, columns, singleColumns, singleColumnsEdit } from '../config/create'
import {
  orderOne,
  schedule_saveItem,
  orderPageUrl_TS,
  orderOne_TS,
  planWaveCreate_TS,
  redomsItembillQuery,
  getAuthByUser,
  postBilltype,
  postbillDPrePosition_TS
} from '../api/api.js'
import { diffOption } from '@/views/kzyWMS/utils/index.js'
import { sorter } from '@/views/kzyWMS/utils/sort.js'

import HCdetailDialog from './HCdetailDialog.vue'
import itemDetail from '@/views/kzyWMS/components/itemDetail'
import workerLogin from '@/views/kzyWMS/outBound/check/innerCheck/components/workerLogin'
import { upcloud_base_item } from '@/config/serviceSettings'
import detailspilt from '@/views/kzyWMS/outBound/schedule/execute/modules/detailspilt.vue'

export default {
  name: 'Create',
  components: { HCdetailDialog, itemDetail, workerLogin, detailspilt },
  data() {
    return {
      items: null,
      loginVisible: false,
      isSupervisedData: {},
      itemfun: null,
      data: [],
      itemId: '',
      columns: [],
      singleColumns: [],
      singleColumnsEdit,
      singleData: [],
      billid: '',
      loading: false,
      spinning: false,
      record: {},
      billIdList: [],
      selectedRowKeys: [],
      orderPageUrl_TS,
      main_remoteData: {},
      params: {
        url: upcloud_base_item + '/item/page',
        params: {},
        timeout: 30000,
        method: 'post'
      },
      billId: '',
      isShow: 1,
      workercode: '',
      toggleFormTag: true,
      orderModifyData: {},
      itemNum: 0,
      computedNum: 0
    }
  },
  created() {
    this.getAuthByUser()
    this.singleColumns = sorter(singleColumns(this))
    diffOption(itemfun(this)).then(res => {
      this.items = res
      this.$nextTick(() => {
        let branchname = this.$store.getters.warehouse.warehouseName
        let branchid = this.$store.getters.warehouse.warehouseId
        this.$refs.modelForm.form.setFieldsValue({ branchname, branchid })
        // 延时调用,以获取仓库、货主数据
        setTimeout(() => {
          this.getData()
        }, 500)
      })
    })
    diffOption(columns).then(res => {
      this.columns = res
    })
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo
    }
  },
  methods: {
    getCheckboxProps(record) {
      return {
        props: {
          disabled: record.isCancelled == 1,
          name: record.name
        }
      }
    },
    checkSelect(record, selected, selectedRows, nativeEvent) {
      record.selected = selected ? '1' : '0'
    },
    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
          this.$nextTick(() => {
            this.$refs.modelForm.form.setFieldsValue({
              consignorid: res.data.list[0].companyId,
              consignorname: res.data.list[0].companyName
            })
          })
        }
        if (!res.success) {
          this.$exception(res)
          return
        }
      })
    },
    loginResult(data, value) {
      if (!data) {
        this.workercode = value.workercode
        this.loginVisible = data
        this.isShow = 2
      }
    },
    // 明细保存
    saveItemDet(record) {
      const params = {
        ...record
      }
      schedule_saveItem(params).then(res => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    itemDet(data) {
      this.itemId = data.itemid
      this.$refs.detailItem.open()
    },
    getData(params = {}) {
      this.main_remoteData = { ...this.$refs.modelForm.form.getFieldsValue(), ...this.params.params, ...params }
    },
    async HcOrder(data) {
      this.billid = data.billid
      const warehouseId = this.$refs.modelForm.form.getFieldValue('branchid')
      this.isSupervisedData = {
        specialWorkType: '波次红冲',
        warehouseId: warehouseId
      }
      const res = await orderOne({ billid: data.billid, pageNum: 1, pageSize: 10 })
      if (res.success) {
        const { list } = res.data
        this.singleData = list
        this.loginVisible = true
      } else {
        this.$exception(res)
      }
    },
    clickEvent() {
      this.isShow = 1
      this.getData()
    },
    handlerSubmit(event, form) {
      event.preventDefault()
      this.$refs.modelForm.form.validateFields((error, values) => {
        if (!!error) return
        this.getData(values)
      })
    },
    selectChange(selectedRowKeys, selectedRows) {
      this.selectedRows1 = selectedRows
      this.selectedRowKeys = selectedRowKeys
      this.billIdList = selectedRowKeys
    },
    // 计划波次
    planWave() {
      const selectedRowKeys = this.selectedRowKeys
      if (selectedRowKeys.length === 0) return this.$message.error('请至少选择一条数据！')
      const billIdList = selectedRowKeys
      const warehouseId = this.$refs.modelForm.form.getFieldValue('branchid')
      console.log(this.$refs.modelForm.form.getFieldValue('branchid'))
      this.$refs.modelForm.form.validateFields((error, values) => {
        if (!error) {
          if (selectedRowKeys.length < 1) {
            this.$message.error('请至少选择一条数据！')
            return
          }
          this.loading = true
          this.$refs.logTable.vLoading = true
          planWaveCreate_TS({ billIdList, warehouseId }).then(res => {
            this.$refs.logTable.vLoading = false
            this.loading = false
            if (res.success) {
              this.$message.success(res.message)
              this.selectedRowKeys = []
              this.singleData = []
              this.billIdList = []
              this.getData(this.$refs.modelForm.form.getFieldsValue())
            } else {
              this.$exception(res)
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    },
    // 发货暂存
    shipmentStaging() {
      const { selectedRowKeys } = this
      if (selectedRowKeys.length === 0) return this.$message.error('请至少选择一条数据！')
      this.$confirm({
        title: '发货暂存',
        content: '发货暂存将关闭订单，无法再操作，确认是否操作？',
        onOk: () => {
          this.loading = true
          this.$refs.logTable.vLoading = true
          postBilltype(selectedRowKeys).then(res => {
            this.$refs.logTable.vLoading = false
            this.loading = false
            if (res.success) {
              this.$message.success(res.message)
              this.selectedRowKeys = []
              this.singleData = []
              this.billIdList = []
              this.getData(this.$refs.modelForm.form.getFieldsValue())
            } else {
              this.$exception(res)
            }
          })
        },
        onCancel() {
        }
      })
    },
    handleCancel(e) {
      this.visible = false
      this.loginVisible = false
    },
    async clickRow(event, activeID, row) {
      this.$refs.logTable.vLoading = true

      this.spinning = true
      const res = await orderOne_TS({ billid: row.billid, pageNum: 1, pageSize: 100 })
      console.log(res)
      const params = {
        billId: res.data[0]?.billid,
        lineBillId: res.data[0]?.lineid
      }
      redomsItembillQuery(params)
      if (res.success) {
        const { data } = res
        this.singleData = data
      }
      this.spinning = false
      this.$refs.logTable.vLoading = false

    },

    orderModify(data) {
      // console.log(data, "3123123213")
      // return
      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' : '',
        isCaseOrPiece: data.isCaseOrPiece, // 0整散合一, 1整散分开

        billid: data.billid,
        lineid: data.lineid,
        itemcode: data.itemcode,
        lotNo: data.lotNo,
        itemname: data.itemname,
        itemId: data.itemid
      }
      this.orderModifyData = params
      //   console.log(this.orderModifyData, "this.orderModifyDatathis.orderModifyDatathis.orderModifyDatathis.orderModifyData")
    },
    clickEvent2(data) {
      if (data == 'handleOkreplenishment') {
        let status = this.$refs.tablelog.chekTableData()
        if (!status) {
          console.log(this.selectedRows1)
          const data = this.$refs.tablelog.innerData


          for (let i = 0; i < data.length; i++) {
            let rd = data[i]
            if (this.orderModifyData.isCaseOrPiece === 1 && rd.scatteredQty > 0 && rd.completeQty > 0) {
              this.$message.error('商品' + this.orderModifyData.billDId + '整散不可同时录入')
              return false
            }

          }


          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.billid,
                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)
            }
          })
          console.log(params, '123123123params')
          postbillDPrePosition_TS(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>

<style lang='less' scoped>
.extend-title {
  font-size: 14px;

  .extend-title {
    font-size: 14px;
    font-weight: bold;
    padding: 12px 0;
    border-bottom: 1px solid #e8e8e8;
    margin-bottom: 12px;
  }
}
</style>
