<!--
@name: 派车单收入业务
@author: 张泽贤
@time: 2023-04-14
@doc:
-->
<template>
  <div class="pages">
    <p-spin :spinning="spinning" v-show="!editType">
      <p-card style="margin-bottom: 10px">
        <p-form-model @submit="handelSubmit" ref="formTarget" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" class="plg-grid-from">
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="货主">
                <p-search-modal
                  :value="form.cargoOwnerName"
                  v-bind="$data.$formItems.consignorAttr"
                  @change="(...args) => onFormChange('consignor', ...args)"
                  :targetClick="false"
                  @blur="(event) => $set(form, 'cargoOwnerName', event.target.value)"
                />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="承运商">
                <p-search-modal
                  :value="form.carrierName"
                  v-bind="$data.$formItems.carrierAttr"
                  @change="(...args) => onFormChange('carrier', ...args)"
                  :targetClick="false"
                  @blur="(event) => $set(form, 'carrierName', event.target.value)"
                />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="司机">
                <p-search-modal
                  :value="form.driverName"
                  v-bind="$data.$formItems.driverAttr"
                  @change="(...args) => onFormChange('driver', ...args)"
                  :targetClick="false"
                  @blur="(event) => $set(form, 'driverName', event.target.value)"
                />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="车牌号">
                <p-search-modal
                  :value="form.vehiclePlateNumber"
                  v-bind="$data.$formItems.carAttr"
                  @change="(...args) => onFormChange('car', ...args)"
                  :targetClick="false"
                  @blur="(event) => $set(form, 'vehiclePlateNumber', event.target.value)"
                />
              </p-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="派车单号">
                <p-input :value="form.loadingBillNo" @blur="(event) => $set(form, 'loadingBillNo', event.target.value)" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="创建时间">
                <p-range-picker v-model="date1" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" style="width: 100%" />
              </p-form-model-item>
            </a-col>
            <a-col :span="12">
              <p-form-model-item :wrapper-col="{ span: 24 }" style="text-align: right">
                <a-space>
                  <p-button type="primary" html-type="submit" icon="search">查询</p-button>
                  <p-button type="submit" @click="onReset">重置</p-button>
                </a-space>
              </p-form-model-item>
            </a-col>
          </a-row>
        </p-form-model>
      </p-card>
      <p-card title="派车单信息" style="margin-bottom: 10px">
        <a-space slot="extra">
          <p-button type="primary" @click="onAdjust" :disabled="!selectedRowKeys.length">核算</p-button>
          <p-button type="primary" @click="onSubmit" :disabled="!selectedRowKeys.length">提交</p-button>
          <a-dropdown>
            <template #overlay>
              <a-menu>
                <a-menu-item key="2">
                  <export-button
                    type="link"
                    :ids="selectedRowKeys"
                    :pages="mainPages"
                    :getSearchValue="() => listParams"
                    downloadFileName="派车单收入业务"
                    :allUrl="UPCLOUD_RDC_TMS_BMS_SERVICE + '/bmsLoadingBill/export'"
                    :currentUrl="UPCLOUD_RDC_TMS_BMS_SERVICE + '/bmsLoadingBill/exportPage'"
                    :selectUrl="UPCLOUD_RDC_TMS_BMS_SERVICE + '/bmsLoadingBill/exportSelected'"
                    >导出</export-button
                  >
                </a-menu-item>
                <a-menu-item type="link" key="3">
                  <p-button type="link" :disabled="!selectedRowKeys.length" @click="printAsnFun">打印</p-button>
                </a-menu-item>
              </a-menu>
            </template>
            <a-button>更多</a-button>
          </a-dropdown>
        </a-space>
        <p-table
          ref="masterTable"
          dragle
          bordered
          rowSelectFixed
          :extendedObjectCode="'15'"
          row-key="id"
          :id="$route.meta.menuId + '_dispatched'"
          :scroll="{ x: true, y: 300 }"
          :columns="loading_columns"
          :data-source.sync="dataSource"
          :remote-url="listRemoteUrl"
          :remoteData="listParams"
          :rowSelectType="2"
          :selectedRowKeys.sync="selectedRowKeys"
          @clickRow="masterClickRow"
          :sign="true"
          :doneBefore="doneBefore"
        >
          <template slot="operation" slot-scope="text, record">
            <a-space>
              <a @click.stop="onEdit(record, 'view')">查看</a>
              <a @click.stop="onEdit(record, 'edit')" :disabled="record.checkStatus > 0">修改</a>
              <a @click.stop="toAdjust(record)" :disabled="record.checkStatus > 0">核算</a>
              <a @click.stop="toSubmit(record)" :disabled="record.checkStatus > 0 || record.settlementStatus != 1">提交</a>
              <a @click.stop="toPrint(record)">打印</a>
            </a-space>
          </template>
        </p-table>
      </p-card>

      <p-card>
        <p-table
          ref="detailsTable"
          dragle
          bordered
          row-key="id"
          :id="$route.meta.menuId + '_detailsTable'"
          :scroll="{ x: true, y: 300 }"
          :columns="details_columns"
          :data-source.sync="detailsDataSource"
          :remote-url="detailsListRemoteUrl"
          :remoteData="detailsListParams"
          :rowSelectType="false"
          :autoLoad="false"
        >
        </p-table>
      </p-card>
    </p-spin>

    <!-- 编辑 -->
    <Edit
      v-if="editType === 'edit' || editType === 'view'"
      :editType="editType"
      :editData="editData"
      :options="options"
      :formExtendedField="formExtendedField"
      :childrenFormExtendedField="childrenFormExtendedField"
      @back="editType = ''"
    ></Edit>

    <!-- 明细 -->
    <orderView
      v-show="editType === 'detailsView'"
      :st="1"
      :record="detailsData"
      :formExtendedField="formExtendedField"
      :goodsExtendedField="childrenFormExtendedField"
      @back="editType = ''"
    ></orderView>
  </div>
</template>

<script>
import * as $formItems from '@/blocks/components/searchModalConfig/index';
import { initDictionary, resultExtendedField } from '@/blocks/utils';
import { UPCLOUD_RDC_TMS_BMS_SERVICE } from '@/config/serviceSettings.js';
import exportButton from '@/blocks/components/export-modal/modal.index.vue';
import { toPrintServer } from '@/utils/printServe.js';
import orderView from '@/views/BMS/$common/model/orderView/index.orderView.vue';

import { setMainColumns, setDetailsColumns } from './js/tableConfig.js';
import { listRemoteUrl, detailsListRemoteUrl, Calculate, Submit } from './js/api.js';
import Edit from './modules/edit.vue';

export default {
  components: { exportButton, Edit, orderView },
  computed: {
    date1: {
      get() {
        return [this.form.startDate, this.form.endDate];
      },
      set(value) {
        this.$set(this.form, 'startDate', value.length ? value[0] + ' 00:00:00' : '');
        this.$set(this.form, 'endDate', value.length ? value[1] + ' 23:59:59' : '');
      },
    },
  },
  data() {
    return {
      $formItems,
      UPCLOUD_RDC_TMS_BMS_SERVICE,
      spinning: false,
      editData: {},
      editType: '', // 空-列表页 view-查看 add-新增 edit-修改
      formExtendedField: [],
      childrenFormExtendedField: [],

      form: {
        loadingBillNo: '',
        startDate: '',
        endDate: '',
      },
      options: {
        LOADING_BILL_STATUS: [],
        STATION_AREAS: [],
      },

      // 主表格
      dataSource: [],
      selectedRowKeys: [],
      listRemoteUrl,
      listParams: {},
      loading_columns: setMainColumns(this, this.tableExtendedField),
      mextendedField_list: [],
      tableExtendedField: [],
      mainPages: { pageNum: 1, pageSize: 15 },

      // 运单表格
      detailsDataSource: [],
      detailsListRemoteUrl,
      detailsListParams: {},
      details_columns: setDetailsColumns(this),
      detailsData: null,
    };
  },
  mounted() {
    initDictionary([{ objectcode: 'LOADING_BILL_STATUS' }, { objectcode: 'STATION_AREAS' }], true).then((res) => {
      for (const key in res) {
        this.options[key] = res[key];
      }
    });
    resultExtendedField({ extendedObjectCode: '18' }).then((res) => {
      if (res) {
        this.formExtendedField.form = res.form;
        this.details_columns = setDetailsColumns(this, res.table);
      }
    });
    resultExtendedField({ extendedObjectCode: '19' }).then((res) => {
      if (res) {
        this.childrenFormExtendedField = res.form;
      }
    });
  },
  methods: {
    handelSubmit(event) {
      event.preventDefault();
      event.submitter.focus();
      this.onSearch();
    },
    // 查询
    onSearch() {
      this.listParams = { ...this.form };
      this.detailsDataSource = [];
    },
    // 重置
    onReset() {
      this.form = {
        loadingBillNo: '',
        startDate: '',
        endDate: '',
      };
    },
    doneBefore(res) {
      const { pageNum, pageSize } = res.data;
      this.mainPages = { pageNum, pageSize };
    },
    masterClickRow(event, activeID, rowRecord) {
      this.editData = { ...rowRecord };
      this.detailsListParams = { id: rowRecord.id };
    },

    // 新增、修改、复制、查看
    onEdit(record = { id: '' }, type) {
      this.editData = record;
      this.editType = type;
    },

    onAdjust() {
      this.WhetherToEnable(Calculate, this.selectedRowKeys, '核算');
    },
    toAdjust(record) {
      this.WhetherToEnable(Calculate, [record.id], '核算');
    },
    onSubmit() {
      this.WhetherToEnable(Submit, this.selectedRowKeys, '提交');
    },
    toSubmit(record) {
      this.WhetherToEnable(Submit, [record.id], '提交');
    },
    WhetherToEnable(method, idList, text) {
      let self = this;
      this.$confirm({
        title: '是否' + text + '?',
        onOk() {
          return new Promise((resolve, reject) => {
            method(idList)
              .then((res) => {
                if (res.success) {
                  self.$message.success(res.message);
                  self.onSearch();
                } else {
                  self.$exception(res);
                }
                resolve();
              })
              .catch(() => {
                self.$exception(res);
                resolve();
              });
          });
        },
      });
    },

    // 打印
    async printAsnFun() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.error('请选择需要打印的订单');
        return;
      }
      // 请选择需要打印的订单/
      let data = {
        params: {
          loadingBillNo: this.selectedRowKeys,
        },
        printBillCode: 'TMS_LOADING_BILL_PRINT',
      };
      try {
        let res = await printAsn(data);
        if (!res.success) {
          this.$exception(res);
          return;
        }
        if (!res.data) {
          this.$message.error('打印数据为空');
          return;
        }
        const printRes = await toPrintServer(res.data.printData, { url: res.data.printAddress });
        if (printRes.success) {
          this.$message.success(printRes.message);
        } else {
          this.$exception(printRes);
        }
      } catch (error) {
        this.$exception(error);
      }
    },

    // 明细查看
    onDetailsView(record) {
      this.detailsData = record;
      this.editType = 'detailsView';
    },

    onFormChange(name, ...args) {
      if (name === 'consignor') {
        this.$set(this.form, 'cargoOwnerName', args[1]);
      } else if (name === 'carrier') {
        this.$set(this.form, 'carrierName', args[1]);
      } else if (name === 'driver') {
        this.$set(this.form, 'driverName', args[1]);
      } else if (name === 'car') {
        this.$set(this.form, 'vehiclePlateNumber', args[1]);
      }
    },
  },
};
</script>