<template>
  <view class="page-raw-checkout">
    <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>
    <u-form class="form" ref="form" :model="form" label-width="140rpx">
      <u-form-item label="车牌号" prop="actualCarNo">
        <u-input v-model="form.actualCarNo" @confirm="onCarNoEnterKeyDown" />
      </u-form-item>
      <u-form-item label="到达时间" prop="arriveTime">
        <u-input :value="form.arriveTime | datetime" disabled />
      </u-form-item>
      <u-form-item label="月台" prop="actualPlatform">
        <u-input
          :value="form.actualPlatform || ''"
          type="select"
          @click="isPlatformSelectShow = true"
        />
        <u-select
          :confirm-text="this.$t('message.product_Confirm')"
          :cancel-text="this.$t('message.product_Cancel')"
          v-model="isPlatformSelectShow"
          :list="platform.getPlatforms.map((p, i) => ({ label: p.name, value: i }))"
          @confirm="onSelectPlatform"
        ></u-select>
      </u-form-item>
      <u-form-item label="离开时间" prop="leaveTime">
        <u-input v-model="form.leaveTime" disabled placeholder="" />
      </u-form-item>
      <u-form-item label="作业时长" prop="jobTimeout">
        <u-input :value="form.jobTimeout" disabled placeholder="" />
      </u-form-item>
      <u-form-item label="超时原因" prop="jobTimeoutReason">
        <u-input
          :value="form.jobTimeoutReason || ''"
          type="select"
          @click="isDelayReasonShow = true"
        />
        <u-select
          :confirm-text="this.$t('message.product_Confirm')"
          :cancel-text="this.$t('message.product_Cancel')"
          v-model="isDelayReasonShow"
          :list="reason.reasons.map((r) => ({ label: r.name, value: r.code }))"
          @confirm="onSelectReason"
        ></u-select>
      </u-form-item>
    </u-form>
    <view class="bottom-bar">
      <u-row>
        <u-col :span="4">
          <u-button type="primary" @click="onSubmit">出门</u-button>
        </u-col>
        <u-col :span="4">
          <u-button type="warning" @click="onReset">重新扫描</u-button>
        </u-col>
        <u-col :span="4">
          <u-button type="error" @click="uni.navigateBack()">返回</u-button>
        </u-col>
      </u-row>
    </view>
  </view>
</template>

<script lang="ts">
import { Component, Ref } from 'vue-property-decorator';
import dayjs from 'dayjs';
import { BasePage } from '@/components/base/page';
import { VForm, VFormRules } from 'vue/types/form';
import { platform } from '@/pages/raw/appointment/checkin/platform';
import { reason } from './reason';
import { Bill, checkout } from './model';
import http from '@/utils/request';
import { url } from '@/utils/url';
import { session } from '@/store/modules/session';

// 创建空看单
const createEmptyBill = (): Bill => ({
  actualCarNo: '',
  arriveTime: '',
  actualPlatform: '',
  leaveTime: '',
  jobTimeout: '',
  jobTimeoutReason: '',
});

@Component
export default class CheckInPage extends BasePage {
  @Ref('form') readonly $form!: VForm;

  // 月台模块
  platform = platform;

  // 超时原因模块
  reason = reason;

  form: Bill = createEmptyBill();

  rules: VFormRules<Bill> = {
    actualCarNo: [
      {
        required: true,
        message: '请输入车牌号',
      },
    ],
  };
  isPlatformSelectShow = false;
  isDelayReasonShow = false;

  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  async onReady() {
    // 设置表单
    this.$form.setRules(this.rules);
    // 设置月台
    const platforms = await platform.getPlatformItems({
      loginName: session.loginName as string,
      warehouseCode: session.warehouseCode as string,
      factoryCode: session.factoryCode as string,
    });
    platform.setPlatforms(platforms);
    // 设置超时原因
    const reasons = await reason.getReasons({
      loginName: session.loginName as string,
    });
    reason.setDelayReasons(reasons);
  }
  // 选择月台
  onSelectPlatform(s: any) {
    const selection = platform.getPlatforms[s[0].value];
    this.form.actualPlatform = selection.sapCode;
  }
  // 选择超时原因
  onSelectReason(r: any) {
    this.form.jobTimeoutReason = r[0].value;
  }
  // 出门
  async onSubmit() {
    const authResult: any = await http.post(url.auth.systime, {
      loginName: session.loginName as string,
    });
    if (authResult.code !== '1') {
      uni.showToast({ icon: 'none', title: authResult.msg });
      throw new Error('auth.systime failed' + authResult.msg);
    } else {
      this.form.leaveTime = authResult.value;
    }

    const arriveTime = dayjs(this.form.arriveTime);
    const leaveTime = dayjs(this.form.leaveTime);
    const duration = Math.abs(leaveTime.diff(arriveTime, 'minute'));
    this.form.jobTimeout = String(duration);

    if (duration > 30 && this.form.jobTimeoutReason === '') {
      uni.showToast({ icon: 'none', title: '请选择超时原因' });
    } else {
      const result: any = await checkout.submitBill({
        actualCarNo: this.form.actualCarNo,
        factoryCode: session.factoryCode as string,
        actualPlatform: this.form.actualPlatform,
        jobTimeout: String(Math.ceil(Number(this.form.jobTimeout))),
        jobTimeoutReason: this.form.jobTimeoutReason,
        leaveTime: dayjs(this.form.leaveTime).toJSON(),
        loginName: session.loginName as string,
      });
      if (result.code === '1') {
        this.onReset();
        uni.showToast({ icon: 'none', title: '离开成功 ' + result.msg });
      } else {
        uni.showToast({ icon: 'none', title: '离开失败，详情：' + result.msg });
      }
    }
  }
  // 清空
  onReset() {
    this.form = createEmptyBill();
  }
  // 车牌号 enter
  onCarNoEnterKeyDown() {
    this.$form.validate(async (valid: boolean) => {
      if (valid) {
        const bill = await checkout.getBillDetail({
          actualCarNo: this.form.actualCarNo,
          factoryCode: session.factoryCode as string,
        });
        this.form.actualCarNo = bill.actualCarNo;
        this.form.arriveTime = bill.arriveTime;
        this.form.actualPlatform = bill.actualPlatform;
      }
    });
  }
}
</script>

<style lang="scss" scoped>
.page-raw-checkout {
  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;
    }
  }

  .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 {
    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>
