<!--
@name: 承运商应付管理-费用结算
@author: 张泽贤
@time: 2022-09-02
@doc:
-->
<template>
  <div class="pages">
    <p-spin :spinning="spinning" v-if="!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" @clickSync="onSearch" icon="search">查询</p-button>
          <p-button @click="onReset">重置</p-button>
          <!-- <p-button type="primary" @click="onSeniorSearch">高级查询</p-button> -->
        </a-space>
        <p-form-model ref="formTarget" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" class="plg-grid-from" @submit="handelSubmit">
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="货主">
                <p-input :value="form.cargoOwnerName" @blur="(event) => (form.cargoOwnerName = event.target.value)" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="订单号">
                <p-input :value="form.orderNo" @blur="(event) => (form.orderNo = event.target.value)" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="运单号">
                <p-input :value="form.shipbillNo" @blur="(event) => (form.shipbillNo = event.target.value)" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="业务类型">
                <p-select v-model="form.orderBusinessType" :options="options.ORDER_BUSINESS_TYPE" allowClear />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="启运日期">
                <p-range-picker v-model="shipmentDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" style="width: 100%" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="送达日期">
                <p-range-picker v-model="deliveryDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" style="width: 100%" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="回单日期">
                <p-range-picker v-model="receiptDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" style="width: 100%" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="正本回单日期">
                <p-range-picker v-model="originalBackDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" style="width: 100%" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="完成日期">
                <p-range-picker v-model="completeDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" style="width: 100%" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="始发地">
                <p-input :value="form.shipperProvinceCityDistrict" @blur="(event) => (form.shipperProvinceCityDistrict = event.target.value)" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="目的地">
                <p-input :value="form.consigneeProvinceCityDistrict" @blur="(event) => (form.consigneeProvinceCityDistrict = event.target.value)" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="费用名称">
                <p-input :value="form.expenseName" @blur="(event) => (form.expenseName = event.target.value)" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="费用单号">
                <p-input :value="form.expenseNo" @blur="(event) => (form.expenseNo = event.target.value)" />
              </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">
          <!-- :disabled="disSettlement" -->
          <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: 600 }"
          :columns="mx_columns"
          :data-source.sync="dataSource"
          :remote-url="listRemoteUrl"
          :remoteData="listParams"
          :rowSelectType="2"
          :selectedRowKeys.sync="selectedRowKeys"
        >
          <template slot="operation" slot-scope="text, record">
            <a-space>
              <a @click.stop="toSettlement(record)">费用结算</a>
            </a-space>
          </template>
        </t-table>
      </p-card>
    </p-spin>

    <orderView v-show="editType === 'view'" :st="1" :record="currentMainDataView" :mode="1" :options="options" :formName="'main'" @back="back" />

    <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 { listRemoteUrl, Review, viewUrl, page_detail_item, page_detail_package } from './js/api.js';
import Dialog from './modules/dialog.vue';
import { setMainColumns } from './js/tableConfig.js';

import orderView from '@/views/BMS/$common/model/orderView/index.orderView.vue'; /**内容查看 */

export default {
  components: { orderView, Dialog },
  computed: {
    shipmentDate: {
      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' : '');
      },
    },
    deliveryDate: {
      get() {
        return [this.form.deliveryStartDate, this.form.deliveryEndDate];
      },
      set(value) {
        this.$set(this.form, 'deliveryStartDate', value.length ? value[0] + ' 00:00:00' : '');
        this.$set(this.form, 'deliveryEndDate', value.length ? value[1] + ' 23:59:59' : '');
      },
    },
    receiptDate: {
      get() {
        return [this.form.receiptStartDate, this.form.receiptEndDate];
      },
      set(value) {
        this.$set(this.form, 'receiptStartDate', value.length ? value[0] + ' 00:00:00' : '');
        this.$set(this.form, 'receiptEndDate', value.length ? value[1] + ' 23:59:59' : '');
      },
    },
    originalBackDate: {
      get() {
        return [this.form.originalBackStartDate, this.form.originalBackEndDate];
      },
      set(value) {
        this.$set(this.form, 'originalBackStartDate', value.length ? value[0] + ' 00:00:00' : '');
        this.$set(this.form, 'originalBackEndDate', value.length ? value[1] + ' 23:59:59' : '');
      },
    },
    completeDate: {
      get() {
        return [this.form.completeStartDate, this.form.completeEndDate];
      },
      set(value) {
        this.$set(this.form, 'completeStartDate', value.length ? value[0] + ' 00:00:00' : '');
        this.$set(this.form, 'completeEndDate', value.length ? value[1] + ' 23:59:59' : '');
      },
    },
    selectLength() {
      return this.selectedRowKeys.length;
    },
  },
  watch: {
    selectLength() {
      this.selectedRow = [];
      let settlementDepartmentSet = new Set(),
        settlementCompanyIdSet = new Set(),
        settlementCompanyCodeSet = new Set(),
        settlementCompanySet = new Set(),
        carrierTypeSet = new Set(),
        carrierIdSet = new Set(),
        carrierCodeSet = new Set(),
        carrierNameSet = new Set(),
        affiliationIdSet = new Set(),
        affiliationCodeSet = new Set(),
        affiliationNameSet = new Set(),
        taxPointSet = new Set(),
        noTaxAmtTotal = 0,
        taxAmtTotal = 0,
        taxTotal = 0,
        settlementCycleSet = new Set();
      this.dataSource.forEach((item) => {
        if (this.selectedRowKeys.includes(item.id)) {
          settlementDepartmentSet.add(item.settlementDepartment);
          settlementCompanyIdSet.add(item.settlementCompanyId);
          settlementCompanyCodeSet.add(item.settlementCompanyCode);
          settlementCompanySet.add(item.settlementCompany);
          carrierTypeSet.add(item.carrierType);
          carrierIdSet.add(item.carrierId);
          carrierCodeSet.add(item.carrierCode);
          carrierNameSet.add(item.carrierName);
          affiliationIdSet.add(item.affiliationId);
          affiliationCodeSet.add(item.affiliationCode);
          affiliationNameSet.add(item.affiliationName);
          this.selectedRow.push(item);
          taxPointSet.add(item.taxPoint ? Number(item.taxPoint) : '');
          noTaxAmtTotal = parseFloat(this.BigJs(noTaxAmtTotal).plus(item.noTaxAmt));
          taxAmtTotal = parseFloat(this.BigJs(taxAmtTotal).plus(item.taxAmt));
          taxTotal = parseFloat(this.BigJs(taxTotal).plus(item.tax));
          settlementCycleSet.add(item.settlementCycle);
        }
      });
      if (settlementDepartmentSet.size === 1 && settlementCompanySet.size === 1 && carrierTypeSet.size === 1) {
        if ([...carrierTypeSet][0] == 1 && carrierIdSet.size === 1) {
          this.dialogForm = {
            carrierId: [...carrierIdSet][0],
            carrierCode: [...carrierCodeSet][0],
            carrierName: [...carrierNameSet][0],
            settlementCompanyId: [...settlementCompanyIdSet][0],
            settlementCompanyCode: [...settlementCompanyCodeSet][0],
            settlementCompany: [...settlementCompanySet][0],
            settlementDepartment: [...settlementDepartmentSet][0],
            taxPoint: taxPointSet.size === 1 ? [...taxPointSet][0] : '',
            noTaxAmt: noTaxAmtTotal,
            taxAmt: taxAmtTotal,
            totTax: taxTotal,
            settlementCycle: settlementCycleSet.size === 1 ? [...settlementCycleSet][0] : '',
            carrierType: [...carrierTypeSet][0],
          };
          this.disSettlement = false;
        } else if ([...carrierTypeSet][0] == 2 && affiliationIdSet.size === 1) {
          this.dialogForm = {
            carrierId: [...affiliationIdSet][0],
            carrierCode: [...affiliationCodeSet][0],
            carrierName: [...affiliationNameSet][0],
            settlementCompanyId: [...settlementCompanyIdSet][0],
            settlementCompanyCode: [...settlementCompanyCodeSet][0],
            settlementCompany: [...settlementCompanySet][0],
            settlementDepartment: [...settlementDepartmentSet][0],
            taxPoint: taxPointSet.size === 1 ? [...taxPointSet][0] : '',
            noTaxAmt: noTaxAmtTotal,
            taxAmt: taxAmtTotal,
            totTax: taxTotal,
            settlementCycle: settlementCycleSet.size === 1 ? [...settlementCycleSet][0] : '',
            carrierType: [...carrierTypeSet][0],
          };
          this.disSettlement = false;
        } else {
          this.disSettlement = true;
        }
      } else {
        this.disSettlement = true;
      }
    },
  },
  data() {
    return {
      spinning: false,
      visible: false,
      editType: '', // 空-列表页 view-查看
      editId: '',
      form: {
        cargoOwnerName: '',
        orderNo: '',
        shipbillNo: '',
        startDate: '',
        endDate: '',
        deliveryStartDate: '',
        deliveryEndDate: '',
        receiptStartDate: '',
        receiptEndDate: '',
        originalBackStartDate: '',
        originalBackEndDate: '',
        completeStartDate: '',
        completeEndDate: '',
        shipperProvinceCityDistrict: '',
        consigneeProvinceCityDistrict: '',
        expenseName: '',
        expenseNo: '',
      },
      options: {
        ORDER_BUSINESS_TYPE: [],
        SETTLEMENT_CYCLE: [],
        TAX_POINT: [],
      },

      // 主表格
      dataSource: [],
      selectedRowKeys: [],
      selectedRow: [],
      listRemoteUrl,
      listParams: {},
      mx_columns: setMainColumns(this),
      disSettlement: true,

      page_detail_item,
      page_detail_package,

      dialogForm: {},

      mextendedField_list: [],
      currentMainDataView: null,
    };
  },
  mounted() {
    initDictionary([{ objectcode: 'ORDER_BUSINESS_TYPE' }, { objectcode: 'SETTLEMENT_CYCLE' }, { objectcode: 'TAX_POINT' }], true).then((res) => {
      for (const key in res) {
        this.options[key] = res[key];
      }
    });
    resultExtendedField({ extendedObjectCode: '20' }).then((res) => {
      if (res) {
        this.mextendedField_list = res.list;
        console.log(this.mextendedField_list);
      }
    });
  },
  methods: {
    viewUrl,
    // 查询
    handelSubmit(event) {
      event.preventDefault();
      event.submitter.focus();
      this.onSearch();
    },
    onSearch() {
      this.listParams = { ...this.form };
    },
    // 重置
    onReset() {
      this.form = {
        cargoOwnerName: '',
        orderNo: '',
        shipbillNo: '',
        startDate: '',
        endDate: '',
        deliveryStartDate: '',
        deliveryEndDate: '',
        receiptStartDate: '',
        receiptEndDate: '',
        originalBackStartDate: '',
        originalBackEndDate: '',
        completeStartDate: '',
        completeEndDate: '',
        shipperProvinceCityDistrict: '',
        consigneeProvinceCityDistrict: '',
        expenseName: '',
      };
    },

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

    onSettlement() {
      this.visible = true;
    },
    toSettlement(editData) {
      this.dialogForm = {
        carrierId: editData.carrierType == 1 ? editData.carrierId : editData.affiliationId,
        carrierCode: editData.carrierType == 1 ? editData.carrierCode : editData.affiliationCode,
        carrierName: editData.carrierType == 1 ? editData.carrierName : editData.affiliationName,
        settlementCompanyId: editData.settlementCompanyId,
        settlementCompanyCode: editData.settlementCompanyCode,
        settlementCompany: editData.settlementCompany,
        settlementDepartment: editData.settlementDepartment,
        taxPoint: Number(editData.taxPoint),
        noTaxAmt: editData.noTaxAmt,
        taxAmt: editData.taxAmt,
        totTax: editData.tax,
        settlementCycle: editData.settlementCycle,
        carrierType: editData.carrierType,
      };
      this.selectedRow = [editData];
      this.visible = true;
    },

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

    back() {
      this.editType = '';
      this.$nextTick(() => {
        this.onSearch();
      });
    },
  },
};
</script>
