<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        :placeholder="$t('place.afterSalesType')"
        clearable
        style="width: 200px;"
        class="filter-item"
        v-model="listQuery.refundType"
        @change="queryRefundReason"
      >
        <el-option
          v-for="afterSaleType in afterSaleTypes"
          :key="afterSaleType.value"
          :label="$t(afterSaleType.label)"
          :value="afterSaleType.value"
        >
        </el-option>
      </el-select>
      <el-select
        :placeholder="$t('place.afterSalesStatus')"
        clearable
        style="width: 200px;"
        class="filter-item"
        v-model="listQuery.status"
      >
        <el-option
          v-for="status in afterSaleStatus"
          :key="status.value"
          :label="$t(status.label)"
          :value="status.value"
        >
        </el-option>
      </el-select>

      <el-select
        v-model="listQuery.exchangeFlag"
        :clearable="true"
        class="filter-item"
        style="width: 200px;"
        :placeholder="$t('exchangeFlag')"
      >
        <el-option key="1" :label="$t('label.yes')" value="1"></el-option>
        <el-option key="0" :label="$t('label.no')" value="0"></el-option>
      </el-select>

      <el-select
        v-model="listQuery.channelCode"
        :clearable="true"
        filterable
        class="filter-item"
        style="width: 200px;"
        :placeholder="$t('place.channel')"
        @change="getStore"
      >
        <el-option
          v-for="item in channel"
          :key="item.code"
          :label="item.name"
          :value="item.code"
        >
        </el-option>
      </el-select>
      <el-select
        v-model="listQuery.storeId"
        :clearable="true"
        filterable
        class="filter-item"
        style="width: 200px;"
        :placeholder="$t('place.shopName')"
        @change="getChannel"
      >
        <el-option
          v-for="item in store"
          :key="item.storeId"
          :label="item.storeName"
          :value="item.storeId"
        >
        </el-option>
      </el-select>
      <el-input
        :placeholder="$t('place.refundNumber')"
        clearable
        style="width: 200px;"
        class="filter-item"
        v-model="listQuery.refundNo"
      />
      <el-input
        :placeholder="$t('place.onlineRefundNumber')"
        clearable
        style="width: 200px;"
        class="filter-item"
        v-model="listQuery.ormRefundId"
      />
      <el-input
        :placeholder="$t('place.shopifyNumber')"
        clearable
        style="width: 200px;"
        class="filter-item"
        v-model="listQuery.shopify"
      />

      <el-input
        :placeholder="$t('place.onlineShopNumber')"
        clearable
        style="width: 200px;"
        class="filter-item"
        v-model="listQuery.ormorder"
      />

      <el-select
        :placeholder="$t('place.afterSalesInitiator')"
        clearable
        style="width: 200px;"
        class="filter-item"
        v-model="listQuery.originatorFlag"
      >
        <el-option
          value="1"
          :label="$t('label.customerService')"
          key="1"
        ></el-option>
        <el-option value="2" :label="$t('label.buyer')" key="2"></el-option>
      </el-select>

      <el-date-picker
        class="filter-item"
        style="display: inline-flex;"
        v-model="createTimePicker"
        type="datetimerange"
        :range-separator="$t('to')"
        :start-placeholder="$t('place.refundCreationStart')"
        :end-placeholder="$t('place.refundCreationEnd')"
        value-format="yyyy-MM-dd HH:mm:ss"
        :default-time="['00:00:00', '23:59:59']"
      >
      </el-date-picker>

      <el-select
        :placeholder="$t('place.refundMethod')"
        clearable
        style="width: 200px;"
        class="filter-item"
        v-model="listQuery.refundMethod"
      >
        <el-option
          value="system"
          :label="$t('label.systemRefund')"
          key="system"
        ></el-option>
        <el-option
          value="manual"
          :label="$t('label.manualRefund')"
          key="manual"
        ></el-option>
      </el-select>

      <el-input
        :placeholder="$t('place.refundAccount')"
        clearable
        style="width: 200px;"
        class="filter-item"
        v-model="listQuery.refundAccount"
      />

      <el-select
        v-model="refundReasonList"
        :clearable="true"
        class="filter-item"
        style="width: 200px;"
        :placeholder="$t('place.refundReason')"
        multiple
        filterable
        @change="queryRefundType"
      >
        <el-option
          v-for="item in this.refundReason"
          :key="item.reasonContentChinese"
          :label="item.reasonContentChinese"
          :value="item.reasonContentChinese"
        >
        </el-option>
      </el-select>

      <el-select
        v-model="listQuery.sendEmailFlag"
        :clearable="true"
        class="filter-item"
        style="width: 200px;"
        placeholder="是否成功发送邮件"
      >
        <el-option key="1" :label="$t('label.yes')" value="1"></el-option>
        <el-option key="0" :label="$t('label.no')" value="0"></el-option>
      </el-select>
      <el-select
        :placeholder="$t('place.signInStatus')"
        clearable
        style="width: 200px;"
        class="filter-item"
        v-model="listQuery.signInStatus"
      >
        <el-option
          v-for="re in signInStatus"
          :key="re.value"
          :label="re.label"
          :value="re.value"
        >
        </el-option>
      </el-select>
    </div>
    <div class="filter-container">
      <!--<el-input placeholder="收件人电话" style="width: 200px;"
          class="filter-item"	v-model="listQuery.receiverMobile"/>-->

      <el-button
        v-waves
        class="filter-item"
        type="success"
        icon="el-icon-search"
        @click="handleFilter"
        >{{ $t("view.search") }}</el-button
      >
      <el-button class="filter-item" @click="exportExcel" type="primary">
        {{ $t("exportRep") }}
      </el-button>
      <!-- <el-button v-waves class="filter-item" type="primary" icon="el-icon-upload"
                 @click="dialogFormUploadVisible = true">{{ $t("view.importData") }}
      </el-button> -->
      <el-button v-waves class="filter-item" type="warning" @click="batchCheck"
        >{{ $t("view.batchAudit") }}
      </el-button>

      <!--新创建退款单  -->
      <el-button
        v-waves
        class="filter-item"
        type="success"
        @click="createNewRefund"
        >{{ $t("view.createRefundOrder") }}
      </el-button>
    </div>

    <!--<div class="filter-container">
      <el-button v-waves class="filter-item" type="primary" @click="orderExport('orderItem')">退款明细导出</el-button>
    </div>-->

    <el-table
      style="width: 100%;"
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      row-key="id"
      stripe
      border
      fit
      highlight-current-row
      :cell-style="tableRowStyleName"
      tooltip-effect="dark"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        align="center"
        type="selection"
        :selectable="selectEnable"
      >
      </el-table-column>
      <el-table-column align="center" type="index"> </el-table-column>
      <el-table-column
        :label="$t('label.refundNumber')"
        width="200"
        align="center"
        prop="refundNo"
      >
      </el-table-column>

      <el-table-column
        :label="$t('label.onlineRefundNumber')"
        width="250"
        align="center"
        prop="ormRefundId"
      >
      </el-table-column>
      <el-table-column
        :label="$t('label.shopifyNumber')"
        width="200"
        align="center"
        prop="cutUser"
      >
      </el-table-column>
      <el-table-column
        :label="$t('label.onlineShopOrder')"
        width="150"
        align="center"
        prop="ormorder"
      >
      </el-table-column>
      <el-table-column
        :label="$t('storeName')"
        align="center"
        min-width="180"
        prop="storeName"
      ></el-table-column>
      <el-table-column
        :label="$t('label.afterSalesType')"
        width="100"
        align="center"
        prop="refundType"
      >
        <template slot-scope="scope">
          {{ scope.row.refundType | refundTypeFilter(that) }}
        </template>
      </el-table-column>

      <!-- <el-table-column :label="$t('label.exchangeGoods')" prop="exchangeFlag" width = "100" >
        <template slot-scope="scope" >
          {{scope.row.exchangeFlag==="1"?'是':'否'}}
        </template>
      </el-table-column> -->

      <el-table-column
        :label="$t('label.afterSalesInitiation')"
        width="110"
        align="center"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.originatorFlag == '1'">
            {{ $t("label.customerService") }}
          </div>
          <div v-if="scope.row.originatorFlag == '2'">
            {{ $t("label.buyer") }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('label.afterSalesStatus')"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag effect="dark" type="warning" v-if="scope.row.status == '4'">
            {{ scope.row.status | statusFilter(that) }}
          </el-tag>
          <el-tag effect="dark" type="info" v-else-if="scope.row.status == '7'">
            {{ scope.row.status | statusFilter(that) }}
          </el-tag>
          <el-tag effect="dark" type="success" v-else>
            {{ scope.row.status | statusFilter(that) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="自动退款"
        align="center"
        prop="autoRefund"
        width="120"
      >
        <template slot-scope="scope">
          {{ scope.row.autoRefund === "1" ? $t("label.yes") : $t("label.no") }}
        </template>
      </el-table-column>

      <el-table-column
        label="是否成功发送邮件"
        align="center"
        prop="sendEmailFlag"
        width="140"
      >
        <template slot-scope="scope">
          {{
            scope.row.sendEmailFlag === "1" ? $t("label.yes") : $t("label.no")
          }}
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('label.applicationTime')"
        width="160"
        align="center"
        prop="timeplaced"
      >
      </el-table-column>
      <el-table-column
        label="财务审核通过时间"
        width="160"
        align="center"
        prop="financialApprovalTime"
      >
      </el-table-column>
      <el-table-column
        :label="$t('label.applicant')"
        width="120"
        align="center"
        prop="userName"
      >
      </el-table-column>
      <el-table-column
        :label="$t('label.refundAmount')"
        width="100"
        align="center"
        prop="refundAmount"
      >
      </el-table-column>
      <el-table-column
        :label="$t('label.shippingRefund')"
        width="100"
        align="center"
        prop="refundPostageAmount"
      >
      </el-table-column>
      <el-table-column
        :label="$t('label.currency')"
        width="100"
        align="center"
        prop="currency"
      >
      </el-table-column>
      <!-- <el-table-column label="退款原因(中文)" width="150" align="center" prop="reasonContentChinese">
      </el-table-column> -->
      <!-- <el-table-column label="退款原因(English)" width="150" align="center" prop="reasonContentEnglish">
      </el-table-column> -->
      <!-- <el-table-column label="其他原因说明" width="100" align="center" prop="otherReason">
      </el-table-column> -->
      <el-table-column
        :label="$t('label.serviceNote')"
        width="150"
        align="center"
        prop="notes"
      >
      </el-table-column>
      <el-table-column
        :label="$t('label.buyerReasonNote')"
        width="150"
        align="center"
        prop="buyNotes"
      >
      </el-table-column>
      <el-table-column
        :label="$t('label.refundMethod')"
        width="150"
        align="center"
        prop="refundMethod"
      >
        <template slot-scope="scope">
          {{ scope.row.refundMethod | refundMethodFilter(that) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('label.accountType')"
        width="150"
        align="center"
        prop="refundAccountType"
      >
        <template slot-scope="scope">
          {{ scope.row.refundAccountType | refundAccountTypeFilter(that) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('label.refundAccount')"
        width="150"
        align="center"
        prop="refundAccount"
      >
      </el-table-column>

      <el-table-column
        :label="$t('label.channelID')"
        width="120"
        align="center"
        prop="channelCode"
      >
      </el-table-column>
      <el-table-column
        :label="$t('label.channelName')"
        width="140"
        align="center"
        prop="channelName"
      >
      </el-table-column>
      <el-table-column
        :label="$t('label.updateTime')"
        width="160"
        align="center"
        prop="lastupdate"
      >
      </el-table-column>
      <el-table-column
        :label="$t('label.updater')"
        width="120"
        align="center"
        prop="lastUserName"
      >
      </el-table-column>
      <el-table-column
        :label="$t('label.operation')"
        fixed="right"
        min-width="360"
        align="left"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleInfo(scope.row.id, 'view')"
            >{{ $t("view.details") }}</el-button
          >
          <el-button
            v-has="'ordersRefund:checkKf'"
            v-if="
              scope.row.refundType == '3' &&
                (scope.row.status == '0' || scope.row.status == '4')
            "
            type="success"
            size="mini"
            @click="editInfo(scope.row)"
            >{{ $t("view.logistics") }}
          </el-button>
          <el-button
            v-has="'ordersRefund:checkKf'"
            v-if="scope.row.status == '0'"
            type="success"
            size="mini"
            @click="handleInfo(scope.row.id, 'cus_check')"
            >{{ $t("view.audit") }}
          </el-button>
          <el-button
            v-has="'ordersRefund:checkKf'"
            v-if="
              scope.row.status == '0' ||
                (scope.row.status == '2' && scope.row.channelCode == 'SHOPIFY')
            "
            type="success"
            size="mini"
            @click="handleRefund(scope.row.id)"
            >{{ $t("view.edit") }}
          </el-button>
          <el-button
            v-has="'ordersRefund:checkKf'"
            v-if="scope.row.status == '7'"
            type="success"
            size="mini"
            @click="createRefund(scope.row.id)"
            >{{ $t("view.create") }}
          </el-button>
          <!--          <el-button-->
          <!--            v-has="'ordersRefund:checkKf'"-->
          <!--            v-if="scope.row.status == '1'"-->
          <!--            size="mini"-->
          <!--            type="danger"-->
          <!--            @click="reject(scope.row.id, scope.row.refundNo)"-->
          <!--            >{{ $t("view.reject") }}-->
          <!--          </el-button>-->
          <el-button
            v-has="'ordersRefund:checkKf'"
            v-if="scope.row.status == '1'"
            size="mini"
            type="danger"
            @click="reject(scope.row.id, scope.row.refundNo)"
            >{{ $t("view.unaudit") }}
          </el-button>
          <el-button
            v-has="'ordersRefund:checkKf'"
            v-if="scope.row.status == '1'"
            size="mini"
            type="warning"
            @click="handleAddNote(scope.row)"
            >{{ $t("view.modifyRemarks") }}
          </el-button>
          <el-button
            v-has="'ordersRefund:checkKf'"
            v-if="scope.row.status == '6'"
            size="mini"
            type="success"
            @click="handleSuccess(scope.row)"
            >{{ $t("view.refundSuccess") }}
          </el-button>
          <!--          <el-button v-has="'ordersRefund:checkKf'" v-if="scope.row.abnormalFlag=='1' "  size="mini"-->
          <!--                     type="success" @click="releaseEx(scope.row)">解除异常-->
          <!--          </el-button>-->
          <!--
                    <el-button v-has="'ordersRefund:checkCw'" v-if="scope.row.status=='5' " type="success" size="mini" @click="handleInfo(scope.row.id,'f_check')">财务审核</el-button>
          -->
          <!--          在在客服审批通过环节客服也可以操作取消-->
          <el-button
            v-if="
              scope.row.status == '0' ||
                scope.row.status == '4' ||
                scope.row.status == '1' ||
                scope.row.status == '2'
            "
            type="danger"
            size="mini"
            @click="cancelInfo(scope.row)"
            >{{ $t("view.cancel") }}
          </el-button>
          <el-button
            v-if="scope.row.slFlag == '1'"
            size="mini"
            type="primary"
            @click="handleCargoTrack(scope.row)"
            >{{ $t("view.cargoTrack") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <swPage
      v-if="total > 0"
      key="2"
      :listQuery="listQuery"
      :total="total"
      pos="btmRight"
      @retPage="retPage"
    />
    <!-- 售后详情-->
    <el-drawer
      :title="$t('title.afterSalesDetails')"
      :visible.sync="refundInfoVisible"
      v-if="refundInfoVisible"
      :direction="direction"
      :size="dialogSize"
    >
      <refundInfoDialog
        @refresh="refresh"
        :refundId="currentRefundId"
        :action="action"
      ></refundInfoDialog>
    </el-drawer>

    <el-dialog
      :title="$t('title.returnLogisticsInfo')"
      :visible.sync="dialogShippFormVisible"
      v-if="dialogShippFormVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="editShipp">
        <el-form-item :label="$t('label.returnWarehouse')" label-width="150px">
          <el-select
            :placeholder="$t('place.pleaseSelect')"
            clearable
            style="width: 200px;"
            class="filter-item"
            v-model="editShipp.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
          :label="$t('label.useSL')"
          label-width="150px"
          v-if="editShipp.slUseable == '1'"
        >
          <el-radio-group v-model="slFlag" @input="changeSL">
            <el-radio label="0">{{ $t("view.notUsed") }}</el-radio>
            <el-radio label="1">{{ $t("view.use") }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          :label="$t('label.returnLogisticsCompany')"
          label-width="150px"
        >
          <el-input
            v-if="slFlag == '0'"
            size="mini"
            v-model="editShipp.shipmodeId"
            :placeholder="$t('place.pleaseFillIn')"
            class="normal-input"
          ></el-input>
          <el-input
            v-if="slFlag == '1'"
            size="mini"
            v-model="editShipp.shipmodeId"
            :placeholder="$t('place.pleaseFillIn')"
            class="normal-input"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('label.returnExpressNumber')"
          label-width="150px"
        >
          <el-input
            v-if="slFlag == '0'"
            size="mini"
            v-model="editShipp.shippingNo"
            :placeholder="$t('place.pleaseFillIn')"
            class="normal-input"
          ></el-input>
          <el-input
            v-if="slFlag == '1'"
            size="mini"
            v-model="editShipp.shippingNo"
            :placeholder="$t('place.pleaseFillIn')"
            class="normal-input"
            disabled
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShippFormVisible = false">{{
          $t("view.cancel")
        }}</el-button>
        <!--        <el-button-->
        <!--          type="primary"-->
        <!--          @click="editShippSub(1)"-->
        <!--          v-loading="btnLoading"-->
        <!--          >{{ $t("view.save") }}</el-button-->
        <!--        >-->
        <el-button
          type="primary"
          @click="editShippSub('')"
          v-loading="btnLoading"
          >{{ $t("view.confirm") }}</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :title="$t('title.nullify')"
      :visible.sync="dialogFormCancelVisible"
      v-if="dialogFormCancelVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="cancelForm">
        <el-form-item :label="$t('label.cancellationNote')" label-width="120px">
          <el-input
            type="textarea"
            :placeholder="$t('place.enterContent')"
            v-model="cancelForm.zfnotes"
            maxlength="150"
            show-word-limit
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormCancelVisible = false">{{
          $t("view.cancel")
        }}</el-button>
        <el-button
          type="primary"
          @click="cancelSubmit"
          v-loading="btnLoading"
          >{{ $t("view.confirm") }}</el-button
        >
      </div>
    </el-dialog>
    <!--售后-->
    <el-dialog
      :title="$t('orderRefund')"
      :fullscreen="true"
      v-if="orderRefundVisible"
      :visible.sync="orderRefundVisible"
    >
      <orderRefundDialog :refundId="currentRefundId"></orderRefundDialog>
      <el-button type="danger" style="float:right" @click="backTable">{{
        $t("back")
      }}</el-button>
    </el-dialog>

    <el-dialog
      :title="$t('orderRefund')"
      :fullscreen="true"
      v-if="orderRefundNewVisible"
      :visible.sync="orderRefundNewVisible"
    >
      <orderRefundNewDialog :refundId="currentRefundId"></orderRefundNewDialog>
      <el-button type="danger" style="float:right" @click="backTable">{{
        $t("back")
      }}</el-button>
    </el-dialog>

    <el-dialog
      :title="$t('title.createRefundOrder')"
      :fullscreen="true"
      v-if="createRefundVisible"
      :visible.sync="createRefundVisible"
    >
      <createRefundDialog></createRefundDialog>
      <el-button type="danger" style="float:right" @click="backTable">{{
        $t("back")
      }}</el-button>
    </el-dialog>

    <el-dialog
      :title="$t('title.importRefund')"
      :visible.sync="dialogFormUploadVisible"
      width="38%"
      :destroy-on-close="destroyOnClose"
    >
      <el-form>
        <el-form-item :label="$t('label.exportTemplate')">
          <el-button class="filter-item" @click="downloadMould" type="primary">
            {{ $t("exportTemplate") }}
          </el-button>
        </el-form-item>

        <el-form-item :label="$t('label.importData')">
          <el-upload
            ref="upload"
            :limit="2"
            accept=".xlsx"
            :headers="headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              {{ $t("view.uploadFile") }}<em>{{ $t("view.clickUp") }}</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              {{ $t("view.xlsxFormatOnly") }}
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormUploadVisible = false">{{
          $t("view.cancel")
        }}</el-button>
        <el-button type="primary" @click="submitUploadList">{{
          $t("view.confirm")
        }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="$t('addNote')"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :visible.sync="addNoteVisible"
      width="40%"
      v-loading="listLoading"
    >
      <el-form ref="addNoteForm" :model="addNoteForm" label-width="auto">
        <el-form-item :label="$t('label.refundNumber')" prop="orderRefundId">
          <el-input
            disabled
            v-model="addNoteForm.orderRefundId"
            placeholder
            class="normal-input"
            style="width: 400px"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('label.serviceNote')" prop="note">
          <el-input
            type="textarea"
            v-model="addNoteForm.note"
            :placeholder="$t('setOrderNote')"
            class="normal-input"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">{{ $t("save") }}</el-button>
          <el-button type="danger" @click="addNoteVisible = false">{{
            $t("back")
          }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      :title="$t('cargoTrack')"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :visible.sync="cargoTrackVisible"
      width="40%"
      v-loading="listLoading"
    >
      <cargoTrackDialog :refundNo="selectedRefundNo"></cargoTrackDialog>
    </el-dialog>
  </div>
</template>

<script>
import waves from "@/directive/waves";
import swPage from "@/views/common/swPage";
import global from "@/views/oms/global";
import refundInfoDialog from "./refundDetail";
import { getToken } from "@/utils/auth";
import {
  fetchList,
  updateshipping,
  cancel,
  warehouseList,
  rejectRefund,
  addNote,
  manualRefundSuccess,
  batchReview,
  getRefundType,
  getRefundReason,
  verifyExport
} from "@/api/oms/refund/refund";
import { dcmAdd } from "@/utils/toolUtil";
import { fetchList as orderFetchList } from "@/api/oms/order/order";
import orderRefundDialog from "@/views/oms/refund-old/components/orderRefundDialog";
import orderRefundNewDialog from "@/views/oms/refund-old/components/orderRefundNewDialog";
import createRefundDialog from "@/views/oms/refund-old/components/createRefundDialog";
import cargoTrackDialog from "@/views/oms/refund-old/components/cargoTrackDialog";
import log from "@/router/modules/log";
import { queryChannelStore, queryChannel } from "@/api/oms/inventory/inventory";
const refundMethodOptions = [
  { key: "system", display_name: "view.systemRefund" },
  { key: "manual", display_name: "view.manualRefund" }
];
const refundMethodKeyValue = refundMethodOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

const refundAccountTypeOptions = [
  { key: "PayPal", display_name: "PayPal" },
  { key: "bankCard", display_name: "view.bankCard" },
  { key: "other", display_name: "view.other" }
];
const refundAccountTypeKeyValue = refundAccountTypeOptions.reduce(
  (acc, cur) => {
    acc[cur.key] = cur.display_name;
    return acc;
  },
  {}
);

export default {
  name: "refundList",
  directives: {
    waves
  },
  components: {
    swPage,
    refundInfoDialog,
    global,
    orderRefundDialog,
    orderRefundNewDialog,
    createRefundDialog,
    cargoTrackDialog
  },
  filters: {
    refundAccountTypeFilter(key, that) {
      return that.$t(refundAccountTypeKeyValue[key]);
    },
    refundMethodFilter(key, that) {
      return that.$t(refundMethodKeyValue[key]);
    },
    statusFilter(key, that) {
      var value = "";
      global.afterSaleStatus.forEach(status => {
        if (status.value == key) {
          value = that.$t(status.label);
        }
      });
      return value;
    },
    refundTypeFilter(key, that) {
      var value = "";
      global.afterSaleType.forEach(refundType => {
        if (refundType.value == key) {
          value = that.$t(refundType.label);
        }
      });
      return value;
    }
  },
  data() {
    return {
      that: this,
      dialogSize: "40%",
      direction: "rtl",
      fileList: [],
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: false,
      destroyOnClose: true,
      addNoteForm: {
        id: null,
        orderRefundId: "",
        note: ""
      },
      addNoteVisible: false,
      channel: [],
      store: [],
      //查询条件
      listQuery: {
        page: 1,
        limit: 10,
        storeId: "",
        channelCode: "",
        refundType: "",
        reasonContentChinese: "",
        shopify: "",
        status: "",
        exchangeFlag: "",
        ordersNo: "",
        ormRefundId: "",
        ormorder: "",
        originatorFlag: "",
        refundNo: "",
        timeplacedLaggerThanEqual: null,
        timeplacedLessThanEqual: null,
        sendEmailFlag: "",
        signInStatus: null
      },
      dialogFormUploadVisible: false,
      formLabelWidth: "120px",
      createTimePicker: null,
      multipleSelection: [],
      selectionList: [],
      channelCodes: global.channelCodes, //渠道编码
      afterSaleStatus: global.afterSaleStatus, //售后状态
      afterSaleTypes: global.afterSaleType, //售后类型
      applyTypes: global.applyType, //售后来源
      signInStatus: global.signInStatusType,
      refundReason: [],
      refundReasonList: [],
      stores: [],
      refundInfoVisible: false,
      currentRefundId: "",
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        // 上传的地址（后台接口）
        url: process.env.VUE_APP_OMS_API + "/ordersRefund/uploadExcel"
      },
      editShipp: {
        id: null,
        shipmodeId: "",
        shippingNo: "",
        warehouseCode: "",
        slUseable: "",
        slFlag: ""
      },
      dialogShippFormVisible: false,
      dialogFormCancelVisible: false,
      cancelForm: {
        refundNo: "",
        zfnotes: ""
      },
      baseURL: process.env.VUE_APP_OMS_API,
      warehouseItems: [],
      btnLoading: false,
      orderRefundVisible: false,
      orderRefundNewVisible: false,
      createRefundVisible: false,
      currentOrdersId: "",
      action: "", //  view  cus_check  t_check
      slFlag: "0",
      staging: {
        shipmodeId: "",
        shippingNo: ""
      },
      cargoTrackVisible: false,
      selectedRefundNo: ""
    };
  },
  created() {
    //获取店铺列表
    this.getStores();
    this.getList();
    this.getChannel();
    this.getStore();
    this.queryRefundReason();
  },
  activated() {
    this.getList();
  },
  computed: {
    // 计算属性的 getter
    headers: function() {
      return {
        "X-Token": getToken()
      };
    }
  },
  methods: {
    handleCargoTrack(e) {
      this.cargoTrackVisible = true;
      this.selectedRefundNo = e.refundNo;
    },
    handleSuccess(e) {
      this.$confirm("确认退款成功吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          var params = { id: e.id };

          manualRefundSuccess(params).then(res => {
            if (200 == res.code) {
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.getList();
            }
          });
        })
        .catch(() => {});
    },
    //获取stores
    getStores() {},

    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then(res => {
        if (200 == res.code) {
          this.total = res.data.total;
          this.list = res.data.list;
        }
        this.listLoading = false;
      });
    },
    retPage() {
      //分页
      this.getList();
    },
    getChannel() {
      queryChannel({ storeId: this.listQuery.storeId }).then(res => {
        if (200 == res.code) {
          this.channel = res.data;
        }
      });
    },
    getStore() {
      queryChannelStore({ channelCode: this.listQuery.channelCode }).then(
        res => {
          if (200 == res.code) {
            this.store = res.data;
          }
        }
      );
    },
    submitUploadList() {
      this.$refs.upload.submit();
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    //文件上传成功返回
    handleFileSuccess(response, file, fileList) {
      if (file.response.code === 200) {
        this.$message({
          message: "导入成功",
          type: "success"
        });
        this.dialogFormUploadVisible = false;
      } else {
        this.$message.error(file.response.msg + ",请重新上传");
        //删除上传列表中，失败的文件
        let index = 0;
        for (const i in fileList) {
          if (fileList[i] == file) {
            index = i;
            break;
          }
        }
        //移出当前文件对象
        fileList.splice(index, 1);
      }
      this.upload.open = false;
      this.upload.isUploading = false;
    },
    //导出模板
    downloadMould() {
      var url = this.baseURL + "ordersRefund/downloadMould";
      window.location.href = url;
    },
    handleFilter() {
      this.listQuery.page = 1;
      if (this.createTimePicker == null) {
        this.listQuery.timeplacedLaggerThanEqual = "";
        this.listQuery.timeplacedLessThanEqual = "";
      } else {
        this.listQuery.timeplacedLaggerThanEqual = this.createTimePicker[0];
        this.listQuery.timeplacedLessThanEqual = this.createTimePicker[1];
      }
      this.getList();
    },

    exportExcel() {
      this.listQuery.page = 1;
      this.listLoading = true;
      if (this.createTimePicker == null) {
        this.listQuery.timeplacedLaggerThanEqual = "";
        this.listQuery.timeplacedLessThanEqual = "";
      } else {
        this.listQuery.timeplacedLaggerThanEqual = this.createTimePicker[0];
        this.listQuery.timeplacedLessThanEqual = this.createTimePicker[1];
      }

      verifyExport(this.listQuery)
        .then(res => {
          if (200 == res.code) {
            var url =
              this.baseURL +
              "ordersRefund/export?storeId=" +
              this.listQuery.storeId +
              "&refundType=" +
              this.listQuery.refundType +
              "&status=" +
              this.listQuery.status +
              "&ormRefundId=" +
              this.listQuery.ormRefundId +
              "&ormorder=" +
              this.listQuery.ormorder +
              "&refundNo=" +
              this.listQuery.refundNo +
              "&channelCode=" +
              this.listQuery.channelCode +
              "&shopify=" +
              encodeURIComponent(this.listQuery.shopify) +
              "&timeplacedLaggerThanEqual=" +
              this.listQuery.timeplacedLaggerThanEqual +
              "&timeplacedLessThanEqual=" +
              this.listQuery.timeplacedLessThanEqual;

            window.location.href = url;
          }
          this.listLoading = false;
        })
        .catch(err => {
          console.log(err);
          this.listLoading = false;
        });
    },

    //查看退款单详情
    /**
     *
     * @param refundId 退款单号
     * @param action 动作： view 查看 ， cus_check 客服审核 f_check 财务审核
     */
    handleInfo(refundId, action) {
      //进入退款单详情查看
      this.currentRefundId = refundId;
      this.action = action;
      this.refundInfoVisible = true;
    },
    editInfo(row) {
      //进入退款单详情查看
      this.editShipp.id = row.id;
      this.editShipp.shipmodeId = row.shipmodeId;
      this.editShipp.shippingNo = row.shippingNo;
      this.editShipp.warehouseCode = row.warehouseCode;
      this.editShipp.slUseable = row.slUseable;
      this.staging.shipmodeId = row.shipmodeId;
      this.staging.shippingNo = row.shippingNo;
      warehouseList().then(res => {
        if (200 == res.code) {
          this.warehouseItems = res.data;
          this.shippingLabelOption();
          this.dialogShippFormVisible = true;
        }
      });
    },
    editShippSub(flag) {
      if (!this.editShipp.warehouseCode) {
        this.$message.error("请选择收退仓库!");
        return false;
      }
      if (!this.editShipp.shipmodeId) {
        this.$message.error("请填写退货物流公司!");
        return false;
      }
      if (!this.editShipp.shippingNo) {
        this.$message.error("请填写退货快递单号!");
        return false;
      }
      this.btnLoading = true;
      this.editShipp.slFlag = this.slFlag;
      updateshipping(this.editShipp).then(
        res => {
          if (200 == res.code) {
            this.$message({
              message: this.$t("optSuccess"),
              type: "success"
            });
            this.editShipp = {
              id: null,
              shipmodeId: "",
              shippingNo: "",
              warehouseCode: "",
              flag: flag
            };
            this.btnLoading = false;
            this.dialogShippFormVisible = false;
            this.getList();
          }
        },
        error => {
          this.btnLoading = false;
        }
      );
    },
    cancelInfo(row) {
      this.cancelForm = {
        refundNo: "",
        zfnotes: ""
      };
      this.cancelForm.refundNo = row.refundNo;
      this.dialogFormCancelVisible = true;
    },
    cancelSubmit() {
      this.$confirm("确认作废/撤销, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.btnLoading = true;
          cancel(this.cancelForm).then(
            res => {
              if (200 == res.code) {
                this.$message({
                  type: "success",
                  message: "作废成功!"
                });
                this.cancelForm = {
                  refundNo: "",
                  zfnotes: ""
                };
                this.btnLoading = false;
                this.dialogFormCancelVisible = false;
                this.getList();
              }
            },
            error => {
              this.btnLoading = false;
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("view.canceled")
          });
        });
    },
    refresh() {
      this.getList();
    },

    //编辑退款申请
    handleRefund(currentRefundId) {
      this.currentRefundId = currentRefundId;
      // this.currentOrdersId = ordersId;
      this.orderRefundVisible = true;
    },

    //新建退款信息
    createRefund(currentRefundId) {
      this.currentRefundId = currentRefundId;
      // this.currentOrdersId = ordersId;
      this.orderRefundNewVisible = true;
    },

    //创建退款单(新逻辑)
    createNewRefund() {
      this.createRefundVisible = true;
    },

    reject(id, refundNo) {
      rejectRefund(id, refundNo).then(res => {
        if (res.code == 200) {
          if (res.msg == "success") {
            this.$message({
              type: "success",
              message: this.$t("view.rejectionSuccess")
            });
          } else {
            this.$message({
              message: res.msg,
              type: "warning"
            });
          }
          this.getList();
        }
      });
    },
    backTable() {
      this.orderRefundVisible = false;
      this.orderRefundNewVisible = false;
      this.createRefundVisible = false;
      this.getList();
    },
    handleAddNote(order) {
      this.addNoteVisible = true;
      this.addNoteForm.orderRefundId = order.refundNo;
      this.addNoteForm.note = order.notes;
      this.addNoteForm.id = order.id;
    },
    submit() {
      this.listLoading = true;
      addNote(this.addNoteForm).then(res => {
        if (200 == res.code) {
          this.$message({
            message: this.$t("optSuccess"),
            type: "success"
          });
          this.getList();
          this.listLoading = false;
          this.addNoteVisible = false;
        }
      });
    },
    // 展示红色背景
    tableRowStyleName({ row }) {
      if (row.totalCount) {
        return "color: red !important;";
      }
    },
    selectEnable(row, index) {
      if (row.refundType === "2" && row.status === "0") {
        return 1;
      } else if (row.refundType === "3" && row.status === "0") {
        return 1;
      } else {
        return 0;
      }
    },
    //获取多选选中数据
    handleSelectionChange(val) {
      // val拿到的是选中行的全部数据，而this.multipleSelection是把val以对象装在数组中
      this.multipleSelection = val;
      // 每次都清空存储的数据，并装入新数据
      this.selectionList = [];
      for (const val of this.multipleSelection) {
        this.selectionList.push(val);
      }
    },

    batchCheck() {
      this.$confirm("确定批量审核？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          batchReview(this.selectionList)
            .then(res => {
              if (200 == res.code) {
                this.$message({
                  message: this.$t("optSuccess"),
                  type: "success"
                });
              }
              this.getList();
              this.listLoading = false;
            })
            .catch(err => {
              this.getList();
              this.listLoading = false;
            });
        })
        .catch(() => {
          this.btnLoading = false;
          this.btndisabled = true;
          this.$message({
            type: "info",
            message: "已取消操作"
          });
        });
    },
    queryRefundType(value) {
      console.log(value);
      this.listQuery.reasonContentChinese = value.join(",");
    },

    queryRefundReason() {
      getRefundReason({ reasonType: this.listQuery.refundType }).then(res => {
        if (200 == res.code) {
          this.refundReason = res.data;
        }
      });
    },
    // releaseEx(row){
    //   console.log(row)
    //   releaseExceptions(row.id).then(res => {
    //     if(200 == res.code){
    //       this.$message({
    //         message: "操作成功",
    //         type: "success"
    //       });
    //       this.getList();
    //     }
    //   })
    // },
    shippingLabelOption() {
      this.changeSL();
    },
    changeSL() {
      if (this.slFlag == "1") {
        this.editShipp.shipmodeId = "/";
        this.editShipp.shippingNo = "/";
      } else {
        this.editShipp.shipmodeId = this.staging.shipmodeId;
        this.editShipp.shippingNo = this.staging.shippingNo;
      }
    }
  }
};
</script>

<style scoped>
.cell > span {
  white-space: nowrap !important;
}
.el-button + .el-button {
  margin-left: 10px;
  margin-top: 10px;
}
</style>
