<template>
  <div class="dialog_container" v-loading.fullscreen.lock="detailLoading">
    <div class="main">
      <div class="box" style="margin-top: 15px;">
        <div class="item_title">{{ $t("view.shippingInfo") }}</div>
        <div class="ptitle">
          <template>
            <el-descriptions
              class="margin-top"
              :title="$t('title.addressInfo')"
              :column="4"
              direction="horizontal"
              v-if="addressInfo.length == 1"
            >
              <el-descriptions-item :label="$t('country')">{{
                addressInfo[0].receiverCountryCode
              }}</el-descriptions-item>
              <el-descriptions-item :label="$t('label.postalCode')">{{
                addressInfo[0].receiverZip
              }}</el-descriptions-item>
              <el-descriptions-item :label="$t('state')">{{
                addressInfo[0].receiverState
              }}</el-descriptions-item>
              <el-descriptions-item :label="$t('city')">{{
                addressInfo[0].receiverCity
              }}</el-descriptions-item>
              <el-descriptions-item :label="$t('suburb')">{{
                addressInfo[0].receiverDistrict
              }}</el-descriptions-item>
              <el-descriptions-item :label="$t('street')">{{
                addressInfo[0].receiverStreet
              }}</el-descriptions-item>
              <el-descriptions-item :label="$t('address')">{{
                addressInfo[0].receiverAddress
              }}</el-descriptions-item>
              <el-descriptions-item :label="$t('dooeNo')">{{
                addressInfo[0].receiverAddress2
              }}</el-descriptions-item>
              <el-descriptions-item :label="$t('recipient')">{{
                addressInfo[0].receiverName
              }}</el-descriptions-item>
              <el-descriptions-item :label="$t('telephone')">{{
                addressInfo[0].receiverPhone
              }}</el-descriptions-item>
              <el-descriptions-item :label="$t('moPhone')">{{
                addressInfo[0].receiverMobile
              }}</el-descriptions-item>
              <el-descriptions-item :label="$t('post')">{{
                addressInfo[0].email
              }}</el-descriptions-item>
              <el-descriptions-item :label="$t('label.shippingFee')">{{
                addressInfo[0].freight
              }}</el-descriptions-item>
            </el-descriptions>
            <div class="container" width="500px" v-if="addressInfo.length > 1">
              <div
                v-for="(item, index) in addressInfo"
                :key="index"
                width="100px"
                margin-right="50px"
              >
                <el-popover
                  placement="top"
                  :title="$t('title.addressInfo')"
                  width="300"
                  offset="300"
                  trigger="hover"
                >
                  <el-descriptions
                    class="margin-top"
                    title=""
                    :column="1"
                    direction="horizontal"
                  >
                    <el-descriptions-item :label="$t('country')">{{
                      item.receiverCountryCode
                    }}</el-descriptions-item>
                    <el-descriptions-item :label="$t('address')">{{
                      item.receiverAddress
                    }}</el-descriptions-item>
                    <el-descriptions-item :label="$t('recipient')">{{
                      item.receiverName
                    }}</el-descriptions-item>
                    <el-descriptions-item :label="$t('post')">{{
                      item.email
                    }}</el-descriptions-item>
                    <el-descriptions-item :label="$t('label.shippingFee')">{{
                      item.freight
                    }}</el-descriptions-item>
                  </el-descriptions>
                  <el-button
                    slot="reference"
                    @click="chooseClick(item.idList)"
                    >{{ item.receiverCountryCode }}</el-button
                  >
                </el-popover>
              </div>
            </div>
          </template>
        </div>
      </div>
      <div
        class="box"
        style="margin-top: 15px;padding-bottom: 10px;"
        v-loading="fromLoading"
      >
        <div class="item_title">{{ $t("view.refundInfo") }}</div>
        <div class="ptitle">
          <el-form
            label-position="left"
            ref="addRefundForm"
            :model="addRefundForm"
          >
            <div class="row">
              <div class="row-item">
                <div class="row">
                  <el-form-item :label="$t('currency')">
                    <el-input
                      disabled
                      v-model="addRefundForm.currency"
                      placeholder
                      class="normal-input"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    class="inputleft"
                    :label="$t('label.afterSalesType')"
                    required
                  >
                    <el-select
                      :placeholder="$t('place.pleaseSelect')"
                      @change="changeRefund(null)"
                      clearable
                      style="width: 200px;"
                      class="filter-item"
                      v-model="addRefundForm.refundType"
                    >
                      <el-option
                        v-for="afterSaleType in afterSaleTypes"
                        :disabled="afterSaleType.disabled"
                        :key="afterSaleType.value"
                        :label="$t(afterSaleType.label)"
                        :value="afterSaleType.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    :label="$t('label.expectedRefundAmount')"
                    required
                  >
                    <el-input
                      v-model="addRefundForm.refundTotalAmount"
                      :disabled="true"
                    />
                  </el-form-item>
                </div>
                <el-form-item :label="$t('label.refundMethod')" required>
                  <el-radio-group v-model="addRefundForm.refundMethod">
                    <el-radio label="system">{{
                      $t("view.systemRefund")
                    }}</el-radio>
                    <el-radio label="manual">{{
                      $t("view.manualRefund")
                    }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  v-if="addRefundForm.refundMethod == 'manual'"
                  :label="$t('label.accountType')"
                  required
                >
                  <el-radio-group v-model="addRefundForm.refundAccountType">
                    <el-radio label="PayPal">PayPal</el-radio>
                    <!-- 银行卡暂时隐藏 -->
                    <!-- <el-radio label="bankCard">银行卡</el-radio> -->
                    <!-- <el-radio label="Gift Card">Gift Card</el-radio> -->
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  :label="$t('label.receivingAccount')"
                  v-if="
                    addRefundForm.refundMethod == 'manual' &&
                      addRefundForm.refundAccountType == 'PayPal'
                  "
                  required
                >
                  <el-input
                    v-model="addRefundForm.refundAccount"
                    :placeholder="$t('place.pleaseFillIn')"
                    class="normal-input"
                  ></el-input>
                </el-form-item>
                <el-form-item :label="$t('label.taxRefund')">
                  <el-radio-group
                    v-model="addRefundForm.refundTaxAble"
                    @change="calculateRefundAmount"
                  >
                    <el-radio label="0">{{ $t("view.noTaxRefund") }}</el-radio>
                    <el-radio label="1">{{ $t("view.taxRefund") }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  v-if="addRefundForm.refundTaxAble == 1"
                  :label="$t('label.taxRefundAmount')"
                >
                  <el-input-number
                    v-model="addRefundForm.refundTaxAmount"
                    :min="0.0"
                    :step="0.01"
                    step-strictly
                    @change="calculateRefundAmount"
                  ></el-input-number>
                </el-form-item>
                <!-- 选择是否退运费-->
                <el-form-item :label="$t('label.shippingFee')">
                  <el-radio-group
                    v-model="addRefundForm.refundPostage"
                    @change="calculateRefundAmount"
                  >
                    <el-radio label="0">{{ $t("view.noRefund") }}</el-radio>
                    <el-radio label="1">{{
                      $t("view.refundShippingFee")
                    }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  v-if="addRefundForm.refundPostage == 1"
                  :label="$t('label.returnShippingFeeAmount')"
                >
                  <el-input-number
                    v-model="addRefundForm.refundPostageAmount"
                    :min="0.0"
                    :step="0.01"
                    step-strictly
                    @change="calculateRefundAmount"
                  ></el-input-number>
                </el-form-item>

                <el-form-item
                  v-if="this.queryRefundType == 3"
                  :label="$t('label.receivingReturnWarehouse')"
                >
                  <el-select
                    :placeholder="$t('place.pleaseSelect')"
                    clearable
                    style="width: 200px;"
                    class="filter-item"
                    v-model="addRefundForm.warehouseCode"
                    @change="ShippingLabelOption"
                  >
                    <el-option
                      v-for="item in warehouseItems"
                      :key="item.key"
                      :label="item.key"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item
                  v-if="
                    addRefundForm.warehouseCode == 'PSJ-G001001' ||
                      addRefundForm.warehouseCode == 'PSJ-G001003' ||
                      addRefundForm.warehouseCode == 'PSJ-H0000024' ||
                      addRefundForm.warehouseCode == 'PSJ-H0000019' ||
                      addRefundForm.warehouseCode == 'PSJ-H0000011' ||
                      addRefundForm.warehouseCode == 'PSJ-G001004'
                  "
                  label="ShippingLabel"
                >
                  <el-radio-group
                    v-model="addRefundForm.slUseable"
                    @change="changeSlradio()"
                  >
                    <el-radio label="0" value="0">{{
                      $t("view.notEnabled")
                    }}</el-radio>
                    <el-radio label="1" value="1">{{
                      $t("view.enabled")
                    }}</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item
                  v-if="
                    this.queryRefundType == 3 &&
                      this.addRefundForm.slUseable == 0
                  "
                  :label="$t('label.returnLogisticsCompanyCode')"
                >
                  <el-input
                    v-model="addRefundForm.shipmodeId"
                    :placeholder="$t('place.pleaseFillIn')"
                    class="normal-input"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  v-if="
                    this.queryRefundType == 3 &&
                      this.addRefundForm.slUseable == 0
                  "
                  :label="$t('label.returnLogisticsNumber')"
                >
                  <el-input
                    v-model="addRefundForm.shippingNo"
                    :placeholder="$t('place.pleaseFillIn')"
                    class="normal-input"
                  ></el-input>
                </el-form-item>
              </div>
              <div class="row-item">
                <el-form-item :label="$t('label.afterSalesInstructions')">
                  <el-input
                    type="textarea"
                    class="afertextarea"
                    :placeholder="$t('place.enterContent')"
                    v-model="addRefundForm.notes"
                    :rows="4"
                    maxlength="150"
                    show-word-limit
                  >
                  </el-input>
                </el-form-item>

                <el-form-item :label="$t('label.uploadVoucher')">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadPhotos"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :headers="headers"
                  >
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </div>
            </div>
          </el-form>
        </div>

        <!-- 因为要多选的问题 不考虑分页 -->
        <div class="box" style="margin-top: 15px;">
          <div class="item_title">
            <span>{{ $t("view.selectItems") }}</span>
            <el-select
              v-if="this.multipleSelection && this.multipleSelection.length > 0"
              v-model="refundReasonAss"
              style="width: 260px;"
              :placeholder="$t('place.selectCheckedRefundReasons')"
              clearable
              @change="chooseReason(refundReasonAss, reasonListAll)"
            >
              <el-option
                v-for="status in reasonListAll"
                :key="status.id"
                :label="status.reasonContentChinese"
                :value="String(status.id)"
              >
              </el-option>
            </el-select>
            <el-input
              v-if="otherReasonFlag == '1'"
              :placeholder="$t('place.enterReason')"
              clearable
              style="width: 220px;"
              class="filter-item"
              v-model="refundOtherReasonAss"
              @change="writeReason(refundOtherReasonAss)"
            />
          </div>
          <div>
            <el-table
              class="itemtable"
              ref="multipleTable"
              @select="handleSelectionChange"
              @select-all="handleSelectionChange"
              style="width: 100%;"
              v-loading="listLoading"
              :key="tableKey"
              :data="tableOrderDeatils"
              row-key="id"
              stripe
              border
              fit
              highlight-current-row
            >
              <el-table-column
                type="selection"
                width="55"
                :selectable="checkSelectable"
              >
              </el-table-column>

              <el-table-column
                :label="$t('label.orderNumber')"
                width="150"
                align="center"
                prop="ordersId"
              >
              </el-table-column>

              <el-table-column
                :label="$t('goodsCode')"
                width="150"
                align="center"
                prop="skuCode"
              >
              </el-table-column>

              <el-table-column
                :label="$t('onlyCode')"
                min-width="180"
                align="center"
                prop=""
              >
                <template slot-scope="scope">
                  <div v-if="scope.row.uniqueCode">
                    <div
                      v-for="(item, index) in scope.row.uniqueCode"
                      :key="index"
                    >
                      {{ item }}
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                :label="$t('goodsName')"
                width="300"
                align="center"
                prop="productName"
              ></el-table-column>

              <el-table-column
                :label="$t('bagSkuCode')"
                width="180"
                align="center"
                prop="bagSkuCode"
              ></el-table-column>

              <el-table-column
                :label="$t('label.originalQuantity')"
                width="80"
                align="center"
                prop="quantity"
              ></el-table-column>

              <el-table-column
                :label="$t('goodsPrice')"
                width="80"
                align="center"
                prop="price"
              ></el-table-column>

              <el-table-column
                :label="$t('offerAmount')"
                width="80"
                align="center"
                prop="discountFee"
              ></el-table-column>

              <el-table-column
                :label="$t('payAmount')"
                width="80"
                align="center"
                prop="totalFee"
              ></el-table-column>

              <el-table-column
                :label="$t('label.refundPercentage')"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  <div v-if="multipleSelection.indexOf(scope.row) == -1">
                    <div>{{ scope.row.refundSales }}</div>
                  </div>
                  <div v-else>
                    <el-input-number
                      v-model="scope.row.refundSales"
                      @change="changePercentage(scope.row)"
                      size="mini"
                      :min="0"
                      :max="1"
                      :step="0.01"
                      step-strictly
                    ></el-input-number>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('label.eligibleQuantity')"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  <div v-if="multipleSelection.indexOf(scope.row) == -1">
                    <div>{{ scope.row.newQuantity }}</div>
                  </div>
                  <div v-else>
                    <!-- <tableEdit :row.sync="scope.row"></tableEdit> -->
                    <el-input-number
                      v-model="scope.row.newQuantity"
                      @change="changeQuantity(scope.row)"
                      size="mini"
                      :min="0"
                      :max="scope.row.maxq"
                      :step="1"
                      step-strictly
                    ></el-input-number>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('label.refundedAmount')"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  <div v-if="multipleSelection.indexOf(scope.row) == -1">
                    <div>0</div>
                  </div>
                  <div v-else>
                    <el-input-number
                      v-model="scope.row.refundAmount"
                      size="mini"
                      @change="refundAmountChange"
                      :min="0.0"
                      :max="scope.row.maxAmount"
                    ></el-input-number>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('label.needPayWithCustomers')"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  <div v-if="multipleSelection.indexOf(scope.row) == -1">
                    <div>0</div>
                  </div>
                  <div v-else>
                    <el-input-number
                      v-model="scope.row.differenceAmount"
                      size="mini"
                      :min="0.0"
                      :max="scope.row.originPaidAmount"
                      @change="refundAmountChange"
                    ></el-input-number>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('label.refundReason')"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  <div v-if="multipleSelection.indexOf(scope.row) == -1"></div>
                  <div v-else>
                    <el-select
                      v-model="scope.row.refundReason"
                      :placeholder="$t('place.pleaseSelect')"
                      clearable
                      @change="refundChange(scope.row.refundReason, scope.row)"
                    >
                      <el-option
                        v-for="status in scope.row.refundReasonList"
                        :key="status.id"
                        :label="status.reasonContentChinese"
                        :value="String(status.id)"
                      >
                      </el-option>
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('label.reasonExplanation')"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  <div v-if="multipleSelection.indexOf(scope.row) == -1"></div>
                  <div v-else>
                    <el-input
                      v-if="scope.row.customOpen == '1'"
                      :placeholder="$t('place.enterReason')"
                      clearable
                      style="width: 200px;"
                      class="filter-item"
                      v-model="scope.row.otherReason"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                width="55"
                :label="$t('label.flashPurchase')"
                align="center"
              >
                <template slot-scope="scope">
                  <el-checkbox
                    v-model="scope.row.flashPurchaseFlag == 1"
                  ></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column
                width="55"
                :label="$t('label.exchangePurchase')"
                align="center"
              >
                <template slot-scope="scope">
                  <el-checkbox
                    v-model="scope.row.exchangePurchaseFlag == 1"
                  ></el-checkbox>
                </template>
              </el-table-column>

              <el-table-column
                :label="$t('label.refundedQuantity')"
                width="80"
                align="center"
                prop="refundQuantity"
              ></el-table-column>
              <el-table-column
                :label="$t('status')"
                width="80"
                align="center"
                prop="status"
              >
                <template slot-scope="scope">
                  {{ scope.row.status | statusFilter }}
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('label.signedForTheReturn')"
                width="80"
                align="center"
                prop="matchStatus"
              >
                <template slot-scope="scope">
                  <span v-if="scope.row.matchStatus == 'unmatch'">
                    {{ $t("label.notMatched") }}
                  </span>
                  <span
                    v-if="
                      scope.row.matchStatus == 'order_matched' ||
                        scope.row.matchStatus == 'matched'
                    "
                  >
                    {{ $t("label.matchedSuccess") }}
                  </span>
                  <span v-if="scope.row.matchStatus == null">
                    {{ $t("label.not") }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 多件多折折扣重算 -->
        <div class="box" v-has="'priceRule:list'">
          <div class="item_title">
            {{ $t("multipleDiscountInfo.multipleDiscountReCal") }}
          </div>
          <div>
            <el-table
              :key="tableKey"
              :data="returnPreviewDatas"
              row-key="id"
              stripe
              border
              fit
              highlight-current-row
            >
              <el-table-column type="index" width="40" />
              <el-table-column
                :label="$t('multipleDiscountInfo.OriginalDiscount')"
                align="center"
                prop="originTip"
              />
              <el-table-column
                :label="$t('multipleDiscountInfo.OriginalMoneny')"
                align="center"
                prop="originalOrderAmount"
              />
              <el-table-column
                :label="$t('multipleDiscountInfo.afterReturnDiscount')"
                align="center"
                prop="currentTip"
              />
              <el-table-column
                :label="$t('multipleDiscountInfo.afterReturnMoney')"
                align="center"
                prop="currentOrderAmount"
              />
              <el-table-column
                :label="$t('multipleDiscountInfo.returnMoney')"
                align="center"
                prop="refundAmount"
              >
                <template slot-scope="scope">
                  {{ scope.row.refundAmount || 0 }}
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('multipleDiscountInfo.needPayMoney')"
                align="center"
                prop="differenceAmount"
              >
                <template slot-scope="scope">
                  {{ scope.row.differenceAmount || 0 }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="box total_box">
          <div class="item_title">
            {{ $t("view.totalRefund") }}
          </div>
          <div class="item_box">
            {{ $t("view.totalRefund") }}：{{ addRefundForm.refundTotalAmount }}
          </div>
        </div>
        <div class="box btn_box">
          <el-button
            :style="btnStyle"
            class="save_btn"
            type="primary"
            @click="submit(this)"
            v-loading="btnLoading"
            >{{ $t("save") }}</el-button
          >
          <el-button type="danger" class="backbtn" @click="back">{{
            $t("back")
          }}</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// import {getRefundReason} from '@/api/oms/refund/refund'
import global from "@/views/oms/global";
import waves from "@/directive/waves";
import { getToken } from "@/utils/auth";
import { dcmSub } from "@/utils/toolUtil";
import {
  queryOrderDetailsByOrmorder,
  statusKeyValue
} from "@/api/oms/order/order";
import {
  validPromotionReq,
  warehouseList,
  checkSubmitRefund,
  backstageSubmitRefund,
  getDetailListByRefundId
} from "@/api/oms/refund/refund";
import { BigNumber } from "bignumber.js";
import tableEdit from "./tableEdit";

export default {
  name: "orderRefundNewDialog",
  props: ["params"],
  directives: {
    waves
  },
  components: {
    global,
    tableEdit
  },
  filters: {
    statusFilter(key) {
      return statusKeyValue[key];
    }
  },
  data() {
    return {
      matchStatus: null,
      listLoading: false,
      detailLoading: false,
      fromLoading: false,
      btnLoading: false,
      addressInfo: [],
      tableOrderDeatils: [],
      multipleSelection: [],
      returnPreviewDatas: [], // 勾选后，退款预览数据
      originReturnPreviewDatas: {}, //记录下来的，退款原来预览数据
      addRefundForm: {
        refundMethod: "system",
        refundAccountType: "PayPal",
        refundAccount: "",
        refundType: "",
        refundPostage: "0",
        refundAmount: 0.0, //商品退款金额
        differenceAmount: 0, // 补款金额
        refundPostageAmount: 0.0,
        warehouseCode: "",
        annexPath: "",
        items: [],
        quantity: 0,
        refundTaxAble: "0", //是否退税
        refundTaxAmount: 0.0, //退税金额
        refundTotalAmount: 0.0, //总计退款金额 = 商品退款金额 + 退运费金额 + 退税金额 。 实际执行时，refundAmount=商品退款金额 + 退税金额；退运费金额单独计算
        // refundReason:'', // 退款原因
        // otherReason:'', // 其他退款理由
        slUseable: "0", //是否开启ShippingLabel选项
        currency: "", //币种
        shipmodeId: "", //退货物流公司编号
        shippingNo: "", //退货物流单号
        notes: ""
      },
      afterSaleTypes: global.afterSaleType, //售后类型
      warehouseItems: [],
      queryRefundType: "",
      queryOrmorder: "",
      btnStyle: "",
      imageUrl: "",
      uploadPhotos: process.env.VUE_APP_OMS_API + "ordersRefund/uploadPhotos",
      reasonListAll: [],
      refundReasonAss: "",
      refundOtherReasonAss: "",
      otherReasonFlag: "",
      tableKey: Math.random(),
      isRefund: true //是否是退款 true:退款 false:补款
    };
  },
  created() {
    //情况清空数据
    this.getWarehouseList();
    this.getDetail();
  },
  computed: {
    // 计算属性的 getter
    headers: function() {
      return {
        "X-Token": getToken()
      };
    }
  },
  methods: {
    getDetail() {
      this.ShippingLabelOption();
      //初始化数据
      this.addRefundForm.refundAmount = 0.0;
      this.addRefundForm.differenceAmount = 0.0;
      this.addRefundForm.noTaxRefundAmount = 0.0;
      this.addRefundForm.noTaxDifferenceAmount = 0.0;
      this.addRefundForm.refundPostage = "0";
      this.addRefundForm.refundPostageAmount = 0.0;
      this.addRefundForm.warehouseCode = "";
      this.addRefundForm.annexPath = "";
      this.addRefundForm.items = [];
      this.addRefundForm.quantity = 0.0;
      this.addRefundForm.refundTaxAble = "0"; //是否退税
      this.addRefundForm.refundTaxAmount = 0.0; //退税金额
      this.addRefundForm.refundTotalAmount = 0.0;
      this.addRefundForm.shipmodeId = "";
      this.addRefundForm.shippingNo = "";
      this.addRefundForm.refundMethod = "system";
      this.addRefundForm.refundAccountType = "PayPal";
      this.addRefundForm.refundAccount = "";
      this.addRefundForm.notes = "";
      this.addressInfo = [];
      this.reasonListAll = [];
      this.refundReasonAss = "";
      this.refundOtherReasonAss = "";
      this.otherReasonFlag = "";

      //查询满足条件的所有订单项
      this.detailLoading = true;
      getDetailListByRefundId(this.params.id)
        .then(res => {
          if (200 == res.code) {
            //第一次查询的退款类型
            this.queryRefundType = res.data.refundType;
            this.queryOrmorder = res.data.ormorder;

            this.addRefundForm = res.data;
            this.addressInfo = res.data.addressList;
            this.reasonListAll = res.data.refundReasonList;
            this.selectIds = res.data.items.map(item => item.orderitemId);
            this.getOrders();
            let oldRefundTaxAmount = BigNumber(
              this.addRefundForm.refundTotalAmount
            )
              .plus(BigNumber(-this.addRefundForm.refundPostageAmount))
              .plus(BigNumber(-this.addRefundForm.refundAmount))
              .toFixed(2);

            if (oldRefundTaxAmount > 0) {
              this.$set(this.addRefundForm, "refundTaxAble", "1"); //是否退税
            } else {
              oldRefundTaxAmount = 0;
              this.$set(this.addRefundForm, "refundTaxAble", "0"); //是否退税
            }
            this.$set(
              this.addRefundForm,
              "refundTaxAmount",
              oldRefundTaxAmount
            ); //是否退税 this.addRefundForm.
          } else {
            this.$message.error(res.msg);
          }
        })
        .finally(() => {
          this.detailLoading = false;
        });
    },
    // 获取订单项
    getOrders() {
      this.listLoading = true;
      let _this = this;
      //查询订单详情
      let query = { ...this.params };
      queryOrderDetailsByOrmorder(query)
        .then(res => {
          if (res.code === 200) {
            let goodsRefundAmount = BigNumber(0);
            this.tableOrderDeatils = res.data;
            let details = [];
            this.refundReasonList = this.addRefundForm.refundReasonList;
            const selectDatas = this.addRefundForm.items;
            const multipleSelection = []; // 默认选中的列
            if (res.data) {
              details = res.data.map(row => {
                // 可用退款件数
                let quantity = 0;
                if (row.refundQuantity > 0) {
                  quantity = dcmSub(row.quantity, row.refundQuantity);
                } else {
                  quantity = row.quantity;
                }
                row.newQuantity = quantity;
                for (let ind2 in selectDatas) {
                  //明细属于当前退款单
                  row.refundReasonList = selectDatas[ind2].refundReasonList;
                  if (selectDatas[ind2].orderitemId === row.orderitemId) {
                    row.refundAmount = selectDatas[ind2].refundAmount;
                    row.newQuantity = selectDatas[ind2].quantity;
                    row.refundReason = String(selectDatas[ind2].refundReason);
                    row.customOpen = this.getCustopen(
                      row.refundReason,
                      selectDatas[ind2].refundReasonList
                    );
                    row.otherReason = selectDatas[ind2].otherReason;
                    row.refundReasonList = selectDatas[ind2].refundReasonList;
                    row.refundItemId = selectDatas[ind2].id;
                    goodsRefundAmount = goodsRefundAmount.plus(
                      BigNumber(selectDatas[ind2].refundAmount)
                    );
                    row.selectedRow = 1;
                    // 选中当前行
                    // _this.$nextTick(() => {
                    //   _this.$refs.multipleTable.toggleRowSelection(row, true);
                    // });

                    multipleSelection.push(row);
                  }
                }
                return row;
              });
              // 默认选中
              this.multipleSelection = multipleSelection;
              //退商品金额计算一下
              this.refundAmount = goodsRefundAmount.toFixed(2);
              this.tableOrderDeatils = details;
              this.$nextTick(() => {
                this.tableOrderDeatils.forEach(row => {
                  if (row.selectedRow == 1) {
                    this.$refs.multipleTable.toggleRowSelection(row, true);
                  }
                });
                this.reCalReturn(); // 获取折扣信息
              });
            }
          }
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    getCustopen(id, arr) {
      let customOpen = "";
      if (id) {
        arr.forEach(item => {
          if (item.id == id) {
            customOpen = item.custom;
          }
        });
      }
      return customOpen;
    },
    //获取退货仓库信息
    getWarehouseList() {
      warehouseList().then(res => {
        if (200 == res.code) {
          this.warehouseItems = res.data;
        }
      });
    },
    //计算退款总额 商品退款金额 + 退运费金额 +退税金额
    calculateRefundAmount() {
      //如果没选择退税 或者税费为空
      if (
        this.addRefundForm.refundTaxAble != "1" ||
        this.addRefundForm.refundTaxAmount === "NaN" ||
        !this.addRefundForm.refundTaxAmount
      ) {
        this.addRefundForm.refundTaxAmount = BigNumber(0)
          .toNumber()
          .toFixed(2);
      }
      //如果没选择退运费 或者运费为空
      if (
        this.addRefundForm.refundPostage != "1" ||
        !this.addRefundForm.refundPostageAmount ||
        this.addRefundForm.refundPostageAmount === "NaN"
      ) {
        this.addRefundForm.refundPostageAmount = BigNumber(0)
          .toNumber()
          .toFixed(2);
      }
      var taxAndShippingAmount = BigNumber(this.addRefundForm.refundTaxAmount)
        .plus(BigNumber(this.addRefundForm.refundPostageAmount))
        .toNumber()
        .toFixed(2);
      let price =
        this.addRefundForm.noTaxRefundAmount !== "NaN" &&
        this.addRefundForm.noTaxRefundAmount > 0
          ? BigNumber(this.addRefundForm.noTaxRefundAmount)
          : BigNumber(this.addRefundForm.noTaxDifferenceAmount).negated();
      this.addRefundForm.refundTotalAmount = BigNumber(taxAndShippingAmount)
        .plus(BigNumber(price))
        .toNumber()
        .toFixed(2);
    },
    // 重新计算退款的金额
    reCalReturn() {
      const formData = {
        ormOrderId: this.queryOrmorder,
        promotionRefundDetails: this.multipleSelection.map(item => ({
          soOrderId: item.ordersId,
          orderItemId: item.orderitemId,
          ormOrderItemId: item.ormOrderItemId,
          quantity: this.queryRefundType === 1 ? 0 : item.newQuantity
        }))
      };
      this.listLoading = true;
      checkSubmitRefund(formData)
        .then(res => {
          if (res.code === 200) {
            const { orderPreviewVO, ordersRefund } = res.data;
            const { isRefund, titleAmount } = orderPreviewVO;
            const refundAmount = isRefund ? titleAmount : 0;
            const differenceAmount = isRefund ? 0 : titleAmount;
            this.returnPreviewDatas = [
              { ...orderPreviewVO, refundAmount, differenceAmount }
            ];
            this.originReturnPreviewDatas = orderPreviewVO;
            this.isRefund = orderPreviewVO.isRefund;
            const totalPrice = this.multipleSelection.reduce((prev, cur) => {
              return prev + cur.totalFee;
            }, 0);
            for (let k in this.multipleSelection) {
              let row = this.multipleSelection[k];
              let data = ordersRefund.items.find(
                item => item.ormOrderItemId === row.ormOrderItemId
              );
              // 金额最大值
              row.maxAmount =
                this.queryRefundType !== "1" ? data.refundAmount : row.totalFee;
              if (orderPreviewVO.isRefund) {
                // 退款
                row.refundAmount = data.refundAmount;
                row.differenceAmount = 0;
              } else {
                // 补差价
                const val = this.calNeedPaidMoney(
                  k,
                  row,
                  orderPreviewVO.titleAmount,
                  totalPrice
                );
                row.originPaidAmount = val;
                row.differenceAmount = val;
                row.refundAmount = 0;
              }
              row.originRefundAmount = data.refundAmount;
            }
            this.jisuan();
          } else {
            this.$message.error(res.msg);
          }
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    // 计算补差价的金额
    calNeedPaidMoney(i, row, differenceAmount, totalPrice) {
      let data = 0;
      if (this.multipleSelection.length === 1) {
        data = differenceAmount;
      } else if (i === String(this.multipleSelection.length - 1)) {
        const price = this.multipleSelection.reduce((prev, cur) => {
          const amont = cur.differenceAmount || 0;
          return prev + amont;
        }, 0);
        // 最后一个的时候，需要用减法
        data = (differenceAmount - price).toFixed(2);
      } else {
        data = ((row.totalFee / totalPrice) * differenceAmount).toFixed(2);
      }
      return Number(data);
    },
    // 当前选中的 退款金额
    handleSelectionChange(val) {
      this.refundAmount = 0;
      this.differenceAmount = 0;
      this.multipleSelection = val;
      // 当数组没有变动时，不用重算
      // if (JSON.stringify(this.selectIds) === JSON.stringify(ids)) return false;
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        // 如果是退款新版本，包含多件多折 需要重算退款金额
        this.reCalReturn();
      } else {
        this.refundAmount = 0;
        this.addRefundForm.refundAmount = 0;
        this.addRefundForm.differenceAmount = 0;
        this.addRefundForm.noTaxRefundAmount = 0;
        this.addRefundForm.noTaxDifferenceAmount = 0;
        this.differenceAmount = 0;
        this.returnPreviewDatas = [];
        this.addRefundForm.refundTotalAmount = 0;
      }
    },
    refundAmountChange() {
      this.jisuan();
    },
    jisuan() {
      this.taxAndShippingAmount = BigNumber(this.addRefundForm.refundTaxAmount)
        .plus(BigNumber(this.addRefundForm.refundPostageAmount))
        .toNumber();

      let refundAmount = BigNumber(0); // 退款金额
      let differenceAmount = BigNumber(0); // 补款单金额
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        for (let uy in this.multipleSelection) {
          var row = this.multipleSelection[uy];
          refundAmount = refundAmount.plus(BigNumber(row.refundAmount));
          differenceAmount = differenceAmount.plus(
            BigNumber(row.differenceAmount)
          );
        }
        this.refundAmount = refundAmount.toNumber().toFixed(2);
        this.differenceAmount = differenceAmount.toNumber().toFixed(2);
      }
      this.$set(this.addRefundForm, "noTaxRefundAmount", this.refundAmount);
      this.$set(
        this.addRefundForm,
        "noTaxDifferenceAmount",
        this.differenceAmount
      );
      const refundNewAmount =
        this.refundAmount === "NaN" ? 0 : this.refundAmount;
      const differenceNewAmount =
        this.differenceAmount === "NaN" ? 0 : this.differenceAmount;
      this.returnPreviewDatas[0].refundAmount = refundNewAmount;
      this.returnPreviewDatas[0].differenceAmount = differenceNewAmount;

      let total = 0;
      let price =
        refundNewAmount > 0 ? refundAmount : differenceAmount.negated();
      // 退款
      total = price
        .plus(BigNumber(this.taxAndShippingAmount))
        .toNumber()
        .toFixed(2);
      this.$set(this.addRefundForm, "refundTotalAmount", total);
    },
    checkSelectable(row) {
      // 虚拟商品不可选
      if (row.skuCode === "BXGYPD250300") return false;
      if (row.refundQuantity > 0) {
        var refcount = dcmSub(row.quantity, row.refundQuantity);
        //发生退款
        if (refcount <= 0 && this.queryRefundType != "1") {
          return false; //不可选择
        }
        row["maxq"] = refcount;
      } else {
        row["maxq"] = row.quantity;
      }

      //未发货
      if (
        this.queryRefundType == "2" &&
        (row.status == "delivery" ||
          row.status == "off" ||
          row.status == "partdelivery")
      ) {
        return false; //不可选择
      }
      //退货退款
      else if (
        this.queryRefundType == "3" &&
        (row.status == "unchecked" ||
          row.status == "check" ||
          row.status == "undelivery")
      ) {
        return false; //不可选择
      }
      // 促销赠品
      // if (row.isGift === "1" && row.isPromotion === 1) {
      //   return false; //不可选择
      // }
      return true;
    },
    refundChange(id, arr) {
      if (id) {
        arr.refundReasonList.forEach(item => {
          if (item.id == id) {
            arr.customOpen = item.custom;
            if (arr.customOpen && arr.customOpen != 1) {
              arr.otherReason = "";
            }
          }
        });
      } else {
        arr.customOpen = "";
      }
    },
    writeReason(otherReason) {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        for (let uy in this.multipleSelection) {
          var row = this.multipleSelection[uy];
          if (row.customOpen == 1) {
            row.otherReason = otherReason;
          }
          ``;
        }
      }
    },
    chooseReason(id, arr) {
      if (id) {
        arr.forEach(item => {
          if (item.id == id) {
            this.otherReasonFlag = item.custom;
          }
        });
      } else {
        this.otherReasonFlag = "";
      }

      if (this.multipleSelection && this.multipleSelection.length > 0) {
        for (let uy in this.multipleSelection) {
          var row = this.multipleSelection[uy];
          row.refundReason = String(id);
          row.customOpen = this.otherReasonFlag;
          if (row.customOpen != 1) {
            row.otherReason = "";
          }
        }
      }
    },
    changeQuantity() {
      this.reCalReturn();
    },
    changePercentage(row) {
      //当前行的退款金额
      row.refundAmount = BigNumber(row.originRefundAmount)
        .div(BigNumber(row.quantity))
        .multipliedBy(BigNumber(row.newQuantity))
        .multipliedBy(BigNumber(row.refundSales))
        .toNumber()
        .toFixed(2);
      this.jisuan();
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.accessUrl;
      if (this.imageUrl) {
        this.addRefundForm.annexPath = this.imageUrl;
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    chooseClick(idList) {
      this.getDetail(idList);
    },
    //创建退款单
    submit() {
      if (this.multipleSelection.some(it => it.matchStatus == "unmatch")) {
        this.$message.error("已签收退货状态匹配错误，请匹配成功后重试!");
        return false;
      }

      var flag = false;
      var str = "";
      if (this.addressInfo.length != 1) {
        this.$message.error("请确保地址信息为1!");
        return false;
      }

      if (flag) {
        this.$message.error(str + ",请点击查询后继续此操作");
        return false;
      }

      //验证通过 保存逻辑
      this.addRefundForm.ormorder = this.queryOrmorder;
      this.addRefundForm.refundType = this.queryRefundType;
      //退货退款仓库验证
      if (
        this.addRefundForm.refundType == 3 &&
        !this.addRefundForm.warehouseCode
      ) {
        this.$message.error("请选择收退货仓库!");
        return false;
      }

      if (this.multipleSelection.length == 0) {
        this.$message.error("请选择要退的货品!");
        return false;
      }

      var items = [];
      this.$confirm(
        "退款总计：" + this.addRefundForm.refundTotalAmount + "，是否确认?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(async () => {
          for (let ind in this.multipleSelection) {
            var obj = this.multipleSelection[ind];
            if (!obj.refundReason) {
              this.$alert(obj.ordersId + ":请选择退款原因");
              return;
            }
            var newobj = {
              productName: obj.productName,
              quantity: this.queryRefundType === 1 ? 0 : obj.newQuantity,
              ormOrderItemId: obj.ormOrderItemId,
              orderitemId: obj.orderitemId,
              skuCode: obj.skuCode,
              refundAmount: obj.refundAmount,
              differenceAmount: obj.differenceAmount,
              refundReason: obj.refundReason,
              otherReason: obj.otherReason,
              soOrdersId: obj.ordersId,
              isGift: obj.isGift,
              isPromotion: obj.isPromotion
            };
            items.push(newobj);
          }
          this.addRefundForm.items = items;
          //这里默认客服发起
          this.addRefundForm.originatorFlag = 1;
          // 总金额, 正数为退款  负数为补款
          let val = Number(this.addRefundForm.refundTotalAmount);
          if (val < 0) {
            this.addRefundForm.differenceAmount = Math.abs(val);
            this.addRefundForm.refundAmount = 0;
          } else {
            this.addRefundForm.refundAmount = val;
            this.addRefundForm.differenceAmount = 0;
          }
          this.btnLoading = true;
          const saveRefund = () => {
            let query = {
              orderPreviewVO: this.originReturnPreviewDatas,
              ordersRefund: this.addRefundForm
            };
            backstageSubmitRefund(query)
              .then(res => {
                if (200 == res.code) {
                  this.$message({
                    message: this.$t("optSuccess"),
                    type: "success"
                  });
                  items = [];
                  this.btnStyle = "display:none";
                }
              })
              .finally(() => {
                this.btnLoading = false;
              });
          };
          const validPromotion = async () => {
            // 校验是否包含促销赠品，不包含直接返回true
            if (
              !this.tableOrderDeatils.some(
                item => item.isGift === "1" && item.isPromotion === 1
              )
            ) {
              return true;
            }
            // TODO 解开注释请求校验
            // 校验是否满足促销条件 满足返回true(不提示)
            const { code, data } = await validPromotionReq(this.addRefundForm);
            if (code === 200) {
              return data.valid;
            }
            return false;
          };
          // TODO 存在赠品的订单，在客服创建未发货退款售后单时，需判断扣除已退款明细之后是否还满足促销条件，若不满足，需弹窗提示客服，由客服判断是否继续执行退款。
          if (await validPromotion()) {
            saveRefund();
          } else {
            const res = await this.$confirm(
              "退款后订单将不满足促销条件，是否确认?",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }
            );
            if (res === "confirm") {
              saveRefund();
            }
          }
        })
        .catch(() => {
          this.btnLoading = false;
          this.$message({
            type: "info",
            message: "已取消操作"
          });
        });
    },
    //TODO 暂时关闭SL
    ShippingLabelOption() {
      this.addRefundForm.slUseable = "0";

      if (
        this.refundType == 3 &&
        this.queryRefundType == 3 &&
        this.addressInfo &&
        this.addressInfo.length > 0 &&
        this.addressInfo[0].receiverCountryCode == "US" &&
        (this.addRefundForm.warehouseCode == "PSJ-H0000024" ||
          this.addRefundForm.warehouseCode == "PSJ-H0000019" ||
          this.addRefundForm.warehouseCode == "PSJ-H0000011" ||
          this.addRefundForm.warehouseCode == "PSJ-G001001" ||
          this.addRefundForm.warehouseCode == "PSJ-G001003" ||
          this.addRefundForm.warehouseCode == "PSJ-G001004")
      ) {
        this.addRefundForm.slUseable = "1";
      } else {
        this.addRefundForm.slUseable = "0";
      }
    },
    changeSlradio() {
      if (this.addRefundForm.slUseable == "0") {
        this.addRefundForm.shipmodeId = "";
        this.addRefundForm.shippingNo = "";
      }
    },
    back() {
      this.$emit("back");
    }
  }
};
</script>

<style lang="scss" scoped>
.head {
  padding: 0px 20px;
  display: flex;
  justify-content: space-between;
  span:nth-child(1) {
    font-size: 15px;
    line-height: 25px;
    color: #909399;
    font-weight: 600;
  }
  span:nth-child(2) {
    line-height: 25px;
    cursor: pointer;
    color: #ae8878;
    font-size: 13px;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 82px;
  height: 82px;
  line-height: 82px;
  text-align: center;
  border-radius: 3px;
  border: 1px solid #dcdfe6;
  margin-left: 49px;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.dialog_container {
  position: relative;
}
.main {
  margin-top: 15px;
  .box {
    .item_title {
      color: #606266;
      font-size: 16px !important;
      line-height: 16px;
      position: relative;
      padding-left: 8px !important;
      &:before {
        position: absolute;
        left: 0px;
        top: 13px;
        content: "";
        display: inline-block;
        width: 3px;
        height: 13px;
        background: #ae8877;
        border-radius: 0px 0px 0px 0px;
      }
    }
    .box_item {
      padding: 0 20px;
      display: flex;
      .item_title {
        line-height: 40px;
        font-size: 18px;
        text-align: left;
        font-weight: 600;
      }
      .item_list {
        text-align: left;
        font-size: 14px;
        color: #606266;
        display: flex;
        p {
          margin: 10px 0;
        }
        div:nth-child(2) {
          margin-left: 30px;
        }
      }
    }
    .item_title {
      padding-left: 20px;
      line-height: 40px;
      font-size: 18px;
      text-align: left;
      font-weight: 600;
    }
  }
}

.ptitle {
  display: flex;
  justify-content: space-between;
  margin: 20px 0px;
  color: #1f2d3d;
  text-align: left;
  font-weight: bold;
  width: 100%;
  /deep/.el-descriptions__title {
    color: #606266;
  }
}
.filter-container {
  .filter-item {
    margin-right: 11px;
  }
}
.container {
  display: flex; /* 使用 Flexbox 布局 */
  justify-content: space-between; /* 将盒子平均分布在容器中 */
}
.row {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  /deep/.el-form-item {
    display: flex;
  }
  .inputleft {
    margin-right: 30px;
    margin-left: 30px;
  }
  .row-item {
    margin-right: 10vw;
    &:last-child {
      margin-right: 0px;
    }
  }
  .afertextarea {
    width: 306px;
  }
}
.el-table {
  font-size: 12px;
  margin: 20px 0px;
}
.itemtable {
  /deep/.has-gutter {
    .el-table__cell {
      background: #f5f0ee;
      padding: 0px;
    }
  }
}
.total_box {
  margin-bottom: 20px;
  .item_box {
    margin-top: 15px;
  }
}
.btn_box {
  position: absolute;
  right: 0px;
  bottom: -24px;
  .el-button {
    padding: 10px 37px;
  }
}
</style>
