<template>
  <zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title + '-列表', essential: true }]">
    <template slot-scope="{activeKey, data}">
      <div v-if="activeKey == 'list'" class="app-container">
        <div class="screen-container">
          <el-form ref="screenForm" :model="screenForm" label-width="70px" size="small" label-position="left">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="订单号" prop="orderId">
                  <el-input v-model="screenForm.orderId" placeholder="请输入订单号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="售后编号" prop="orderRefundId">
                  <el-input v-model="screenForm.orderRefundId" placeholder="请输入售后编号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="会员昵称" prop="userName">
                  <el-input v-model="screenForm.userName" placeholder="请输入会员昵称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="screenForm.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="网点名称" prop="websitId">
                  <el-select v-model="screenForm.websitId" placeholder="全部" filterable>
                    <el-option label="全部" value=""></el-option>
                    <el-option :label="item.name" :value="item.id" v-for="(item, index) in websiteList"
                      :key="index"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <!--          <el-col :xs="24" :sm="12" :lg="6">-->
              <!--            <el-form-item label="当前状态" prop="orderStatus">-->
              <!--              <el-select v-model="screenForm.orderStatus" placeholder="全部">-->
              <!--                <el-option label="全部" value=""></el-option>-->
              <!--                <el-option :label="item.label" :value="item.value" v-for="(item, index) in screen_status" :key="index"></el-option>-->
              <!--              </el-select>-->
              <!--            </el-form-item>-->
              <!--          </el-col>-->

              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="申请时间" prop="createDate">
                  <el-date-picker v-model="screenForm.createDate" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
                    range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="处理时间" prop="examineDate">
                  <el-date-picker v-model="screenForm.examineDate" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
                    range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :lg="6" class="tr">
                <el-form-item label="">
                  <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
                  <el-button size="small" @click="resetScreenForm">清空</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <div class="tabs-container order-tabs-container clearfix">
          <div class="fl">
            <el-tabs v-model="tabCurrent" type="card" @tab-click="changeTabs">
              <el-tab-pane label="全部" name="ALL"></el-tab-pane>
              <el-tab-pane label="待商家处理" name="DSJCL"></el-tab-pane>
              <el-tab-pane label="待买家处理" name="DMJCL"></el-tab-pane>
              <el-tab-pane label="待商家收货" name="DSJSH"></el-tab-pane>
              <el-tab-pane label="已完成" name="OVER"></el-tab-pane>
            </el-tabs>
          </div>
          <div class="fr">
            <el-button v-if="$restrict('exp')" size="small" type="primary" @click="handleExport">导出报表</el-button>
          </div>
        </div>
        <div class="order-main-container">
          <div class="table-top">
            <el-row style="width:100%">
              <el-col :span="6"><span class="item product">商品信息</span></el-col>
              <el-col :span="3" style="text-align: right"><span class="item">单价(元)/数量</span></el-col>
              <el-col :span="3" style="text-align: center"><span class="item">买家信息</span></el-col>
              <el-col :span="3" style="text-align: center"><span class="item">订单金额</span></el-col>
              <el-col :span="3" style="text-align: center"><span class="item">退款金额</span></el-col>
              <el-col :span="3" style="text-align: center"><span class="item">维权类型/状态</span></el-col>
              <el-col :span="3" style="text-align: center"><span class="item">操作</span></el-col>
            </el-row>
          </div>
          <div class="order-item" v-for="(order, index) in dataList" :key="order.orderRefundId" @click="cporder(order)">
            <div class="order-top">
              <el-row>
                <el-col :xs="24" :sm="24" :lg="20">
                  <span><b>售后编号</b>：{{ order.orderRefundId }}</span>
                  <span><b>申请时间</b>：{{ order.createTime }}</span>
                  <span><b>商户</b>：{{ order.companyWechatName || '无' }}</span>
                  <span><b>发货状态</b>：{{ order.logisticsNo ? '已发货' : '未发货' }}</span>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="4" style="text-align: right;">
                  <el-link type="primary" v-if="$restrict('orderNote')" :underline="false"
                    @click="showRemark(order)">订单备注</el-link>
                  <el-link type="primary" v-if="$restrict('detail')" :underline="false"
                    @click="showDetail(order.orderRefundId)">查看详情</el-link>
                  <!-- <el-link type="primary" :underline="false" @click="queryWorkOrder(order.orderId)">订单工单</el-link> -->
                </el-col>
              </el-row>
            </div>
            <div class="order-content">
              <el-row style="width:100%">
                <el-col :span="9" style="height: 100%;">
                  <div class="col-item-pro">
                    <div v-if="order.examineStatus === 'FAIL'">
                      <div v-for="orderItem in order.orderDetails" :key="orderItem.orderDetailId">
                        <div class="pro-item">
                          <div class="left">
                            <div class="image">
                              <img :src="orderItem.imgUrl" style="height:80px;width: 80px;">
                            </div>
                            <div class="main">
                              <span>{{ orderItem.goodsName }}</span>
                              <span class="spec">{{ orderItem.goodsSpecName }}-{{ orderItem.goodsSpecValue }}</span>
                            </div>
                          </div>
                          <div class="right">
                            <span>￥{{ orderItem.price }}</span>
                            <span>x{{ orderItem.num }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div v-else>
                      <div v-for="orderItem in order.orderDetails" :key="orderItem.orderDetailId">
                        <div class="pro-item" v-if="orderItem.refund">
                          <div class="left">
                            <div class="image">
                              <img :src="orderItem.imgUrl" style="height:80px;width: 80px;">
                            </div>
                            <div class="main">
                              <span>{{ orderItem.goodsName }}</span>
                              <span class="spec"
                                v-if="orderItem.goodsSpecName === '默认' && orderItem.goodsSpecValue === '默认'">默认</span>
                              <span class="spec" v-else>{{ orderItem.goodsSpecName }}-{{ orderItem.goodsSpecValue
                              }}</span>
                            </div>
                          </div>
                          <div class="right">
                            <span>￥{{ orderItem.price }}</span>
                            <span>x{{ orderItem.refundNum }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-col>
                <el-col :span="3" style="height: 100%;">
                  <div class="col-item">
                    <div>{{ order.userName }}</div>
                    <div>{{ order.phone }}</div>
                  </div>
                </el-col>
                <el-col :span="3" style="height: 100%;">
                  <div class="col-item">
                    <div class="totalprice">￥{{ order.payAmount }}</div>
                  </div>
                </el-col>
                <el-col :span="3" style="height: 100%;">
                  <div class="col-item">
                    <div class="totalprice">￥{{ order.refundAmount }}</div>
                  </div>
                </el-col>
                <el-col :span="3" style="height: 100%;">
                  <div class="col-item">
                    <div>{{ order.refundType | REFUND_CURRENT_TYPE_FILTER }}</div>
                    <div>{{ order.orderStatus | ORDER_REFUND_CURRENT_STATUS_FILTER }}</div>
                  </div>
                </el-col>
                <el-col :span="3" style="height: 100%;">
                  <div class="col-item">
                    <div class="operate" v-if="order.orderStatus === 'DSJCL'">
                      <div>
                        <el-button v-if="$restrict('agree')" slot="reference" type="text" size="small"
                          @click="changeExamineStatus(order.orderRefundId, 'OK', order.refundType, order.orderId, 1)">同意</el-button>
                      </div>
                      <div>
                        <el-button v-if="$restrict('reject')" slot="reference" type="text" size="small"
                          @click="changeExamineStatus(order.orderRefundId, 'FAIL')">拒绝</el-button>
                      </div>
                      <div>
                        <!-- toWorkOrderDetail(order.orderId) -->
                        <el-button type="text" size="small" v-if="order.toWorkOrder && $restrict('workOrder_detail')"
                          @click="queryWorkOrder(order.orderId)">查看工单</el-button>
                      </div>
                    </div>
                    <div class="operate" v-if="order.orderStatus === 'DSJSH'">
                      <div v-if="$restrict('confirmReceipt')">
                        <el-popconfirm title="确定要收货吗？" @confirm="receiveProd(order.orderRefundId)">
                          <el-button slot="reference" type="text" size="small">确认收货</el-button>
                        </el-popconfirm>
                      </div>
                      <div v-if="order.logisticsNo && $restrict('viewLogistics')">
                        <el-button type="text" size="small" @click="queryLogistics(order)">查看物流</el-button>
                      </div>
                      <div>
                        <el-button type="text" size="small" v-if="order.toWorkOrder && $restrict('workOrder_detail')"
                          @click="toWorkOrderDetail(order.orderId)">查看工单</el-button>
                      </div>
                    </div>
                    <el-button type="text" size="small"
                      v-if="order.refundType == 'REFUND_GOODS' && order.orderStatus == 'OVER'"
                      @click="changeExamineStatus(order.orderRefundId, 'OK', 'REFUND_GOODS_DETAIL', order.orderId, 2); returnGoodsForm.refundMessage = order.refundMessage">查看退货信息</el-button>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div class="order-remark buyer" v-if="order.buyerMsg">买家留言：{{ order.buyerMsg }}</div>
            <div class="order-remark saler" v-if="order.remark">商家备注：{{ order.remark }}</div>
          </div>
          <div class="no-data" v-if="dataList.length <= 0">暂无订单</div>
        </div>
        <div class="pagination clearfix">
          <div class="fr">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="10"
              layout="total, sizes, prev, pager, next, jumper" :total="listTotal">
            </el-pagination>
          </div>
        </div>
      </div>
      <!-- 订单备注 -->
      <div v-if="activeKey == 'remark'" class="app-container">
        <el-input type="textarea" :autosize="{ minRows: 8, maxRows: 16 }" placeholder="请输入备注内容" v-model="remark"
          maxlength="100" show-word-limit>
        </el-input>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveRemark(data.removeTab)">保 存</el-button>
          <el-button @click="cancelRemark; data.removeTab()">取 消</el-button>
        </div>
      </div>
      <!-- 物流信息 -->
      <div v-if=" activeKey == 'materialDetail' " class="app-container">
        <el-table :data=" logistics " style="width: 100%" size="mini">
          <el-table-column prop="logisticsNo" label="快递单号" align="center"></el-table-column>
          <el-table-column prop="comName" label="物流公司" align="center"></el-table-column>
          <el-table-column prop="time" label="物流时间" align="center"></el-table-column>
          <el-table-column prop="state" label="物流状态" align="center">
            <template slot-scope="scope">
              {{ scope.row.state | EXPRESS_CURRENT_STATE_FILTER }}
            </template>
          </el-table-column>
          <el-table-column prop="context" label="物流详情" align="center"></el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="logisticsVisible = false;data.removeTab()">关 闭</el-button>
        </div>
      </div>
      <!-- 退货确认 -->
      <div v-if=" activeKey == 'REFUND_GOODS' || activeKey == 'REFUND_GOODS_DETAIL' " class="app-container">
        <el-form :model=" returnGoodsForm " :rules=" returnGoodsFormRules " ref="returnGoodsForm" label-width="80px"
          label-position="left">
          <el-row :gutter=" 20 ">
            <el-col :span=" 24 ">
              <el-form-item label="卖家留言" prop="refundMessage">
                <el-input type="textarea" :rows=" 5 " :disabled=" activeKey == 'REFUND_GOODS_DETAIL' "
                  v-model=" returnGoodsForm.refundMessage " placeholder="请输入卖家留言"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span=" 24 ">
              <el-card class="box-card">
                <el-tabs v-model=" typeIndex " @tab-click=" changeType ">
                  <el-tab-pane label="发货数量" name="1"></el-tab-pane>
                  <el-tab-pane v-if="joinCode" label="退货条码" name="2"></el-tab-pane>
                </el-tabs>
                <br />
               <!-- <el-button size="small" v-show=" typeIndex == 2 && activeKey == 'REFUND_GOODS' " type="primary"
                  @click="addCode()">新增</el-button>
                <el-button size="small" v-show=" typeIndex == 1 && activeKey == 'REFUND_GOODS' " type="primary"
                  @click="handleDownload('导入条码模板')">导入条码模板下载</el-button> -->
                <div class="table">
                  <!-- 发货数量 -->
                  <el-form v-show=" typeIndex == 1 " ref="formData1" :model=" formData1 " label-width="0" size="small"
                    label-position="left">
                    <el-table :data=" formData1.list " element-loading-text="Loading" border fit highlight-current-row
                      stripe>
                      <el-table-column prop="brandName" align="center" label="品牌"></el-table-column>
                      <el-table-column prop="mainName" align="center" label="大类"></el-table-column>
                      <el-table-column prop="smallName" align="center" label="小类"></el-table-column>
                      <el-table-column prop="goodsName" align="center" label="商品名称"></el-table-column>
                      <el-table-column prop="goodsMaterialSpecsName" align="center" label="规格型号"></el-table-column>
                      <el-table-column prop="goodsMaterialUnit" align="center" label="单位">
                        <template slot-scope="scope">
                          {{scope.row.goodsMaterialUnit == 'C'?'整套':scope.row.goodsMaterialUnit == 'I'?"单个":''}}
                        </template>
                      </el-table-column>
                      <el-table-column prop="num" align="center" label="数量"></el-table-column>
                      <el-table-column prop="insideNum" align="center" label="内机数量"></el-table-column>
                      <el-table-column prop="outNum" align="center" label="外机数量"></el-table-column>
                      <el-table-column prop="partNum" align="center" label="配件数量"></el-table-column>
                      <el-table-column prop="refundInsideCodeQty" align="center" label="导入内机条码数量"
                        width="140"></el-table-column>
                      <el-table-column prop="refundOutCodeQty" align="center" label="导入外机条码数量"
                        width="140"></el-table-column>
                      <el-table-column prop="refundPartsCodeQty" align="center" label="导入配件条码数量"
                        width="140"></el-table-column>
                      <!-- <el-table-column label="操作" align="center" width="140" fixed="right">
                        <template slot-scope="scope" v-if=" formType != 2 && joinCode && activeKey == 'REFUND_GOODS' ">
                          <el-upload action='_' :show-file-list=' false ' :http-request=" importCode ">
                            <el-button @click="orderDetailId = scope.row.orderDetailId" size="mini"
                              type="text">导入条码</el-button>
                          </el-upload>
                        </template>
                      </el-table-column> -->
                    </el-table>
                  </el-form>
                  <!-- 发货条码 -->
                  <el-form ref="formData2" :model=" formData2 ">
                    <el-table v-show=" typeIndex == 2 " :data=" formData2.list " element-loading-text="Loading" border fit
                      highlight-current-row stripe>
                      <el-table-column label="品牌" align="center">
                        <template slot-scope="scope">
                          <el-form-item>
                            <el-input type="text" v-model=" scope.row.brandName " :disabled=" true "
                              placeholder="请输入"></el-input>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column label="商品大类" align="center">
                        <template slot-scope="scope">
                          <el-form-item>
                            <el-input type="text" v-model=" scope.row.mainName " :disabled=" true "
                              placeholder="请输入"></el-input>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column label="商品小类" align="center">
                        <template slot-scope="scope">
                          <el-form-item>
                            <el-input type="text" v-model=" scope.row.smallName " :disabled=" true "
                              placeholder="请输入"></el-input>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column prop="" align="center" label="商品名称">
                        <template slot-scope="scope">
                          <el-form-item>
                            <el-input type="text" v-model=" scope.row.goodsMaterialName " :disabled=" true "
                              placeholder="请输入"></el-input>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column label="规格型号" align="center">
                        <template slot-scope="scope">
                          <el-form-item :prop=" 'list.' + scope.$index + '.specs' "
                            :rules=" [{ required: true, message: `请选择规格型号`, trigger: 'blur' }] ">
                            <el-select v-model=" scope.row.specs " @change=" (e) => { changeSpecs(e, scope.row) } "
                              value-key="goodsMaterialSpecsName"
                              :disabled=" isEdit2 != scope.$index || formType == 2 || activeKey == 'REFUND_GOODS_DETAIL' "
                              placeholder="请选择" style="width: 100%;">
                              <el-option v-for="(      item, ind      ) in       formData1.list      " :key=" ind "
                                :label=" item.goodsMaterialSpecsName " :value=" item ">
                              </el-option>
                            </el-select>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column label="物料类型" align="center">
                        <template slot-scope="scope">
                          <el-form-item :prop=" 'list.' + scope.$index + '.goodsMaterialItemType' "
                            :rules=" [{ required: true, message: `请选择物料类型`, trigger: 'blur' }] ">
                            <el-select v-model=" scope.row.goodsMaterialItemType "
                              @change=" (e) => { changeMaterial(e, scope.row) } "
                              :disabled=" isEdit2 != scope.$index || formType == 2 || activeKey == 'REFUND_GOODS_DETAIL' "
                              placeholder="请选择" style="width: 100%;">
                              <el-option
                                v-for="(      item, ind      ) in       [{ name: '内机', id: 'INSIDE' }, { name: '外机', id: 'OUT' }, { name: '配件', id: 'PARTS' }]      "
                                :key=" ind " :label=" item.name " :value=" item.id ">
                              </el-option>
                            </el-select>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column label="物料名称" align="center">
                        <template slot-scope="scope">
                          <el-form-item :prop=" 'list.' + scope.$index + '.material' "
                            :rules=" [{ required: true, message: `请选择物料名称`, trigger: 'blur' }] ">
                            <el-select v-model=" scope.row.material " @focus="
                              (e) => {
                                if (!scope.row.goodsMaterialItemType) {
                                  return $message.warning('请先选择物料类型！');
                                }
                              }
                            " @change="
  (e) => {
    scope.row.materialName = e.name
    scope.row.stockQty = (e.uniqueCode == 'YES' ? 1 : null)
    scope.row.uniqueCode = e.uniqueCode
    scope.row.goodsMaterialItemId = e.itemId

  }
" value-key="name" :disabled=" isEdit2 != scope.$index || formType == 2 || activeKey == 'REFUND_GOODS_DETAIL' "
                              placeholder="请选择" style="width: 100%;">
                              <el-option v-for="(      item, ind      ) in       scope.row.materialList      " :key=" ind "
                                :label=" item.name " :value=" item ">
                              </el-option>
                            </el-select>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column prop="" align="center" label="是否一物一码">
                        <template slot-scope="scope">
                          <el-form-item>
                            {{scope.row.uniqueCode=='YES'?'是':scope.row.uniqueCode=='NO'?'否':''}}
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column prop="" align="center" label="条码">
                        <template slot-scope="scope">
                          <el-form-item :prop=" 'list.' + scope.$index + '.materialCode' "
                            :rules=" [{ required: true, message: `请输入条码`, trigger: 'blur' }] ">
                            <el-input type="text" v-model=" scope.row.materialCode "
                              :disabled=" isEdit2 != scope.$index || formType == 2 || activeKey == 'REFUND_GOODS_DETAIL' "
                              placeholder="请输入"></el-input>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column prop="" align="center" label="数量">
                        <template slot-scope="scope">
                          <el-form-item :prop=" 'list.' + scope.$index + '.stockQty' "
                            :rules=" [{ required: true, message: `请输入数量`, trigger: 'blur' }] ">
                            <el-input type="number" v-model=" scope.row.stockQty "
                              :disabled=" isEdit2 != scope.$index || formType == 2 || activeKey == 'REFUND_GOODS_DETAIL' || scope.row.uniqueCode == 'YES' "
                              placeholder="请输入"></el-input>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" align="right" width="140" fixed="right">
                        <template slot-scope="scope" v-if=" formType != 2 && activeKey == 'REFUND_GOODS' ">
                          <el-button size="mini" type="primary" v-if=" scope.$index == isEdit2 "
                            @click="saveCode(scope.row)">保存</el-button>
                          <el-button size="mini" type="primary" v-if=" scope.$index != isEdit2 "
                            @click="isEdit2 = scope.$index">编辑</el-button>
                          <el-popconfirm title="确定删除吗？" @confirm="delCode(scope.row.orderDetailCodeId,scope.$index)">
                            <el-button slot="reference" size="mini" type="danger">删除</el-button>
                          </el-popconfirm>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-form>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="returnGoodsVisible = false;data.removeTab()">关 闭</el-button>
          <el-button type="primary" v-if=" activeKey == 'REFUND_GOODS' " @click="saveReturnGoods(data.removeTab)">确
            定</el-button>
        </div>
      </div>
    </template>
  </zj-tab-page>
</template>

<script>
import { getRefundList, saveRefundRemark, changeExamineStatus, receiveProd, getWebsiteList, getOrderDetail, getCodeDetail, getMaterialList, listImport2, saveCode2, delCode2 } from "@/api/order"
import { getExpress } from "@/api/common"
import { downloadFiles } from '@/utils/util'
import { commonTemplateDownload } from '@/api/common.js'
import '@/styles/order-list.scss'

export default {
  name: "order_refund",
  data() {
    return {
      screenForm: { // 筛选表单数据
        orderId: '', // 订单号
        orderRefundId: '', // 售后编号
        userName: '', // 会员昵称
        phone: '', // 手机号
        websitId: '', // 网点名称
        createDate: '', // 创建时间
        examineDate: '', // 支付时间
        orderStatus: '',
      },
      returnGoodsForm: {
        refundMessage: ''
      },
      tabCurrent: 'ALL',
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: [],
      remarkVisible: false,
      editOrderId: '',
      remark: '', // 订单备注
      logisticsVisible: false,
      logistics: [],
      detail: {},
      websiteList: [],
      formType: 'add',
      formVisible: false,
      returnGoodsVisible: false,
      typeIndex: '1',
      formData1: {
        list: [],
      },
      formData2: {
        list: [],
      },
      isEdit1: 0,
      isEdit2: 0,
      joinCode: JSON.parse(localStorage.getItem('greemall_user')).joinCode,
      orderDetailId: '',
      returnGoodsFormRules: {
        // refundMessage: [{ required: true, message: '请填写卖家留言', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getList();
    this.getWebsiteList();
    if (this.$route.query.id) {
      this.showDetail(this.$route.query.id)
    }
  },
  methods: {
    queryWorkOrder(id) {
      this.$router.push({
        name: 'workOrderPool',
        params: {
          pageName: id,
          pageType: 'saleOrderId',
          pageCode: id,
        },
      })
    },
    changeTabs(tab, event) {
      // this.$refs.screenForm.resetFields();
      this.screenForm.orderStatus = this.tabCurrent === 'ALL' ? '' : tab.$options.propsData.name
      this.currentPage = 1;
      this.getList();
    },
    // 获取数据列表
    getList() {
      this.listLoading = true;
      let pageData = {
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      let screenData = {
        orderId: this.screenForm.orderId, // 订单号
        orderRefundId: this.screenForm.orderRefundId, // 售后编号
        userName: this.screenForm.userName, // 会员昵称
        phone: this.screenForm.phone, // 手机号
        websitId: this.screenForm.websitId,
        orderStatus: this.screenForm.orderStatus, // 状态
        startCreateTime: this.screenForm.createDate ? this.screenForm.createDate[0] : '', // 创建时间
        endCreateTime: this.screenForm.createDate ? this.screenForm.createDate[1] : '', // 创建时间
        startExamineTime: this.screenForm.examineDate ? this.screenForm.examineDate[0] : '', // 处理时间
        endExamineTime: this.screenForm.examineDate ? this.screenForm.examineDate[1] : '', // 处理时间
      };
      let params = {};
      Object.assign(params, screenData, pageData);

      getRefundList(params).then(res => {
        this.dataList = res.data.records;
        this.listTotal = res.data.total;
        this.listLoading = false;
      })
    },
    getOrderDetail(orderId) {
      getOrderDetail({ orderId: orderId || this?.order_cp?.orderId || "" }).then(res => {
        this.formData1.list = res.data.orderDetails
      })
    },
    changeType() {
      this.getOrderDetail()
      this.getCodeDetail()
    },
    getCodeDetail(orderRefundId) {
      getCodeDetail({ orderId: this?.order_cp?.orderId || orderRefundId || this.editOrderId || this?.order_cp?.orderRefundId || "" }).then(async res => {
        for (var item of res.data) {
          item.specs = { goodsMaterialSpecsName: item.specsName }
          item.material = { name: item.materialName }
          item.materialList = await this.getMaterialList(item.specsName, item.goodsMaterialItemType)
        }
        this.formData2.list = res.data
      })
    },
    async getMaterialList(specsName, type) {
      return new Promise((resolve, reject) => {
        getMaterialList({
          pageNum: 1,
          pageSize: -1,
          specsName,
          type
        }).then(async res => {
          resolve(res.data.records)
        })
      })

    },
    async changeSpecs(e, row) {
      row.brandName = e.brandName
      row.brandId = e.brandId
      row.mainName = e.mainName
      row.mainId = e.mainNumber
      row.smallName = e.smallName
      row.smallId = e.smallNumber
      row.specsName = e.goodsMaterialSpecsName
      row.goodsMaterialName = e.goodsName
      row.goodsMaterialId = e.goodsMaterialId
      row.material = null
      row.materialName = ''
      row.stockQty = ''
      row.uniqueCode = ''
      row.materialList = await this.getMaterialList(row.specsName, row.goodsMaterialItemType)
      row.orderDetailId = e.orderDetailId
    },
    async changeMaterial(e, row) {
      if (!row.specs) {
        return this.$message.warning('请先选择规格型号！');
      }
      row.material = null
      row.materialName = ''
      row.stockQty = ''
      row.uniqueCode = ''
      row.materialList = await this.getMaterialList(row.specsName, row.goodsMaterialItemType)
    },
    //发货新增条码
    addCode() {
      this.$refs.formData2.validate((valid) => {
        if (valid) {
          this.isEdit2 = 0
          this.formData2.list.unshift({
            brandId: '',
            brandName: '',
            mainId: '',
            mainName: '',
            stockQty: '',
            smallId: '',
            smallName: '',
            goodsMaterialItemType: '',
            goodsMaterialName: '',
            goodsMaterialId: '',
            materialCode: '',
            uniqueCode: '',
            specs: null,
            specsName: '',
            materialName: '',
            material: null,
            materialList: [],
            orderDetailId: '',
            goodsMaterialItemId: ''
          })
        }
      });
    },
    delCode(orderDetailCodeId, index) {
      if (orderDetailCodeId) {
        delCode2({
          orderDetailCodeId
        }).then(res => {
          if (res.code == 200) {
            this.$message({ type: 'success', message: '删除成功!' })
            this.getOrderDetail()
            this.getCodeDetail()
          } else {
            this.$message.error(res.msg);
          }
        })
      } else {
        this.formData2.list.splice(index, 1)
      }
    },
    saveCode(orderDetailCodes) {
      const that = this
      let params = [{
        ...orderDetailCodes,
        orderId: this.editOrderId,
      }]
      delete params[0].material;
      delete params[0].specs;
      this.$refs.formData2.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          saveCode2(params).then(res => {
            if (res.code == 200) {
              that.$message.success('保存成功!')
              this.getOrderDetail()
              this.getCodeDetail()
            }
          })
        }
      })
    },
    openForm(type, order) {
      this.$refs.tabPage.addTab({
        // 对应显示的模块
        activeKey: type,
        // 唯一标识
        key: type,
        // 页签名称
        label: ({ remark: "订单备注", materialDetail: "查看物流", REFUND_GOODS: "退货确认", REFUND_GOODS_DETAIL: '查看退货信息' })[type],
        // 打开时事件
        triggerEvent: () => {
          this.typeIndex = '1'
          this.$nextTick(() => {
            this.formType = type
            this.formVisible = true
            if (type == 'remark') {
              this.remarkVisible = true
              this.editOrderId = order.orderRefundId
              this.remark = order.remark
            }
            if (type == 'materialDetail') {
              this.logisticsVisible = true
              getExpress({ logisticsNo: order.logisticsNo }).then(res => {
                this.logistics = res.data
              })
            }
            if (type == 'REFUND_GOODS') {
              this.returnGoodsVisible = true
              this.editOrderId = order.orderRefundId
            }
          })
        },
        // 关闭时事件
        closeEvent: () => {

        }
      })
    },
    // 查看详情
    queryDetail(orderRefundId) {
    },
    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getList();
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },
    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1;
      this.getList();
    },
    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields();
      this.currentPage = 1;
      this.getList();
    },

    // 网点列表
    getWebsiteList() {
      getWebsiteList({
        pageNum: 1,
        pageSize: 1000,
        type: 'C'
      }).then(res => {
        this.websiteList = res.data;
      })
    },

    showRemark(order) {
      this.openForm('remark', order)
    },
    cancelRemark() {
      this.remarkVisible = false
      this.editOrderId = ''
      this.remark = ''
    },
    saveRemark(cancel) {
      const params = {
        orderRefundId: this.editOrderId,
        remark: this.remark
      }
      saveRefundRemark(params).then(() => {
        cancel('list')
        this.cancelRemark();
        this.getList();
        this.$successMsg('保存成功');
      })
    },
    saveReturnGoods(cancel) {
      changeExamineStatus({
        orderRefundId: this.editOrderId,
        examineStatus: 'OK',
        refundMessage: this.returnGoodsForm.refundMessage
      }).then(() => {
        cancel('list')
        this.getList();
        this.$successMsg('操作成功');
      })
    },
    cporder(order) {
      this.order_cp = order
    },
    // 变更维权处理状态
    changeExamineStatus(orderRefundId, examineStatus, refundType, orderId, type) {
      if (refundType == 'REFUND_GOODS' || refundType == 'REFUND_GOODS_DETAIL') {
        this.getOrderDetail(orderId)
        this.getCodeDetail(orderRefundId)
        this.openForm(refundType, { orderRefundId })
      } else {
        this.$prompt('请输入卖家留言', examineStatus == 'OK' ? '同意' : '拒绝', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          changeExamineStatus({
            orderRefundId,
            examineStatus,
            refundMessage: value
          }).then(() => {
            this.getList();
            this.$successMsg('操作成功');
          })
        }).catch(() => { });
      }

    },
    // 查看物流
    queryLogistics(order) {
      this.openForm('materialDetail', order)
    },
    // 查看详情
    showDetail(orderRefundId) {
      // let {href} = this.$router.resolve({path: `/order/order_refund_detail?orderRefundId=${orderRefundId}`});
      // window.open(href, '_blank');
      this.$router.push({
        name: "order_refund_detail",
        query: {
          orderRefundId
        }
      })
    },
    receiveProd(orderRefundId) {
      receiveProd({ orderRefundId }).then(() => {
        this.getList();
        this.$successMsg('操作成功');
      })
    },

    // 查看工单
    toWorkOrderDetail(orderId) {
      // let {href} = this.$router.resolve({path: `/order/workOrder_detail?orderId=${orderId}`});
      // window.open(href, '_blank');
      this.$router.push({
        name: "workOrder_detail",
        query: {
          orderId
        }
      })
    },

    // 导出
    handleExport() {
      let screenData = {
        orderId: this.screenForm.orderId, // 订单号
        orderRefundId: this.screenForm.orderRefundId, // 售后编号
        userName: this.screenForm.userName, // 会员昵称
        phone: this.screenForm.phone, // 手机号
        websitId: this.screenForm.websitId,
        orderStatus: this.screenForm.orderStatus, // 状态
        startCreateTime: this.screenForm.createDate ? this.screenForm.createDate[0] : '', // 创建时间
        endCreateTime: this.screenForm.createDate ? this.screenForm.createDate[1] : '', // 创建时间
        startExamineTime: this.screenForm.examineDate ? this.screenForm.examineDate[0] : '', // 处理时间
        endExamineTime: this.screenForm.examineDate ? this.screenForm.examineDate[1] : '', // 处理时间
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };
      downloadFiles('order/refund/downLoadExcel', screenData);
    },

    importCode(data) {
      const loading = this.$loading({
        lock: true,
        text: '正在导入',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      var formdata = new FormData()
      formdata.append('file', data.file)
      let params = {
        orderDetailId: this.orderDetailId
      }
      if (!!params) {
        for (const key in params) {
          if (Object.hasOwnProperty.call(params, key)) {
            formdata.append(key, params[key])
          }
        }
      }
      listImport2({ formdata })
        .then(res => {
          this.getOrderDetail()
          this.getCodeDetail()
          loading.close()
          this.$message({
            type: 'success',
            message: '导入成功!'
          })
        })
        .catch(err => {
          loading.close()
          this.$message({
            type: 'error',
            message: err.message || '导入失败'
          })
        })
    },

    // 下载导入模版
    handleDownload(title) {
      commonTemplateDownload({ name: '导入条码.xlsx' }, title).then(res => {
        this.$message({
          message: '下载成功',
          type: 'success'
        })
      }).catch(err => {
        this.$message.error('下载失败')
      })
    },
  }
}
</script>
