<!--
@name: 司机应付管理-费用结算
@author: 张泽贤
@time: 2023-04-27
@doc:
-->
<template>
  <div class="pages">
    <p-spin :spinning="spinning" v-show="!editType">
      <a-page-header class="page-header" :title="'司机应付管理-' + $route.meta.title" :bordered="false" style="background-color: #fff; margin-bottom: 10px">
        <a-space slot="extra">
          <p-button type="primary" icon="search" @clickSync="handelSubmit">查询</p-button>
          <p-button type="primary" @clickSync="onReset">重置</p-button>
        </a-space>
        <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" v-show="false">
              <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>
                </a-space>
              </p-form-model-item>
            </a-col>
          </a-row>
        </p-form-model>
      </a-page-header>

      <p-card title="派车单信息" style="margin-bottom: 10px">
        <a-space slot="extra">
          <a-badge :count="selectedRowKeys.length" :overflow-count="999">
            <p-button type="primary" @click="onSettlement">{{ !selectedRowKeys.length ? '全部费用结算' : '费用结算' }}</p-button>
          </a-badge>
        </a-space>
        <t-table
          ref="masterTable"
          dragle
          bordered
          row-key="id"
          :id="$route.meta.menuId + '_expenseSettlement'"
          :scroll="{ x: true, y: 300 }"
          :columns="mx_columns"
          :data-source.sync="dataSource"
          :remote-url="listRemoteUrl"
          :remoteData="listParams"
          :rowSelectType="2"
          :selectedRowKeys.sync="selectedRowKeys"
          @clickRow="handleRowClick"
        >
          <template slot="operation" slot-scope="text, record">
            <a-space>
              <a @click.stop="toSettlement(record)">费用结算</a>
            </a-space>
          </template>
        </t-table>
      </p-card>

      <p-card :bordered="false" :bodyStyle="{ minHeight: '300px' }">
        <a-tabs style="background-color: #fff" v-model="tabsKey">
          <a-tab-pane :key="1" tab="商品信息">
            <goodsTable ref="childrenTable_1" :options="options" :isShow="tabsKey === 1" :tableExtendedField="childrenTableExtendedField" :mainRowKey="mainId" />
          </a-tab-pane>
          <a-tab-pane :key="2" tab="包裹信息">
            <parcelTable ref="childrenTable_2" :options="options" :isShow="tabsKey === 2" :mainRowKey="mainId" />
          </a-tab-pane>
          <a-tab-pane :key="3" tab="审批信息">
            <approveTable ref="childrenTable_3" :url="auditTableInfoUrl" :options="options" :isShow="tabsKey === 3" :mainRowKey="mainId" />
          </a-tab-pane>
          <a-tab-pane :key="4" tab="费用信息">
            <adjustTable ref="childrenTable_4" ::options="options" :isShow="tabsKey === 4" :mainRowKey="mainId" />
          </a-tab-pane>
          <a-tab-pane :key="5" tab="操作日志">
            <logTable ref="childrenTable_5" :options="options" :isShow="tabsKey === 5" :mainRowKey="mainId" />
          </a-tab-pane>
        </a-tabs>
      </p-card>
    </p-spin>

    <pageOrderView
      v-show="editType === 'view'"
      :st="1"
      :url="mainViewUrl"
      :goodsExtendedField="childrenTableExtendedField"
      :record="currentMainDataView"
      :mode="3"
      :showFeedTable="true"
      :mainId="mainId"
      :options="options"
      @back="onBack"
    />

    <Dialog :dialogForm="dialogForm" :selectedRow="selectedRow" :options="options" :visible="visible" :mextendedField_list="mextendedField_list" @onCancel="onCancel" />
  </div>
</template>

<script>
import { initDictionary, resultExtendedField } from '@/blocks/utils/index.js';
import * as $formItems from '@/blocks/components/searchModalConfig/index';
import pageOrderView from '@/views/BMS/$common/model/pageOrderView/index.pageOrderView.vue'; /**派车单明细表 */

import { listRemoteUrl, mainViewUrl, auditTableInfoUrl, initPaySettlement } from './js/api.js';
import { setMainColumns } from './js/tableConfig.js';

import goodsTable from './model/childrenTable/goodsTable.vue'; /**明细表 */
import parcelTable from './model/childrenTable/parcelTable.vue'; /**明细表 */
import adjustTable from './model/childrenTable/adjustTable.vue'; /**明细表 */
import approveTable from './model/childrenTable/approveTable.vue'; /**明细表 */
import logTable from './model/childrenTable/logTable.vue'; /**明细表 */

import Dialog from './modules/dialog.vue';

export default {
  components: { goodsTable, parcelTable, adjustTable, approveTable, logTable, pageOrderView, Dialog },
  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' : '');
      },
    },
  },
  watch: {
    tabsKey(value) {
      this.childrenTableReload();
    },
  },
  data() {
    return {
      auditTableInfoUrl,
      $formItems,
      spinning: false,
      editType: '', // 空-列表页 view-查看
      mainId: '',
      tabsKey: 1,

      form: {
        cargoOwnerName: '',
        carrierName: '',
        driverName: '',
        vehiclePlateNumber: '',
        loadingBillNo: '',
        startDate: '',
        endDate: '',
      },
      options: {
        ORDER_BUSINESS_TYPE: [],
        CHECK_STATUS: [],
        SETTLEMENT_CYCLE: [],
        TAX_POINT: [],
      },

      // 主表格
      dataSource: [],
      selectedRowKeys: [],
      listRemoteUrl,
      listParams: {},
      mx_columns: setMainColumns(this, this.tableExtendedField),
      tableExtendedField: [],

      formExtendedField: [],
      childrenTableExtendedField: [],
      currentMainDataView: null,
      mainViewUrl,

      dialogForm: {},
      selectedRow: [],
      mextendedField_list: [],
      visible: false, // 弹窗控制
    };
  },
  mounted() {
    initDictionary([{ objectcode: 'ORDER_BUSINESS_TYPE' }, { objectcode: 'CHECK_STATUS', groupcode2: 'BMS2' }, { objectcode: 'SETTLEMENT_CYCLE' }, { objectcode: 'TAX_POINT' }], true).then((res) => {
      for (const key in res) {
        this.options[key] = res[key];
      }
    });
    resultExtendedField({ extendedObjectCode: '15' }).then((res) => {
      if (res) {
        this.tableExtendedField = res.table;
        this.formExtendedField = res.form;
        // this.orderMx_columns = setOrderColumns(this, this.tableExtendedField);
        this.mx_columns = setMainColumns(this, this.tableExtendedField);
      }
    });
    resultExtendedField({ extendedObjectCode: '17' }).then((res) => {
      if (res) {
        this.childrenTableExtendedField = res.table;
      }
    });
    resultExtendedField({ extendedObjectCode: '20' }).then((res) => {
      if (res) {
        this.mextendedField_list = res.list;
      }
    });
  },
  methods: {
    handelSubmit(event) {
      event?.preventDefault();
      event?.submitter?.focus?.();
      this.onSearch();
    },
    // 查询
    onSearch() {
      this.listParams = { ...this.form };
      this.detailsDataSource = [];
    },
    // 重置
    onReset() {
      this.form = {
        cargoOwnerName: '',
        carrierName: '',
        driverName: '',
        vehiclePlateNumber: '',
        loadingBillNo: '',
        startDate: '',
        endDate: '',
      };
    },

    onEdit(editData, type) {
      this.currentMainDataView = editData;
      this.editType = type;
    },

    onBack() {
      this.editType = '';
      this.currentMainDataView = null;
    },

    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]);
      }
    },

    // 明细表查询
    childrenTableReload() {
      this.$nextTick(() => {
        let table = this.$refs['childrenTable_' + this.tabsKey];
        if (table) {
          table.dataSource = [];
          this.mainId && table.reload();
        }
      });
    },
    // 明细表清空
    childrenTableClear() {
      this.$nextTick(() => {
        let table = this.$refs['childrenTable_' + this.tabsKey];
        if (table) {
          table.dataSource = [];
        }
      });
    },
    // 主表点击
    handleRowClick(event, key, data) {
      this.mainId = key;
    },

    // 费用结算
    onSettlement() {
      let list = [];
      this.dataSource.forEach((item) => {
        if (this.selectedRowKeys.includes(item.id)) list.push(item);
      });
      this.selectedRow = [...list];
      this.initPaySettlement(this.selectedRowKeys);
    },
    toSettlement(editData) {
      this.selectedRow = [editData];
      this.initPaySettlement([editData.id]);
    },

    // 关闭弹窗
    onCancel() {
      this.visible = false;
      this.$refs.masterTable.reload();
    },

    // 通过接口获取信息
    initPaySettlement(feeIdList) {
      this.spinning = true;
      initPaySettlement(feeIdList).then((res) => {
        this.spinning = false;
        if (res.success) {
          this.dialogForm = {
            ...res.data,
            carrierId: res.data.driverId,
            carrierCode: res.data.driverCode,
            carrierName: res.data.driverName,
            taxPoint: res.data.taxPoint === null ? undefined : ~~res.data.taxPoint,
          };
          this.visible = true;
        } else {
          this.$exception(res);
        }
      });
    },
  },
};
</script>

<style>
</style>