<template>
  <div>
    <p-modal title="生成结算单" width="80%" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="onCancel">
      <p-tabs :animated="false" :activeKey="activeKey" @tabClick="activeKey = $event">
        <a-space v-if="activeKey == 2" slot="tabBarExtraContent">
          <p-button type="primary" @click="onAdd">添加派车单</p-button>
          <p-button type="danger" @click="onDel" :disabled="!selectedRowKeys.length">剔除派车单</p-button>
        </a-space>
        <p-tab-pane key="1" tab="结算单信息" :forceRender="true">
          <p-form-model ref="dialogForm" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" class="plg-grid-from" :rules="rules">
            <a-row>
              <a-col :span="6">
                <p-form-model-item label="结算单号" prop="settlementNo">
                  <p-input v-model="form.settlementNo" disabled />
                </p-form-model-item>
              </a-col>
              <a-col :span="12">
                <p-form-model-item label="结算单名称" prop="settlementName" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                  <p-input v-model="form.settlementName" />
                </p-form-model-item>
              </a-col>
              <a-col :span="6">
                <p-form-model-item label="结算周期" prop="settlementCycle">
                  <p-select v-model="form.settlementCycle" :options="options.SETTLEMENT_CYCLE" allowClear />
                </p-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="6">
                <p-form-model-item label="往来单位" prop="carrierName">
                  <p-input v-model="form.carrierName" disabled />
                </p-form-model-item>
              </a-col>
              <a-col :span="6">
                <p-form-model-item label="结算公司" prop="settlementCompany">
                  <p-input v-model="form.settlementCompany" disabled />
                </p-form-model-item>
              </a-col>
              <a-col :span="6">
                <p-form-model-item label="结算部门" prop="settlementDepartment">
                  <p-input v-model="form.settlementDepartment" disabled />
                </p-form-model-item>
              </a-col>
              <a-col :span="6">
                <p-form-model-item label="挂账结束日期" prop="endDate">
                  <p-date-picker v-model="form.endDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" style="width: 100%" />
                </p-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="6">
                <p-form-model-item label="开票结束日期" prop="invoiceEndDate">
                  <p-date-picker v-model="form.invoiceEndDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" style="width: 100%" />
                </p-form-model-item>
              </a-col>
              <a-col :span="6">
                <p-form-model-item label="税点" prop="taxPoint">
                  {{ form.taxPoint}}点
                  <!-- <p-select v-model="form.taxPoint" placeholder="请选择税点" :options="options.TAX_POINT" allowClear @change="priceChange" /> -->
                </p-form-model-item>
              </a-col>
              <a-col :span="6">
                <p-form-model-item label="未税金额" prop="noTaxAmt">
                  {{ form.noTaxAmt }}元
                  <!-- <p-input-number v-model="form.noTaxAmt" style="width: 100%" :min="0" @change="priceChange" /> -->
                </p-form-model-item>
              </a-col>
              <a-col :span="6">
                <p-form-model-item label="含税金额" prop="taxAmt">
                  {{ form.taxAmt }}元
                  <!-- <p-input readOnly v-model="form.taxAmt" style="width: 100%" /> -->
                </p-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="6">
                <p-form-model-item label="总税额" prop="tax">
                  {{ form.tax }}元
                  <!-- <p-input-number v-model="form.tax" style="width: 100%" disabled /> -->
                </p-form-model-item>
              </a-col>
              <a-col :span="12">
                <p-form-model-item label="备注" prop="memo" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                  <p-textarea v-model="form.memo" :auto-size="{ minRows: 3, maxRows: 5 }" />
                </p-form-model-item>
              </a-col>
            </a-row>

            <a-divider orientation="left" v-if="mextendedField_list.length">扩展属性</a-divider>
            <extendedField :mextendedField_list="mextendedField_list" :type="'edit'" :form="form"></extendedField>
          </p-form-model>
        </p-tab-pane>
        <p-tab-pane key="2" tab="派车单盘点" :forceRender="true">
          <t-table
            ref="masterTable"
            dragle
            bordered
            row-key="id"
            :id="$route.meta.menuId + '_expenseSettlementDialog'"
            :scroll="{ y: 600 }"
            :columns="mx_columns"
            :data-source.sync="dataSource"
            :rowSelectType="2"
            :selectedRowKeys.sync="selectedRowKeys"
            :autoLoad="false"
            :pagination="false"
          >
          </t-table>
        </p-tab-pane>
      </p-tabs>
    </p-modal>
    <p-search-modal v-bind="searchConfig" @change="(...args) => onFormBlur('waybill', ...args)" v-show="false" :open="waybillDialog" />
  </div>
</template>

<script>
import { getComputedParameter } from '@/blocks/utils/index.js';
import extendedField from '@/blocks/extendedField/index.vue';
import { formatDate, getSpecDate } from '@/blocks/utils';

import { settlementSave, Code, initPaySettlement } from '../js/api.js';
import { setQueryFormItmes } from '../js/form.js';
import { setMainColumns, setDialogColumns } from '../js/tableConfig.js';

export default {
  components: { extendedField },
  props: {
    options: {
      type: Object,
      default: () => ({}),
    },
    visible: {
      type: Boolean,
      default: false,
    },
    mextendedField_list: {
      type: Array,
      default: () => [],
    },
    dialogForm: {
      type: Object,
      default: () => ({}),
    },
    selectedRow: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.$nextTick(() => {
          this.activeKey = '1';
          Code({ code: 'SETTLEMENT_NAME_ID', codetype: 'L' }).then((res) => {
            let time = formatDate(new Date(), '%YY-%MM') + '-01';
            let nextTime = formatDate(getSpecDate(-1, formatDate(time)), '%YY%MM');
            let settlementName = this.dialogForm.carrierName + '-' + nextTime + '-结算单-' + res.data;
            this.form = {
              ...this.dialogForm,
              settlementName: settlementName,
              settlementCycle: this.dialogForm.settlementCycle ? Number(this.dialogForm.settlementCycle) : '',
            };
            this.dataSource = [...this.selectedRow];
          });
        });
      }
    },
  },
  data() {
    const columns = setMainColumns(this);
    columns.pop();
    const searchConfig = setQueryFormItmes(this).waybillAttr;
    searchConfig.tableConfig.columns = columns;

    return {
      confirmLoading: false,
      activeKey: '1',
      searchConfig,

      form: {
        settlementNo: '',
        settlementName: '',
        settlementCycle: '',
        carrierName: '',
        settlementCompany: '',
        settlementDepartment: '',
        endDate: '',
        invoiceEndDate: '',
        taxPoint: '',
        taxAmt: '',
        noTaxAmt: '',
        tax: '',
      },
      rules: {
        settlementName: [{ required: true, message: '结算单名称不能为空', trigger: 'change' }],
        settlementCompany: [{ required: true, message: '结算公司不能为空', trigger: 'change' }],
        settlementDepartment: [{ required: true, message: '结算部门不能为空', trigger: 'change' }],
      },

      // 主表格
      dataSource: [],
      selectedRowKeys: [],
      mx_columns: setDialogColumns(this),

      setQueryFormItmes: setQueryFormItmes(this),
      waybillDialog: false,
    };
  },
  methods: {
    // 保存
    handleOk() {
      this.$refs.dialogForm.validate((valid) => {
        if (!valid) {
          this.activeKey = '1';
          return;
        }

        if (!this.dataSource.length) {
          this.activeKey = '2';
          this.$message.error('请添加费用');
          return;
        }
        let request = { ...this.form, feeIdList: this.dataSource.map((item) => item.id) };
        this.confirmLoading = true;
        settlementSave(request)
          .then((res) => {
            if (res.success) {
              this.$message.success(res.message);
              this.$emit('onCancel');
            } else {
              this.$exception(res);
            }
          })
          .finally(() => {
            this.confirmLoading = false;
          });
      });
    },

    priceChange() {
      if (this.form.taxPoint && this.form.noTaxAmt) {
        let noTaxAmt = getComputedParameter(this.form.noTaxAmt, 'cost');

        let tax = parseFloat(this.BigJs(this.form.taxPoint).times(noTaxAmt).div(100));
        let taxAmt = parseFloat(this.BigJs(tax).plus(noTaxAmt));
        this.form.noTaxAmt = noTaxAmt;
        this.form.tax = getComputedParameter(tax, 'cost');
        this.form.taxAmt = getComputedParameter(taxAmt, 'cost');
      } else {
        this.form.tax = undefined;
        this.form.taxAmt = undefined;
      }
    },

    onAdd() {
      this.waybillDialog = false;
      setTimeout(() => {
        this.waybillDialog = true;
      }, 100);
    },
    onDel() {
      let newList = [];
      this.dataSource.forEach((item) => {
        if (!this.selectedRowKeys.includes(item.id)) {
          newList.push(item);
        }
      });
      this.listUpdate(newList);
    },
    onCancel() {
      this.$emit('onCancel');
    },
    onFormBlur(name, ...args) {
      if (name === 'waybill') {
        this.selectedRowKeys = [];
        let newList = this.dataSource.concat(args[2]);
        this.listUpdate(newList);
      }
    },

    listUpdate(newList) {
      let feeIdList = newList.map((item) => item.id);
      initPaySettlement(feeIdList).then((res) => {
        if (res.success) {
          this.form = {
            ...this.form,
            taxPoint: res.data.taxPoint === null ? undefined : ~~res.data.taxPoint,
            noTaxAmt: res.data.noTaxAmt,
            taxAmt: res.data.taxAmt,
            tax: res.data.tax,
          };

          this.dataSource = [...newList];
        } else {
          this.$exception(res);
        }
      });
    },
  },
};
</script>