<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="冲销作业" name="offset">
        <el-form :model="queryOpen" :inline="true" size="small" label-width="100px">
          <el-form-item label="请款单位"><el-input v-model="queryOpen.requestUnit" clearable style="width:180px" /></el-form-item>
          <el-form-item label="客户编号"><el-input v-model="queryOpen.custNo" clearable style="width:180px" /></el-form-item>
          <el-form-item label="客户名称"><el-input v-model="queryOpen.custName" clearable style="width:180px" /></el-form-item>
          <el-form-item label="货单开始日期"><el-date-picker v-model="queryOpen.offStartDate" type="date" value-format="yyyy-MM-dd" style="width:180px" /></el-form-item>
          <el-form-item label="货单结束日期"><el-date-picker v-model="queryOpen.offEndDate" type="date" value-format="yyyy-MM-dd" style="width:180px" /></el-form-item>
          <el-form-item label="发票号码"><el-input v-model="queryOpen.invoiceNo" clearable style="width:180px" /></el-form-item>
          <el-form-item label="账款年月"><el-input v-model="queryOpen.acctYm" placeholder="yyyy-MM" clearable style="width:180px" /></el-form-item>
          <el-form-item label="发票状况">
            <el-select v-model="queryOpen.invoiceStatus" clearable style="width:180px">
              <el-option label="未开立" value="0" />
              <el-option label="已开立" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="loadOpenPay">查询</el-button>
          </el-form-item>
        </el-form>

        <el-row class="mb8">
          <el-button type="primary" plain size="mini" :disabled="!selectedOpenPay.length" @click="startOffset" v-hasPermi="['erp:arap:offset:save']">开始冲销</el-button>
        </el-row>

        <el-table :data="openPayList" v-loading="loadingOpen" @selection-change="onOpenSelect">
          <el-table-column type="selection" width="55" />
          <el-table-column label="收付款单号" prop="payNo" min-width="160" />
          <el-table-column label="客户编号" prop="custNo" min-width="120" />
          <el-table-column label="客户名称" prop="custName" min-width="150" />
          <el-table-column label="银行卡号" prop="bankNo" min-width="150" />
          <el-table-column label="单据日期" prop="payDate" min-width="120" />
          <el-table-column label="未清金额" prop="openAmt" min-width="120" />
        </el-table>

        <el-dialog title="冲销窗口" :visible.sync="openOffsetDialog" width="1300px" append-to-body :close-on-click-modal="false">
          <el-form :model="offsetForm" label-width="110px" size="small">
            <el-row :gutter="8">
              <el-col :span="6"><el-form-item label="冲销日期"><el-date-picker v-model="offsetForm.offDate" type="date" value-format="yyyy-MM-dd" style="width:100%" /></el-form-item></el-col>
              <el-col :span="6"><el-form-item label="冲销单号"><el-input v-model="offsetForm.offNo" disabled /></el-form-item></el-col>
              <el-col :span="6"><el-form-item label="客户编号"><el-input v-model="offsetForm.custNo" disabled /></el-form-item></el-col>
              <el-col :span="6"><el-form-item label="总未清款"><el-input :value="sumOpenAmt.toFixed(4)" disabled /></el-form-item></el-col>
            </el-row>
            <el-row :gutter="8">
              <el-col :span="6"><el-form-item label="可冲金额"><el-input :value="availAmt.toFixed(4)" disabled /></el-form-item></el-col>
              <el-col :span="6"><el-form-item label="总冲金额"><el-input :value="sumOffAmt.toFixed(4)" disabled /></el-form-item></el-col>
            </el-row>
          </el-form>

          <el-table :data="orderList" @selection-change="onOrderSelect" ref="orderTable">
            <el-table-column type="selection" width="55" />
            <el-table-column label="单据种类" prop="docType" width="100" />
            <el-table-column label="客户编号" prop="custNo" width="120" />
            <el-table-column label="客户名称" prop="custName" width="140" />
            <el-table-column label="单据日期" prop="docDate" width="120" />
            <el-table-column label="单据编号" prop="docNo" width="160" />
            <el-table-column label="总计金额" prop="totalAmt" width="120" />
            <el-table-column label="未清款金额" prop="openAmt" width="120" />
            <el-table-column label="冲销金额" width="140">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.offAmt" :min="0" :max="Number(scope.row.openAmt || 0)" :precision="4" :step="1" style="width: 120px" />
              </template>
            </el-table-column>
            <el-table-column label="冲销折让金额" width="150">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.offDiscAmt" :min="0" :max="Number(scope.row.openAmt || 0)" :precision="4" :step="1" style="width: 120px" />
              </template>
            </el-table-column>
            <el-table-column label="未冲金额" width="120">
              <template slot-scope="scope">
                {{ calcUnoff(scope.row).toFixed(4) }}
              </template>
            </el-table-column>
            <el-table-column label="税后折让金额" width="150">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.afterTaxDiscAmt" :min="0" :precision="4" :step="1" style="width: 120px" />
              </template>
            </el-table-column>
            <el-table-column label="已收账款" width="120">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.recvArAmt" :min="0" :precision="4" :step="1" style="width: 100px" />
              </template>
            </el-table-column>
          </el-table>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="saveOffsetAction">保 存</el-button>
            <el-button @click="openOffsetDialog=false">取 消</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>

      <el-tab-pane label="反冲销作业" name="reverse">
        <el-form :model="queryRev" :inline="true" size="small" label-width="90px">
          <el-form-item label="冲销日期"><el-date-picker v-model="queryRev.offStartDate" type="date" value-format="yyyy-MM-dd" style="width:180px" /></el-form-item>
          <el-form-item label="冲销单号"><el-input v-model="queryRev.offNo" clearable style="width:180px" /></el-form-item>
          <el-form-item label="请款单位"><el-input v-model="queryRev.requestUnit" clearable style="width:180px" /></el-form-item>
          <el-form-item label="客户名称"><el-input v-model="queryRev.custName" clearable style="width:180px" /></el-form-item>
          <el-form-item><el-button type="primary" size="mini" @click="loadRevList">查询</el-button></el-form-item>
        </el-form>

        <el-table :data="revList" v-loading="loadingRev">
          <el-table-column label="冲销日期" prop="offDate" width="120" />
          <el-table-column label="冲销单号" prop="offNo" width="180" />
          <el-table-column label="客户编号" prop="custNo" width="120" />
          <el-table-column label="总冲销金额" prop="totalOffAmt" width="140" />
          <el-table-column label="操作" width="160">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="openReverseDialog(scope.row)">反冲销</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog title="反冲销窗口" :visible.sync="openRevDialog" width="1200px" append-to-body :close-on-click-modal="false">
          <el-table :data="revItems" @selection-change="onRevItemSelect">
            <el-table-column type="selection" width="55" />
            <el-table-column label="单据种类" prop="docType" width="100" />
            <el-table-column label="客户编号" prop="custNo" width="120" />
            <el-table-column label="客户名称" prop="custName" width="140" />
            <el-table-column label="单据日期" prop="docDate" width="120" />
            <el-table-column label="单据编号" prop="docNo" width="160" />
            <el-table-column label="总计金额" prop="totalAmt" width="120" />
            <el-table-column label="未清款金额" prop="openAmt" width="120" />
            <el-table-column label="冲销金额" prop="offAmt" width="120" />
            <el-table-column label="冲销折让金额" prop="offDiscAmt" width="140" />
            <el-table-column label="收款单号" prop="recvNo" width="140" />
            <el-table-column label="收款方式" prop="recvType" width="120" />
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="saveReverse">保 存</el-button>
            <el-button @click="openRevDialog=false">取 消</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { listOffsetOpenPay, listOffsetOrders, saveOffset, listOffsetRecords, getOffset, reverseOffset } from "@/api/erp/arap";

export default {
  name: "ArapOffset",
  data() {
    return {
      activeTab: "offset",
      loadingOpen: false,
      queryOpen: { pageNum: 1, pageSize: 10, requestUnit: "", custNo: "", custName: "", offStartDate: "", offEndDate: "", invoiceNo: "", acctYm: "", invoiceStatus: "" },
      openPayList: [],
      selectedOpenPay: [],
      openOffsetDialog: false,
      offsetForm: { offDate: "", offNo: "", custNo: "" },
      orderList: [],
      selectedOrderRows: [],
      loadingRev: false,
      queryRev: { pageNum: 1, pageSize: 10, offStartDate: "", offNo: "", requestUnit: "", custName: "" },
      revList: [],
      openRevDialog: false,
      currentRevHead: null,
      revItems: [],
      selectedRevItems: [],
    };
  },
  computed: {
    sumOpenAmt() {
      return (this.orderList || []).reduce((s, r) => s + Number(r.openAmt || 0), 0);
    },
    availAmt() {
      const payAmt = (this.selectedOpenPay || []).reduce((s, r) => s + Number(r.openAmt || 0), 0);
      const returnAmt = (this.selectedOrderRows || []).filter(r => r.docType === "RETURN").reduce((s, r) => s - Number(r.openAmt || 0), 0);
      return payAmt + returnAmt;
    },
    sumOffAmt() {
      return (this.selectedOrderRows || []).reduce((s, r) => s + Number(r.offAmt || 0) + Number(r.offDiscAmt || 0), 0);
    },
  },
  created() {
    this.loadOpenPay();
    this.loadRevList();
  },
  methods: {
    loadOpenPay() {
      this.loadingOpen = true;
      listOffsetOpenPay(this.queryOpen).then(res => {
        this.openPayList = res.rows || [];
        this.loadingOpen = false;
      });
    },
    onOpenSelect(rows) {
      this.selectedOpenPay = rows || [];
    },
    onOrderSelect(rows) {
      this.selectedOrderRows = rows || [];
      (this.orderList || []).forEach(r => {
        const hit = (rows || []).some(x => x.id === r.id);
        if (hit && Number(r.offAmt || 0) === 0) r.offAmt = Number(r.openAmt || 0);
      });
    },
    calcUnoff(row) {
      return Number(row.openAmt || 0) - Number(row.offAmt || 0) - Number(row.offDiscAmt || 0);
    },
    startOffset() {
      if (!this.selectedOpenPay.length) return;
      const custNo = this.selectedOpenPay[0].custNo;
      if (this.selectedOpenPay.some(x => x.custNo !== custNo)) {
        this.$modal.msgError("请先选择同一客户的收付款单");
        return;
      }
      listOffsetOrders({ custNo, startDate: this.queryOpen.offStartDate, endDate: this.queryOpen.offEndDate, remark: this.queryOpen.billRemark }).then(res => {
        const rows = res.data || [];
        if (!rows.length) {
          this.$modal.msgWarning("无可冲销订单");
          return;
        }
        this.orderList = rows.map(r => ({ ...r, offAmt: 0, offDiscAmt: 0, afterTaxDiscAmt: 0, recvArAmt: 0 }));
        this.offsetForm.offDate = this.parseTime(new Date(), "{y}-{m}-{d}");
        this.offsetForm.offNo = "";
        this.offsetForm.custNo = custNo;
        this.openOffsetDialog = true;
      });
    },
    saveOffsetAction() {
      if (!this.selectedOrderRows.length) {
        this.$modal.msgError("请至少选择一条货单");
        return;
      }
      for (const row of this.selectedOrderRows) {
        if (Number(row.offAmt || 0) + Number(row.offDiscAmt || 0) > Number(row.openAmt || 0)) {
          this.$modal.msgError(`单据${row.docNo}冲销金额超出未清款`);
          return;
        }
      }
      const payload = {
        offDate: this.offsetForm.offDate,
        requestUnit: this.selectedOpenPay[0].requestUnit || this.selectedOpenPay[0].custNo,
        custNo: this.selectedOpenPay[0].custNo,
        custName: this.selectedOpenPay[0].custName,
        openPayIds: this.selectedOpenPay.map(x => x.id),
        itemList: this.selectedOrderRows.map(x => ({
          docType: x.docType,
          custNo: x.custNo,
          custName: x.custName,
          docDate: x.docDate,
          docNo: x.docNo,
          totalAmt: x.totalAmt,
          openAmt: x.openAmt,
          offAmt: Number(x.offAmt || 0),
          offDiscAmt: Number(x.offDiscAmt || 0),
          unoffAmt: this.calcUnoff(x),
          afterTaxDiscAmt: Number(x.afterTaxDiscAmt || 0),
          recvArAmt: Number(x.recvArAmt || 0),
        })),
      };
      this.$modal.confirm("确认保存冲销吗？").then(() => saveOffset(payload)).then(() => {
        this.$modal.msgSuccess("冲销保存成功");
        this.openOffsetDialog = false;
        this.loadOpenPay();
        this.loadRevList();
      }).catch(() => {});
    },
    loadRevList() {
      this.loadingRev = true;
      listOffsetRecords(this.queryRev).then(res => {
        this.revList = res.rows || [];
        this.loadingRev = false;
      });
    },
    openReverseDialog(row) {
      this.currentRevHead = row;
      getOffset(row.id).then(res => {
        this.revItems = (res.data && res.data.itemList) ? res.data.itemList.filter(i => String(i.revStatus || "0") === "0") : [];
        this.selectedRevItems = [];
        this.openRevDialog = true;
      });
    },
    onRevItemSelect(rows) {
      this.selectedRevItems = rows || [];
    },
    saveReverse() {
      if (!this.currentRevHead || !this.selectedRevItems.length) {
        this.$modal.msgError("请先选择要反冲销的货单");
        return;
      }
      const payload = {
        id: this.currentRevHead.id,
        reverseItemIds: this.selectedRevItems.map(x => x.id),
      };
      this.$modal.confirm("确认执行反冲销吗？").then(() => reverseOffset(payload)).then(() => {
        this.$modal.msgSuccess("反冲销成功");
        this.openRevDialog = false;
        this.loadRevList();
      }).catch(() => {});
    },
  },
};
</script>

