<script lang="ts" setup>
import { getOperatoringCheckAPI, postOperatoringReturnAPI, postOperatoringUploadAPI } from '@/api/warehouse'
import { scanCode } from '@/utils/tools'

definePage({
  style: {
    navigationBarTitleText: '',
    navigationBarBackgroundColor: '#1488f5',
    navigationBarTextStyle: 'white',
  },
})
const btnStyle = computed(() => ({
  backgroundColor: '#f1f8fd',
  color: '#64a3db',
  borderColor: '#64a3db',
}))
const pageType = ref('1') // 1:领料 2:还料
const paging = ref(null)
const loading = ref(false)
const tableData = ref<any>([])
const popupRef = ref(null)
const formData = reactive({
  batteryCode: '',
})
const submitConfig = reactive({
  loadingText: '提交中...',
  loading: false,
})

function handleScan() {
  scanCode({
    success(res: any) {
      const { code } = res
      addCode(code)
    },
    fail(res) {
      console.log(res)
    },
  })
}

function handleAddByCode() {
  popupRef.value.open('bottom')
}

// 添加
async function addCode(code: string, callback = null) {
  if (!code) {
    uni.showToast({
      title: '请输入电池编号',
      icon: 'none',
    })
    return
  }
  // 判断列表中是否存在该编号
  if (tableData.value.some(item => item.batteryCode === code)) {
    uni.showToast({
      title: '该编号已存在',
      icon: 'none',
    })
    return
  }

  // 电池检测
  try {
    uni.showLoading({
      title: '正在添加...',
    })
    const res: any = await getOperatoringCheckAPI({
      code,
    })
  }
  catch (error) {
    console.error(error)
    uni.showToast({
      title: '电池编号错误',
      icon: 'none',
    })
    return
  }
  finally {
    uni.hideLoading()
  }

  tableData.value.push({
    batteryCode: code,
  })

  callback && callback()
}

function handleDelete(index: number) {
  tableData.value.splice(index, 1)
}

function popupClose() {
  formData.batteryCode = ''
}

// 重置列表
function resetData() {
  tableData.value = []
}

async function handleSubmit() {
  if (tableData.value && tableData.value.length === 0) {
    uni.showToast({
      title: '请添加电池编号',
      icon: 'none',
    })
    return
  }
  submitConfig.loading = true
  try {
    const codes = tableData.value.map(it => it.batteryCode)
    console.log(codes)

    if (pageType.value === '1') {
      const res = await postOperatoringUploadAPI({ codes })
    }
    else {
      const res = await postOperatoringReturnAPI({ codes })
    }
    uni.showToast({
      title: pageType.value === '1' ? '领料成功' : '还料成功',
    })
    resetData()
  }
  catch (err) {
    uni.showToast({
      title: '提交失败',
      icon: 'none',
    })
  }
  finally {
    submitConfig.loading = false
  }
}

onLoad((query) => {
  const { type } = query
  pageType.value = type
  uni.setNavigationBarTitle({
    title: type === '1' ? '领电池' : '还电池',
  })
})

onMounted(() => {

})
</script>

<template>
  <view>
    <z-paging
      ref="paging"
      bg-color="#f3f3f3"
    >
      <view class="container">
        <uni-table
          ref="table"
          :loading="loading"
          stripe border
          empty-text="请扫码添加设备"
        >
          <uni-tr>
            <uni-th align="center" width="200">
              电池编号
            </uni-th>
            <uni-th align="center" width="100">
              操作
            </uni-th>
          </uni-tr>
          <uni-tr v-for="(item, index) in tableData" :key="index">
            <uni-td align="center">
              {{ item.batteryCode }}
            </uni-td>
            <uni-td>
              <view class="uni-group">
                <button class="uni-button" size="mini" type="warn" @click="handleDelete(index)">
                  删除
                </button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
      </view>

      <template #bottom>
        <view class="bottom-button-zaping">
          <view class="tools">
            <uv-button text="扫码新增" :custom-style="btnStyle" @click="handleScan" />
            <uv-button text="编号新增" :custom-style="btnStyle" @click="handleAddByCode" />
          </view>
          <uv-button
            type="primary"
            text="确认领取"
            :loading-text="submitConfig.loadingText"
            :loading="submitConfig.loading"
            @click="handleSubmit"
          />
        </view>
      </template>
    </z-paging>
    <!-- 弹窗 -->
    <uv-popup ref="popupRef" round="15" @change="popupClose">
      <view class="popup-content">
        <view class="title">
          电池编号
        </view>
        <view class="input_bar">
          <uv-input v-model="formData.batteryCode" placeholder="请输入" border="surround" />
        </view>
        <view class="btn_bar">
          <uv-button
            type="primary"
            text="添加"
            @click="() => {
              addCode(
                formData.batteryCode,
                function() {
                  popupRef.close()

                })
            }"
          />
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<style lang="scss" scoped>
.tools {
  display: flex;
  justify-content: space-around;
  margin-bottom: 30rpx;
}
.container {
  padding: 20rpx 30rpx;
  width: calc(100% - 60rpx);
}

.uni-group {
  display: flex;
  justify-content: center;
  align-items: center;
}

.popup-content {
  padding: 20rpx;
  width: calc(100% - 40rpx);
  z-index: 9999;

  .title {
    font-size: 30rpx;
    font-weight: bold;
    display: flex;
    justify-content: center;
  }

  .input_bar {
    margin: 30rpx;
  }

  .btn_bar {
    margin-top: 100rpx;
  }
}
</style>
