<template>
  <view class="page-raw-receipt">
    <!-- 头部 -->
    <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">{{ $t('message.dn_ReceivingGoods') }}</view>
      <view class="right"></view>
    </view>
    <view class="content">
      <!-- 单号 -->
      <view class="single">
        <view class="single-left">
          <view>{{ $t('message.dn_OddNumbers') }}</view>
          <u-search :placeholder="$t('message.dn_PleaseScan')" v-model.trim="form.documentNo" @search="query" :show-action="false"></u-search>
        </view>
        <view class="single-right">
          <u-button type="primary" @click="query">{{ $t('message.Query') }}</u-button>
        </view>
      </view>
      <!-- 采购单号 -->
      <view class="Purchase-title">
        <view class="Purchase">
          <view>{{ $t('message.Purchase') }}</view>
          <jPicker sureColor="#ff0000" style="width: 260rpx" @bindpicker="poListChoice" showKey="value" valKey="value" :val="poNo" class="search" :options="poList" />
        </view>
      </view>
      <!-- 物料 -->
      <view class="material">
        <view class="material-left">
          <view>{{ $t('message.Materiel') }}</view>
          <jPicker sureColor="#ff0000" style="width: 260rpx" @bindpicker="materialChoice" showKey="value" valKey="value" :val="every.materialCode" class="search" :options="materialList" />
        </view>
      </view>
      <view class="material"
        ><view class="material-right">
          <view class="material-right-title">{{ $t('message.CommissionedMaterielDesc') }}</view>
          <view class="material-right-code" style="overflow: hidden">{{ every.materialDesc }}</view>
        </view>
      </view>

      <!-- 需求数量 -->
      <view class="number">
        <view class="number-left">
          <view class="number-left-title">{{ $t('message.DemandQuantity') }}</view>
          <u-input v-model="every.requestAmount" placeholder=" " :type="type" :border="border" class="input" disabled style="padding: '0'" />
        </view>
        <view class="number-right">
          <view class="number-right-title">{{ $t('message.Cumulative') }}</view>
          <u-input v-model="every.receiptAmount" placeholder="" :type="type" :border="border" class="input" disabled style="padding: '0'" />
        </view>
      </view>
      <!-- 库位 -->
      <view class="library">
        <view class="library-left">
          <view>{{ $t('message.CommissionedLocation') }}</view>
          <jPicker sureColor="#ff0000" style="width: 230rpx" @bindpicker="LocationChoice" showKey="value" valKey="value" :val="wl.value" class="search" :options="Location" />
        </view>
        <view class="library-right">
          <view class="library-right-title">{{ $t('message.CommissionedThisNumber') }}</view>
          <u-input v-model="receiptAmount" :placeholder="$t('message.po_PleaseInput')" type="number" :border="border" class="input" />
        </view>
      </view>
      <!-- 添加 -->
      <view class="add">
        <u-button type="primary" @click="Add">{{ $t('message.product_add') }}</u-button>
      </view>
      <wyb-table class="table" ref="table" width="100%" show-left-and-right-border :headers="headers" :contents="LocationList" :show-vert-border="false" @onCellClick="deleteItem($event)"></wyb-table>
    </view>
    <!-- 底部按钮 -->
    <view class="bottom-bar">
      <u-row class="button-bar">
        <u-col :span="4">
          <u-button type="primary" @click="bill">{{ $t('message.detailed') }}</u-button>
        </u-col>
        <u-col :span="4">
          <u-button type="primary" @click="onSubmit">{{ $t('message.po_Submit') }}</u-button>
        </u-col>
        <u-col :span="4">
          <u-button type="error" @click="uni.navigateBack({})">{{ $t('message.po_Return') }}</u-button>
        </u-col>
      </u-row>
    </view>
  </view>
</template>
<script lang="ts">
import { Component } from 'vue-property-decorator';
import { BasePage } from '@/components/base/page';
import jPicker from '@/components/J-Picker/jPicker.vue';
import { session } from '@/store/modules/session';
import model from './model';
import LocationDetail from './model.location';
import { headers } from './config';
@Component({
  components: {
    jPicker,
  },
})
export default class dnReceiptDom extends BasePage {
  model = model;
  form: any = {
    documentNo: '',
  };
  // 原始物料列表（这里不准确，要修改）
  material: any = [];
  poList: any = [];
  materialList: any = [];
  // 当前被选择中原材料
  every: any = {};
  everyIndex: any = '';
  value = '';
  headers = headers;
  type = 'text';
  //要提交的数据
  DNReceivingList: any = [];
  border = true;
  //本次数量
  receiptAmount: any = '';
  //库位
  Location: LocationDetail[] = [];
  //添加的库位和数量的列表
  LocationList: any = [];
  //所选择的库位对象
  wl: any = {
    value: null,
  };
  //所选择的采购单号
  poNo: any = null;
  // 需求数量
  requestAmount: number = null;
  // 页面初始化
  // 页面需要清空仓库，因此需要复用该方法
  async initLocation(condition): Promise<LocationDetail[]> {
    console.log('condition>>>>>>>>>>>>>>>>>>.', condition);
    //页面初始化 获取可选库位
    let list: Array<LocationDetail> = [];
    let means: any = JSON.parse(localStorage.getItem('__GWMS_APP_STATE_DATA__') as any);
    let sendSpot = JSON.parse(localStorage.getItem('sendSpot') as any);
    let content = {
      loginName: means.session.user.loginName,
      sendSpot: sendSpot,
      factoryCode: means.session.user.factoryCode,
      workArea: session.workareaCode,
    };
    let res: any = await this.model.queryByFactoryCodeAndWorkAreaCode(content);
    console.log('>>>>>>>>>>>>>>', res);
    res.forEach((item: LocationDetail) => {
      if (item.sendSpot === condition.sendSpot) {
        let pickerName: any = {};
        pickerName.label = item.locationCode;
        pickerName.value = item.locationCode + '(' + item.sendSpot + ')';
        pickerName.sendSpot = item.sendSpot;
        list.push(pickerName);
      }
    });
    return list;
  }
  //输入单号 查询数据
  async query() {
    this.empty()
    if (!this.form.documentNo) {
      this.customToast(this.$t('message.Commission_tips1') as any);
      return;
    }
    await this.model.ImportQueryOrderInfo(this.form.documentNo);
    if (model.code == '1') {
      if(this.model.orderInInfoList.length == 0){
        this.empty()
        return
      }
      uni.showToast({
        icon: 'success',
        title: this.$t('message.successful') as any,
      });
      let list: any = localStorage.getItem('list');
      localStorage.removeItem('list');
      this.material = JSON.parse(list);
      this.DNReceivingList = JSON.parse(list);
      this.DNReceivingList.forEach((item: any) => {
        item.wllist = [];
      });
      this.poList = [...this.DNReceivingList]; //结构
      let arr = this.removeDuplicates(this.poList, 'poNo');
      // 组装下拉结构
      arr.forEach((item: any) => {
        item.label = item.poNo;
        item.value = item.poNo;
      });
      this.poList = arr;
      // 自动化流程改造测试
      this.poListChoice({
        pickerName: this.poList.find(() => true),
      });
    }
  }
  // 去除重复 方法
  // 传入数组 list 及要去重的属性 valueKey
  // 返回去重后的数组对象
  removeDuplicates(list, valueKey: string) {
    let temp = {};
    let arr = [];
    arr = list.reduce(function (item, next) {
      temp[next[valueKey]] ? '' : (temp[next[valueKey]] = true && item.push(next));
      return item;
    }, []);
    return arr;
  }
  // ADD方法后的库存数量检测
  totalLocation(list: []) {
    const receiptAmount = list.reduce((total: number, nextItem: any): any => {
      return total + +nextItem.receiptAmount;
    }, 0);
    return receiptAmount;
  }
  //选择采购单后触发的回调事件
  poListChoice(e: any) {
    this.receiptAmount = '';
    this.poNo = e.pickerName.value;
    // 过滤重复物料
    this.materialList = JSON.parse(JSON.stringify(this.removeDuplicates(this.material, 'materialCode')));
    // 返回物料中poNo为选中的项；
    this.materialList = this.materialList.filter((item: any) => {
      if (item.poNo == e.pickerName.value) {
        item.label = item.materialCode;
        item.value = item.materialCode;
        return true;
      }
    });
    // 自动化流程改造测试
    this.materialChoice({
      pickerName: this.materialList.find(() => true),
    });
  }
  //选择物料后触发的回调事件  本次数量：receiptAmount  需求数量：requestAmount
  async materialChoice(e: any) {
    this.receiptAmount = '';
    // 待放入新增中的公共对象
    this.every = { ...e.pickerName };
    //清空库位列表 避免库位重复添加
    console.log('this.every', this.every);
    this.Location = [];
    // 查询时初始化仓库
    this.Location = await this.initLocation(this.every);

    // 自动化流程改造测试
    this.LocationChoice({
      pickerName: this.Location.find(() => true),
    });
    this.DNReceivingList.forEach((item: any, index: any) => {
      if (item.poNo == this.every.poNo && item.materialCode == this.every.materialCode && item.poLine == this.every.poLine) {
        this.everyIndex = index;
      }
    });
    this.every = this.DNReceivingList[this.everyIndex];
    console.log('this.every', this.every);
  }
  //选择库位后触发的回调事件
  LocationChoice(e: any) {
    this.wl = e.pickerName;
  }
  //点击添加
  Add() {
    // const count = this.totalLocation(this.LocationList);
    const count = parseFloat(this.every.requestAmount);
    if (this.receiptAmount == '' || !this.wl.value) {
      this.customToast(this.$t('message.Commission_tips2') as any);
      return;
    }
    if (parseFloat(this.receiptAmount) <= 0) {
      this.customToast(this.$t('message.Commission_tips3') as any);
      return;
    }
    if (parseFloat(this.receiptAmount) > count || parseFloat(this.receiptAmount) + parseFloat(this.every.receiptAmount) > count) {
      this.customToast(this.$t('message.Commission_tips4') as any);
      return;
    }
    let isTrue = true;
    this.DNReceivingList[this.everyIndex].wllist.forEach((item: any) => {
      if (item.wlCode == this.wl.label && item.receiptAmount == this.receiptAmount) {
        this.customToast(this.$t('message.repeatedly') as any);
        return (isTrue = false);
      }
    });
    if (isTrue == true) {
      this.LocationList.push({
        ...this.every,
        receiptAmount: this.receiptAmount,
        wlCode: this.wl.label,
      });
      this.DNReceivingList[this.everyIndex].wllist.push(this.LocationList[this.LocationList.length - 1]);
      let num: any = 0;
      this.DNReceivingList[this.everyIndex].wllist.forEach((item: any) => {
        num += parseFloat(item.receiptAmount);
        item.wllist = null;
      });
      this.DNReceivingList[this.everyIndex].receiptAmount = num;
      this.receiptAmount = '';
      this.every = this.DNReceivingList[this.everyIndex];
    }
  }
  deleteItem(e: any) {
    uni.showModal({
      content: this.$t('message.product_Delete') as string,
      cancelText: this.$t('message.Cancel') as string,
      confirmText: this.$t('message.workArea_Confirm') as string,
      success: (res) => {
        if (res.confirm) {
          this.LocationList.splice(e.contentIndex, 1);
          let externalIndex: number = 0;
          this.DNReceivingList.forEach((item: any, index: any) => {
            if (item.poNo == e.lineData.poNo && item.materialCode == e.lineData.materialCode && item.poLine == e.lineData.poLine) {
              externalIndex = index;
            }
          });
          let inside: number = 0;
          this.DNReceivingList[externalIndex].wllist.forEach((item: any, index: any) => {
            if (item.receiptAmount == e.lineData.receiptAmount && item.wlCode == e.lineData.wlCode) {
              inside = index;
            }
          });
          this.DNReceivingList[externalIndex].wllist.splice(inside, 1);
          let num: number = 0;
          this.DNReceivingList[externalIndex].wllist.forEach((item: any) => {
            num += parseFloat(item.receiptAmount);
          });
          this.DNReceivingList[externalIndex].receiptAmount = num;
        } else if (res.cancel) {
          return;
        }
      },
    });
  }
  // 重置页面数据
  async resetForm() {
    // this.form.documentNo = '';
    // 清空 add table
    this.LocationList = [];
    // 仓库
    this.Location = [];
    this.poNo = '';
    this.poList = [];
    // 清空 当前选择的库位对象
    this.wl = {
      value: null,
    };
    // 清空 物料对象
    this.every = {};
    // 清空 原始物料列表
    // this.material = [];
    // 清空 去重后的物料列表
    this.materialList = [];
    // 清空 当前累计数量
    this.receiptAmount = null;
    this.DNReceivingList = [];
    await this.query();
  }
  empty() {
    this.LocationList = [];
    this.Location = [];
    this.poNo = '';
    this.poList = [];
    this.wl = {
      value: null,
    };
    this.every = {};
    this.materialList = [];
    this.receiptAmount = null;
    this.DNReceivingList = [];
  }
  async onSubmit() {
    if (this.LocationList.length === 0) {
      this.customToast(this.$t('message.Commission_tips5') as any);
      return null;
    }
    await this.model.submitOrderInEnter(this.DNReceivingList);
    this.resetForm();
  }
  async bill() {
    if (this.form.documentNo == '') {
      this.customToast(this.$t('message._tips6') as any);
      return;
    }
    let person = JSON.parse(localStorage.getItem('__GWMS_APP_STATE_DATA__') as any);
    let content = {
      loginName: person.session.user.loginName,
      dnNo: this.form.documentNo,
    };
    await this.model.querydetaildlist(content);
    this.toPage(this.page.raw.ingoods.dnReceipt.Local);
  }
}
</script>
<style lang="scss" scoped>
.page-raw-receipt {
  background: #f2f2f2 linear-gradient(0deg, #f2f2f2 0%, #4a78ea 51%, #1753ea 100%) no-repeat;
  background-size: 100% 600rpx;
  padding: 118rpx 30rpx 162rpx;
  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;
    }
  }
  .content {
    width: 100%;
    background: white;
    border-radius: 15rpx;
    padding: 10rpx;
    .single {
      width: 100%;
      height: 100rpx;
      display: flex;
      .single-left {
        width: 80%;
        height: 100%;
        display: flex;
        view {
          width: 110rpx;
          height: 100%;
          line-height: 100rpx;
        }
      }
      .single-right {
        button {
          margin-top: 15rpx;
          width: 150rpx;
          height: 70rpx;
        }
      }
    }
    .Purchase-title {
      width: 100%;
      .Purchase {
        width: 60%;
        height: 100%;
        display: flex;
        view {
          width: 140rpx;
          line-height: 100rpx;
        }
      }
    }
    // .material {
    //   width: 100%;
    //   height: 100rpx;
    //   display: flex;
    //   .material-left {
    //     width: 100%;
    //     height: 100%;
    //     display: flex;
    //     view {
    //       width: 100rpx;
    //       line-height: 100rpx;
    //     }
    //   }
    // }
    .material {
      width: 100%;
      height: 100rpx;
      display: flex;
      .material-left {
        width: 100%;
        height: 100%;
        display: flex;
        view {
          width: 140rpx;
          line-height: 100rpx;
          text-align: left;
        }
      }
      .material-right {
        width: 100%;
        height: 100%;
        display: flex;
        .material-right-title {
          width: 140rpx;
          height: 100%;
          line-height: 100rpx;
        }
        .material-right-code {
          width: 80%;
          height: 100%;
          line-height: 100rpx;
          text-align: left;
          padding-left: 10px;
        }
      }
    }
    .number {
      height: 100rpx;
      display: flex;
      .number-left {
        width: 45%;
        height: 100%;
        display: flex;
        .number-left-title {
          width: 120rpx;
          height: 100%;
          line-height: 100rpx;
        }
        .input {
          width: 200rpx;
          height: 70rpx;
          margin-top: 15rpx;
          margin-left: 15rpx;
        }
      }
      .number-right {
        width: 55%;
        height: 100%;
        display: flex;
        .number-right-title {
          width: 140rpx;
          height: 100%;
          //text-align: center;
          line-height: 100rpx;
        }
        .input {
          width: 200rpx;
          height: 70rpx;
          margin-top: 15rpx;
          margin-left: 15rpx;
        }
      }
    }
    // .library {
    //   width: 100%;
    //   height: 100rpx;
    //   display: flex;
    //   .library-left {
    //     width: 50%;
    //     height: 100%;
    //     display: flex;
    //     view {
    //       width: 100rpx;
    //       line-height: 100rpx;
    //     }
    //     .search {
    //       padding-left: 30px;
    //     }
    //   }
    //   .library-right {
    //     width: 50%;
    //     height: 100%;
    //     display: flex;
    //     .library-right-title {
    //       width: 120rpx;
    //       height: 100%;
    //       line-height: 100rpx;
    //     }
    //     .input {
    //       width: 200rpx;
    //       height: 70rpx;
    //       margin-top: 15rpx;
    //       margin-left: 15rpx;
    //     }
    //   }
    // }
    .add {
      width: 100%;
      height: 100rpx;
      position: relative;
      button {
        position: absolute;
        top: 10rpx;
        right: 20rpx;
      }
    }
  }
  .bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 99;
    background: #ffffff;
    box-shadow: 0 1rpx 20rpx 0 rgba(128, 128, 128, 0.2);
    padding: 20rpx;
  }
}
</style>
