<template>
  <gui-page :custom-header="true" :is-header-sized="false" :header-class="['gui-theme-background-color']">
    <template #gHeader>
      <view style="height:44px;" class="gui-flex gui-nowrap gui-rows gui-align-items-center">
        <!-- 使用组件实现返回按钮及返回首页按钮 -->
        <text
          style="font-size:44rpx;"
          class="gui-header-leader-btns gui-color-white font-icons"
          @tap="goBack"
        >&#xe6c5;</text>
        <!-- 导航文本此处也可以是其他自定义内容 -->
        <text
          class="gui-h4 gui-blod gui-flex1 gui-text-center gui-ellipsis gui-color-white gui-primary-text"
        >物料拆合</text>
        <!-- 此处加一个右侧展位元素与左侧同宽，实现标题居中 -->
        <!-- 实际宽度请根据自己情况设置 -->
        <view style="width:40px;" />
        <!-- 如果右侧有其他内容可以利用条件编译和定位来实现-->
      </view>
    </template>
    <template #gBody>
      <view class="form">
        <view class="row-1">
          <view class="row-1-card">
            <uni-easyinput
              ref="easyinput"
              v-model="submitParams.materialNo"
              :input-border="false"
              :clearable="false"
              type="text"
              focus
			  @focus="handleInputFocus"
              placeholder="请扫描物料"
              @confirm="confirmMaterial"
            />
            <text class="font-icons" @click="handleMapass">&#xe6b7;</text>
          </view>
        </view>
        <view class="row-2">
          <view class="row-2-card">
            <uni-easyinput
              ref="easyinput2"
              v-model="submitParams.splitQty"
              :input-border="false"
              :clearable="false"
              type="number"
              focus
			  @focus="handleInputFocus"
              placeholder="请输入拆分数量"
            />
          </view>
        </view>
        <view class="row-3">
          <view class="row-3-card">
            <view class="row-space-between">
              <text>物料编码</text>
              <text>{{ submitParams.materialNo }}</text>
            </view>
            <view class="row-space-between">
              <text>物料名称</text>
              <text>{{ submitParams.materialName }}</text>
            </view>
            <view class="row-space-between">
              <text>物料批次</text>
              <text>{{ submitParams.materialLots }}</text>
            </view>
            <view class="row-space-between">
              <text>批次数量</text>
              <text>{{ submitParams.inQty }}</text>
            </view>
          </view>
        </view>
        <view class="row-operation">
          <view class="row-operation-card">
            <view class="button" size="primary" @click="handleSplit">
              <text class="gui-color-white">拆分</text>
            </view>
          </view>
        </view>
        <uni-popup ref="errorTip" type="dialog">
          <uni-popup-dialog
            type="error"
            cancel-text="关闭"
            confirm-text="确认"
            title="提示"
            :content="errorTipMessage"
            @confirm="handleCloseErrorTipsModal"
            @close="handleCloseErrorTipsModal"
          />
        </uni-popup>
      </view>
    </template>
  </gui-page>
</template>

<script>
import {
  defineComponent,
  ref
} from 'vue'
export default defineComponent({
  setup() {
    const goBack = function() {
      uni.$goBack('/pages/workbranch/warehouse/materialDisass/materialWorkBranch')
    }
    const errorTip = ref('')
    const errorTipMessage = ref('')
    const easyinput = ref('')
    const easyinput2 = ref('')
    const errorState = ref(0)
    const isFetch = ref(false)
    const submitParams = ref({
      splitQty: '', // 拆分数量
      materialNo: '', // 物料编码
      materialName: '', // 物料名称
      materialLots: '', // 物料批次
      inQty: '' // 批次数量
    })
    // 校验参数
    const validatorList = ref({
      splitQty: '拆分数量',
      materialNo: '物料编码',
      materialName: '物料名称',
      materialLots: '物料批次',
      inQty: '批次数量'
    })
    const handleMapass = function() {
      // #ifdef APP-PLUS
      const mpaasScanModule = uni.requireNativePlugin('Mpaas-Scan-Module')
      mpaasScanModule.mpaasScan({
        // 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
        'scanType': ['qrCode', 'barCode'],
        // 是否隐藏相册，默认false不隐藏
        'hideAlbum': false
      },
      (ret) => {
        if (ret.resp_code === 1000) {
          uni.$reqGet('splitOrMergeScanMaterial', {
            qrCode: ret.resp_result
          })
            .then(({
              code,
              data,
              msg
            }) => {
              if (code === 0) {
                submitParams.value.id = data?.id // 物料编码
                submitParams.value.qrCode = data?.qrCode
                submitParams.value.materialNo = data?.materialNo // 物料编码
                submitParams.value.materialName = data?.materialName // 物料名称
                submitParams.value.materialLots = data?.qrCode // 物料批次
                submitParams.value.inQty = data?.inQty // 批次数量
              } else {
                // #ifdef APP-PLUS
                plus.device.beep(2)
                // #endif
                errorTipMessage.value = msg
                errorTip.value.open()
                errorState.value = 0
              }
            })
        }
      })
      // #endif
    }

    // 扫描物料输入框回车事件
    const confirmMaterial = function(e) {
      uni.$reqGet('splitOrMergeScanMaterial', {
        qrCode: e
      })
        .then(({
          code,
          data,
          msg
        }) => {
          if (code === 0) {
            submitParams.value.id = data?.id // 物料编码
            submitParams.value.qrCode = data?.qrCode
            submitParams.value.materialNo = data?.materialNo // 物料编码
            submitParams.value.materialName = data?.materialName // 物料名称
            submitParams.value.materialLots = data?.qrCode // 物料批次
            submitParams.value.inQty = data?.inQty // 批次数量
          } else {
            // #ifdef APP-PLUS
            plus.device.beep(2)
            // #endif
            errorTipMessage.value = msg
            errorTip.value.open()
            errorState.value = 0
          }
        })
    }

    // 拆分
    const handleSplit = function() {
      if (isFetch.value === true) {
        uni.showToast({
          title: '物料拆分中...',
          icon: 'none',
          duration: 2000
        })
      } else {
        const keys = Object.keys(submitParams.value)
        for (let x = 0; x < keys.length; x++) {
          const validataIsItEmpty = ['', null, undefined, NaN].includes(submitParams.value[keys[
            x]])
          if (validataIsItEmpty) {
            uni.showToast({
              title: validatorList.value[keys[x]] + '不能为空！',
              icon: 'none',
              duration: 2000
            })
            return
          }
        }
        isFetch.value = true
        submitParams.value.remainderQty = parseInt(submitParams.value.inQty) - parseInt(
          submitParams.value.splitQty)
        uni.$reqPost('materialSplit', submitParams.value)
          .then(({
            code,
            data,
            msg
          }) => {
            isFetch.value = false
            submitParams.value.splitQty = 0
            submitParams.value.id = ''
            submitParams.value.qrCode = ''
            submitParams.value.materialNo = ''
            submitParams.value.materialName = ''
            submitParams.value.materialLots = ''
            submitParams.value.inQty = ''
            if (code === 0) {
              const copyData = JSON.parse(JSON.stringify(data)) ?? []
              // 时间格式转换
              copyData.forEach(item => {
                item.createTime = $parseTime(item
                  .createTime)
              })
              const message = {
                'ClientId': 'webclient',
                'templateName': 'http://192.168.1.156:9900/Upload/Tables/s_reportmodel/202303011142368103/materialSplit.btw',
                'DataList': data
              }
              // uni.$useStore().mqttConfig.publish('adminS001', JSON.stringify(message), {
              //   qos: 1
              // })
            } else {
              // #ifdef APP-PLUS
              plus.device.beep(2)
              // #endif
              errorTipMessage.value = msg
              errorTip.value.open()
              errorState.value = 0
            }
          })
      }
    }

    const setInputFocus = function() {
      submitParams.value.materialNo = ''
      easyinput.value.onBlur()
      easyinput.value.onFocus()
    }

    // 关闭错误信息弹窗
    const handleCloseErrorTipsModal = async function() {
      errorTip.value.close()
      if (errorState.value === 0) {
        await setInputFocus()
      }
    }
	
	// 禁用软键盘
	const handleInputFocus = function() {
		setTimeout(() => {
			uni.hideKeyboard()
		}, 100)
	}
	
    return {
      goBack,
      easyinput,
      easyinput2,
      errorTip,
      errorTipMessage,
      submitParams,
      handleMapass,
      handleSplit,
      confirmMaterial,
	  handleInputFocus,
      handleCloseErrorTipsModal
    }
  }
})
</script>

<style lang="scss" scoped>
	.gui-header-leader-btns {
		color: black;
		font-size: 24px !important;
		margin-left: 24rpx;
	}

	.gui-sbody {
		font-size: 14px;
		background-color: rgba(234, 239, 242, 1);
	}

	.form {
		margin-top: 85px;
	}

	.row-1,
	.row-3 {
		height: 55px;
		display: flex;
		justify-content: center;
		background-color: white;
	}

	.row-2 {
		height: 55px;
		display: flex;
		background-color: white;
	}

	.row-2,
	.row-3 {
		margin-top: 10px;
	}

	.row-1 {

		.row-1-card {
			flex: 1;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
		}
	}

	.row-3 {
		height: 200px;

		.row-3-card {
			display: flex;
			flex-direction: column;

			.row-space-between {
				flex: 1;
				width: calc(100vw - 40px);
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				padding-left: 20px;
				padding-right: 20px;
				padding-top: 12px;
				padding-bottom: 12px;
			}
		}

	}

	.row-1-card,
	.row-2-card {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		padding-left: 10px;
		padding-right: 10px;
	}

	.row-operation {
		height: 110px;
		padding-left: 20px;
		padding-right: 20px;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;

		.row-operation-card {
			flex: 1;

			.btn-row-1 {
				margin-bottom: 5px !important;
			}
		}
	}

	.input-200 {
		width: 200px;
		padding-left: 10px;
	}

	.input-300 {
		width: 300px;
		padding-left: 10px;
	}

	.font-icons {
		width: 40px;
		font-size: 20px;
	}
</style>
