<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-col :span="7">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              v-model="queryParams.customerId"
              placeholder="请选择客户"
              clearable
              filterable
              @change="handleQuery"
            >
              <el-option
                v-for="item in customSelectData"
                :key="item.id"
                :label="item.customName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-form-item label="回单日期" prop="returnReceiptDate">
        <el-date-picker
          clearable
          v-model="queryParams.returnReceiptDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择回单日期"
        >
        </el-date-picker>
      </el-form-item> -->
        <el-col :span="10">
          <el-form-item label="日期范围" prop="startTime">
            <el-date-picker
              v-model="timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="timeRangeChange"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="备注" prop="accountsReceivableRemark">
            <el-input
              v-model="queryParams.accountsReceivableRemark"
              size="medium"
              clearable
              @keyup.enter.native="handleQuery"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="账务类型" prop="accountingType">
            <el-select
              v-model="queryParams.accountingType"
              value-key=""
              placeholder="请选择账务类型"
              clearable
              filterable
              @change="handleQuery"
            >
              <el-option
                v-for="item in dict.type.accounting_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="" prop="returnReceipt">
            <el-radio-group
              @change="handleQuery"
              v-model="queryParams.returnReceipt"
            >
              <el-radio :label="0">未收回单</el-radio>
              <el-radio :label="1">收到回单</el-radio>
              <el-radio :label="''">全部</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item class="ml20" label="" prop="billingType">
            <el-radio-group
              @change="handleQuery"
              v-model="queryParams.billingType"
            >
              <el-radio :label="1">一类开票</el-radio>
              <el-radio :label="2">二类开票</el-radio>
              <el-radio :label="''">全部</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:SaleAccountsReceivableDetail:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:SaleAccountsReceivableDetail:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:SaleAccountsReceivableDetail:remove']"
          >删除</el-button
        >
      </el-col> -->
      <!-- :disabled="multiple" -->
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-claim"
          size="mini"
          @click="handlerReceipt"
          >回单</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:SaleAccountsReceivableDetail:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="SaleAccountsReceivableDetailList"
      @selection-change="handleSelectionChange"
      @cell-click="cellClick"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="账务类型" align="center" prop="accountingType">
        <template slot-scope="scope">
          {{ getDictLabel(scope.row.accountingType, "accounting_type") }}
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="customName" />
      <el-table-column
        label="日期"
        align="center"
        prop="accountsReceivableDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.accountsReceivableDate, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售单号" align="center" prop="saleNo" />
      <!-- <el-table-column label="产品编号" align="center" prop="productId" /> -->
      <el-table-column label="品名" align="center" prop="productName" />
      <el-table-column
        label="规格"
        align="center"
        prop="productSpecifications"
      />
      <el-table-column label="等级" align="center" prop="productLevel" />
      <el-table-column label="颜色" align="center" prop="productColour" />
      <el-table-column label="批号" align="center" prop="lotNumber" />
      <el-table-column label="箱数" align="center" prop="boxNum" />
      <el-table-column label="重量" align="center" prop="weight" />
      <el-table-column label="单价" align="center" prop="productPrice" />
      <el-table-column label="应收" align="center" prop="amountReceivable" />
      <el-table-column label="已收" align="center" prop="receivedAmount" />
      <el-table-column label="余额" align="center" prop="amounts" />
      <el-table-column label="付款方式" align="center" prop="paymentMethod">
        <template slot-scope="scope">{{
          getDictLabel(
            scope.row.paymentMethod,
            "collection_registration_payment_method"
          )
        }}</template>
      </el-table-column>
      <el-table-column label="开票类型" align="center" prop="billingType">
        <template slot-scope="scope">
          {{
            getDictLabel(
              scope.row.billingType,
              "accounts_receivable_billing_type"
            )
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        align="center"
        prop="accountsReceivableRemark"
      />
      <el-table-column
        label="结算单位"
        align="center"
        prop="settlementUnitName"
      />
      <el-table-column label="通知单号" align="center" prop="noticeNumber" />
      <el-table-column label="开票" align="center" prop="billingFlag">
        <template slot-scope="scope">
          <el-checkbox
            true-label="1"
            false-label="0"
            v-model="scope.row.billingFlag"
            @change="billingFlagChange(scope.row)"
          ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column label="回单" align="center" prop="returnReceipt">
        <template slot-scope="scope">
          <el-checkbox
            true-label="1"
            false-label="0"
            v-model="scope.row.returnReceipt"
            @change="returnReceiptChange(scope.row)"
          ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column
        label="回单日期"
        align="center"
        prop="returnReceiptDate"
        width="180"
      >
        <template slot-scope="scope">
          <el-date-picker
            style="width: 150px"
            v-if="scope.row.returnReceiptDateShow"
            v-model="scope.row.returnReceiptDate"
            type="date"
            size="mini"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            @change="returnReceiptChange(scope.row)"
          >
          </el-date-picker>

          <span v-else>{{
            parseTime(scope.row.returnReceiptDate, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="回单备注"
        align="center"
        width="100px"
        prop="returnReceiptRemark"
      >
        <template slot-scope="scope">
          <el-input
            style="width: 85px"
            v-if="scope.row.returnReceiptRemarkShow"
            v-model="scope.row.returnReceiptRemark"
            @blur="returnReceiptChange(scope.row)"
            size="mini"
          ></el-input>
          <span v-else>
            {{ scope.row.returnReceiptRemark }}
          </span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" plain size="small">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                ><el-button
                  size="mini"
                  type="text"
                  @click="handlerReceipt(scope.row.id)"
                  >回 单</el-button
                ></el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改应收账明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户编号" prop="customerId">
          <el-input v-model="form.customerId" placeholder="请输入客户编号" />
        </el-form-item>
        <el-form-item label="应收账日期" prop="accountsReceivableDate">
          <el-date-picker
            clearable
            v-model="form.accountsReceivableDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择应收账日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="销售单号" prop="saleNo">
          <el-input v-model="form.saleNo" placeholder="请输入销售单号" />
        </el-form-item>
        <el-form-item label="销售产品编号" prop="saleProductNo">
          <el-input
            v-model="form.saleProductNo"
            placeholder="请输入销售产品编号"
          />
        </el-form-item>
        <el-form-item label="产品编号" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入产品编号" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品规格" prop="productSpecifications">
          <el-input
            v-model="form.productSpecifications"
            placeholder="请输入产品规格"
          />
        </el-form-item>
        <el-form-item label="产品等级" prop="productLevel">
          <el-input v-model="form.productLevel" placeholder="请输入产品等级" />
        </el-form-item>
        <el-form-item label="产品颜色" prop="productColour">
          <el-input v-model="form.productColour" placeholder="请输入产品颜色" />
        </el-form-item>
        <el-form-item label="批号" prop="lotNumber">
          <el-input v-model="form.lotNumber" placeholder="请输入批号" />
        </el-form-item>
        <el-form-item label="箱数" prop="boxNum">
          <el-input v-model="form.boxNum" placeholder="请输入箱数" />
        </el-form-item>
        <el-form-item label="重量" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量" />
        </el-form-item>
        <el-form-item label="产品单价" prop="productPrice">
          <el-input v-model="form.productPrice" placeholder="请输入产品单价" />
        </el-form-item>
        <el-form-item label="应收金额" prop="amountReceivable">
          <el-input
            v-model="form.amountReceivable"
            placeholder="请输入应收金额"
          />
        </el-form-item>
        <el-form-item label="已收金额" prop="receivedAmount">
          <el-input
            v-model="form.receivedAmount"
            placeholder="请输入已收金额"
          />
        </el-form-item>
        <el-form-item label="金额" prop="amounts">
          <el-input v-model="form.amounts" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="付款方式" prop="paymentMethod">
          <el-input v-model="form.paymentMethod" placeholder="请输入付款方式" />
        </el-form-item>
        <el-form-item label="应收账备注" prop="accountsReceivableRemark">
          <el-input
            v-model="form.accountsReceivableRemark"
            placeholder="请输入应收账备注"
          />
        </el-form-item>
        <el-form-item label="结算单位" prop="settlementUnit">
          <el-input
            v-model="form.settlementUnit"
            placeholder="请输入结算单位"
          />
        </el-form-item>
        <el-form-item label="回单" prop="returnReceipt">
          <el-input v-model="form.returnReceipt" placeholder="请输入回单" />
        </el-form-item>
        <el-form-item label="回单日期" prop="returnReceiptDate">
          <el-date-picker
            clearable
            v-model="form.returnReceiptDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择回单日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="回单备注" prop="returnReceiptRemark">
          <el-input
            v-model="form.returnReceiptRemark"
            placeholder="请输入回单备注"
          />
        </el-form-item>
        <el-form-item label="通知单号" prop="noticeNumber">
          <el-input v-model="form.noticeNumber" placeholder="请输入通知单号" />
        </el-form-item>
        <el-form-item label="备用列1" prop="spare1">
          <el-input v-model="form.spare1" placeholder="请输入备用列1" />
        </el-form-item>
        <el-form-item label="备用列2" prop="spare2">
          <el-input v-model="form.spare2" placeholder="请输入备用列2" />
        </el-form-item>
        <el-form-item label="备用列3" prop="spare3">
          <el-input v-model="form.spare3" placeholder="请输入备用列3" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="创建者ID" prop="createById">
          <el-input v-model="form.createById" placeholder="请输入创建者ID" />
        </el-form-item>
        <el-form-item label="更新者ID" prop="updateById">
          <el-input v-model="form.updateById" placeholder="请输入更新者ID" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 回单弹窗 -->
    <el-dialog title="回单登记" :visible.sync="receiptShow" width="500px">
      <el-form
        ref="returnReceiptForm"
        :model="returnReceiptForm"
        :rules="receiptFormrules"
        label-width="80px"
      >
        <el-form-item label="回单号" prop="receiptNo">
          <el-input
            v-model="returnReceiptForm.receiptNo"
            placeholder="请输入回单号"
          />
        </el-form-item>
        <el-form-item label="客户" prop="customId">
          <el-select
            v-model="returnReceiptForm.customId"
            placeholder="请选择回单客户"
            clearable
            filterable
          >
            <el-option
              v-for="item in customSelectData"
              :key="item.id"
              :label="item.customName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收到回单" prop="isReceive">
          <el-radio-group v-model="returnReceiptForm.isReceive">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="回单日期" prop="receiveDate">
          <el-date-picker
            v-model="returnReceiptForm.receiveDate"
            type="date"
            size="normal"
            placeholder="选择回单日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="receiveRemark">
          <el-input
            v-model="returnReceiptForm.receiveRemark"
            size="normal"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="receiptShow = false">取 消</el-button>
        <el-button type="primary" @click="submitReceiptForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加发票对话框 -->
    <el-dialog
      title="添加发票"
      :visible.sync="billingVisible"
      width="800px"
      append-to-body
    >
      <el-row :gutter="20">
        <el-form
          ref="billingForm"
          :model="billingForm"
          :rules="billingFormRules"
          label-width="80px"
        >
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerId">
              <el-select
                v-model="billingForm.customerId"
                placeholder="请选择客户"
                clearable
                filterable
                @change="getSettlementUnitList"
              >
                <el-option
                  v-for="item in customSelectData"
                  :key="item.id"
                  :label="item.customName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票号" prop="invoiceNumber">
              <el-input
                v-model="billingForm.invoiceNumber"
                placeholder="请输入发票号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票日期" prop="invoiceDate">
              <el-date-picker
                clearable
                v-model="billingForm.invoiceDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择发票日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票类型" prop="invoiceType">
              <el-select
                v-model="billingForm.invoiceType"
                placeholder="请选择发票类型"
                clearable
                filterable
              >
                <el-option
                  v-for="item in dict.type.finished_product_invoice_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="开票金额" prop="billingAmount">
              <el-input
                v-model="billingForm.billingAmount"
                placeholder="请输入开票金额"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经手人" prop="personInCharge">
              <el-input
                v-model="billingForm.personInCharge"
                placeholder="请输入经手人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="结算单位" prop="settlementUnitId">
              <el-select
                v-model="billingForm.settlementUnitId"
                clearable
                filterable
              >
                <el-option
                  v-for="item in settlementUnitList"
                  :key="item.ids"
                  :label="item.customerName"
                  :value="item.id"
                >
                </el-option>
              </el-select>

              <el-button
                class="ml10"
                icon="el-icon-edit"
                @click="editSettleUnit"
              ></el-button>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="billingForm.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-dialog
        width="600px"
        :title="customName + '的结算单位'"
        :visible.sync="innerVisible"
        append-to-body
      >
        <el-button
          type="primary"
          size="small"
          @click="addSettleUnit"
          icon="el-icon-plus"
          :disabled="adding"
          >新增</el-button
        >
        <el-table :data="settleTableData" border stripe>
          <el-table-column type="index" width="50" />
          <el-table-column prop="customerName" label="单位名称">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{ scope.row.customerName }}</span>
              <el-input
                v-else
                v-model="scope.row.customerName"
                size="mini"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="customerRegion" label="单位地区">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{
                scope.row.customerRegion
              }}</span>
              <el-input
                v-else
                v-model="scope.row.customerRegion"
                size="mini"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <!-- 编辑 -->
              <div class="btn-wrap" v-show="scope.row.isEdit && scope.row.id">
                <el-button
                  type="success"
                  size="small"
                  @click="addSettleUnitConfirm(scope.row)"
                  >保存</el-button
                >
                <el-button type="info" size="small" @click="initSettleTableData"
                  >取消</el-button
                >
              </div>
              <!-- 待编辑 -->
              <div class="btn-wrap" v-show="!scope.row.isEdit && scope.row.id">
                <el-button
                  type="primary"
                  size="small"
                  @click="scope.row.isEdit = true"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="small"
                  @click="deleteUnit(scope.row)"
                  >删除</el-button
                >
              </div>
              <!-- 待新增 -->
              <div class="btn-wrap" v-show="!scope.row.id">
                <el-button
                  type="primary"
                  size="small"
                  @click="addSettleUnitConfirm(scope.row)"
                  >新增</el-button
                >
                <el-button
                  type="danger"
                  size="small"
                  @click="cancelAdd(scope.$index)"
                  >取消</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div slot="footer" class="dialog-footer">
          <el-button @click="innerCancel">关 闭</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBillingForm">确 定</el-button>
        <el-button @click="billingCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSaleAccountsReceivableDetail,
  getSaleAccountsReceivableDetail,
  delSaleAccountsReceivableDetail,
  addSaleAccountsReceivableDetail,
  updateSaleAccountsReceivableDetail,
  addBilling,
  cancelBilling,
} from "@/api/system/SaleAccountsReceivableDetail";
import {
  getCustomList,
  customerSettlementUnit,
  addSettlementUnit, //新增结算单位
  updateSettlementUnit,
  deleteSettlementUnit,
} from "@/api/system/SaleRegistrationCollection";
import moment from "moment";

export default {
  name: "saleAccountsReceivableDetail",
  dicts: [
    "accounting_type",
    "accounts_receivable_billing_type",
    "collection_registration_payment_method",
    "finished_product_invoice_type",
  ],
  data() {
    return {
      receiptIds: [], //回单ids
      receiptShow: false, //回单弹窗
      timeRange: [], //日期范围
      customSelectData: [], //客户list
      returnReceiptForm: {
        receiptNo: "", //回单号
        customId: "", //客户id
        isReceive: true, //收到回单
        receiveDate: "", //回单日期
        receiveRemark: "", //回单备注
      }, //回单
      receiptFormrules: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应收账明细表格数据
      SaleAccountsReceivableDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        accountingType: null,
        customerId: null,
        accountsReceivableDate: null,
        saleNo: null,
        saleProductNo: null,
        productId: null,
        productName: null,
        productSpecifications: null,
        productLevel: null,
        productColour: null,
        lotNumber: null,
        boxNum: null,
        weight: null,
        productPrice: null,
        amountReceivable: null,
        receivedAmount: null,
        amounts: null,
        paymentMethod: null,
        billingType: "",
        accountsReceivableRemark: null,
        settlementUnit: null,
        returnReceipt: "",
        returnReceiptDate: null,
        returnReceiptRemark: null,
        noticeNumber: null,
        status: 2,
        spare1: null,
        spare2: null,
        spare3: null,
        startTime: null,
        endTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 开票表单
      innerVisible: false,
      settleTableData: [],
      customName: "",
      settlementUnitList: [],
      currentRow: {},
      billingVisible: false,
      billingForm: {},
      billingFormRules: {
        customerId: [
          { required: true, message: "客户不能为空", trigger: "change" },
        ],
        invoiceNumber: [
          { required: true, message: "发票号码不能为空", trigger: "blur" },
        ],
        invoiceDate: [
          { required: true, message: "发票日期不能为空", trigger: "change" },
        ],
        invoiceType: [
          { required: true, message: "发票类型不能为空", trigger: "change" },
        ],
        billingAmount: [
          { required: true, message: "开票金额不能为空", trigger: "blur" },
        ],
        personInCharge: [
          { required: true, message: "负责人不能为空", trigger: "blur" },
        ],
        settlementUnitId: [
          { required: true, message: "结算单位不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.initSelectData();
  },
  computed: {
    adding() {
      if (!this.settleTableData.length) return false;
      return this.settleTableData.some((item) => !item.id);
    },
  },
  methods: {
    // 确认开票
    submitBillingForm() {
      this.$refs["billingForm"].validate((valid) => {
        if (valid) {
          if (this.billingForm.id != null) {
            updateFinishedProductInvoice(this.billingForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.billingVisible = false;
              this.getList();
            });
          } else {
            this.billingForm.accountsReceivableDetailId = this.currentRow.id;
            this.billingForm.billingFlag = 1;

            addBilling(this.billingForm).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.billingVisible = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消开票
    billingCancel() {
      this.billingVisible = false;
      this.getList();
    },
    /* 删除单位 */
    async deleteUnit(row) {
      this.$confirm("是否确认删除该单位?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            let res = await deleteSettlementUnit(row.id);
            if (res.code == 200) {
              this.$message.success("删除成功!");
              this.initSettleTableData();
            } else {
              throw new Error(res.msg);
            }
          } catch (error) {
            this.$message.error(error);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /* 确认新增/修改一条结算单位 */
    async addSettleUnitConfirm(row) {
      let { customerName, customerRegion, id } = row;
      if (!customerName || !customerRegion) {
        this.$message.warning("请完善数据!");
        return;
      }
      let customerId = this.billingForm.customerId;
      let fun = id ? updateSettlementUnit : addSettlementUnit;
      let payload = {
        customerId,
        customerRegion,
        customerName,
      };
      if (id) {
        payload.id = id;
      }
      try {
        let res = await fun(payload);
        if (res.code == 200) {
          this.$message.success("操作成功!");
          this.initSettleTableData();
        } else {
          throw new Error(res.msg);
        }
      } catch (error) {
        this.$message.error(error);
      }
    },
    /* 内层弹窗关闭回调 */
    innerCancel() {
      this.innerVisible = false;
      this.getSettlementUnitList();
    },
    /* 新增一条结算单位 */
    addSettleUnit() {
      this.settleTableData.unshift({
        customerName: "",
        customerRegion: "",
        isEdit: true,
      });
    },
    /* 初始化结算单位表格数据 */
    async initSettleTableData() {
      await this.getSettlementUnitList();
      this.settleTableData = this.settlementUnitList.map((item) => {
        return {
          ...item,
          isEdit: false,
        };
      });
    },
    // 开始编辑结算单位
    async editSettleUnit() {
      let customerId = this.billingForm.customerId;
      if (!customerId) {
        this.$message.warning("请先选择客户名称");
        return;
      }
      this.customName = this.customSelectData.find(
        (item) => item.id == this.billingForm.customerId
      )?.customName;
      await this.initSettleTableData();
      console.log(111);
      this.innerVisible = true;
    },
    // 获取结算单位下拉框数据
    async getSettlementUnitList() {
      let customerId = this.billingForm.customerId;
      if (!customerId) {
        this.$message.warning("请先选择客户名称");
        return;
      }
      try {
        let payload = {
          customerId,
          isEnablePaging: false,
        };
        let res = await customerSettlementUnit(payload);
        if (res.code == 200) {
          this.settlementUnitList = res.rows;
        } else {
          throw new Error(res.msg);
        }
      } catch (error) {
        this.$message.error(error);
      }
    },
    // 新增开票
    addBilling() {
      this.resetBillingForm();
      this.billingVisible = true;
    },
    resetBillingForm() {
      this.billingForm = {
        id: null,
        invoiceDate: null,
        customerId: null,
        settlementUnitId: null,
        invoiceNumber: null,
        invoiceType: null,
        billingAmount: null,
        personInCharge: null,
        remark: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        delFlag: null,
      };
      this.resetForm("billingForm");
    },
    // 开票回调
    async billingFlagChange(row) {
      let billingFlag = row.billingFlag;
      if (billingFlag == 1) {
        //开票
        this.currentRow = row;
        this.addBilling();
      } else {
        this.$confirm("是否确认取消开票?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            // 取消开票
            let payload = {
              id: row.finishedProductInvoiceId,
              accountsReceivableDetailId: row.id,
              billingFlag: 0,
            };
            let res = await cancelBilling(payload);
            if (res.code == 200) {
              this.$message({
                message: "取消开票成功",
                type: "success",
              });
              this.getList();
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
              this.getList();
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
            this.getList();
          });
      }
    },
    // 根据字典value获取字典label
    getDictLabel(value, dict) {
      return (
        this.dict.type[dict].find((item) => {
          return item.value === value;
        })?.label || ""
      );
    },
    // 修改回单数据
    async returnReceiptChange(row) {
      console.log(row.returnReceiptDate);
      // return;
      try {
        let payLoad = {
          id: row.id,
          returnReceipt: row.returnReceipt,
          returnReceiptDate:
            row.returnReceipt == "1" ? row.returnReceiptDate || new Date() : "",
          returnReceiptRemark:
            row.returnReceipt == "1" ? row.returnReceiptRemark || "" : "",
        };
        let res = await updateSaleAccountsReceivableDetail(payLoad);
        if (res.code == 200) {
          this.$message.success("修改成功");
          this.getList();
        } else {
          throw new Error(res.msg);
        }
      } catch (error) {
        this.$message.error(error);
      }
    },

    // 单元格点击回调
    cellClick(row, column, cell, event) {
      console.log(row, column, cell, event);
      let columnList = ["returnReceiptDate", "returnReceiptRemark"];
      if (columnList.includes(column.property)) {
        row[column.property + "Show"] = true;
      }
    },
    // 提交回单回调
    submitReceiptForm() {},
    // 回单回调
    handlerReceipt(id) {
      // let ids=[id]||this.ids;
      this.receiptIds = [id] || this.ids;
      this.receiptShow = true;
    },
    // 日期范围改变回调
    timeRangeChange(val) {
      this.queryParams.startTime = moment(val[0]).format("YYYY-MM-DD");
      this.queryParams.endTime = moment(val[1]).format("YYYY-MM-DD");
      this.handleQuery();
    },
    // 初始化下拉框选择数据
    async initSelectData() {
      // 客户数据
      try {
        let res1 = await getCustomList({ isEnablePaging: false });
        if (res1.code == 200) {
          this.customSelectData = res1.rows;
        } else {
          throw new Error(res1.msg);
        }
      } catch (error) {
        this.$message.error(error);
      }
    },
    /** 查询应收账明细列表 */
    getList() {
      this.loading = true;
      listSaleAccountsReceivableDetail(this.queryParams).then((response) => {
        this.SaleAccountsReceivableDetailList = response.rows.map((item) => {
          return {
            ...item,
            returnReceiptDateShow: false,
            returnReceiptRemarkShow: false,
          };
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        accountingType: null,
        customerId: null,
        accountsReceivableDate: null,
        saleNo: null,
        saleProductNo: null,
        productId: null,
        productName: null,
        productSpecifications: null,
        productLevel: null,
        productColour: null,
        lotNumber: null,
        boxNum: null,
        weight: null,
        productPrice: null,
        amountReceivable: null,
        receivedAmount: null,
        amounts: null,
        paymentMethod: null,
        billingType: null,
        accountsReceivableRemark: null,
        settlementUnit: null,
        returnReceipt: null,
        returnReceiptDate: null,
        returnReceiptRemark: null,
        noticeNumber: null,
        status: null,
        spare1: null,
        spare2: null,
        spare3: null,
        remark: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加应收账明细";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getSaleAccountsReceivableDetail(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改应收账明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateSaleAccountsReceivableDetail(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSaleAccountsReceivableDetail(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除应收账明细编号为"' + ids + '"的数据项？')
        .then(function () {
          return delSaleAccountsReceivableDetail(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/SaleAccountsReceivableDetail/export",
        {
          ...this.queryParams,
        },
        `SaleAccountsReceivableDetail_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
