<template>
  <view class="mian">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      @clickLeft="back"
      title="登记溢出物品"
    >
    </uni-nav-bar>
    <view class="">
      <view class="title"> 存放货位 </view>
      <view class="huowe-wrap">
        <view class="row">
          <view class="item" @click="handlscanCheck"> 扫描货位码 </view>
        </view>
        <view class="row">
          <!-- 仓库 -->
          <view class="item s2">
            <picker
              @change="pickerConfirm('ck', $event)"
              :range-key="'name'"
              :range="option_ck"
            >
              <view class="uni-input">{{ form.ck.name || '选择仓库' }}</view>
            </picker>
          </view>
          <!-- 库区 -->
          <view class="item s2">
            <picker
              @change="pickerConfirm('kq', $event)"
              :range-key="'areaName'"
              :range="option_kq"
            >
              <view class="uni-input">{{
                form.kq.areaName || '选择库区'
              }}</view>
            </picker>
          </view>
        </view>
        <view class="row">
          <!-- 货架 -->
          <view class="item s2">
            <picker
              @change="pickerConfirm('hj', $event)"
              :range-key="'goodsshelvesCode'"
              :range="option_hj"
            >
              <view class="uni-input">{{
                form.hj.goodsshelvesCode || '选择货架'
              }}</view>
            </picker>
          </view>
          <!-- 货位 -->
          <view class="item s2" @click="open('goodsAllocation')">
            {{ form.hw.goodsAllocationCode || '选择货位' }}
          </view>
        </view>
      </view>

      <view class="title"> 定义资产 </view>
      <view class="huowe-wrap">
        <view class="row">
          <view class="item">
            <picker
              @change="pickerConfirm('propertyType', $event)"
              :range-key="'dictValue'"
              :range="option_propertyType"
            >
              <view class="uni-input">{{
                form.propertyType.dictValue || '选择资产类型'
              }}</view>
            </picker>
          </view>
        </view>
        <view class="row" v-if="form.propertyType.dictValue">
          <view class="item" @click="open('selectSupplies')">
            {{
              form.materialsInformation.name ||
              `选择${form.propertyType.dictValue}信息`
            }}
          </view>
        </view>
      </view>
      <view class="order-list" v-if="form.materialsInformation">
        <view class="s1">
          <view class="b1">
            {{ form.materialsInformation.assetName }}
          </view>
          <view class="b2"> </view>
        </view>
        <view class="wrap">
          <view class="item">
            <view class="label"> 编码 </view>
            <view class="value">
              {{ form.materialsInformation.informationCode }}
            </view>
          </view>
          <view class="item">
            <view class="label"> 类型 </view>
            <view class="value">
              {{ form.materialsInformation.classificationUrl }}
            </view>
          </view>
        </view>
        <view class="wrap">
          <view class="item">
            <view class="label"> 牌号 </view>
            <view class="value">
              {{ form.materialsInformation.brandNum }}
            </view>
          </view>
          <view class="item">
            <view class="label"> 型号 </view>
            <view class="value">
              {{ form.materialsInformation.modelType }}
            </view>
          </view>
        </view>
        <view class="wrap">
          <view class="item">
            <view class="label">
              <text style="color: red">*</text>最小包装单元
            </view>
            <view class="input-wrap">
              <u--input
                class="input"
                placeholder="请输入"
                border="surround"
                v-model="form.measurementUnit"
              ></u--input>
            </view>
          </view>
          <view class="item">
            <view class="label">
              {{ form.materialsInformation.measuringUnit }}/{{
                form.materialsInformation.packingUnit
              }}
            </view>
            <view class="value"> </view>
          </view>
        </view>
        <view class="wrap">
          <view class="item">
            <view class="label"> <text style="color: red">*</text>数量 </view>
            <view class="input-wrap">
              <u--input
                class="input"
                type="number"
                placeholder="请输入"
                border="surround"
                v-model="form.checkNum"
              ></u--input>
            </view>
          </view>
        </view>
        <view class="wrap">
          <view class="item">
            <view class="label">
              <text style="color: red">*</text>
              批次号
            </view>
            <view class="input-wrap">
              <u--input
                class="input"
                placeholder="请输入"
                border="surround"
                v-model="form.batchNum"
              ></u--input>
            </view>
          </view>
        </view>
      </view>
      <!-- 弹框 -->
      <goodsAllocation
        ref="goodsAllocation"
        :dataInfo="option_hw"
        @succeed="succeedGoodsAllocation"
      >
      </goodsAllocation>
      <selectSupplies
        ref="selectSupplies"
        :classificationIds="form.propertyType.id"
        @succeed="succeedSelectSupplies"
      >
      </selectSupplies>
    </view>
    <view class="fixed-bottom">
      <view class="btn-wrap">
        <button type="primary" class="qr-btn" @click="onsubmit">
          确认信息
        </button>
        <button type="primary" class="qx-btn" @click="back">取消</button>
      </view>
    </view>
    <!-- <ScanCode @scancodedate="cbScancodedate" :model="'uni'"></ScanCode> -->
  </view>
</template>

<script>
import goodsAllocation from '../components/goodsAllocation.vue'
import selectSupplies from '../components/selectSupplies.vue'
import ScanCode from '@/components/ScanCode.vue'
import { mapActions, mapGetters } from 'vuex'
import { postJ, post, get } from '@/utils/api'
import { reject } from 'lodash'
import dictEnum from '@/enum/dict'
export default {
  components: {
    goodsAllocation,
    selectSupplies,
    ScanCode
  },
  data () {
    return {
      dictName: '物品类型',
      // 工单id
      workOrderId: '',
      /* 仓库/货位所有信息 */
      warehouseInfo: [],
      form: {
        // 仓库
        ck: '',
        // 库区
        kq: '',
        // 货架
        hj: '',
        // 货位
        hw: '',
        // 资产类型
        propertyType: '',
        // 物料信息
        materialsInformation: '',
        // 计量单位数量
        measurementUnit: '',
        // 数量
        checkNum: '',
        // 批次号
        batchNum: ''
      },
      MyDict: {
        code: {
          1: '生产设备',
          2: '舟皿',
          3: '物料',
          4: '产品',
          5: '周转车',
          6: '模具',
          7: '备品备件'
        },
        assetTypeDict: {
          1: 'SHENGCHANSHEBEI',
          2: 'ZHOUMIN',
          3: 'WULIAO',
          4: 'CHANPIN',
          5: 'ZHOUZHUANCHE',
          6: 'MOJU',
          7: 'BEIPINBEIJIAN'
        }
      },
      qrContent: '',
      barType: ''
    }
  },
  computed: {
    ...mapGetters(['dict', 'getDict', 'getDictValue']),
    option_ck () {
      return this.warehouseInfo
    },
    option_kq () {
      if (this.form.ck) {
        return this.form.ck.wareHouseArea
      } else {
        return []
      }
    },
    option_hj () {
      if (this.form.kq) {
        return this.form.kq.wareHouseGoodsshelves
      } else {
        return []
      }
    },
    option_hw () {
      if (this.form.hj) {
        return this.form.hj.wareHouseGoodsAllocation
      } else {
        return []
      }
    },
    option_propertyType () {
      return this.dict[dictEnum[this.dictName]] || []
    }
  },
  watch: {
    'form.propertyType': function (Nval) {
      this.form.materialsInformation = ''
    }
  },
  created () {
    this.getwarehouseList()
    if (this.dictName) {
      this.requestDict(this.dictName)
    }
  },
  onLoad (option) {
    this.workOrderId = option.workOrderId
  },
  onShow () {
    let _this = this
    uni.$off('scancodedate') // 每次进来先 移除全局自定义事件监听器
    uni.$on('scancodedate', function (data) {
      _this.cbScancodedate(data)
    })
  },
  onUnload () {
    uni.$off('scancodedate')
  },
  onHide () {
    uni.$off('scancodedate')
  },
  methods: {
    ...mapActions('dict', ['requestDict']),
    // 返回
    back () {
      uni.navigateBack({
        delta: 1
      })
    },
    // 弹窗确认
    pickerConfirm (type, e) {
      this.form[type] = this['option_' + type][e.detail.value]
      if (type == 'ck') {
        this.form.kq = ''
        this.form.hj = ''
        this.form.hw = ''
      }
      if (type == 'kq') {
        this.form.hj = ''
        this.form.hw = ''
      }
      if (type == 'hj') {
        this.form.hw = ''
      }
    },
    // 默认值
    defaultIndex (type) {
      if (this.option[type].length < 1) {
        return []
      }
      let index = this.option[type].findIndex(n => {
        return n.id == this.form[type].id
      })
      if (index !== -1) {
        return [index]
      } else {
        return []
      }
    },
    // 打开弹窗
    open (type) {
      this.$refs[type].open()
    },
    succeedGoodsAllocation (e) {
      this.form.hw = e.data
    },
    succeedSelectSupplies (e) {
      this.form.materialsInformation = e.data
    },
    //获取仓库/货位
    getwarehouseList () {
      post(this.apiUrl + '/outInWarehouse/select/getWarehouseChildren').then(
        res => {
          if (res.success) {
            this.warehouseInfo = res.data
          }
        }
      )
    },
    // 确认
    onsubmit () {
      this.verification()
        .then(() => {
          let par = {}
          par.workOrderId = this.workOrderId

          par.assetBrand = this.form.materialsInformation.brandNum
          par.assetCode = this.form.materialsInformation.informationCode
          par.assetId = this.form.materialsInformation.id
          par.assetName = this.form.materialsInformation.informationName
          par.assetSku = this.form.materialsInformation.informationName
          par.assetTypeDict = this.form.propertyType.dictCode

          par.bizTypeId = this.form.materialsInformation.id
          // 最小包装单位
          par.minPackUnit = this.form.materialsInformation.packingUnit
          // 计量单位数量
          par.measurementUnit = this.form.measurementUnit
          // 物品数量
          par.checkNum = this.form.checkNum
          // 批次号
          par.batchNo = this.form.batchNum
          // 计量单位
          par.unit = this.form.materialsInformation.measuringUnit
          par.informationId = this.form.materialsInformation.id
          par.informationCode = this.form.materialsInformation.informationCode
          // 参考单价
          par.univalence = this.form.materialsInformation.univalence
          par.univalenceUnit = this.form.materialsInformation.univalenceUnit

          let ck = {
            warehouseId: this.form.ck.id,
            warehouseName: this.form.ck.name
          }
          let kq = {
            reservoirId: this.form.kq.areaId,
            reservoirName: this.form.kq.areaName
          }
          let hj = {
            goodsShelfId: this.form.hj.goodsshelvesId,
            goodsShelfName: this.form.hj.goodsshelvesCode
          }
          let hw = {
            goodsAllocationId: this.form.hw.goodsAllocationId,
            goodsAllocationName: this.form.hw.goodsAllocationCode
          }
          par = Object.assign(par, ck, kq, hj, hw)

          postJ(this.apiUrl + '/repertoryCheck/meanwhileSave', par).then(
            res => {
              if (res.success) {
                uni.showToast({
                  title: '登记成功',
                  duration: 1000
                })
                setTimeout(() => {
                  this.back()
                }, 1000)
              }
            }
          )
        })
        .catch(err => {
          uni.showToast({
            title: err,
            icon: 'none'
          })
        })
    },
    /* 验证 */
    verification () {
      return new Promise((resolve, reject) => {
        if (!this.form.ck) {
          reject('请选择仓库')
        }
        if (!this.form.kq) {
          reject('请选择库区')
        }
        if (!this.form.hj) {
          reject('请选择货架')
        }
        if (!this.form.hw) {
          reject('请选择货位')
        }
        if (!this.form.propertyType) {
          reject('请选择资产类型')
        }
        if (!this.form.materialsInformation) {
          reject('请选择物料信息')
        }
        if (!this.form.checkNum) {
          reject('请输入数量')
        }
        if (!this.form.measurementUnit) {
          reject('请输入计量单位')
        }
        if (!this.form.batchNum) {
          reject('请输入批次号')
        }
        resolve()
      })
    },
    // 扫码枪扫码
    cbScancodedate (data) {
      this.Scancodedate(data.code)
    },
    async Scancodedate (code) {
      this.qrContent = code.trim()
      this.barType = this.setBarType(this.qrContent)
      await this.getScanData()
      //let res = await this.getScanCheckMate()
    },
    // 相机扫码
    handlscanCheck () {
      // this.Scancodedate(data.code)
      let _this = this
      uni.scanCode({
        success: function (res) {
          _this.Scancodedate(res.result)
        }
      })
    },
    // 获取扫码货位详情
    getScanData () {
      let par = {
        qrContent: this.qrContent,
        barType: this.barType
        /* qrContent: '20230406/锤锤工厂/A-feifei01/D002/模压备件组/B01/C001@_@2',
					barType: 2 */
      }
      return postJ(this.apiUrl + '/scan/getAssetInfo', par).then(res => {
        console.log('par', par)
        if (!res.data.warehouseId) {
          uni.showToast({
            title: '扫描货位码失败，请检查货位码',
            icon: 'none',
            duration: 1000
          })
        }
        let ck = this.warehouseInfo.find(n => {
          return n.id == res.data.warehouseId
        })
        if (ck) {
          this.form.ck = ck
        }

        let kq = this.option_kq.find(n => {
          return n.areaId == res.data.warehouseAreaId
        })

        if (kq) {
          this.form.kq = kq
        }

        let hj = this.option_hj.find(n => {
          return n.goodsshelvesId == res.data.warehouseAreaGoodsId
        })

        if (hj) {
          this.form.hj = hj
        }

        let hw = this.option_hw.find(n => {
          return n.goodsAllocationId == res.data.id
        })
        if (hw) {
          // 已满不选
          if (hw.allocationStatus == 3 || hw.allocationStatus == 4) {
            uni.showToast({
              title: '该货位已满或失效',
              duration: 1000
            })
            // 清空
            this.form.kq = ''
            this.form.hj = ''
            this.form.hw = ''
            return
          }
          this.form.hw = hw
        }
      })
    },
    // 设置barType
    setBarType (val) {
      let index = val.indexOf('@_@')
      let result = 0
      if (index !== -1) {
        let item = val.substr(index + 3, 1)
        if (item) {
          result = Number(item)
        }
      }
      return result
    }
  }
}
</script>

<style lang="scss" scoped>
$cols: 2;
$marginWidth: 10rpx;

.mian {
  padding-bottom: 300rpx;
}

.title {
  padding: 20rpx;
  color: #333333;
  font-size: 28rpx;
  font-weight: bold;
}

.huowe-wrap {
  padding: 0 20rpx;

  .row {
    display: flex;

    & + .row {
      margin-top: 10rpx;
    }

    .item {
      flex: 1;
      display: flex;
      border: 1px solid #aaaaaa;
      color: #333333;
      font-size: 28rpx;
      height: 66rpx;
      justify-content: center;
      align-items: center;
    }

    .item.s2 {
      width: calc((100% - #{($cols - 1)} * $marginWidth) / #{$cols});
      margin-left: $marginWidth;
    }

    .item.s2:nth-of-type(#{$cols}n + 1) {
      margin-left: 0;
    }
  }
}

.fixed-bottom {
  background-color: #fff;
  width: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  padding: 30rpx;
  box-sizing: border-box;

  .btn-wrap {
    margin-top: 30rpx;

    .qr-btn {
      background-color: #70b603f3;
    }

    .qx-btn {
      background-color: transparent;
      color: #555555;
      margin-top: 20rpx;
    }
  }
}

.order-list {
  padding: 30rpx 20rpx;
  border-bottom: 1px solid #f2f2f2;
  position: relative;

  &.active {
    background-color: #caf982;
  }

  .s1 {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .b1 {
      color: #555555;
      font-size: 30rpx;
    }

    .b2 {
      color: #000000;
      font-size: 28rpx;
    }
  }

  .wrap {
    display: flex;
    margin-top: 20rpx;

    .item {
      color: #555555;
      font-size: 28rpx;
      display: flex;
      width: 340rpx;
      align-items: center;

      .label {
        margin-right: 20rpx;
        white-space: nowrap;
      }

      .input-wrap {
        padding-right: 20rpx;
      }

      .input {
        border: 1px solid #f2f2f2;
      }
    }
  }

  .uni-input {
    border: 1px solid #f2f2f2;
    font-size: 28rpx;
  }
}
</style>
