<template>
  <div>
    <searchTable
      ref="searchTable"
      v-show="isShow == 1"
      :tableSize="tableSize"
      :title="title"
      :columns="columns"
      :remoteUrl="params"
      :rowKey="rowKey"
      :formItems="setFormItems"
      :tableBtnArray="tableEtraBtns"
      :btnEventArray="btnEventArray"
      :searchColNum="searchColNum"
      :tableAutoLoad="false"
      :isQuery="true"
      @select="tableSelect"
      @clickRow="clickRow"
      @formChange="formChange"
    >
      <div style="margin-top:20px" slot="bottomComponets">
        <p-table
          ref="itemsTable"
          size="small"
          :scroll="{ x: 5200 }"
          :remoteUrl="remoteParams"
          :remoteData="remoteParams.params"
          :remoteParams="remoteParams.params"
          :columns="singleColumns"
          :autoLoad="false"
          :rowSelectType="false"
          rowKey="lineid"
          :pagination="false"
          bordered
        >
          <template slot="action" slot-scope="text, record">
            <a style="margin: 0 5px" @click.stop="itemDet(record)">详情</a>
            <a style="margin: 0 5px" @click.stop="orderModify(record)">库位修改</a>
          </template>
        </p-table>
      </div>
    </searchTable>
    <itemDetail ref="detailItem" :itemId="itemId" />
    <workerLogin :loginVisible="loginVisible" :isSupervisedData="isSupervisedData" @loginResult="loginResult" @handleCancel="handleCancel"></workerLogin>
    <HCdetailDialog v-if="isShow == 2" :billid="billid" @clickEvent="clickEvent"></HCdetailDialog>
      <detailspilt
      v-if="isShow == 3"
      ref="tablelog"
      @clickEvent="clickEvent"
      :orderModifyData="orderModifyData"
      :num="itemNum"
    ></detailspilt>
  </div>
</template>

<script>
// 设置默认仓库
import { columns, singleColumns } from './config/columns'
import { itemfun } from './config/searchItems'
import { getAuthByUser, executeDispatch, postbillDPrePosition, postbillDPrePosition_TS1 } from './api'
import { diffOption } from '@/views/kzyWMS/utils/index.js'
import { sorter } from '@/views/kzyWMS/utils/sort.js'
import searchTable from '../../components/searchTable.vue'
import card from '../../components/card/card.vue'
import itemDetail from '@/views/kzyWMS/components/itemDetail'
import workerLogin from '@/views/kzyWMS/outBound/check/innerCheck/components/workerLogin'
import HCdetailDialog from '@/views/kzyWMS/outBound/schedule/HCdetailDialog.vue'
import detailspilt from '@/views/kzyWMS/outBound/schedule/execute/modules/detailspilt.vue'

import { upcloud_base_wh_outbound } from "@/config/serviceSettings";
import { toPrintServer, tempType } from '@/views/kzyWMS/utils/printServer.js'

export default {
  name: 'InnerCheck',
  // mixins: [setwarehouse],
  components: { searchTable, card, itemDetail, workerLogin, HCdetailDialog, detailspilt },
  data() {
    return {
      params: {
        url: upcloud_base_wh_outbound+'/special-wave/billhpage',
        params: {},
        timeout: 30000,
        method: 'post'
      },
      remoteParams: {
        url: upcloud_base_wh_outbound+'/wave/billdbybillid',
        params: {},
        timeout: 30000,
        method: 'post'
      },
      rowKey: 'billid',
      title: '创建下发',
      tableSize: 'small',
      columns: null,
      singleColumns: sorter(singleColumns),
      setFormItems: itemfun(this),
      selectedRows: [],
      loginVisible: false,
      isSupervisedData: {},
      workercode: '',
      tableEtraBtns: [
        {
          label: '红冲',
          click: data => {
            this.redEvent(data)
          }
        }
      ],
      searchColNum: 3,
      btnEventArray: [
        {
          label: '创建并下发',
          type: 'primary',
          click: () => {
            this.examine()
          }
        },
        {
          label: '打印',
          type: 'primary',
          click: () => {
            this.outercheckhPrint()
          }
        }
      ],
      isShow: 1,
      itemId: '',
      billId:'',
      orderModifyData: {},
      rowRecord: {},
      computedNum: 0,
      itemNum: 0
    }
  },
  created() {
    diffOption(columns).then(res => {
      this.columns = sorter(res)
    })
    this.getAuthByUser()
  },
  mounted() {
    let branchname = this.$store.getters.warehouse.warehouseName
    let branchid = this.$store.getters.warehouse.warehouseId
    this.$refs.searchTable.$refs.searchForm.$refs.formTarget.form.setFieldsValue({
      branchname: branchname,
      branchid: branchid
    })
  },
  computed: {},
  methods: {
    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(() => {
            console.log(this.$refs.searchTable.$refs.searchForm)
            this.$refs.searchTable.$refs.searchForm.$refs.formTarget.form.setFieldsValue({
              consignorid: res.data.list[0].companyId,
              consignorname: res.data.list[0].companyName
            })
          })
        }
        if (!res.success) {
          this.$exception(res)
          return
        }
      })
    },
    formChange(event, value, rowData, form, name) {},
    redEvent(data) {
      this.billid = data.billid
      const warehouseId = this.$refs.searchTable.$refs.searchForm.$refs.formTarget.form.getFieldValue('branchid')
      this.isSupervisedData = {
        specialWorkType: '波次红冲',
        warehouseId: warehouseId
      }
      this.loginVisible = true
    },
    clickEvent() {
      this.isShow = 1
      this.$refs.searchTable.tableReload()
    },
    examine() {
      if(this.selectedRows.length < 1) {
        this.$message.error('请至少选择一条数据！')
        return
      }
      let list = this.selectedRows.reduce((prev,currentValue,currentIndex,arr) =>{ prev.push(currentValue.billid); return prev;},[])
      const warehouseId = this.$refs.searchTable.$refs.searchForm.$refs.formTarget.form.getFieldsValue().branchid
      const params = {
        billIdList: list,
        warehouseId: warehouseId,
      }
      executeDispatch(params).then(res => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.$message.success(res.message)
        this.selectedRows = []
        this.$refs.searchTable.tableReload()
      })
    },
    loginResult(data, value) {
      if (!data) {
        ;(this.workercode = value.workercode), (this.loginVisible = data)
        this.isShow = 2
      }
    },
    orderModify(data) {
      console.log(data)
      this.isShow = 3
      this.itemNum = data.itemQty
      this.computedNum = data.itemQty
      const params = {
        warehouseId: this.rowRecord.branchid,
        cargoOwnerId: this.rowRecord.consignorid,
        billId: data.billid,
        billDId: data.billDId,
        itemId: data.itemid,
        manufacturerLotNum: data.lotNo,
        status: data.stockStatus ? data.stockStatus : '',
        subStatus: this.rowRecord.billtype == '7' ? '3' : ''
      }
      this.orderModifyData = params
    },
    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.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, 'paramsparamsparamsparamsparams')
          postbillDPrePosition_TS1(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
      }
    },
    handleCancel(e) {
      this.loginVisible = false
    },
    clickRow(event, activeID, rowRecord) {
      console.log(rowRecord,'rowRecordrowRecordrowRecord')
      this.rowRecord = rowRecord
      let params = {
        billid: rowRecord.billid,
        pageNum: 1,
        pageSize: 100
      }
      this.$refs.itemsTable.reload({ params: params })
    },
    itemDet(data) {
      this.itemId = data.itemid
      this.$refs.detailItem.open()
    },
    tableSelect(record, selected, selectedRows, nativeEvent) {
      this.selectedRows = selectedRows
    },
    outercheckhPrint() {
      if(this.selectedRows.length < 1) {
        this.$message.error('请至少选择一条数据！')
        return
      }
      let srcCodes = this.selectedRows.reduce((current,item)=> {
        current.push(item.billno)
        return current
      },[])
      const warehouseId = this.$store.getters.warehouse.warehouseId
      outerPapersliphPrint({ srcCodes,warehouseId }).then(res=> {
        if (!res.success) {
          this.$exception(res)
          return
        }
        let printdata = []
        res.data.forEach(item =>{
            item.data.forEach(items => {
              printdata.push(items)
            })
          })
        toPrintServer(printdata, warehouseId, tempType.wfhcd).then(res => {
          if (!res.success) {
            this.$exception(res)
            return
          }
          this.$message.success(res.message);
        })
        this.$message.success(res.message);
        this.$refs.searchTable.tableReload()
        this.selectedRows = []
      })

    }
  }
}
</script>
