/**
 * 菜单模块
 */
import { Module, VuexModule, Mutation, Action, getModule } from 'vuex-module-decorators';
import store from '@/store';
import http from '@/utils/request';
import { url } from '@/utils/url';
import { session, User } from '@/store/modules/session';
import { platform } from '@/pages/raw/appointment/checkin/platform';

// 看单列表
export interface Bill {
  warehouseCode?: string;
  warehouseName?: string;
  warehouseType?: string;
  loginName?: string;
  userName?: string;
  factoryCode?: string;
  factoryName?: string;
  sapFactoryCode?: string;
  locationCode?: string;
  workareaCode?: string;
  hideKdOrderNo?: any;
  documentNo: string;
  carNo: string;
  actualCarNo?: string;
  appointmentTime: string;
  arriveTime?: string;
  leaveTime?: string;
  appointmentPlatform: string;
  actualPlatform?: string;
  sequenceNumber?: any;
  jobTimeout?: any;
  jobTimeoutReason?: any;
  sendSpot: string;
}

@Module({
  dynamic: true,
  store,
  namespaced: true,
  name: 'checkin',
})
class CheckInService extends VuexModule {
  // 看单列表
  bills: Array<Bill> = [];

  // 看单列表 getter
  get getBills() {
    return this.bills.map((bill, index) => ({
      ...bill,
      index: index + 1,
    }));
  }

  // 获取看单
  @Action
  async getBillDetail({
    hideKdOrderNo,
    factoryCode,
    loginName,
  }: {
    hideKdOrderNo: string;
    factoryCode: User['factoryCode'];
    loginName: User['loginName'];
  }): Promise<Bill> {
    const result: any = await http.post(url.appointmentreg.kd.query, {
      hideKdOrderNo,
      factoryCode,
      loginName,
    });
    return result.list[0];
  }

  // 提交看单列表
  @Action
  async submitBills() {
    const bills: any = this.bills.map((bill) => {
      const pf = platform.getPlatforms.find((p) => p.sapCode === bill.appointmentPlatform);
      return {
        documentNo: bill.documentNo,
        carNo: bill.carNo,
        actualPlatform: pf ? pf.code : bill.appointmentPlatform,
        sendSpot: bill.sendSpot,
        appointmentTime: bill.appointmentTime,
        factoryCode: session.factoryCode,
        loginName: session.loginName,
      };
    });

    await http.post(url.appointmentreg.save, bills);
    this.clear();
  }

  // 增加看单
  @Mutation
  add(bill: Bill) {
    this.bills = this.bills.concat([bill]);
    return 'a';
  }

  // 设置看单项
  @Mutation
  splice({ index, item }: { index: number; item?: Bill }) {
    if (item) this.bills.splice(index, 1, item);
    else this.bills.splice(index, 1);
  }

  // 清空
  @Mutation
  clear() {
    this.bills = [];
  }
}

export const checkin = getModule(CheckInService);
