<!--
@name: 叫号管理
@author: 张泽贤
@time: 2022-07-18
@doc:
-->
<template>
  <div class="pages">
    <p-spin :spinning="spinning" v-if="!editType">
      <p-card style="margin-bottom: 10px">
        <p-form-model ref="formTarget" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" class="plg-grid-from" :rules="rules">
          <a-row>
            <a-col :span="3">
              <p-form-model-item label="" :wrapper-col="{ span: 24 }">{{ nowDateStr.date }} {{ nowDateStr.week }}</p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="仓库" prop="branchName">
                <p-search-modal v-model="form.branchName" v-bind="$data.$formItems.parkBranchAttr" @change="(...args) => onFormChange('branch', ...args)" />
              </p-form-model-item>
            </a-col>
          </a-row>
          <br />
          <a-row>
            <a-col
              :span="3"
              v-for="(item, index) in dateList"
              :key="index"
              @click="appointmentTimeClick(index, item)"
              :class="{
                dateCount: true,
                pointer: item.count !== 0,
                dateSelect: index === dateIndex,
              }"
            >
              {{ item.appointmentTime }}<br />已排队：{{ item.count }}
            </a-col>
          </a-row>
        </p-form-model>
      </p-card>
      <p-card title="预约列表" style="margin-bottom: 10px">
        <t-table
          ref="masterTable"
          dragle
          bordered
          row-key="appointmentId"
          :id="$route.meta.menuId + '_callNumber'"
          :scroll="{ x: true }"
         :vScrollX="{enabled:true}"
        :vScrollY="{enabled:true,rows:10}"
          @selectChange="selectKey=>selectedRowKeys=selectKey"
          :columns="call_columns"
          :data-source.sync="dataSource"
          :remote-url="listRemoteUrl"
          :remoteData="listParams"
          :rowSelectType="false"
          :autoLoad="false"
        >
          <template slot="reserveNumber" slot-scope="text, record">
            <a @click.stop="toDialog(record.appointmentId, record.reserveNumber)">{{ record.reserveNumber }}</a>
          </template>
          <template slot="queueNumber" slot-scope="text, record">
            <a @click.stop="toDialog(record.appointmentId, record.reserveNumber)">{{ record.queueNumber }}</a>
          </template>
          <template slot="operation" slot-scope="text, record">
            <a-space>
              <a @click.stop="toJump(record)">插队</a>
            </a-space>
          </template>
        </t-table>
      </p-card>
      <a-row :gutter="10">
        <a-col :span="6">
          <p-card title="等待区" v-show="vehiclePlateNumberList.length" style="height: 500px; background: #fff">
            <div v-for="(item, index) in vehiclePlateNumberList" :key="index">{{ item.vehiclePlateNumber }}</div>
          </p-card>
        </a-col>
        <a-col :span="18" style="height: 500px; overflow: auto">
          <p-card v-for="(item, index) in platformList" :key="index" :title="item.platformCode">
            <t-table dragle bordered row-key="id" :scroll="{ x: true, y: 300 }" :data-source.sync="item.data" :rowSelectType="false" :autoLoad="false" :pagination="false">
              <t-table-column data-index="vehiclePlateNumber" title="当前装卸车辆">
                <template slot-scope="text, record">
                  <a @click.stop="toDialog(record.appointmentId, record.reserveNumber)">{{ record.vehiclePlateNumber }}</a>
                </template>
              </t-table-column>
              <t-table-column data-index="queueNumberTime" title="取号时间" />
              <t-table-column data-index="loadingTime" title="仓库停留时长" />
              <t-table-column data-index="nextVehiclePlateNumber" title="下一装卸车辆">
                <template slot-scope="text, record">
                  <a @click.stop="toDialog(record.nextAppointmentId, record.nextReserveNumber)">{{ record.nextVehiclePlateNumber }}</a>
                </template>
              </t-table-column>
              <t-table-column key="action" title="操作">
                <template slot-scope="text, record">
                  <a-space>
                    <a @click.stop="next_one(record, item.platformCode)">下一位</a>
                    <a @click.stop="passNumber(record, item.platformCode)">过号</a>
                  </a-space>
                </template>
              </t-table-column>
            </t-table>
          </p-card>
        </a-col>
      </a-row>

      <p-modal :title="'运单：' + selectReserveNumber" width="80%" :visible="visible" @ok="visible = false" @cancel="visible = false">
        <t-table
          ref="dialogTable"
          dragle
          bordered
          row-key="shipbillId"
          :id="$route.meta.menuId + '_callNumberDialog'"
          :scroll="{ x: true, y: 300 }"
          :columns="mx_columns"
          :data-source.sync="dialogDataSource"
          :remote-url="dialogListRemoteUrl"
          :remoteData="dialogListParams"
          :rowSelectType="false"
          :sign="true"
        >
        </t-table>
      </p-modal>
    </p-spin>

    <!-- 查看 -->
    <edit
      v-show="editType === 'view'"
      parcelTable
      :options="options"
      :record="editId ? { shipbillId: editId } : null"
      :formExtendedField="formExtendedField"
      @back="editType = ''"
    ></edit>
  </div>
</template>

<script>
import { formatDate, resultExtendedField } from '@/blocks/utils';
import * as $formItems from '@/blocks/components/searchModalConfig/index';
import { setMainColumns } from '@/blocks/components/scheduling/js/table/tableConfig.js';
import edit from '@/blocks/components/orderView/index.orderView.vue';

import {
  queryTimeCount,
  listRemoteUrl,
  insertSort,
  platformAndVehicle,
  queryWaitingZone,
  next_one,
  passNumber,
  dialogListRemoteUrl,
  viewUrl,
  page_detail_item,
  page_detail_package,
} from './js/api.js';
import { setCallColumns } from '../js/tableConfig.js';

export default {
  components: { edit },
  data() {
    return {
      formExtendedField: {
        form: [],
        formTable:[]
      },
      $formItems,
      spinning: false,
      visible: false,
      editType: '',
      editId: '',

      nowDate: new Date(),
      nowDateStr: {
        date: '',
        week: '',
      },

      form: {
        branchId: '',
        branchName: '',
        branchAddress: '',
      },
      dateList: [],
      dateIndex: -1,

      // 主表格
      dataSource: [],
      listRemoteUrl,
      listParams: {},
      call_columns: setCallColumns(this),

      platformList: [],

      vehiclePlateNumberList: [],

      selectReserveNumber: '',
      dialogDataSource: [],
      dialogListRemoteUrl,
      dialogListParams: {},
      mx_columns: setMainColumns(this, this.tableExtendedField),
      mextendedField_list: [],
      tableExtendedField: [],
      page_detail_item,
      page_detail_package,

      rules: {
        branchName: [{ required: true, message: '仓库不能为空', trigger: 'change' }],
      },
    };
  },
  mounted() {
    resultExtendedField({ extendedObjectCode: '15' }).then((res) => {
      if (res) {
        this.formExtendedField.form = res.form
      }
    })
    resultExtendedField({ extendedObjectCode: '17' }).then((res) => {
      if (res) {
        this.formExtendedField.formTable = res.table
      }
    })
    this.nowDateStr = {
      date: formatDate(this.nowDate),
      week: '星期' + '日一二三四五六'.charAt(this.nowDate.getDay()),
    };
    // resultExtendedField({ extendedObjectCode: '13' }).then((res) => {
    //   if (res) {
    //     this.mextendedField_list = res.list
    //     this.tableExtendedField = res.table
    //   }
    // })

    let warehouseList = this.$store.getters.userInfo.warehouseList;
    if (warehouseList && warehouseList.length === 1) {
      this.form.branchId = warehouseList[0].warehouseId;
      this.form.branchName = warehouseList[0].warehouseName;
      this.listParams = { branchId: this.form.branchId };
      this.queryTimeCount();
      this.platformAndVehicle();
      this.queryWaitingZone();
    }
  },
  methods: {
    viewUrl,
    // 插队
    toJump(record) {
      this.spinning = true;
      insertSort({ appointmentId: record.appointmentId })
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.allSearch();
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },

    // 仓库各预约时间段排队数查询
    queryTimeCount() {
      queryTimeCount({ branchId: this.form.branchId }).then((res) => {
        if (res.success) {
          this.dateList = [...(res.data || [])];
        } else {
          this.$exception(res);
        }
      });
    },

    // 月台与当前装卸车辆查询
    platformAndVehicle() {
      platformAndVehicle({ branchId: this.form.branchId }).then((res) => {
        if (res.success) {
          this.platformList = [...(res.data || [])];
        } else {
          this.$exception(res);
        }
      });
    },

    // 等待区车辆查询
    queryWaitingZone() {
      queryWaitingZone({ branchId: this.form.branchId }).then((res) => {
        if (res.success) {
          this.vehiclePlateNumberList = [...(res.data || [])];
        } else {
          this.$exception(res);
        }
      });
    },

    // 下一位
    next_one(record, platformCode) {
      this.spinning = true;
      next_one({ appointmentId: record.appointmentId, branchId: this.form.branchId, platformCode })
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.allSearch();
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },

    // 过号
    passNumber(record, platformCode) {
      this.spinning = true;
      passNumber({ appointmentId: record.appointmentId, branchId: this.form.branchId, platformCode })
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.allSearch();
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },

    onFormChange(name, ...args) {
      if (name === 'branch') {
        if (args[2].length) {
          this.form.branchId = args[2][0].id;
          this.form.branchName = args[2][0].name;
          this.form.branchAddress = args[2][0].address;
          this.listParams = { branchId: this.form.branchId };
          this.queryTimeCount();
          this.platformAndVehicle();
          this.queryWaitingZone();
        } else {
          this.form.branchId = '';
          this.form.branchName = '';
          this.form.branchAddress = '';
        }
      }
    },

    // 全页面查询
    allSearch() {
      this.$refs.masterTable.reload();
      this.queryTimeCount();
      this.platformAndVehicle();
      this.queryWaitingZone();
    },

    // 弹窗
    toDialog(appointmentId, reserveNumber) {
      this.selectReserveNumber = reserveNumber || '';
      this.visible = true;
      this.dialogListParams = { appointmentId };
    },

    // 查看
    toView(editData = { shipbillId: '' }) {
      this.editId = editData.shipbillId;
      this.editType = 'view';
    },

    appointmentTimeClick(index, item) {
      if (item.count === 0) return;
      if (this.dateIndex !== index) {
        this.dateIndex = index;
        this.listParams = { ...this.listParams, appointmentTime: item.appointmentTime };
      } else {
        this.dateIndex = -1;
        this.listParams = { ...this.listParams, appointmentTime: '' };
      }
    },
  },
};
</script>

<style lang="less" scoped>
.dateCount {
  border-radius: 5px;
  padding: 10px;
  text-align: center;
  line-height: 2;
  color: #999;
}

.pointer {
  cursor: pointer;
  color: #000;
}

.dateSelect {
  background-color: #2b80ff;
  color: #fff;
}
</style>