<template>
  <view class="page-offline-in">
    <view class="header" :style="{ backgroundColor: `rgba(23, 83, 234, ${scrollTop / 100})` }">
      <view class="left">
        <u-icon class="icon" name="arrow-left" @click="uni.navigateBack()" />
      </view>
      <view class="title">成品下线入库</view>
      <view class="right"></view>
    </view>
    <wyb-table
      class="table"
      ref="table"
      width="100%"
      enable-check="multiple"
      show-left-and-right-border
      first-col-bg-color="#fff"
      :headers="[{ label: '条码', key: 'code', width: 620 }]"
      :contents="barCodeList"
      :show-vert-border="false"
    />
    <view class="bottom-bar">
      <view class="extra">
        <u-row>
          <u-col :span="2"> 条码 </u-col>
          <u-col :span="10">
            <u-input placeholder="条码" v-model="form.barCode" @confirm="onBarCodeConfirm" />
          </u-col>
        </u-row>
        <u-row>
          <u-col :span="2"> LPN </u-col>
          <u-col :span="3">
            <u-input placeholder="LPN" :disabled="!isLPNEditable" v-model="form.trayNo" />
          </u-col>
          <u-col :span="2"> 合计 </u-col>
          <u-col :span="3"> {{ barCodeList.length }} </u-col>
        </u-row>
      </view>
      <view class="container">
        <u-row>
          <u-col :span="6">
            <u-button type="error" @click="onDeleteBarCodeListItem">删除</u-button>
          </u-col>
          <u-col :span="6">
            <u-button type="primary" @click="onConfirmInbound">收货完成</u-button>
          </u-col>
        </u-row>
      </view>
    </view>
  </view>
</template>

<script lang="ts">
import { Component } from 'vue-property-decorator';
import { BasePage } from '@/components/base/page';
import dayjs from 'dayjs';
import { session } from '@/store/modules/session';
import model from './model';

@Component
export default class OfflineIn extends BasePage {
  // 页面 model
  model = model;

  // 物料类型编码（确定于第一个扫描条码）
  productTypeCode = '';

  // 页面表单
  form = {
    barCode: '',
    trayNo: '',
  };

  // 条码列表
  barCodeList: Array<{ code: string; checked: boolean }> = [];

  // LPN 输入框是否可编辑
  get isLPNEditable() {
    return this.productTypeCode === '';
  }

  /**
   * 条码验证
   */
  async onBarCodeConfirm() {
    const toast = (title: string) => uni.showToast({ icon: 'none', title });

    // 本地验证
    if (this.barCodeList.length === 500) {
      toast('扫描数量已到上限，请先点击【完成】上架后再继续扫描！');
      return;
    }

    const barCode = this.form.barCode;

    if (getProductTypeCode(barCode) === '') {
      toast('输入条码错误必须20/22位！');
      return;
    }

    if (!new RegExp('[0-9a-zA-Z]+$').test(barCode)) {
      toast('海尔条码不允许有特殊符号，请核实条码是否正确", "扫描条码错误');
      return;
    }

    if (
      // 如果是佛山滚筒工厂，判断是不是滚筒的条码（"CE"开头）
      session.factoryCode === '1045' &&
      barCode.length === 20 &&
      barCode.substring(0, 2) !== 'CE'
    ) {
      toast('当前条码非滚筒条码！');
      return;
    }

    if (
      (barCode.length === 20 && barCode.charAt(15) === 'Y') ||
      (barCode.length === 22 && barCode.charAt(17) === 'Y')
    ) {
      toast('样品机不允许入库');
      return;
    }

    // 第一次扫描条码时，创建物料类型编码
    if (this.productTypeCode === '') {
      this.productTypeCode = getProductTypeCode(this.form.barCode);
    }

    if (getProductTypeCode(this.form.barCode) !== this.productTypeCode) {
      toast(`当前条码对应物料${getProductTypeCode(this.form.barCode)}与当前物料不一致！`);
    }

    if (this.barCodeList.some((item) => item.code === barCode)) {
      toast('输入的条码重复！');
      return;
    }

    // 如果托盘号为空，生成托盘号
    if (this.form.trayNo === '') {
      this.form.trayNo = createTrayNo();
    }

    // 服务端验证
    const params = {
      factoryCode: '1999',
      user: '1999',
      sign: '', // 固定为 ''
      areaCode: '19990009',
      regionCode: '1999C11',
      whCode: '1999C1',
      productCode: this.productTypeCode,
      trackNo: this.form.trayNo,
      paras: [barCode],
    };
    try {
      const dt = await model.validateBarCode(params);
      console.log('status', dt);
      if (dt.status !== 'S') {
        toast('扫描失败!');
        if (this.barCodeList.length === 0) {
          this.productTypeCode = '';
        }
        return;
      }

      this.barCodeList = [...this.barCodeList, { code: barCode, checked: false }];
    } catch {
      if (this.barCodeList.length === 0) {
        this.productTypeCode = '';
      }
    }
  }

  /**
   * 删除条码
   */
  onDeleteBarCodeListItem() {
    this.barCodeList = this.barCodeList.filter((item) => !item.checked);
  }

  /**
   * 确认收货
   */
  async onConfirmInbound() {
    if (this.form.trayNo == null || this.form.trayNo === '') {
      uni.showToast({ icon: 'none', title: '托盘号不能为空' });
      return;
    }
    if (this.barCodeList.length === 0) {
      uni.showToast({ icon: 'none', title: '请先扫描条码' });
      return;
    }
    this.form.barCode = '';

    const params = {
      sign: '',
      factoryCode: '1999',
      user: '1999',
      areaCode: '19990009',
      regionCode: '1999C11',
      whCode: '1999C1',
      remark: '1',
      productCode: this.productTypeCode,
      trackNo: this.form.trayNo.toUpperCase(),
      paras: this.barCodeList.map((item) => item.code),
    };

    const { status, msg } = await model.inbound(params);
    if (status !== 'S') {
      uni.showToast({ icon: 'none', title: msg });
    } else {
      this.productTypeCode = '';
      this.barCodeList = [];
      this.form.trayNo = '';
    }
  }

  mounted() {
    this.productTypeCode = '';
  }
}

/**
 * 获取物料类型编码（从 barCode）
 * @param barCode 条码
 */
function getProductTypeCode(barCode: string) {
  if (barCode == null || barCode === '') {
    return '';
  }
  if (barCode.length === 20) {
    return barCode.substring(0, 9).toUpperCase();
  }
  if (barCode.length === 22) {
    return barCode.substring(0, 11).toUpperCase();
  }
  return '';
}

/**
 * 创建托盘号
 */
function createTrayNo() {
  let ret = '';
  ret += 'XP';
  ret += dayjs().format('DDHHmmss');
  ret += Math.floor(Math.random() * 100)
    .toString()
    .padStart(2, '0');
  return ret;
}
</script>

<style lang="scss" scoped>
.page-offline-in {
  background: #f2f2f2 linear-gradient(0deg, #f2f2f2 0%, #4a78ea 51%, #1753ea 100%) no-repeat;
  background-size: 100% 600rpx;
  padding: 118rpx 30rpx 280rpx;
  min-height: 100%;

  .header {
    position: fixed;
    top: 36rpx;
    left: 0;
    right: 0;
    z-index: 99;
    display: flex;
    height: 88rpx;
    line-height: 88rpx;
    color: #fff;
    font-size: 34rpx;
    font-weight: 500;
    text-align: center;
    .title {
      flex: 3;
    }
    .left,
    .right {
      flex: 1;
    }
    .icon {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 88rpx;
      height: 88rpx;
    }
  }

  .form {
    background-color: #fff;
    padding: 40rpx;
    border-radius: 10rpx;
    box-shadow: 0 0 20rpx 0 rgba(128, 128, 128, 0.2);

    .u-form-item {
      padding: 30rpx 0;
      line-height: 35rpx;
    }
  }

  .bottom-bar {
    z-index: 21;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;

    .container {
      background: #ffffff;
      box-shadow: 0 1rpx 20rpx 0 rgba(128, 128, 128, 0.2);
      padding: 20rpx;
    }

    .extra {
      background-color: #fff;
      margin: 5px;
      border-radius: 5px;
      padding: 0 10px;
    }

    .bottom-info {
      .u-form-item {
        padding: 0;
      }
    }
  }
}
</style>
