<template>
  <div class="mod-print-thirdAfterSales">
    <!-- 搜索相关区域 -->
    <div class="search-bar">
      <el-form :inline="true" class="search-form" ref="searchForm" :model="searchForm" label-width="auto" size="small">
        <div class="input-row">
          <el-form-item label="售后渠道" class="search-form-item" v-if="shopId === 1">
            <el-select v-model="searchForm.printChannel" clearable>
<!--              <el-option label="广森" value="GSART" v-if="shopId === 1"></el-option>-->
<!--              <el-option label="快印" value="KuaiYin" v-if="shopId === 1"></el-option>-->
<!--              <el-option label="蜗牛" value="WoNiu" v-if="shopId === 1"></el-option>-->
              <el-option label="闪电" value="Lightning" v-if="shopId === 1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="订单编号" class="search-form-item">
            <el-input type="text" clearable v-model="searchForm.orderNumber" placeholder="请输入订单编号"></el-input>
          </el-form-item>
          <el-form-item label="快递单号" class="search-form-item">
            <el-input type="text" clearable v-model="searchForm.deliveryNo" placeholder="请输入运单号"></el-input>
          </el-form-item>
          <el-form-item label="售后类型" class="search-form-item">
            <el-select v-model="searchForm.type" clearable>
              <el-option label="瑕疵" value="瑕疵"></el-option>
              <el-option label="裁切" value="裁切"></el-option>
              <el-option label="毛边" value="毛边"></el-option>
              <el-option label="翘边" value="翘边"></el-option>
              <el-option label="错发" value="错发"></el-option>
              <el-option label="少发" value="少发"></el-option>
              <el-option label="漏发" value="漏发"></el-option>
              <el-option label="退件" value="退件"></el-option>
              <el-option label="补发" value="补发"></el-option>
              <el-option label="物流" value="物流"></el-option>
              <el-option label="改地址" value="改地址"></el-option>
              <el-option label="改快递" value="改快递"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="售后状态">
            <el-select
              v-model="searchForm.status"
              clearable
              placeholder="请选择售后状态"
              size="small">
              <el-option key="0" label="待处理" value="0"></el-option>
              <el-option key="1" label="已处理" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="登记人">
            <el-select
              v-model="searchForm.registrant"
              clearable
              placeholder="请选择登记人"
              size="small">
<!--              <el-option key="zh" label="志华" value="志华"></el-option>-->
              <el-option key="fq" label="方权" value="方权"></el-option>
              <el-option key="wx" label="文祥" value="文祥"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="下单时间"  clearable>
            <el-date-picker
              :default-time="['00:00:00', '23:59:59']"
              size="small"
              v-model="orderTimeDateRange"
              type="datetimerange"
              :range-separator="this.$i18n.t('time.tip')"
              value-format="yyyy-MM-dd HH:mm:ss"
              :start-placeholder="this.$i18n.t('time.start')"
              :end-placeholder="this.$i18n.t('time.end')">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="售后登记时间"  clearable>
            <el-date-picker
              :default-time="['00:00:00', '23:59:59']"
              size="small"
              v-model="afterSalesDateRange"
              type="datetimerange"
              :range-separator="this.$i18n.t('time.tip')"
              value-format="yyyy-MM-dd HH:mm:ss"
              :start-placeholder="this.$i18n.t('time.start')"
              :end-placeholder="this.$i18n.t('time.end')">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <div class="default-btn primary-btn" @click="searchChange()">{{$t('crud.searchBtn')}}</div>
            <div class="default-btn" @click="resetSearchForm('searchForm')">{{$t('shop.resetMap')}}</div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!-- 列表相关区域 -->
    <div class="main-container">
      <div class="operation-bar">
        <div class="default-btn primary-btn" v-if="shopId === 1" @click="addOrUpdateHandle()">新增售后</div>
        <div class="default-btn info-btn" v-if="shopId === 1" @click="openWxRefundDialog()">申请微信退款</div>
<!--        <div class="default-btn primary-btn" v-if="shopId === 1" @click.stop="getUpload()">导入售后数据</div>-->
      </div>
      <div class="table-con spec-table">
        <el-table
          ref="specListTable"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%">
          <!-- 售后渠道 -->
          <el-table-column label="售后渠道" prop="printChannel" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.printChannel}}</span>
            </template>
          </el-table-column>
          <!-- 订单编号 -->
          <el-table-column label="订单编号" prop="orderNumber" align="center" width="100px">
            <template slot-scope="scope">
              <span>{{ scope.row.orderNumber}}</span>
            </template>
          </el-table-column>
          <!-- 快递单号 -->
          <el-table-column label="快递单号" prop="deliveryNo" align="center" width="80px">
            <template slot-scope="scope">
              <span>{{ scope.row.deliveryNo}}</span>
            </template>
          </el-table-column>
          <el-table-column label="产品名称" prop="prodName" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.prodName}}</span>
            </template>
          </el-table-column>
          <!-- 售后类型，比如瑕疵问题，裁剪问题 -->
          <el-table-column label="售后类型" prop="type" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.type}}</span>
            </template>
          </el-table-column>
          <!-- 订单时间 -->
          <el-table-column label="下单时间" prop="orderTime" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.orderTime}}</span>
            </template>
          </el-table-column>
          <!-- 售后登记时间 -->
          <el-table-column label="售后登记时间" prop="createTime" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime}}</span>
            </template>
          </el-table-column>
          <!-- 退款金额 -->
          <el-table-column label="退款金额(按成本)" prop="refundAmount" align="center" width="80px">
            <template slot-scope="scope">
              <span>{{ scope.row.costAmount}}</span>
            </template>
          </el-table-column>
          <el-table-column label="退款金额" v-if="shopId === 1" prop="refundAmount" align="center" width="50px">
            <template slot-scope="scope">
              <span>{{ scope.row.refundAmount}}</span>
            </template>
          </el-table-column>
          <!-- 退款方式 -->
          <el-table-column label="退款方式" v-if="shopId == 1" prop="refundType" align="center" width="50px">
            <template slot-scope="scope">
              <span v-if="scope.row.refundType === 0">余额</span>
              <span v-if="scope.row.refundType === 1">微信</span>
            </template>
          </el-table-column>
          <!-- 退款方式 -->
          <el-table-column label="登记人" v-if="shopId == 1" prop="registrant" align="center" width="50px">
            <template slot-scope="scope">
              <span>{{ scope.row.registrant}}</span>
            </template>
          </el-table-column>
          <!-- 进度，待处理，已处理， -->
          <el-table-column label="售后状态" prop="progress" align="center" width="120px">
            <template slot-scope="scope">
              <el-tag effect="dark" type="danger" v-if="scope.row.status === 0">待处理</el-tag>
              <el-tag effect="dark" type="success" v-if="scope.row.status === 1">已处理</el-tag>
            </template>
          </el-table-column>
          <!-- 结算状态，未结算，已结算， -->
<!--          <el-table-column label="结算状态" prop="settleStatus" align="center" width="80px">-->
<!--            <template slot-scope="scope">-->
<!--              <el-tag effect="dark" type="danger" v-if="scope.row.settleStatus === 0">未结算</el-tag>-->
<!--              <el-tag effect="dark" type="success" v-if="scope.row.settleStatus === 1">已结算</el-tag>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column align="center" fixed="right" :label="$t('publics.operating')" width="auto">
            <template slot-scope="scope">
              <div class="text-btn-con">
                <div class="default-btn text-btn" @click="addOrUpdateHandle(scope.row.id, true)">详情</div>
                <div class="default-btn text-btn" v-if="shopId == 1" @click="addOrUpdateHandle(scope.row.id, false)">{{$t("crud.updateBtn")}}</div>
                <div class="default-btn text-btn" v-if="shopId == 1" @click.stop="deleteHandle(scope.row.id)">{{$t("text.delBtn")}}</div>
                </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
        <el-pagination
          v-if="dataList.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>
    <add-or-update ref="addOrUpdate" @refreshDataList="refreshChange"></add-or-update>
    <el-dialog
      :modal="false"
      title="导入售后数据"
      :close-on-click-modal="false"
      :visible.sync="importDialogVisible"
      @close="handleImportClose"
      width="38%">
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="$http.adornUrl('/print/thirdAfterSales/importAfterSales')"
        :headers="{ Authorization: $cookie.get('Authorization_vs'),locale:lang }"
        :limit="1"
        name="file"
        :file-list="files"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :auto-upload="false">
        <div slot="tip" class="el-upload__tip"></div>
        <el-button slot="trigger" size="small" icon="el-icon-upload2" style="margin-right: 20px">上传</el-button>
        <el-button size="small" type="primary" @click="submitUpload" :loading="uploading">提 交</el-button>
      </el-upload>
    </el-dialog>
    <el-dialog
      :modal="false"
      title="申请微信退款"
      :close-on-click-modal="false"
      :visible.sync="wxRefundVisible"
      @close="closeRefundDialog"
      width="38%">
      <el-form :model="wxRefundData" label-position="right">
        <el-form-item label="订单号" label-width="70px">
          <el-input v-model="wxRefundData.orderNumber" placeholder="请输入订单号" @change="queryWxRefundInfo"></el-input>
          <span style="color: red" v-if="wxRefundBalanceVisible">{{orderRefundQueryInfo}}</span>
        </el-form-item>
        <el-form-item label="退款金额" label-width="70px">
          <el-input v-model="wxRefundData.refundAmount" type="number" placeholder="请输入退款金额"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleWxRefund()">确认退款</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AddOrUpdate from './thirdAfterSales-add-or-update'
export default {
  data () {
    return {
      dataList: [],
      lang: localStorage.getItem('lang') || 'zh_CN',
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      wxRefundVisible: false,
      wxRefundBalanceVisible: false,
      shopId: this.$store.state.user.shopId,
      wxRefundData:{},
      searchForm: {
        printChannel: null,
        status: null,
        type: null,
        orderTime: null,
        orderNumber: null,
        deliveryNo: null,
        settleStatus: null,
        registrant: null
      }, // 搜索
      dataListLoading: false,
      addOrUpdateVisible: false,
      orderTimeDateRange: [],
      afterSalesDateRange: [],
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      importDialogVisible: false,
      uploading: false,
      files:[],
      orderRefundQueryInfo:{}
    }
  },
  components: {
    AddOrUpdate
  },
  created () {
    this.getDataList(this.page);
  },
  mounted () {
  },
  methods: {
    openWxRefundDialog(){
      this.wxRefundVisible = true;
    },
    closeRefundDialog(){
      this.wxRefundVisible = false;
      this.wxRefundBalanceVisible = false;
      this.wxRefundData = {}
    },
    queryWxRefundInfo(){
      this.$http({
        url: this.$http.adornUrl(`/order/refund/refundQuery/`+ this.wxRefundData.orderNumber),
        method: 'get',
      }).then(({ data }) => {
        if(data){
          this.orderRefundQueryInfo = "订单支付金额：" + data.payAmount + "元，已退款金额：" + data.totalRefundAmount + "元，可退款金额：" + (data.payAmount - data.totalRefundAmount).toFixed(2) + "元"
        }else{
          this.orderRefundQueryInfo
        }
      })
      this.wxRefundBalanceVisible = true;
    },
    handleWxRefund(){
      this.$http({
        url: this.$http.adornUrl('/order/refund/partRefundRequest'),
        method: 'post',
        data: this.$http.adornData(this.wxRefundData)
      }).then(({data}) => {
        this.wxRefundBalanceVisible = false;
        this.wxRefundVisible = false;
        this.wxRefundData = {};
        this.$message({
          message: '退款发起成功',
          type: 'success'
        })
      })
    },
    getDataList (page) {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/print/thirdAfterSales/page'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign({
            current: page == null ? this.page.currentPage : page.currentPage,
            size: page == null ? this.page.pageSize : page.pageSize,
            'afterSalesStartTime': this.afterSalesDateRange == null ? null : this.afterSalesDateRange[0],
            'afterSalesEndTime': this.afterSalesDateRange == null ? null : this.afterSalesDateRange[1],
            'orderStartTime': this.orderTimeDateRange == null ? null : this.orderTimeDateRange[0],
            'orderEndTime': this.orderTimeDateRange == null ? null : this.orderTimeDateRange[1],
            'orderNumber': this.searchForm.orderNumber,
            'printChannel': this.searchForm.printChannel,
            'type': this.searchForm.type,
            'status': this.searchForm.status,
            'deliveryNo': this.searchForm.deliveryNo,
            'registrant': this.searchForm.registrant,
          },
          )
        )
      }).then(({data}) => {
        this.dataList = data.records
        this.page.total = data.total
        this.dataListLoading = false
      })
    },
    // 新增 / 修改
    addOrUpdateHandle (id, isView) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id, isView)
      })
    },
    deleteHandle (id) {
      this.$confirm(this.$i18n.t('admin.isDeleOper') + '?', this.$i18n.t('text.tips'), {
        confirmButtonText: this.$i18n.t('crud.filter.submitBtn'),
        cancelButtonText: this.$i18n.t('crud.filter.cancelBtn'),
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/print/thirdAfterSales/' + id),
          method: 'delete',
          data: this.$http.adornData({})
        }).then(({ data }) => {
          this.$message({
            message: this.$i18n.t('publics.operation'),
            type: 'success'
          })
          this.refreshChange()
        })
      }).catch(() => { })
    },
    getUpload(){
      this.importDialogVisible = true;
    },
    submitUpload () {
      this.$refs.upload.submit();
    },
    handleUploadSuccess (response, file, fileList) {
      this.importDialogVisible = false;
      this.uploading = false;
      this.getDataList(this.page, null, false)
    },
    handleUploadError (error, file, fileList) {
      this.importDialogVisible = false;
      this.uploading = false;
    },
    handleImportClose(){
      this.importDialogVisible = false;
      this.files = [];
    },
    // 刷新回调
    refreshChange () {
      // this.page.currentPage = 1
      // this.this.addOrUpdateVisible = false;
      this.getDataList(this.page)
    },
    searchChange (params) {
      // this.searchForm = params
      this.getDataList(this.page)
    },
    handleSizeChange (val) {
      this.page.pageSize = val
      this.getDataList()
    },
    handleCurrentChange (val) {
      this.page.currentPage = val
      this.getDataList()
    },
    /**
     * 重置表单
     * @param {String} formName 表单名称
     */
    resetSearchForm (formName) {
      this.$refs[formName].resetFields()
      this.searchForm = {}
    },
  }
}
</script>
<style lang="scss">
.mod-print-thirdAfterSales {
}
</style>
