<template>
  <view>
    <u-navbar
      title-color="#fff"
      title-width="360"
      back-icon-color="#ffffff"
      :back-text-style="{ color: '#fff' }"
      back-text="返回"
      title="样品称重"
      :border-bottom="false"
      :custom-back="customBack"
      :background="{ 'background-color': '#0055A2' }"
    ></u-navbar>

    <u-row class="content-title" gutter="16">
      <u-col span="3">
        <view class="content-title-name">
          <text>待称重样品</text>
        </view>
        <u-gap height="10" bg-color="#0055A2"></u-gap>
      </u-col>
      <u-col span="6">
        <view class="content-title-name">
          <text>{{ currentAuncel.code === '' ? '电子天平' : currentAuncel.code }}</text>
        </view>
        <u-gap height="10" bg-color="#0055A2"></u-gap>
      </u-col>
      <u-col span="3">
        <view class="content-title-name">
          <text>已称重样品</text>
        </view>
        <u-gap height="10" bg-color="#0055A2"></u-gap>
      </u-col>
    </u-row>

    <u-row gutter="16" class="content-main-height" align="top">
      <u-col span="3">
        <scroll-view scroll-y scroll-with-animation class="content-main-left" :scroll-top="scrollTop">
          <view
            v-for="(sample, index) in notWeighSampleList"
            :key="index"
            class="u-tab-item"
            :class="[current == index ? 'u-tab-item-active' : '']"
            :data-current="index"
            @tap.stop="swichSample(index)"
          >
            <u-row gutter="20" style="width: 100%">
              <u-col span="3" style="padding: 0rpx">
                <view>
                  <text>【{{ sample.sort }}】</text>
                </view>
              </u-col>
              <u-col span="9">
                <view>
                  <text>{{ sample.sampleCode }}</text>
                </view>
                <view style="padding-top: 20rpx">
                  <text>{{ sample.dataSourceType | getDataSourceTypeShow }}{{ sample.goodsName }}</text>
                </view>
              </u-col>
            </u-row>
          </view>
        </scroll-view>
        <view class="content-main-left-operation">
          <u-row>
            <u-col span="2"></u-col>
            <u-col span="8">
              <view>
                <view style="padding: 20rpx; text-align: right">
                  <text style="font-size: 30rpx; height: 50rpx">顺序称重：</text>
                  <u-switch
                    v-model="orderWeighChecked"
                    active-color="#19be6b"
                    inactive-color="#eee"
                    @change="orderWeighChange"
                  ></u-switch>
                </view>
              </view>
            </u-col>
            <u-col span="2"></u-col>
          </u-row>
        </view>
      </u-col>
      <u-col span="6">
        <view class="content-main-height">
          <view class="auncel-container">
            <view class="auncel">
              <view class="auncel-title">
                <view style="padding-top: 40rpx; height: 100rpx; width: 100%; text-align: center">
                  <text style="font-size: 44rpx; font-weight: 300"
                    >【{{ currentSample.sort }}】 {{ currentSample.dataSourceType | getDataSourceTypeShow }}</text
                  >
                </view>

                <view style="padding-top: 30rpx; height: 100rpx; width: 100%; text-align: center">
                  <text style="font-size: 44rpx; font-weight: 300">{{ currentSample.sampleCode }}</text>
                </view>
                <view
                  style="
                    padding-top: 20rpx;
                    padding-left: 140rpx;
                    padding-right: 140rpx;
                    display: flex;
                    justify-content: center;
                    align-content: center;
                  "
                >
                  <block v-if="currentSample.dataSourceType">
                    <u-row v-if="currentSample.dataSourceType == 2 || currentSample.dataSourceType == 3">
                      <u-col span="1"></u-col>
                      <u-col span="3">
                        <u-input
                          style="color: #3b4144; background-color: #ffffff"
                          v-model="currentCupNum"
                          type="number"
                          border="border"
                          :disabled="checkCupNumReadonly"
                          placeholder="杯号"
                        />
                      </u-col>
                      <u-col span="2">
                        <text style="width: 100%; text-align: left">号杯</text>
                      </u-col>
                      <u-col span="4">
                        <u-input
                          style="color: #3b4144; background-color: #ffffff"
                          v-model="currentSample.remarks"
                          type="number"
                          border="border"
                          placeholder="样重比例"
                        />
                      </u-col>
                      <u-col span="2">
                        <text style="width: 100%; text-align: left">%</text>
                      </u-col>
                    </u-row>
                    <u-row v-else>
                      <u-col span="2"></u-col>
                      <u-col span="7">
                        <u-input
                          style="color: #3b4144; background-color: #ffffff"
                          v-model="currentCupNum"
                          type="number"
                          border="border"
                          :disabled="checkCupNumReadonly"
                          placeholder="杯号"
                        />
                      </u-col>
                      <u-col span="3">
                        <text style="width: 100%; text-align: left">号杯</text>
                      </u-col>
                    </u-row>
                  </block>
                </view>
              </view>

              <view class="auncel-weight">
                <view class="weight">
                  <view
                    :class="
                      currentAuncel.weightStable == 0
                        ? 'weight-data-yellow'
                        : currentAuncel.weightStable == 1
                        ? 'weight-data'
                        : 'weight-data-warning'
                    "
                    @click="selectAuncel"
                  >
                    {{ currentAuncel.weightData }}
                  </view>
                  <view class="weight-unit">{{ currentAuncel.weightUnit }}</view>
                </view>
              </view>
            </view>
          </view>
          <view>
            <view style="padding: 0rpx 60rpx 10rpx 60rpx">
              <block v-if="currentAuncel.code !== ''">
                <u-button
                  style="height: 140rpx; font-size: 80rpx"
                  type="success"
                  :disabled="confirmWeightDisabled"
                  shape="circle"
                  @click="confirm"
                  >确认采集</u-button
                >
              </block>
            </view>
          </view>
        </view>
      </u-col>
      <u-col span="3">
        <view class="content-main-height">
          <scroll-view scroll-y scroll-with-animation class="content-main-right" :scroll-top="scrollTop">
            <view
              v-for="(sample, index) in finishWeighSampleList"
              :key="index"
              class="u-tab-item"
              style="height: 240rpx"
            >
              <u-row gutter="20" style="width: 100%">
                <u-col span="3" style="padding: 0rpx">
                  <view>
                    <text>【{{ sample.sort }}】</text>
                  </view>
                  <view style="padding-top: 20rpx">
                    <text>{{ sample.cupNum }}号杯</text>
                  </view>
                  <view v-if="sample.remarks" style="padding-top: 20rpx">
                    <text>{{ sample.remarks }}</text>
                  </view>
                </u-col>
                <u-col span="9">
                  <view>
                    <text>{{ sample.sampleCode }}</text>
                  </view>
                  <view style="padding-top: 20rpx">
                    <text>{{ sample.dataSourceType | getDataSourceTypeShow }}{{ sample.goodsName }}</text>
                  </view>
                  <view style="padding-top: 20rpx">
                    <text style="padding-left: 20rpx">{{ sample.sampleWeight }} g</text>
                    <u-button style="margin-left: 20rpx" size="mini" type="error" @click="weighRevoke(sample.id)"
                      >撤销</u-button
                    >
                  </view>
                </u-col>
              </u-row>
            </view>
          </scroll-view>
          <view class="content-main-right-operation">
            <u-row>
              <u-col span="2"></u-col>
              <u-col span="8">
                <u-button
                  :disabled="finishWeighSampleList.length == 0"
                  class="btn-operation"
                  type="success"
                  @click="submit"
                  >立即提交</u-button
                >
              </u-col>
              <u-col span="2"></u-col>
            </u-row>
          </view>
        </view>
      </u-col>
    </u-row>
  </view>
</template>

<script>
export default {
  data() {
    return {
      scrollTop: 0, //tab标题的滚动条位置
      current: 0, // 预设当前项的值
      menuHeight: 0, // 左边菜单的高度
      menuItemHeight: 0, // 左边菜单item的高度
      orderWeighChecked: true, //顺序称重
      weightDataIsToZero: false, //重量数据是否归零
      currentCupNum: '',
      currentSample: {}, //当前样品
      currentTaskNo: '', //当前任务样品
      currentTaskType: '', //当前任务类型
      currentAuncel: {
        id: '',
        name: '',
        code: '',
        weightStable: 0,
        weightData: '请选天平',
        weightUnit: ''
      },
      allWeighSampleCount: 0,
      notWeighSampleList: [],
      finishWeighSampleList: []
    }
  },
  computed: {
    confirmWeightDisabled() {
      if (
        this.currentSample.sampleCode &&
        this.currentAuncel.weightStable == 1 &&
        Number(this.currentAuncel.weightData) > 0
      ) {
        return false
      }
      return true
    },
    checkCupNumReadonly() {
      if (!this.currentAuncel || this.currentAuncel.id == '') return true
      return false
    }
  },
  onLoad(param) {
    //console.log(param);
    if (param.currentTaskNo) {
      this.currentTaskNo = param.currentTaskNo
      this.currentTaskType = param.currentTaskType
    }
    if (param.currentAuncelId) {
      this.currentAuncel.id = param.currentAuncelId
      this.currentAuncel.weightData = ''
    }
    if (param.currentAuncelName) {
      this.currentAuncel.name = param.currentAuncelName
    }
    if (param.currentAuncelCode) {
      this.currentAuncel.code = param.currentAuncelCode
    }
    this.getAssayTaskDetail(this.currentTaskNo)
  },
  onShow() {
    console.log('onShow')

    //注册websocket
    let regData = {
      msgId: this.$helper.uuid(),
      cmd: 'register',
      clientType: 'caaClient',
      data: {
        userId: this.userInfo.user_id,
        tenantId: this.userInfo.tenant_id,
        userRealName: this.userInfo.real_name
      }
    }
    this.$measure.setRegData(JSON.stringify(regData))
    this.$measure.reOpen()

    //监听websocket返回来的数据
    //设备数据
    uni.$on('deviceData', res => {
      switch (res.deviceType) {
        case 'auncel':
          //console.log(res);
          if (this.currentAuncel.id === res.deviceId) {
            this.currentAuncel.weightData = res.weightData
            this.currentAuncel.weightUnit = res.weightUnit
            this.currentAuncel.weightStable = res.weightStable
            this.currentAuncel.isConnected = 1
            if (Number(res.weightData) == 0) {
              this.weightDataIsToZero = true
            }
          }
          break
        default:
          break
      }
    })
    //设备状态
    uni.$on('deviceStatus', res => {
      if (this.currentAuncel.id === res.deviceId) {
        console.log(res)
        if (res.connected == 0) {
          this.currentAuncel.weightStable = 0
          this.currentAuncel.weightData = '天平断开'
          this.currentAuncel.weightUnit = ''
        }
      }
      this.currentAuncel.isConnected = res.connected
    })
    //控制设备状态
    uni.$on('controlDevice', res => {
      if (this.currentAuncel.id === res.deviceId) {
        console.log(res)

        this.currentAuncel.id = ''
        this.currentAuncel.name = ''
        this.currentAuncel.code = ''
        this.currentAuncel.weightStable = 0
        this.currentAuncel.weightData = '请选天平'
        this.currentAuncel.weightUnit = ''
      }
    })
    //连接断开
    uni.$on('connClose', res => {
      //重置
      this.currentAuncel.weightData = ''
      this.currentAuncel.weightUnit = ''
      this.currentAuncel.weightStable = 0
      this.currentAuncel.controlUserName = ''
      this.currentAuncel.isConnected = 0
    })
  },
  onHide() {
    console.log('onHide')
    //移除监听websocket返回来的数据
    uni.$off('deviceData')
    uni.$off('deviceStatus')
    uni.$off('controlDevice')
    uni.$off('connClose')
  },
  onUnload() {
    //取消控制
    //发送控制请求
    let controlDevice = {
      msgId: this.currentAuncel.id,
      cmd: 'controlDevice',
      clientType: 'caaClient',
      data: {
        deviceId: this.currentAuncel.id,
        isControl: false,
        controlRealName: this.userInfo.username
      }
    }
    //发送控制数据
    this.$measure.send(JSON.stringify(controlDevice))
  },
  methods: {
    //返回上一页
    customBack() {
      uni.redirectTo({
        url: '/pages/sample/sample-weigh'
      })
    },
    //切换样品
    async swichSample(index) {
      if (index == this.current) return
      if (this.orderWeighChecked) return //顺序称重不允许选中
      this.current = index
      // 如果为0，意味着尚未初始化
      if (this.menuHeight == 0 || this.menuItemHeight == 0) {
        await this.getElRect('menu-scroll-view', 'menuHeight')
        await this.getElRect('u-tab-item', 'menuItemHeight')
      }
      // 将菜单菜单活动item垂直居中
      this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2
      this.currentSample = this.notWeighSampleList[index]
    },
    // 获取一个目标元素的高度
    getElRect(elClass, dataVal) {
      new Promise((resolve, reject) => {
        const query = uni.createSelectorQuery().in(this)
        query
          .select('.' + elClass)
          .fields({ size: true }, res => {
            // 如果节点尚未生成，res值为null，循环调用执行
            if (!res) {
              setTimeout(() => {
                this.getElRect(elClass)
              }, 10)
              return
            }
            this[dataVal] = res.height
          })
          .exec()
      })
    },
    confirm() {
      //保存数据
      if (!this.weightDataIsToZero) {
        this.$helper.showToast({
          title: '天平必须先回零！'
        })
        return
      }
      //获取当前重量
      let weight = this.currentAuncel.weightData
      //获取当前样品
      let sample = this.notWeighSampleList[this.current]
      //判断杯号
      if (this.currentCupNum == null || typeof this.currentCupNum == 'undefined') this.currentCupNum = ''
      if (this.currentCupNum === '') {
        this.$helper.showToast({
          title: '杯号不允许为空！'
        })
        return
      }

      if (this.current < this.notWeighSampleList.length - 1) {
        this.currentSample = this.notWeighSampleList[this.current + 1]
      }
      //杯号
      sample.cupNum = this.currentCupNum
      //删除当前样品
      this.notWeighSampleList.splice(this.current, 1)
      //样品重量赋值
      sample.sampleWeight = weight
      //天平编号赋值
      sample.auncelNo = this.currentAuncel.code
      if (sample.remarks) {
        sample.remarks = sample.remarks + '%'
      }
      this.$u.api
        .auncelWeigh(sample)
        .then(res => {
          //this.finishWeighSampleList.push(sample);
          //确认采集重量后，归零设为false
          this.weightDataIsToZero = false
          this.getAssayTaskDetail(this.currentTaskNo)
          if (this.orderWeighChecked) {
            this.current = 0
          } else {
            this.current = -1
            this.currentSample = {}
          }
        })
        .catch(err => {
          this.showLoading = false
          console.log(err)
        })
    },
    submit() {
      if (this.notWeighSampleList.length != 0) {
        this.$helper.showToast({
          title: '当前任务“' + this.currentTaskNo + '”尚未完成称重！'
        })
        return
      }
      uni.showModal({
        title: '提示',
        content: '确定提交数据？',
        cancelColor: '#0055A2',
        confirmColor: '#0055A2',
        success: res => {
          if (res.cancel) {
            console.log('用户点击取消')
            return
          }
          //显示loading
          uni.showLoading({
            title: '正在提交...'
          })
          this.$u.api
            .weighBatchSubmitByTaskNo(this.currentTaskNo)
            .then(res => {
              this.$helper.showToast({
                title: '提交成功！'
              })
              uni.redirectTo({
                url: '/pages/sample/sample-weigh'
              })
              uni.hideLoading()
            })
            .catch(err => {
              uni.hideLoading()
              this.$helper.showToast({
                title: '提交失败！'
              })
              console.log(err)
            })
        }
      })
      /**
       if(this.currentTaskType == 4) { //临时样
       let ids = [];
       this.finishWeighSampleList.forEach(item => {
       ids.push(item.id);
       });

       this.$u.api
       .weighBatchSubmitByIds(ids.join(","))
       .then(res => {
       this.$helper.showToast({
       title: '提交成功！'
       });
       })
       .catch(err => {
       this.showLoading = false;
       console.log(err);
       });
       } else {//其他批量秤完提交
       //if(this.allWeighSampleCount == this.finishWeighSampleList.length) {
       console.log(this.notWeighSampleList)
       if(this.notWeighSampleList.length == 0) {
       this.$u.api
       .weighBatchSubmitByTaskNo(this.currentTaskNo)
       .then(res => {
       this.$helper.showToast({
       title: '提交成功！'
       });
       uni.redirectTo({
       url: '/pages/sample/sample-weigh'
       });
       })
       .catch(err => {
       this.showLoading = false;
       console.log(err);
       });
       } else {
       this.$helper.showToast({
       title: '当前任务“'+this.currentTaskNo+'”尚未完成称重！'
       });
       return;
       }
       }
       **/
    },
    weighRevoke(id) {
      uni.showModal({
        title: '提示',
        content: '确定撤销当前数据？',
        cancelColor: '#0055A2',
        confirmColor: '#0055A2',
        success: res => {
          if (!res.confirm) {
            console.log('用户点击取消')
            return
          }
          this.$u.api
            .auncelWeighRevoke(id)
            .then(res => {
              this.getAssayTaskDetail(this.currentTaskNo)
              if (this.orderWeighChecked) {
                this.current = 0
              } else {
                this.current = -1
                this.currentSample = {}
              }
            })
            .catch(err => {
              this.showLoading = false
              console.log(err)
            })
        }
      })
    },
    //自动生成杯号（仅顺序称重）：第一杯：手填，后续杯 = 上一杯 + 1
    autoGenerateCupNum() {
      if (!this.orderWeighChecked) return
      //取上一杯
      this.currentCupNum = ''
      let preSample = null
      if (this.finishWeighSampleList && this.finishWeighSampleList.length > 0) preSample = this.finishWeighSampleList[0]
      if (preSample == null) {
        return
      }
      const cupNum = preSample.cupNum
      if (!isNaN(cupNum)) this.currentCupNum = Number(cupNum) + 1
    },
    getAssayTaskDetail(taskNo) {
      this.notWeighSampleList = []
      this.finishWeighSampleList = []
      this.$u.api
        .getAssayTaskDetailListByTaskNo({ taskNo: taskNo })
        .then(res => {
          let dataList = res.result
          this.allWeighSampleCount = dataList.length
          dataList.forEach((item, index) => {
            if (item.weightSubmitStatus == 0) {
              this.notWeighSampleList.push(item)
            } else if (item.weightSubmitStatus == 1) {
              this.finishWeighSampleList.unshift(item)
              //this.finishWeighSampleList.push(item);
            }
          })
          this.showLoading = false
          //console.log(this.currentSample);
          if (this.notWeighSampleList[0]) {
            if (this.orderWeighChecked) {
              this.current = 0
              this.currentSample = this.notWeighSampleList[0]
            } else {
              this.current = -1
              this.currentSample = {}
            }
          }
          this.autoGenerateCupNum() //计算生成当前杯号
        })
        .catch(err => {
          this.showLoading = false
          console.log(err)
        })
    },
    selectAuncel() {
      if (this.currentAuncel.weightData === '请选天平') {
        uni.navigateTo({
          url:
            '/pages/auncel/auncel-select?currentTaskNo=' +
            this.currentTaskNo +
            '&currentTaskType=' +
            this.currentTaskType
        })
      }
    },
    orderWeighChange(e) {
      if (e && this.notWeighSampleList.length > 0) {
        //this.current = 0;
        //this.currentSample = this.notWeighSampleList[0];
        this.getAssayTaskDetail(this.currentTaskNo)
        return
      }
      this.current = -1
      this.currentSample = {}
    }
  },
  filters: {
    getDataSourceTypeShow(val) {
      if (val == 2) return '【筛上】'
      if (val == 3) return '【筛下】'
      return ''
    }
  }
}
</script>
<style lang="scss" scoped>
.content-title {
  height: 110rpx;
  width: 100%;
  font-size: 46rpx;
  font-weight: 300;
}

.content-title-name {
  padding: 20rpx;
  text-align: center;
}

.content-main-height {
  height: calc(100vh - 250rpx);
}

.content-main-left {
  height: calc(100vh - 410rpx);
  background-color: #f6f6f6;
}

.u-tab-item {
  height: 160rpx;
  background: #f6f6f6;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  color: #444;
  font-weight: 400;
  line-height: 1;
  border-width: 4rpx;
  border-bottom: dotted;
}

.u-tab-item-active {
  position: relative;
  color: #0055a2;
  font-size: 36rpx;
  font-weight: 600;
  background: #fff;
}

.u-tab-item-active::before {
  content: '';
  position: absolute;

  height: 32rpx;
  left: 0;
  top: 39rpx;
}

.content-main-left-operation {
  height: 160rpx;
  padding-top: 30rpx;
}

.content-main-right {
  height: calc(100vh - 410rpx);
}

.content-main-right-operation {
  height: 160rpx;
  padding-top: 30rpx;
}

.btn-operation {
  height: 100rpx;
  font-size: 36rpx;
}

.auncel-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.auncel {
  width: 800rpx;
  height: 800rpx;
  background-image: url(../../static/images/auncel.png);
  background-repeat: no-repeat;
  background-size: 100%;
}

.auncel-title {
  width: 100%;
  height: 420rpx;
}

.auncel-weight {
  padding: 40rpx;
}

.weight {
  width: 100%;
  min-width: 200px;
  height: 200rpx;
  padding: 0 30rpx;
  display: flex;
  flex-direction: row;
  //background-color: #2c405a;
}

.weight-data {
  flex-grow: 1;
  height: 100%;
  color: #4cd964;
  text-align: right;
  line-height: 200rpx;
  letter-spacing: 4rpx;
  font-size: 150rpx;
  font-family: zzjc-lcd;
}

.weight-data-yellow {
  flex-grow: 1;
  height: 100%;
  color: #ffff00;
  text-align: right;
  line-height: 200rpx;
  letter-spacing: 4rpx;
  font-size: 150rpx;
  font-family: zzjc-lcd;
}

.weight-data-warning {
  flex-grow: 1;
  height: 100%;
  color: #ff3333;
  text-align: right;
  line-height: 200rpx;
  font-size: 150rpx;
  font-family: zzjc-lcd;
}

.weight-unit {
  color: #ffffff;
  font-size: 130rpx;
  line-height: 200rpx;
  padding-left: 20rpx;
}
</style>
