<template>
  <view class="page-kan-dan-detail">
    <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
      :headers="headers"
      :contents="details"
      :show-vert-border="false"
    />
    <view class="bottom-bar">
      <view class="extra">
        <u-row>
          <u-col :span="2"> 看单号: </u-col>
          <u-col :span="8">
            <u-input v-model="hideKdOrderNo" @confirm="onKdOrderNoConfirm" placeholder="看单号" />
          </u-col>
        </u-row>
        <u-row>
          <u-col :span="2"> 接收人 </u-col>
          <u-col :span="3">
            <u-input v-model="receiverName" @confirm="onReceiverNameConfirm" placeholder="接收人" />
          </u-col>
          <u-col :span="2"> 口令 </u-col>
          <u-col :span="3">
            <u-input v-model="operatorPass" placeholder="口令" />
          </u-col>
        </u-row>
      </view>
      <view class="container">
        <u-row>
          <u-col :span="6">
            <u-button type="primary" @click="onTakeoutConfirm">确认</u-button>
          </u-col>
          <u-col :span="6">
            <u-button type="error" @click="uni.navigateBack({ delta: 1 })">返回</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 { order, OrderDetail } from '@/pages/raw/handover/kan-dan/model';
import { auth } from '@/store/modules/auth';
import { pick, omit, cloneDeep } from 'lodash/fp';
import { headers } from './config';
import { session } from '@/store/modules/session';

@Component
export default class KanDanHandOverDetails extends BasePage {
  hideKdOrderNo = '';

  receiver = '';
  receiverName = '';
  operatorPass = '';

  isBusinessFinished = true;

  headers = headers;

  details: Array<OrderDetail> = [];

  async mounted() {
    try {
      const details = await order.getOrderDetails({
        list: order.orders.map((o) => o.kdOrderNo),
        loginName: session.loginName as string,
        factoryCode: session.factoryCode as string,
      });
      this.details = details.map((d) => ({ ...d, checked: false }));
      this.isBusinessFinished = false;
    } catch (e) {
      uni.showToast({ icon: 'none', title: e.message });
    }
  }

  beforeDestroy() {
    if (order.orders.length > 0 && !this.isBusinessFinished) {
      this.unlockOrder();
      order.clear();
    }
  }

  async onKdOrderNoConfirm() {
    if (this.hideKdOrderNo === '') {
      uni.showToast({ icon: 'none', title: '请扫描看单号' });
    } else if (order.orders.length >= 10) {
      uni.showToast({ icon: 'none', title: '看单号已扫 10 条' });
    } else {
      const odr = await order.takeOrder({
        loginName: session.loginName as string,
        factoryCode: session.factoryCode as string,
        hideKdOrderNo: this.hideKdOrderNo,
      });
      if (order.orders.some((o) => o.kdOrderNo === odr.kdOrderNo)) {
        uni.showToast({ icon: 'none', title: '看单号已扫' });
      } else {
        order.add({ order: odr });
        const odDetails = await order.getOrderDetails({
          list: order.orders.map((o) => o.kdOrderNo),
          factoryCode: session.factoryCode as string,
          loginName: session.loginName as string,
        });
        this.details = odDetails
          .filter((d) => d.checkCode === '1')
          .map((d) => ({ ...d, checked: false }));
      }
    }
  }

  async onReceiverNameConfirm() {
    try {
      const userInfo = await auth.getUserInfo({
        loginName: this.receiverName,
      });
      this.receiver = this.receiverName;
      this.receiverName = userInfo.userName;
    } catch (e) {
      this.receiver = '';
      this.receiverName = '';
    }
  }

  async onTakeoutConfirm() {
    if (this.details.length === 0) {
      uni.showToast({ icon: 'none', title: '没有可以交接的数据' });
    } else if (this.operatorPass === '') {
      uni.showToast({ icon: 'none', title: '请输入口令' });
    } else if (this.receiverName === '') {
      uni.showToast({ icon: 'none', title: '请输入接收人' });
      this.operatorPass = '';
    } else {
      await auth.checkPassword({
        rfPwd: this.operatorPass,
        loginName: session.loginName as string,
        factoryCode: session.factoryCode as string,
      });
      try {
        await order.takeoutOrder({
          list: this.details.map((d) => ({
            ...pick(
              [
                'materialCode',
                'amount',
                'sendSpot',
                'sapFactoryCode',
                'materialDesc',
                'unit',
                'wkposCode',
                'checkResult',
                'kdOrderNo',
                'prdOrder',
                'factoryCode',
                'checkCode',
                'firstHvDate',
                'mrpCode',
                'orderNo',
                'orderOutId',
                'requestAmount',
                'serialNo',
                'totalHvAmount',
                'whCode',
                'poNo',
                'poLine',
              ],
              d,
            ),
            allAmount: String(d.allAmount),
            loginName: session.loginName as string,
          })),
          operatorPass: this.receiver,
          factoryCode: session.factoryCode as string,
          loginName: session.loginName as string,
        });
        this.receiver = '';
        this.receiverName = '';
        this.operatorPass = '';
        this.details = [];
        this.isBusinessFinished = true;
        // uni.navigateBack({ delta: 1 });
        setTimeout(() => {
          uni.navigateBack({ delta: 1 });
        }, 2000);
      } catch (e) {
        uni.showToast({ icon: 'none', title: e.message });
      }
    }
  }

  async unlockOrder() {
    const copiedDetails = cloneDeep(this.details);
    order.clear();
    await order.unlockOrder({
      list: copiedDetails.map((d) => ({
        ...(omit(['checked'], d) as OrderDetail),
        loginName: session.loginName as string,
      })),
      loginName: session.loginName as string,
      factoryCode: session.factoryCode as string,
    });
  }
}
</script>

<style lang="scss" scoped>
.page-kan-dan-detail {
  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>
