<template>
  <!-- 盘点清单 -->
  <view class="">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      @clickLeft="back"
      :title="`盘点清单(${infoData.bizTypeName})`"
    >
      <block slot="right">
        <view class="bc-btn" @click="handlBc"> 提交 </view>
      </block>
    </uni-nav-bar>
    <view class="tab-title">
      <view
        v-for="[key, item] in Object.entries(tabList)"
        :key="key"
        class="tab-item"
        :class="{ active: active == key }"
        @click="changeChartsTab(key)"
        >{{ key }}({{ item.num }})
      </view>
    </view>
    <view class="tab-main">
      <uni-search-bar
        @input="search"
        v-model="searchKey"
        cancelButton="none"
        placeholder="编码/名称/货位/批次"
      >
      </uni-search-bar>
      <template v-if="tabList[active].list.length > 0">
        <view
          class="order-list"
          v-for="(item, index) in tabList[active].list"
          :key="index"
        >
          <view class="s1">
            <view class="b1"> {{ item.assetName }}({{ item.assetCode }}) </view>
            <view class="b2">
              <template v-if="[5, 6, 7].includes(item.equStatus)">
                <view
                  class="type"
                  :style="styleClass(el.type)"
                  v-for="el in ycEquStatus(item)"
                >
                  {{ dict.equStatus[el.type] }}({{ el.num }})
                </view>
              </template>

              <view class="type" :style="styleClass(item.equStatus)" v-else>
                {{ dict.equStatus[item.equStatus] }}
              </view>
            </view>
          </view>
          <view class="wrap">
            <view class="item">
              <view class="label"> 牌号 </view>
              <view class="value">
                {{ item.assetBrand }}
              </view>
            </view>
            <view class="item">
              <view class="label"> 型号 </view>
              <view class="value">
                {{ item.assetSku }}
              </view>
            </view>
          </view>
          <view class="wrap">
            <view class="item">
              <view class="label"> 类型 </view>
              <view class="value">
                {{ item.assetTypeDictDESC }}
              </view>
            </view>
          </view>
          <view class="wrap">
            <view class="item">
              <view class="label"> 最小单元 </view>
              <view class="value">
                {{ item.measurementUnit }} {{ item.unit }}/{{
                  item.minPackUnit
                }}
              </view>
            </view>
            <view class="item">
              <view class="label"> 数量 </view>
              <view class="value">
                <text v-if="active == '待盘点'">{{ item.yetNum }}/</text
                >{{ item.inventoryNum }}
              </view>
            </view>
          </view>
          <view class="wrap" style="padding-right: 100rpx">
            <view class="item" v-if="item.equStatus == 3" style="width: 100%">
              <view class="label"> 货位 </view>
              <view class="value">
                {{ item.warehouseName }}/{{ item.reservoirName }}/{{
                  item.goodsShelfName
                }}/{{ item.goodsAllocationName }}
              </view>
            </view>
          </view>
          <!-- <view class="wrap">
						<view class="item">
							<view class="label">
								货位
							</view>
							<view class="value">
								{{item.warehouseName}}/{{item.reservoirName}}/{{item.goodsShelfName}}/{{item.goodsAllocationName}}
							</view>
						</view>
					</view> -->
          <template
            v-if="isExecute && (infoData.status == 1 || infoData.status == 6)"
          >
            <template v-if="active == '待盘点'">
              <view
                class="bd-btn"
                @click="handlSdpd(item)"
                v-if="item.inventoryNum > 0"
              >
                手动盘点
              </view>
              <view class="bd-btn" @click="handlQrpd(item)" v-else>
                标记已盘
              </view>
            </template>
            <view
              class="bd-btn"
              @click="handlDelete(item)"
              v-if="active == '已盘点' || active == '异常记录'"
            >
              移除
            </view>
          </template>
        </view>
      </template>
      <u-empty v-else> </u-empty>
    </view>
    <view
      class="fixed-bottom"
      v-if="isExecute && (infoData.status === 1 || infoData.status == 6)"
    >
      <view class="ycdj" @click="handlYc"> 溢出登记 </view>
      <!-- 	<view class="smpd" @click="handlscanCheck">
				扫码盘点
			</view> -->
      <view class="smpd" @click="handlscanCheck"> 扫码盘点 </view>
    </view>
    <view class="fixed-bottom" v-if="isExecute && infoData.status === 0">
      <view class="kspd" @click="handlStart"> 开始盘点 </view>
    </view>
    <!-- <ScanCode @scancodedate="cbScancodedate" :model="'uni'"></ScanCode> -->
  </view>
</template>

<script>
import { postJ, post, get } from '@/utils/api'
let [page, size, isEnd] = [1, 20, true]
import ScanCode from '@/components/ScanCode.vue'
import _ from 'lodash'

export default {
  components: {
    ScanCode
  },
  data () {
    return {
      active: '待盘点',
      tabList: {
        待盘点: {
          num: 0,
          type: [0],
          list: []
        },
        已盘点: {
          num: 0,
          type: [4],
          list: []
        },
        异常记录: {
          num: 0,
          type: [1, 2, 3, 5, 6, 7],
          list: []
        }
      },
      searchKey: '',
      /* 盘点工单id */
      workOrderId: '',
      // 工单编码
      workOrderCode: '',
      // 盘点类型，仓库内，仓库外
      BizType: '',
      // 工单详情
      infoData: '',
      dict: {
        equStatus: {
          0: '待盘',
          1: '丢失',
          2: '破损',
          3: '溢出',
          4: '正常',
          5: '异常'
        }
      },
      // 扫码条码信息
      qrContent: '',
      barType: '',
      ScanData: ''
    }
  },
  onLoad (data) {
    this.workOrderId = data.id
    this.workOrderCode = data.workOrderCode
    this.BizType = data.BizType
    this.search = _.debounce(this.search, 1000)
  },
  onShow () {
    this.initPagination()
    this.getdata()
    this.getNum()
    this.getdetales()
    let _this = this
    uni.$off('scancodedate') // 每次进来先 移除全局自定义事件监听器
    uni.$on('scancodedate', function (data) {
      _this.cbScancodedate(data)
    })
  },
  onUnload () {
    uni.$off('scancodedate')
  },
  onHide () {
    uni.$off('scancodedate')
  },
  onReachBottom () {
    if (isEnd) {
      return
    }
    this.getMoreLists()
    console.log('触底')
  },
  onPullDownRefresh () {
    this.initPagination()
    this.getdata()
    this.getNum()
    console.log('下拉刷新')
  },
  computed: {
    // 当前是否为执行人
    isExecute () {
      let userInfo = uni.getStorageSync('userInfo')
      // 当前登录人id
      let userId = userInfo.id
      console.log()
      // 审批人id
      let executeUserId = this.infoData.executeUserId
      if (executeUserId == userId) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    changeChartsTab (key) {
      this.active = key
      this.initPagination()
      this.getdata()
      this.getNum()
    },
    search (e) {
      this.searchKey = e
      this.initPagination()
      this.getdata()
    },
    getdata () {
      uni.showLoading({
        title: '加载中'
      })
      let par = {
        size: size,
        page: page,
        workOrderId: this.workOrderId,
        equStatusList: this.tabList[this.active].type,
        searchKey: this.searchKey,
        bizType: Number(this.BizType)
        //bizType:2
      }
      //par = this.URLSearchParams(par)
      postJ(this.apiUrl + '/repertoryCheck/getList', par).then(res => {
        if (res.success) {
          let list = this.tabList[this.active].list
          this.tabList[this.active].list = [...list, ...res.data.records]
          let pages = res.data.pages

          if (page < pages) {
            isEnd = false
          } else {
            isEnd = true
          }
          console.log(page, pages, isEnd)
          setTimeout(() => {
            uni.stopPullDownRefresh()
            uni.hideLoading()
          }, 1000)
        }
      })
    },
    getMoreLists () {
      page++
      this.getdata()
    },
    // 初始化分页
    initPagination () {
      size = 10
      page = 1
      isEnd = true
      this.tabList[this.active].list = []
    },
    // 删除清单
    handlDelete (item) {
      uni.showModal({
        content: '是否移除已盘清单？',
        success: res => {
          if (res.confirm) {
            let par = {
              id: item.id
            }
            par = this.URLSearchParams(par)
            post(this.apiUrl + '/repertoryCheck/deleteInventory?' + par).then(
              res => {
                if (res.success) {
                  uni.showToast({
                    title: '已移除'
                  })
                  this.initPagination()
                  this.getdata()
                  this.getNum()
                }
              }
            )
          }
        }
      })
    },
    // 获取数量
    getNum () {
      let par = {
        workOrderId: this.workOrderId
      }
      par = this.URLSearchParams(par)
      post(this.apiUrl + '/repertoryCheck/statistics?' + par).then(res => {
        if (res.success) {
          this.tabList['待盘点'].num = res.data.stayNum
          this.tabList['已盘点'].num = res.data.yetNum
          this.tabList['异常记录'].num = res.data.abnormalNum
        }
      })
    },
    // 跳转盘点详情
    handlBc () {
      let par = {
        workOrderId: this.workOrderId
      }
      par = this.URLSearchParams(par)
      uni.navigateTo({
        url: '/pages/warehouse/workOrder/details/details?' + par
      })
    },
    // 手动盘点
    handlSdpd (item) {
      let par = {
        workOrderId: this.workOrderId,
        planInventoryId: item.id,
        bizType: this.BizType,
        info: encodeURIComponent(JSON.stringify(item))
      }
      par = this.URLSearchParams(par)
      uni.navigateTo({
        url: '/pages/warehouse/workOrder/manualCheck/manualCheck?' + par
      })
    },
    // 扫码盘点
    handlscanCheck () {
      // this.Scancodedate(data.code)
      let _this = this
      uni.scanCode({
        success: function (res) {
          _this.Scancodedate(res.result)
        }
      })
    },
    // 溢出登记
    handlYc () {
      let par = {
        workOrderId: this.workOrderId
      }
      par = this.URLSearchParams(par)
      uni.navigateTo({
        url:
          '/pages/warehouse/workOrder/registerOverflow/registerOverflow?' + par
      })
    },
    // 获取工单详情
    getdetales () {
      let par = {
        workOrderId: this.workOrderId
      }
      postJ(this.apiUrl + '/repertoryCheck/getCheckDetail', par).then(res => {
        if (res.success) {
          this.infoData = res.data
          this.infoData.status = res.data.status.code
        }
      })
    },
    // 开始盘点
    handlStart () {
      let par = this.URLSearchParams({
        workOrderCode: this.workOrderCode
      })
      post(this.apiUrl + '/workOrder/execute?' + par).then(res => {
        if (res.success) {
          uni.showToast({
            title: '操作成功'
          })
          this.getdetales()
        }
      })
    },
    // 异常的显示
    ycEquStatus (item) {
      let list = []
      if (item.loseNum) {
        list.push({
          type: 1,
          num: item.loseNum
        })
      }
      if (item.damageNum) {
        list.push({
          type: 2,
          num: item.damageNum
        })
      }
      if (item.normalNum) {
        list.push({
          type: 4,
          num: item.normalNum
        })
      }
      return list
    },
    styleClass (type) {
      switch (Number(type)) {
        case 0:
        case 4:
          return 'background-color: #70B603;color: #fff;'
        case 1:
          return 'background-color: #feeaeb;color: #555;'
        case 2:
          return 'background-color: #555;color: #fff;'
        case 3:
          return 'background-color: #dacde6;color: #fff;'
        default:
          break
      }
    },
    // 数量为0标记已盘
    handlQrpd (item) {
      uni.showModal({
        content: '该清单没有可盘项，是否标记已盘？',
        success: res => {
          if (res.confirm) {
            let par = {
              planInventoryId: item.id
            }
            par = this.URLSearchParams(par)
            post(this.apiUrl + '/repertoryCheck/checkVerify?' + par).then(
              res => {
                if (res.success) {
                  uni.showToast({
                    title: '操作成功'
                  })
                  this.initPagination()
                  this.getdata()
                  this.getNum()
                }
              }
            )
          }
        }
      })
    },
    // 扫码枪扫码
    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()
      // 扫码失败
      if (!res.success) return
      if (res.message === 'false') {
        uni.showToast({
          title: '该资产不在盘点清单内',
          duration: 2000,
          icon: 'none'
        })
        return
      }
      let par = {
        workOrderId: this.workOrderId,
        info: encodeURIComponent(JSON.stringify(res.data)),
        bizType: this.BizType
      }
      par = this.URLSearchParams(par)
      uni.navigateTo({
        url: '/pages/warehouse/workOrder/scanCheck/scanCheck?' + par
      })
    },
    // 设置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
    },
    // 获取扫码设备详情
    getScanData () {
      let par = {
        qrContent: this.qrContent,
        barType: this.barType
      }
      return postJ(this.apiUrl + '/scan/getAssetInfo', par).then(res => {
        this.ScanData = res.data
      })
    },
    // 获取扫码盘点明细数据
    getScanCheckMate () {
      if (!this.ScanData.assetCode) {
        uni.showToast({
          title: '设备编码为空'
        })
        return
      }

      let par = {
        assetCode: this.ScanData.assetCode,
        bizType: this.BizType,
        workOrderId: this.workOrderId

        // assetCode: 'w05xing0002test0510050',
        // bizType: '1',
        // workOrderId: '9173'
      }
      console.log(par)
      return postJ(
        this.apiUrl + '/repertoryCheck/scanCheckMate',
        par,
        true,
        false
      ).catch(err => {
        if (err.code === '222') {
          uni.showModal({
            title: '提示',
            content: err.message,
            confirmText: '确认', // 确认按钮的文字
            showCancel: false, // 是否显示取消按钮，默认为 true
            success: res => {}
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.bc-btn {
  height: 60rpx;
  line-height: 60rpx;
  background-color: #157a2c;
  font-size: 28rpx;
  color: #fff;
  padding: 0 30rpx;
  border-radius: 10rpx;
}

.tab-title {
  position: fixed;
  width: 100%;
  display: flex;
  justify-content: space-between;
  height: 82rpx;
  line-height: 82rpx;
  background-color: #ffffff;
  border-bottom: 1px solid #f2f2f2;
  z-index: 99;
  box-sizing: border-box;

  .tab-item {
    width: 50%;
    text-align: center;
    font-size: 32rpx;
    color: $uni-text-color-grey;
  }

  .tab-item.active {
    color: $j-primary-border-green;
    border-bottom: 1px solid $j-primary-border-green;
  }
}

.tab-main {
  margin-top: 82rpx;
  padding-bottom: 82rpx;
}

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

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

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

    .b2 {
      color: #000000;
      font-size: 28rpx;
      display: flex;
      width: 500rpx;
      justify-content: flex-end;
    }

    .type {
      font-size: 28rpx;
      height: 40rpx;
      padding: 0 10rpx;
      line-height: 40rpx;

      & + .type {
        margin-left: 10rpx;
      }

      &.yc {
        background-color: #dacde6;
      }

      &.ds {
        background-color: #feeaeb;
      }

      &.ps {
        background-color: #cbcbcb;
      }
    }
  }

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

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

      .label {
        margin-right: 20rpx;
      }
    }
  }
}

.bd-btn {
  height: 56rpx;
  padding: 0 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #4b7902;
  font-size: 28rpx;
  border: 1px solid #4b7902;
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
}

.fixed-bottom {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80rpx;
  display: flex;
  border: 1px solid #157a2c;
  box-sizing: border-box;

  .ycdj {
    background-color: #fff;
    width: 200rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #157a2c;
  }

  .smpd {
    background-color: #157a2c;
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}

.kspd {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #157a2c;
  color: #fff;
  font-size: 28rpx;
}
</style>
