<template>
  <div>
    <div>
      <p-card title="容器上架">
        <a-row>
          <a-col :span="12">
            <div>
              <p-grid-form ref="itemForm" :disableItem="disableItem" :items="formItems"> </p-grid-form>
            </div>
            <a-row :gutter="[16, 16]" style="margin: 20px">
              <a-col :span="11">
                <!-- <img width="50%" height="100px" src="/img/盒子.png" alt="" /> -->
                <viewer :images="photo" class="imgPhoto">
                  <template v-for="(src, index) in photo">
                    <img :class="index > 0 ? 'oneclass' : 'othersclass'" :src="src" :key="index" />
                  </template>
                </viewer>
              </a-col>
              <a-col class="inPalletLocationClass" :span="11">
                <!-- <p-button :size="size" type="primary" style="margin-left: 20px" class="group-btn-b" @click="numberA">
                  -10
                </p-button>
                <p-button :size="size" type="primary" style="margin-left: 15px" class="group-btn-b" @click="numberB">
                  -1
                </p-button>
                <p-button :size="size" type="primary" style="margin-left: 15px" class="group-btn-b" @click="numberC">
                  +10
                </p-button>
                <p-button :size="size" type="primary" style="margin-left: 15px" class="group-btn-b" @click="numberD">
                  +1
                </p-button> -->
                <div class="input-a" style="margin-top: 10px; font-weight: bold; color: red">
                  * {{ selectLabel }}
                  <!-- <p-select class="input-b" v-model="inPalletLocation" placeholder="确认货位" /> -->
                  <a-auto-complete
                    ref="completeDate"
                    :data-source="completeDate"
                    v-model="inPalletLocation"
                    style="width: 200px"
                    placeholder="请输入货位编码"
                    @select="completeSelect"
                    @change="completeChange"
                    :filter-option="filterOption"
                  />
                </div>
                <div class="testName">
                  {{ message }}
                </div>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="12">
            <div class="num">
              <span class="abcType">{{ abc }}</span>
              <span>{{ number }}/{{ sumCount }}</span>
            </div>
            <img-list :list="imgList"></img-list>
          </a-col>
        </a-row>

        <div class="group-btn btnClass">
          <!-- <p-checkbox @change="onChange" :disabled="inPalletLocation =='XN0001'" :checked="checked" style="margin-left: 20px"> {{ checkName }}</p-checkbox> -->
          <!-- <div class="btnClass"> -->
          <!-- <a href="/inBound/pendingOrders">
              <p-button type="primary" class="group-btn-a" >
                任务解挂
              </p-button>
            </a> -->
          <!-- <p-button type="primary" class="group-btn-a" @click="taskUp"> 任务挂起 </p-button> -->
          <p-button type="primary" class="group-btn-a" :disabled="confirmationStatus" @click="goodsAbcTypeconfirm">
            上架确认
          </p-button>
          <p-button type="primary" class="group-btn-a" @click="returnShelves"> 归还货架 </p-button>
          <!-- </div> -->
        </div>
        <a slot="extra" href="#">
          <p-button type="primary" style="margin-left: 10px" @click="reallocate"> 重新分配 </p-button>
          <p-button type="primary" style="margin-left: 10px" @click="usableCheck"> 货位修改 </p-button>
        </a>
      </p-card>
    </div>
    <div>
      <p-modal
        title="货位修改"
        :width="1000"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <div>
          <p-grid-form :span="8" ref="palletNoItems" :items="palletNoItems" @submit="palletNoItemsSubmit">
          </p-grid-form>
          <p-table
            ref="logTable"
            style="margin-top: 10px"
            :columns="tableColumns"
            rowKey="_id"
            :expandRowByClick="false"
            :dataSource.sync="dataSource"
            :loading="tabLoding"
            :rowSelectType="1"
            @selectChange="locationChange"
            @dblclickRow="positionDblclickRow"
            :hasRowSelectCheck="true"
            dragle
            auto-width
            bordered
          >
          </p-table>
        </div>
      </p-modal>
    </div>

    <div>
      <p-modal
        title="AGV上架任务选择"
        :width="1350"
        :visible="visible1"
        :confirm-loading="confirmLoading1"
        @ok="handleOk1"
        @cancel="handleCancel1"
      >
        <div>
          <p-grid-form :span="8" ref="goodsItems" :items="goodsItems" @submit="goodhanlderSubmit"> </p-grid-form>
          <p-table
            ref="modalTable"
            style="margin-top: 10px"
            :columns="containerColumns"
            rowKey="taskId"
            :expandRowByClick="false"
            :dataSource.sync="containerData"
            :loading="containerLoding"
            :rowSelectType="1"
            @selectChange="selectChange"
            @dblclickRow="dblclickRow"
            :hasRowSelectCheck="true"
            dragle
            auto-width
            bordered
          >
          </p-table>
        </div>
      </p-modal>
    </div>

    <div>
      <p-modal
        title="重新分配货位"
        :width="1000"
        :visible="visibleAllocation"
        :confirm-loading="conAllocation"
        @ok="allocationOk"
        @cancel="allocationCancel"
        :footer="null"
        :destroyOnClose="true"
      >
        <div>
          <p-grid-form :span="8" ref="allocationForm" :items="allocationItems" @submit="hanlderSubmit"> </p-grid-form>
          <p-table
            ref="allocationTable"
            style="margin-top: 10px"
            :columns="allocationColumns"
            rowKey="palletLocation"
            :expandRowByClick="false"
            :remoteUrl="remoteUrl"
            :remoteParams="remoteData"
            :remoteData="remoteData"
            :loading="allocationLoding"
            :rowSelectType="1"
            @checkRow="allocationChange"
            dragle
            auto-width
            bordered
          >
          </p-table>
        </div>
      </p-modal>
    </div>
  </div>
</template>
<script>
import {
  formItems,
  goodsItems,
  tableColumns,
  containerColumns,
  allocationItems,
  allocationColumns,
  palletNoItems,
  taskSchedulingFun,
} from './js/config'
import {
  getInboundTasks,
  inboundConfirm,
  taskHangUp,
  autoCallRcs,
  getAvailableLocation,
  getOneInboundTask,
  updateGoodsAllocation,
  containerNoReturn,
  getContainerNoInfo,
  adjustmentLocation,
  autoAllocation,
  getInventLocation,
  queryConfirmABC,
  queryImages,
  getContainer,
  checkStation,
  getPallet,
} from './api'
import imgList from '../components/imagelist'
// import { taskSchedulingFun } from '@/utils/util'
import 'viewerjs/dist/viewer.css'
import VueViewer from 'v-viewer'
import Vue from 'vue'
import { QN_BASEURL } from '../serviceSettings'
const baseUrl = QN_BASEURL
Vue.use(VueViewer)
const imgs = ['/img/盒子.png', '/img/盒子1.png', '/img/盒子2.png']
export default {
  components: {
    'img-list': imgList,
    // 'p-viewer': VueViewer,
  },
  data() {
    return {
      formItems: formItems(this),
      goodsItems: goodsItems(this),
      palletNoItems: palletNoItems(this),
      // disableItem: [],
      disableItem: [
        // 'goodsBarcode',
        // 'goodsName',
        // 'stateDescription',
        // 'prodArea',
        // 'goodsOwnerName',
        // 'goodsType',
        // 'goodsShelves',
        // 'lotNo',
        // 'goodsAllocation',
        // 'qty',
        // 'approveDocNo',
        // 'taskId',
        // 'prodDate',
        // 'validDate',
        // 'goodsBigTypeStr',
        // 'goodsOwnId',
      ],
      size: 'large',
      selectLabel: '上架货位编码',
      checkName: ' 自动叫车',
      message: '请扫描站台',
      number: 0,
      sumCount: 0,
      checked: true,
      inPalletLocation: '',
      completeDate: [],
      realityQty: 0,
      isClock: 0,
      visible: false,
      confirmLoading: false,
      tableColumns: tableColumns,
      dataSource: [],
      tabLoding: false,
      shelves: '',
      timer: null,
      visible1: false,
      confirmLoading1: false,
      containerData: [],
      containerColumns: containerColumns,
      containerLoding: false,
      selectedRows: {},
      // imgPhoto:[],
      photo: ['/img/盒子.png', '/img/盒子1.png', '/img/盒子2.png'], //预览图
      imgList: {},
      isArrive: 0,
      locationRow: {},
      taskState: {
        step: 0,
        currentMassage: '',
        stateArray: [
          {
            step: 0,
            massage: '',
            stateCode: '',
            title: '已获取站台信息',
            executeFun: '',
          },
        ],
      },
      visibleAllocation: false,
      conAllocation: false,
      allocationLoding: false,
      allocationItems: allocationItems(this),
      allocationColumns: allocationColumns,
      allocationData: [],
      allocationRow: [],
      positionRowSelectCheck: false,
      remoteUrl: {
        url: baseUrl + '/api/v1/inbound/findNewPalletNo',
        method: 'post',
      },
      remoteData: {},
      abc: '',
      timeOne: null,
      wareGoodsId: '',
      imgs,
      stationNo: '',
      taskSchedulingFun: null,
      confirmationStatus: false,
    }
  },
  created() {
    // this.getOption()
    // this.imgPhoto = this.photo[0]
    this.disableItemFun()
  },
  mounted() {
    //定位光标
    this.focusFun('stationNo')
    // 生成定时任务实例
    this.taskScheduling = taskSchedulingFun('api', {}, 3000)
  },
  destroyed() {
    clearInterval(this.timer)
  },
  watch: {
    realityQty: function (newVal, oldVal) {
      let qty = +this.$refs.itemForm.form.getFieldsValue().qty
      if (newVal > qty) {
        this.$message.error(this.$lang('上架数量不能大于数量'))
      }
    },
    // inPalletLocation: {
    //   handler(val) {
    //     if (val == 'XN0001') {
    //       this.checked = false
    //       this.onChange('', 'XN')
    //       this.$nextTick(() => {
    //         this.$refs.allocationForm.form.setFieldsValue({ goodsAllocation: '', goodsShelves: '' })
    //       })
    //     }
    //   },
    // },
    // wareGoodsId: {
    //   handler(val) {
    //     const wareGoodsId = val
    //     queryImages({ wareGoodsId }).then((res) => {
    //       if (res.success) {
    //         if (res.data && res.data.length > 0) {
    //           this.photo = res.data
    //         } else {
    //           this.photo = imgs
    //         }
    //       }
    //     })
    //   },
    // },
  },
  methods: {
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////勾选逻辑
    //货架修改
    locationChange(selectedRowKeys, selectedRows) {
      this.locationRow = selectedRows
      console.log(selectedRows, 'selectedRows11111111111')
    },
    //选择商品编码逻辑
    selectChange(selectedRowKeys, selectedRows) {
      // 勾选框
      this.selectedRows = selectedRows
      // this.selectedRowKeys = selectedRowKeys
    },
    // 货架重新分配逻辑
    allocationChange(selectedRowKeys, selectedRows) {
      // 勾选框
      this.allocationRow = selectedRows
      console.log(selectedRowKeys, selectedRows, 'allocationChange')
    },

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////主流程逻辑

    //////////////////////////////////////////////定时器逻辑
    polling(params, type) {
      //data接口参数
      //type 轮询调用类型
      getOneInboundTask(params)
        .then((res) => {
          console.log('测试是否执行')
          this.message = res.message
          //请求失败
          if (!res.success) {
            //接口失败停止定时任务
            this.taskScheduling('end')
            return
          }
          //状态码 200 停止调用
          if (res.code == '200') {
            this.taskScheduling('end')
            //填充主表单数据
            this.$refs.itemForm.form.setFieldsValue(res.data.results[0])
            //填充右边图片数据
            this.imgList = this.arraySort(res.data.palletLocationList)
            console.log(this.abc, 'this.abc')
            return
          }
        })
        .catch((error) => {
          //接口异常停止定时任务
          this.taskScheduling('end')
        })
    },
    pollings(params, type) {
      getOneInboundTask(params)
        .then((res) => {
          console.log('测试是否执行')
          this.message = res.message
          //请求失败
          if (!res.success) {
            //接口失败停止定时任务
            return
          }
          //状态码 200 停止调用
          if (res.code == '200') {
            //填充主表单数据
            this.$refs.itemForm.form.setFieldsValue(res.data.results[0])
            //填充右边图片数据
            this.imgList = this.arraySort(res.data.palletLocationList)
            this.abc = res.data.results[0].abcType
            return
          }
          this.pollings(params, type)
        })
        .catch((error) => {})
    },
    ///////////////////////////////////////////输入框扫码逻辑

    //扫码站台号
    stationNoEnter() {
      const params = this.$refs.itemForm.form.getFieldsValue()
      var num = 0
      // if (!REGEX_letter(params.stationNo)) {
      //   this.$message.error('请输入大写字母！')
      //   return
      // }
      checkStation({ stationNo: params.stationNo }).then((res) => {
        if (res.code === '200') {
          this.$message.success(this.$lang('验证通过'))
          this.stationNo = params.stationNo
          this.$refs.itemForm.$refs.list.$refs.containerNo.$el.querySelector('input').focus()
          this.message = '请扫描容器号/商品条码'
          if (!res.data) {
            return
          }
          this.$refs.itemForm.form.setFieldsValue(res.data.results[0])
          this.abc = res.data.results[0].abcType
          this.wareGoodsId = res.data.results[0]?.wareGoodsId
          console.log(this.wareGoodsId)
          this.sumCount = res.data.results[0].sumCount
          this.number = res.data.results[0].currentCount
          if (!res.data.containerList) {
            num = 1
            const tt = this.$refs.itemForm.form.getFieldsValue()
            if (num === 1) {
              let data = [tt]
              // this.taskScheduling('start',this.polling,data,'scanCodeItem')
              this.pollings(data)
              // this.timer = setInterval(() => {
              //   this.timerTask([tt])
              // }, 2000)
            } else {
              // clearInterval(this.timer)
            }
            return
          }
          num = 2
          this.imgList = this.arraySort(res.data.containerList)
          this.message = '请确认货位'
          return
        } else if (res.code === '201') {
          this.$message.error(this.$lang(res.message))
          this.$refs.itemForm.form.setFieldsValue({ stationNo: '' })
        }
      })
    },
    //扫描容器
    containerNoEnter() {
      const params = this.$refs.itemForm.form.getFieldsValue()
      getContainer({
        stationNo: params.stationNo,
        containerNo: params.containerNo,
      }).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return false
        }
        this.message = '请扫描商品/容器条码'
        this.$message.success(this.$lang(res.message))
      })
    },
    //扫描商品编码
    barCodeEnter() {
      const params = this.$refs.itemForm.form.getFieldsValue()
      this.reset()
      if (!params.stationNo) {
        this.$message.error(this.$lang('请输入站台号'))
        return
      }
      const data = {
        stationNo: params.stationNo,
        containerNo: params.containerNo,
        itemCode: params.itemCode,
      }
      getInboundTasks(data).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return
        }
        if (!res.data) {
          this.$message.error(res.message)
          return
        }
        // this.sumCount = res.data.results.length
        // this.number +=1
        this.message = res.message
        // res.data.results[0].stationNo = params.stationNo
        // this.shelves = res.data.results[0].goodsShelves
        if (res.data.results.length > 1) {
          this.visible1 = true
          this.containerData = res.data.results
        } else {
          // sumCount   currentCount
          this.sumCount = res.data.results[0].sumCount
          this.number = res.data.results[0].currentCount
          this.abc = res.data.results[0].abcType
          this.$refs.itemForm.form.setFieldsValue(res.data.results[0])
          this.imgList = this.arraySort(res.data.palletLocationList)
          if (res.code == '301') {
            const params = res.data.results
            // this.taskScheduling('start',this.polling,params,'scanCodeItem')
            this.pollings(params)
          }

          // if (this.isArrive === 0) {
          //   this.timer = setInterval(() => {
          //     this.timerTask(res.data.results)
          //   }, 2000)
          // } else {
          //   this.sumCount = res.data.results[0].sumCount
          //   this.number = res.data.results[0].currentCount
          //   res.data.results[0].containerNo = res.data.results[0].goodsBarcode
          //   this.$refs.itemForm.form.setFieldsValue(res.data.results[0])
          //   this.imgList = this.arraySort(res.data.palletLocationList)
          //   clearInterval(this.timer)
          // }
        }
        this.message = res.message
      })
    },

    ///////////////////////////////////////////非扫码逻辑
    //商品abc
    async goodsAbcTypeconfirm() {
      if (!this.inPalletLocation) {
        this.$message.error(this.$lang('请确认货位再进行上架确认'))
        return
      }
      if (!this.checked) {
        this.confirmation()
        return
      }
      let inPalletLocation = this.inPalletLocation.trim()
      const params = this.$refs.itemForm.form.getFieldsValue()
      let res = await queryConfirmABC({
        bizPropertyId: params.bizPropertyId,
        palletNo: params.palletNo,
        abcType: this.abc,
        palletLocation: inPalletLocation,
      })
      var that = this
      if (!res.success) {
        this.$message.error(res.message)
        return false
      }
      if (res.data <= 0) {
        this.$confirm({
          title: '所选货位与货架ABC属性不符,是否确认上架？',
          okText: '是',
          cancelText: '否',
          onOk() {
            that.confirmation()
            return
          },
          onCancel() {
            return
          },
        })
      } else {
        this.confirmation()
      }
    },

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////非流程操作

    ////////////////////////////////右上方按钮逻辑
    //选择上架商品
    handleOk1(e) {
      this.confirmLoading1 = true
      this.isArrive = 0
      console.log(this.isArrive, this.selectedRows, '上架弹框确认')
      if (this.selectedRows.length < 1) {
        this.$message.warning(this.$lang('请先选择需要上架的货位'))
        return
      }
      // this.timer = setInterval(() => {
      //   this.confirmLoading1 = false
      // }, 2000)
      this.$nextTick(() => {
        this.$refs.goodsItems.form.resetFields()
        this.visible1 = false
      })
      this.confirmLoading1 = false
      var rows = this.selectedRows[0]
      this.$refs.itemForm.form.setFieldsValue(rows)
      this.abc = rows.abcType
      this.wareGoodsId = rows?.wareGoodsId
      clearInterval(this.timer)
      if (this.isArrive === 0) {
        // this.setIntervalTask(this.selectedRows)
        // this.taskScheduling('start',this.polling,this.selectedRows,'scanCodeStationNo')
        this.pollings(this.selectedRows)
        // this.timer = setInterval(() => {
        //   this.timerTask(this.selectedRows)
        // }, 2000)
      } else {
        // clearInterval(this.timer)
      }
    },
    //选择上架商品查询
    goodhanlderSubmit(e, form) {
      e.preventDefault()
      const params = this.$refs.goodsItems.form.getFieldsValue()
      const params1 = this.$refs.itemForm.form.getFieldsValue()
      const data = {
        pageNum: 1,
        data: {
          ...params1,
          ...params,
        },
      }
      getInboundTasks(data).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return false
        }
        this.containerData = res.data.results
        res.data.list.forEach((t) => {
          this.message = res.message
          if (t.taskState != 10) {
            t.realityQty = t.qty
            this.$refs.itemForm.form.setFieldsValue(t)
          }
        })
      })
    },
    //重新分配弹窗弹出
    reallocate() {
      this.allocationData = []
      const params = this.$refs.itemForm.form.getFieldsValue()
      const data = {
        bizPropertyId: params.bizPropertyId,
        itemHealthCategory: params.itemHealthCategory,
        stationNo: params.stationNo,
        itemId: params.goodsId,
        lotId: params.lotId,
        ownerId: params.ownerId,
        locationType: params.locationType,
        abcType: params.abcType,
      }
      if (!params.stationNo) {
        this.$message.warning(this.$lang('请先输入站台号'))
        return
      }
      this.visibleAllocation = true
      delete params.goodsShelves
      this.remoteData = data
    },
    //重新分配查询数据
    hanlderSubmit(e, form) {
      e.preventDefault()
      const params = this.$refs.itemForm.form.getFieldsValue()
      // this.remoteUrl.data.isHangUp = 40
      console.log(params, 'params')
      const data = {
        bizPropertyId: params.bizPropertyId,
        itemHealthCategory: params.itemHealthCategory,
      }
      const qyeryparams = this.$refs.allocationForm.form.getFieldsValue()
      this.remoteData = { ...this.remoteData, ...data, ...qyeryparams }
      // getContainerNoInfo(params).then((res) => {
      //   if (!res.success) {
      //     this.$message.error(res.message)
      //     return false
      //   }
      //   this.allocationData = res.data.list.map((tt) => ({ ...tt, _id: Math.random() + '' }))
      // })
    },
    //调整确认
    adjustment() {
      console.log(this.allocationRow, 'this.allocationRow')
      if (this.allocationRow.length < 1) {
        this.$message.warning(this.$lang('请先选择需要调整的货位'))
        return
      }
      const values = this.$refs.itemForm.form.getFieldsValue()
      const params = {
        oldLocationType: values.locationType,
        newLocationType: this.allocationRow[0].locationType,
        stationNo: values.stationNo,
        oldPalletNo: values.palletNo,
        newPalletNo: this.allocationRow[0].palletNo,
        planes: this.allocationRow[0].planes,
        taskId: values.taskId,
        palletLocation: this.allocationRow[0].palletLocation,
        itemHealthCategory: values.itemHealthCategory,
      }
      adjustmentLocation(params).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return false
        }
        this.$message.success(this.$lang('调整成功'))
        this.visibleAllocation = false
        this.$refs.itemForm.form.setFieldsValue({
          palletLocation: this.allocationRow[0].palletLocation,
        })
        this.imgList = {}
        const getParams = [this.$refs.itemForm.form.getFieldsValue()]
        console.log(getParams, 'params')
        // this.taskScheduling('start',this.polling,getParams,'scanCodeItem')
        this.pollings(getParams)

        // if (getParams.goodsShelves == '') {
        //   this.timer = setInterval(() => {
        //     this.timerTask([getParams])
        //   }, 2000)
        // } else {
        //   clearInterval(this.timer)
        // }
      })
    },

    //查询修改货位接口

    // 货位修改查询和弹窗弹出
    usableCheck() {
      const params = this.$refs.itemForm.form.getFieldsValue()
      console.log(params)
      getAvailableLocation({
        stationNo: params.stationNo,
        pageSize: 200,
        pageNum: 1,
        palletNo: params.palletNo,
        bizPropertyId: params.bizPropertyId,
      }).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return false
        }
        if (!res.data) {
          this.$message.warning(this.$lang('没有可以修改的货位信息'))
          return
        }
        this.dataSource = res.data.list.map((tt) => ({ ...tt, _id: 'a' + Math.random() }))
        this.visible = true
      })
    },
    palletNoItemsSubmit(e, form) {
      e.preventDefault()
      const params = this.$refs.itemForm.form.getFieldsValue()
      const formParams = this.$refs.palletNoItems.form.getFieldsValue()
      getAvailableLocation({
        stationNo: params.stationNo,
        pageSize: 200,
        pageNum: 1,
        palletNo: params.palletNo,
        bizPropertyId: params.bizPropertyId,
        ...formParams,
      }).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return false
        }
        if (!res.data) {
          this.$message.warning(this.$lang('没有可以修改的货位信息'))
          return
        }
        this.dataSource = res.data.list.map((tt) => ({ ...tt, _id: 'a' + Math.random() }))
      })
    },
    // 货位修改弹框确认
    handleOk(e) {
      this.confirmLoading = true
      const values = this.$refs.itemForm.form.getFieldsValue()
      this.$refs.itemForm.form.setFieldsValue({ realityQty: 0 })
      this.$refs.itemForm.form.setFieldsValue({ tuiJian: this.locationRow[0].tuiJian })
      console.log(this.locationRow, 'locationRow')
      let { palletLocation } = values
      updateGoodsAllocation({
        stationNo: values.stationNo,
        palletNo: values.palletNo,
        planes: this.locationRow[0].planes,
        palletLocation: this.locationRow[0].palletLocation,
        oldPalletLocation: palletLocation,
        taskId: values.taskId,
      }).then((res) => {
        this.confirmLoading = false
        if (!res.success) {
          this.$message.error(res.message)
          return false
        }
        // this.imgList = this.arraySort(res.data)
        this.$refs.itemForm.form.setFieldsValue({
          palletLocation: this.locationRow[0].palletLocation,

          //   palletLocation
        })
        this.inPalletLocation = this.locationRow[0].palletLocation
        let params = [this.$refs.itemForm.form.getFieldsValue()]
        this.visible = false
        // this.taskScheduling('start',this.polling,params,'scanCodeItem')
        this.pollings(params)
        this.$message.success(this.$lang('货位修改成功'))
      })
    },
    // 货位修改弹框关闭
    handleCancel(e) {
      this.visible = false
    },
    // 货位调整弹框关闭
    allocationCancel(e) {
      this.visibleAllocation = false
    },
    // 商品弹框关闭
    handleCancel1(e) {
      this.$nextTick(() => {
        this.$refs.goodsItems.form.resetFields()
        this.visible1 = false
      })
    },
    //////////////////////////////////////////////////////下方按钮逻辑

    // 上架确认
    confirmation() {
      const params = this.$refs.itemForm.form.getFieldsValue()
      let data = [params]
      console.log(this.inPalletLocation, this.completeDate, 'this.inPalletLocation')
      // ||  || params.containerNo === ''
      // if (this.inPalletLocation === '') {
      //   this.$message.error(this.$lang('请确认货位再进行上架确认'))
      //   return
      // }
      params.inPalletLocation = this.inPalletLocation

      params.abcType = this.abc
      this.confirmationStatus = true
      inboundConfirm(params)
        .then((res) => {
          this.confirmationStatus = false
          if (!res.success) {
            this.$message.error(res.message)
            return false
          }
          this.message = res.message
          if (res.code !== '200') {
            this.getOption()
          }
          // const params = res.data.results
          if (res.code === '200') {
            this.$message.success('上架成功')
            // this.reset()
            this.abc = ''
            // this.taskScheduling('start',this.polling,data,'confirmation')
            // this.timeOne = setInterval(() => {
            //   getOneInboundTask([params]).then((tt) => {
            //     if (!tt.success) {
            //       this.reset()
            //       this.$exception(tt)
            //       clearInterval(this.timeOne)
            //       this.timeOne = null
            //       return false
            //     }
            //     this.message = tt.message
            //     if (tt.code == '201' || tt.code == '200') {
            //       clearInterval(this.timeOne)
            //       this.timeOne = null
            //     }
            //     //上架商品全部上架完成
            //     if (!tt.data) {
            //       this.reset()
            //       return
            //     }
            //     if (!tt.data.containerList) {
            //       this.imgList = []
            //     }
            //     this.$refs.itemForm.form.setFieldsValue(tt.data.results[0])
            //     this.abc = tt.data.results[0].abcType
            //     this.imgList = this.arraySort(tt.data.containerList)
            //     // this.inPalletLocation = ''
            //     this.completeDate = []
            //     this.getOption()
            //     this.focusFun('containerNo')
            //     this.onChange()
            //     this.wareGoodsId = res.data.results[0]?.wareGoodsId
            //   })
            // }, 2000)
          } else if (res.code === '201') {
            // this.taskScheduling('start',this.polling,data,'confirmation')
            this.pollings(data)
          } else if (res.code === '202') {
            this.$message.success(res.message)
            this.imgList = {}
            let tt = this.$refs.itemForm.form.getFieldsValue()
            tt.goodsShelves = ''
            tt.goodsAllocation = ''
            this.inPalletLocation = ''
            if (!res.data) {
              //  this.taskScheduling('start',this.polling,data,'confirmation')
              this.pollings(data)
              // this.timer = setInterval(() => {
              //   this.timerTask([tt])
              // }, 2000)
            } else {
              // this.taskScheduling('end')
              // clearInterval(this.timer)
            }
          } else if (res.code === '203') {
            var that = this
            this.$confirm({
              title: '当前商品大类有任务未完成，是否归还货架？',
              okText: '是',
              cancelText: '否',
              onOk() {
                // setTimeout(Math.random() > 0.5 ? resolve : reject, 1000)
                that.returnShelves()
                return
              },
              onCancel() {
                getOneInboundTask([params]).then((tt) => {
                  if (!tt.success) {
                    that.reset()
                    that.$exception(tt)
                    return false
                  }
                  if (!tt.data.containerList) {
                    that.imgList = {}
                  }
                  that.$refs.itemForm.form.setFieldsValue(tt.data.results[0])
                  that.abc = res.data.results[0].abcType
                  that.wareGoodsId = res.data.results[0].wareGoodsId
                  that.imgList = that.arraySort(tt.data.containerList)
                  that.inPalletLocation = ''
                  that.completeDate = []
                  console.log(that.completeDate, 'that.completeDate')
                  // that.getOption()
                  that.$message.success(that.$lang('上架成功'))
                  that.focusFun('containerNo')
                  that.message = '请扫描容器号/商品条码'
                })
              },
            })
          } else if (res.code == '204') {
            this.$message.success(res.message)
            this.imgList = {}
            // this.taskScheduling('start',this.polling,data,'confirmation')
            this.pollings(data)
          }
        })
        .catch((error) => {
          this.confirmationStatus = true
        })
    },
    // 挂起
    taskUp() {
      const params = this.$refs.itemForm.form.getFieldsValue()
      if (!params.stationNo) {
        this.$message.warning(this.$lang('请先输入站台号'))
        return false
      }
      let data = {
        stationNo: params.stationNo,
        taskId: params.taskId,
        palletNo: params.palletNo,
        // isHangUp: 40, //挂起40
      }
      taskHangUp(data).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return false
        }
        this.$message.success(this.$lang('挂起成功'))
        this.reset()
        this.$refs.itemForm.form.setFieldsValue({ stationNo: params.stationNo })
        this.focusFun('containerNo')
      })
    },
    //归还货架
    returnShelves() {
      const params = this.$refs.itemForm.form.getFieldsValue()
      if (!params.stationNo) {
        this.$message.error('请输入站台号')
        return
      }
      if (!params.palletNo) {
        this.$message.error('请输入货架号')
        return
      }
      containerNoReturn({
        stationNo: params.stationNo,
        locationType: params.locationType,
        palletNo: params.palletNo,
        itemHealthCategory: params.itemHealthCategory,
      }).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return false
        }
        this.reset()
        // this.onChange()
        this.message = '请扫描商品/容器条码'
        this.$message.success(this.$lang(res.message))
        if (res.code == 200) {
          // this.getPallet(params)
        }
        return true
      })
    },
    getPallet(parmas) {
      getPallet(parmas).then((res) => {
        if (res.success) {
          if (res.code != 200) {
            this.getPallet(parmas)
          }
        }
      })
    },

    //商品条码弹框双击选择
    dblclickRow(event, activeID, rowRecord) {
      this.addSelect(rowRecord)
      console.log(event, activeID, rowRecord, 'rowRecord')
    },
    //货位修改双击选择
    positionDblclickRow(event, activeID, rowRecord) {
      // this.positionRowSelectCheck = true
      // this.position(rowRecord)
      // console.log(event, activeID, rowRecord, 'rowRecord')
    },
    //暂时废弃
    //货位双击选择
    position(rowRecord) {
      const values = this.$refs.itemForm.form.getFieldsValue()
      updateGoodsAllocation({
        oldGoodsShelves: values.goodsAllocation,
        newGoodsShelves: rowRecord.shelveLocation,
      }).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return false
        }
        this.imgList = this.arraySort(res.data)
        this.$refs.itemForm.form.setFieldsValue({
          goodsAllocation: rowRecord.shelveLocation,
        })
        this.visible = false
        this.$message.success(this.$lang('货位修改成功'))
      })
    },
    addSelect(rowRecord) {
      this.isArrive = 0
      console.log(this.isArrive, rowRecord, '上架弹框确认')
      this.visible1 = false
      this.confirmLoading1 = false
      this.$refs.itemForm.form.setFieldsValue(rowRecord)
      clearInterval(this.timer)
      if (this.isArrive === 0) {
        this.timer = setInterval(() => {
          this.timerTask([rowRecord])
        }, 2000)
      } else {
        clearInterval(this.timer)
      }
    },

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////通用方法逻辑

    //获取货位select
    getOption() {
      const { stationNo, containerNo } = this.$refs.itemForm.form.getFieldsValue()
      const params = {
        stationNo,
        containerNo,
      }
      getInventLocation(params).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return false
        }
        this.completeDate = res.data
        console.log(this.completeDate, '111111111')
      })
    },

    //禁用输入框方法
    disableItemFun() {
      formItems().forEach((item) => {
        if (
          item.name !== 'stationNo' &&
          item.name !== 'containerNo' &&
          item.name !== 'itemCode' &&
          item.name !== 'inQty' &&
          item.name !== 'palletNo'
        ) {
          this.disableItem.push(item.name)
        }
      })
    },
    //清空数据逻辑
    reset() {
      const params = this.$refs.itemForm.form.getFieldsValue()
      this.$refs.itemForm.form.resetFields()
      this.imgList = {}
      this.number = 0
      this.sumCount = 0
      this.inPalletLocation = ''
      this.$refs.itemForm.form.setFieldsValue({ stationNo: this.stationNo })
      this.isArrive = 0
      this.abc = ''
      this.photo = imgs
      this.wareGoodsId = ''
    },
    //光标跳转逻辑
    focusFun(data) {
      if (!data) return
      this.$nextTick(() => {
        if (data == 'completeDate') {
          this.$refs.completeDate.$el.querySelector('input').focus()
        } else {
          this.$refs.itemForm.$refs.list.$refs[data].$el.querySelector('input').focus()
        }
      })
    },
    //获取箱子顺序
    arraySort(list) {
      console.log(list)
      let data = {
        1: [],
        2: [],
        3: [],
        4: [],
      }
      if (!list) {
        return
      }
      list.forEach((i) => {
        data[i.layer].push(i)
      })
      console.log(data)
      // this.boxList = data
      return data
    },
    // arraySort(list) {
    //   if (!list) return []
    //   let arr = list
    //   let a = null
    //   let b = null
    //   let len = arr.length
    //   let n = Math.floor(len / 2)
    //   for (let i = 0; i < n; i++) {
    //     if (i % 2 == 0) {
    //       a = arr[i]
    //       arr[i] = arr[len - (i + 1) - 1]
    //       arr[len - (i + 1) - 1] = a
    //     } else {
    //       b = arr[i]
    //       arr[i] = arr[len - i]
    //       arr[len - i] = b
    //     }
    //   }
    //   return arr
    // },

    //////////////////////////////////////////////////////////////////////////////////////////////////////以下为暂时无用逻辑，或许会再次启用
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //货位重新分配确认
    allocationOk(e) {
      this.confirmLoading = true
      this.$nextTick(() => {
        this.visible = false
        const values = this.$refs.itemForm.form.getFieldsValue()
        console.log(this.locationRow, 'locationRow')
        updateGoodsAllocation({
          oldGoodsShelves: values.goodsAllocation,
          newGoodsShelves: this.locationRow[0].shelveLocation,
        }).then((res) => {
          if (!res.success) {
            this.$message.error(res.message)
            return false
          }
          this.imgList = this.arraySort(res.data)
          this.$refs.itemForm.form.setFieldsValue({
            goodsAllocation: this.locationRow[0].shelveLocation,
          })
          this.confirmLoading = false
        })
      })
    },

    setIntervalTask(rows) {
      // debugger
      this.timer = setInterval(() => {
        getOneInboundTask(rows).then((res) => {
          if (!res.success) {
            this.$message.error(res.message)
            clearInterval(this.timer)
            this.timer = null
            return false
          }
          //关闭弹窗
          this.$nextTick(() => {
            this.visible1 = false
          })
          if (res.code == '200') {
            // 状态200 货架到位,请上架
            //任务进度
            this.sumCount = res.data.results[0].sumCount
            this.number = res.data.results[0].currentCount
            //货架到位后填充数据
            this.$refs.itemForm.form.setFieldsValue(res.data.results[0])
            console.log('上架商品，清除定时器')
            clearInterval(this.timer)
            this.timer = null
            this.focusFun('completeDate')
            this.message = res.message
          } else if (res.code == '201') {
            // 状态201 任务被挂起，请选择其他任务
            this.message = res.message
            clearInterval(this.timer)
            this.timer = null
          } else if (res.code == '202') {
            //202货架调整，请等待"
            //任务进度
            this.sumCount = res.data.results[0].sumCount
            this.number = res.data.results[0].currentCount
            //货架到位后填充数据
            this.$refs.itemForm.form.setFieldsValue(res.data.results[0])
            this.message = res.message
          } else if (res.code == '204') {
            //204货架移动中，请等待"
            //任务进度
            this.sumCount = res.data.results[0].sumCount
            this.number = res.data.results[0].currentCount
            //货架到位后填充数据
            this.$refs.itemForm.form.setFieldsValue(res.data.results[0])
            this.message = res.message
          }
        })
      }, 2000)
    },

    // 货架信息
    timerTask(rows) {
      rows.sumCount = this.sumCount
      rows.currentCount = this.number
      getOneInboundTask(rows).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          clearInterval(this.timer)
          return false
        }
        setTimeout(() => {
          this.visible1 = false
          this.confirmLoading1 = false
          // this.imgList = res.data.containerList
          this.sumCount = res.data.results[0].sumCount
          this.number = res.data.results[0].currentCount
          res.data.results[0].containerNo = res.data.results[0].goodsBarcode
          // this.selectedRows[0].stationNo = values.stationNo
          this.$refs.itemForm.form.setFieldsValue(res.data.results[0])
          this.message = res.message
          //判断wareGoodsId变化获取图片
          this.wareGoodsId = res.data.results[0]?.wareGoodsId
          //判断货架是否到位

          if (res.data.containerList) {
            if (res.data.containerList[0].isArrive === 0) {
              this.isArrive = 0
              // this.message = '货架搬运中'
            } else {
              this.abc = res.data.results[0].abcType
              this.isArrive = 1
              this.message = res.message
              // sumCount   currentCount
              // this.wareGoodsId = res.data.results[0].wareGoodsId
              this.sumCount = res.data.results[0].sumCount
              this.number = res.data.results[0].currentCount
              this.imgList = res.data.containerList ? this.arraySort(res.data.containerList) : []
              if (res.code == '201' || res.code == '200') {
                clearInterval(this.timer)
                this.timer = null
              }
              this.focusFun('completeDate')
            }
          } else {
            this.abc = res.data.results[0].abcType || ''
            this.isArrive = 0
            // this.message = '货架搬运中'
          }
          //是否虚拟货位
          let isXuNi = res.data?.results[0].isXn
          if (isXuNi == 1) {
            this.message = '请上架商品'
            clearInterval(this.timer)
          }
        }, 2000)
      })
    },
    //自动叫车逻辑
    onChange(e, status) {
      console.log(e)
      if (e) {
        this.checked = e.target.checked
      }
      if (this.checked) {
        this.isClock = 0
      } else {
        this.isClock = 1
      }
      const params = this.$refs.itemForm.form.getFieldsValue()
      autoCallRcs({
        stationNo: params.stationNo,
        isClock: this.isClock, //自动叫车：0:自动，1:手动
        goodsId: status == 'XN' ? params.goodsId : '',
        // goodsId: status == 'XN' ? params.goodsId : '',
      }).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return false
        }
      })
    },
    numberA() {
      const params = this.$refs.itemForm.form.getFieldsValue().realityQty
      const numberTest = params - 10
      this.$refs.itemForm.form.setFieldsValue({ realityQty: numberTest })
      this.realityQty = this.$refs.itemForm.form.getFieldsValue().realityQty
    },
    numberB() {
      const params = this.$refs.itemForm.form.getFieldsValue().realityQty
      const numberTest = params - 1
      this.$refs.itemForm.form.setFieldsValue({ realityQty: numberTest })
      this.realityQty = this.$refs.itemForm.form.getFieldsValue().realityQty
    },
    numberC() {
      const params = this.$refs.itemForm.form.getFieldsValue().realityQty
      const numberTest = params + 10
      this.$refs.itemForm.form.setFieldsValue({ realityQty: numberTest })
      this.realityQty = this.$refs.itemForm.form.getFieldsValue().realityQty
    },
    numberD() {
      const params = this.$refs.itemForm.form.getFieldsValue().realityQty
      const numberTest = params + 1
      this.$refs.itemForm.form.setFieldsValue({ realityQty: numberTest })
      this.realityQty = this.$refs.itemForm.form.getFieldsValue().realityQty
    },
    // 解挂
    lossUnregister() {
      const params = this.$refs.itemForm.form.getFieldsValue()
      let data = {
        taskId: params.taskId,
        isHangUp: 50, //解挂50
      }
      taskHangUp(data).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return false
        }
        this.$message.success(this.$lang('解挂成功'))
        this.reset()
        this.$refs.itemForm.form.setFieldsValue({ stationNo: params.stationNo })
      })
    },
    //自动分配
    automatic() {
      const params = this.$refs.itemForm.form.getFieldsValue()
      autoAllocation(params).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return false
        }
        this.$message.success(this.$lang('自动分配成功'))
        this.visibleAllocation = false
        this.$refs.itemForm.form.setFieldsValue({
          goodsShelves: '',
          goodsAllocation: '',
        })
        this.imgList = []
        const getParams = this.$refs.itemForm.form.getFieldsValue()
        if (getParams.goodsShelves == '') {
          console.log(getParams.goodsShelves, 'goodsShelves')
          this.timer = setInterval(() => {
            this.timerTask([getParams])
          }, 2000)
        } else {
          clearInterval(this.timer)
        }
      })
    },

    filterOption(input, option) {
      // console.log(input, option, '2222222222')
      return option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
    },
    completeSelect(value, option) {
      this.inPalletLocation = value
      console.log(value, option, 'completeSelect')
    },
    completeChange(value) {
      this.inPalletLocation = value
      console.log(value, 'completeChange')
    },
  },
}
</script>
<style lang="less">
/deep/ .ant-input {
  font-weight: bold;
}
.oneclass {
  display: none;
}
.group-btn {
  // float: right;
  //  border: 1px solid #409eff;
  margin: 15px;
  font-weight: bold;
  font-size: 15px;
  .group-btn-a {
    margin-left: 40px;
    height: 50px;
    width: 150px;
  }
}
.group-btn-b {
  width: 50px;
}
.select-a {
  .select-b {
    margin-top: 15px;
    width: 180px;
  }
}
.testName {
  font-weight: bold;
  font-size: 30px;
  color: red;
}
.num {
  font-weight: bold;
  font-size: 35px;
  .abcType {
    display: inline-block;
    margin-right: 15px;
    color: red;
  }
}
.btnClass {
  display: inline-block;
  position: relative;
  bottom: 100px;
  left: 22%;
}
.input-a {
  font-size: 20px;
}
.inPalletLocationClass {
  display: inline-block;
  position: relative;
  bottom: 45px;
  // right: 40px;
}
.input-b {
  margin-left: 5px;
  width: 220px;
}
.imgPhoto {
  // margin-left: 100px;
  height: 138px;
  overflow: hidden;
}
</style>
