<template>
  <div class="new-after-sales-order">
    <el-form
      :model="orderDetail"
      ref="orderDetail"
      size="mini"
      :inline="true"
      label-width="120px"
      class="mini-form"
      label-position="left"
    >
      <el-card shadow="never" class="box-card">
        <div slot="header">
          <h3 style="margin-top: 0"><span></span>售后单信息</h3>
        </div>
        <el-descriptions :column="2" size="medium" labelClassName="all-class">
          <el-descriptions-item label="平台订单号"
            >{{ orderDetail.platformCode || "--"
            }}<i
              v-if="orderDetail.platformCode"
              class="el-icon-document-copy"
              @click="copyText(orderDetail.platformCode)"
            ></i
          ></el-descriptions-item>
          <el-descriptions-item label="" labelClassName="else-form">
            <el-form-item
              label="平台售后单编号:"
              label-width="130px"
              prop="afterSalesPlatformCode"
              :rules="[
                {
                  required: true,
                  message: '请输入平台售后单编号',
                  trigger: 'change',
                },
              ]"
            >
              <el-input
                :disabled="editStatus"
                v-model.trim="orderDetail.afterSalesPlatformCode"
                style="width: 240px"
                clearable
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="店铺">
            {{ orderDetail.shopName || "--" }}</el-descriptions-item
          >
          <el-descriptions-item label="购买会员">{{
            orderDetail.vipName || "--"
          }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <span class="color-g">{{
              filterStatus(orderDetail.orderStatus)
            }}</span></el-descriptions-item
          >
          <el-descriptions-item label="订单发货状态">{{
              typefilter(orderDetail.deliveryStatus, deliveryStatusList)
          }}</el-descriptions-item>
          <el-descriptions-item label="销售金额（元）">{{
            orderDetail.orderPrice
              ? `￥${$numFormat(orderDetail.orderPrice)}`
              : "--"
          }}</el-descriptions-item>
          <el-descriptions-item label="实付金额（元）">{{
            orderDetail.payPrice
              ? `￥${$numFormat(orderDetail.payPrice)}`
              : "--"
          }}</el-descriptions-item>
          <el-descriptions-item label="收货人手机">{{
            orderDetail.userMobile || "--"
          }}</el-descriptions-item>
          <el-descriptions-item label="收货人">{{
            orderDetail.userName || "--"
          }}</el-descriptions-item>
          <el-descriptions-item label="" labelClassName="else-form">
            <el-form-item
              label="售后单类型:"
              prop="afterSalesType"
              :rules="[
                {
                  required: true,
                  message: '请选择售后单类型',
                  trigger: 'change',
                },
              ]"
            >
              <el-select
                filterable
                v-model="orderDetail.afterSalesType"
                :disabled="editStatus"
                placeholder="请选择"
                clearable
                style="width: 240px"
                @change="typeChange"
              >
                <el-option
                  v-for="dict in orderTypeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="" labelClassName="else-form">
            <el-form-item
              label="售后原因:"
              prop="refundReason"
              :rules="[
                {
                  required: true,
                  message: '请选择售后原因',
                  trigger: 'change',
                },
              ]"
            >
              <el-select
                filterable
                v-model="orderDetail.refundReason"
                placeholder="请选择"
                clearable
                style="width: 240px"
                allow-create
              >
                <el-option
                  v-for="dict in afterSalesResonsList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.label"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item
            label=""
            labelClassName="else-form"
            v-if="orderDetail.afterSalesType"
          >
            <el-form-item
              label="退款类型:"
              prop="refundType"
              :rules="[
                {
                  required: true,
                  message: '请选择退款类型',
                  trigger: 'change',
                },
              ]"
            >
              <el-select
                filterable
                v-model="orderDetail.refundType"
                placeholder="请选择"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in refundTypeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item
            label=""
            labelClassName="else-form"
            v-if="orderDetail.afterSalesType"
          >
            <el-form-item
              label="退款金额:"
              prop="refundAmount"
              :rules="
                orderDetail.afterSalesType == 'COMPENSATION_REFUND'
                  ? [
                      {
                        required: true,
                        message: '请输入退款金额',
                        trigger: 'change',
                      },
                    ]
                  : []
              "
            >
              <el-input
                v-model.trim="orderDetail.refundAmount"
                :disabled="orderDetail.afterSalesType != 'COMPENSATION_REFUND'"
                style="width: 240px"
                clearable
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item
            label=""
            labelClassName="else-form"
            v-if="
              orderDetail.afterSalesType != 'REFUND_MONEY_GOODS' &&
              orderDetail.afterSalesType != 'EXCHANGE_GOOD' &&
              orderDetail.afterSalesType
            "
          >
            <el-form-item
              label="已给用户退款:"
              prop="hasRefundUser"
              :rules="[
                {
                  required: true,
                  message: '请选择已给用户退款',
                  trigger: 'change',
                },
              ]"
            >
              <el-select
                filterable
                v-model="orderDetail.hasRefundUser"
                placeholder="请选择"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in whetherShippingList2"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item
            label=""
            labelClassName="else-form"
            v-if="
              orderDetail.afterSalesType == 'REFUND_MONEY_GOODS' ||
              (orderDetail.afterSalesType == 'EXCHANGE_GOOD' &&
                orderDetail.afterSalesType)
            "
          >
            <el-form-item
              label="退货物流单号:"
              prop="returnLogisticsExpressNo"
              :rules="[
                {
                  required: true,
                  message: '请输入退货物流单号',
                  trigger: 'change',
                },
              ]"
            >
              <el-input
                v-model.trim="orderDetail.returnLogisticsExpressNo"
                style="width: 240px"
                clearable
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item
            label=""
            labelClassName="else-form"
            v-if="
              orderDetail.afterSalesType == 'REFUND_MONEY_GOODS' ||
              (orderDetail.afterSalesType == 'EXCHANGE_GOOD' &&
                orderDetail.afterSalesType)
            "
          >
            <el-form-item
              label="退货物流公司:"
              prop="returnLogisticsExpressComName"
              :rules="[
                {
                  required: true,
                  message: '请选择退货物流公司',
                  trigger: 'change',
                },
              ]"
            >
              <el-select
                filterable
                v-model="orderDetail.returnLogisticsExpressComName"
                placeholder="请选择"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in returnLogisticsCompanyList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="" labelClassName="else-form">
            <el-form-item
              label="对接客服人员:"
              prop="customerService"
              :rules="[
                {
                  required: true,
                  message: '请输入对接客服人员',
                  trigger: 'change',
                },
              ]"
            >
              <el-input
                v-model.trim="orderDetail.customerService"
                style="width: 240px"
                clearable
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="" labelClassName="else-form">
            <el-form-item
              label="售后申请时间:"
              prop="auditTime"
              :rules="[
                {
                  required: true,
                  message: '请选择售后申请时间',
                  trigger: 'change',
                },
              ]"
            >
              <el-date-picker
                v-model="orderDetail.auditTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                style="width: 240px"
                placeholder="请选择售后申请时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="" labelClassName="else-form">
            <el-form-item
              label="备注:"
              prop="remark"
              class="remarks-class"
              :rules="[
                { required: true, message: '请输入备注', trigger: 'change' },
              ]"
            >
              <el-input
                v-model.trim="orderDetail.remark"
                clearable
                type="textarea"
                maxlength="100"
                placeholder="填写备注，不超过100个字"
                resize="none"
                rows="3"
              />
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <el-card
        shadow="never"
        class="box-card box-card1"
        v-if="
          orderDetail.afterSalesType == 'REFUND_MONEY_GOODS' ||
          orderDetail.afterSalesType == 'EXCHANGE_GOOD'
        "
      >
        <div slot="header">
          <h3><span></span>订单发货列表</h3>
        </div>
        <el-table :data="orderDetail.deliveryInfos" border stripe class="w100">
          <el-table-column
            min-width="160"
            prop="deliveryCode"
            label="发货商品信息"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.skuNo }}/{{ scope.row.skuName }}
            </template>
          </el-table-column>
          <el-table-column prop="num" label="发货件数" align="center" />
          <el-table-column
            prop="uniqueCodes"
            label="发货商品串码"
            align="center"
          />
          <el-table-column prop="deliveryCode" label="发货单号" align="center">
            <template slot-scope="scope">
              {{ scope.row.deliveryCode
              }}<i
                class="el-icon-document-copy"
                @click="copyText(scope.row.deliveryCode)"
              ></i>
            </template>
          </el-table-column>
          <el-table-column label="发货仓库" align="center" prop="warehouseName">
          </el-table-column>
          <el-table-column
            label="仓库发货"
            align="center"
            prop="hasWarehouseDelivery"
          >
            <template slot-scope="scope">
              {{ scope.row.hasWarehouseDelivery == 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column
            label="电商平台发货"
            align="center"
            prop="uniqueCodes"
          >
            <template slot-scope="scope">
              {{ scope.row.hasPlatformDelivery == 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column label="发货时间" align="center" prop="deliveryTime">
          </el-table-column>
          <!-- <el-table-column label="是否代发" align="center" prop="uniqueCodes">
        </el-table-column>
        <el-table-column label="代发供货商" align="center" prop="supplierName">
        </el-table-column> -->
          <el-table-column label="物流信息" align="center" prop="uniqueCodes">
            <template slot-scope="scope">
              <div>{{ scope.row.expressComName }}</div>
              <div @click="showEx(scope.row)" class="link-ex">
                {{ scope.row.expressNo
                }}<i
                  class="el-icon-document-copy"
                  @click.stop="copyText(scope.row.expressNo)"
                ></i>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card
        shadow="never"
        class="box-card box-card1"
        v-if="
          orderDetail.afterSalesType &&
          orderDetail.afterSalesType != 'COMPENSATION_REFUND'
        "
      >
        <div slot="header">
          <h3><span></span>售后商品申请</h3>
        </div>
        <el-table :data="orderDetail.orderItems" border stripe class="w100">
          <el-table-column prop="goodName" min-width="160" label="售后商品信息">
            <template slot-scope="scope">
              {{ scope.row.skuNo }}/{{ scope.row.skuName }}
            </template>
          </el-table-column>
          <el-table-column prop="num" label="销售数量(件)" align="center" />
          <el-table-column prop="costPrice" label="成本价(元)" align="center">
            <template slot-scope="scope">
              ￥{{ $numFormat(scope.row.costPrice) }}
            </template>
          </el-table-column>
          <el-table-column prop="salePrice" label="销售单价(元)" align="center">
            <template slot-scope="scope">
              ￥{{ $numFormat(scope.row.salePrice) }}
            </template>
          </el-table-column>
          <el-table-column
            label="销售金额(元)"
            align="center"
            prop="actualAmount"
          >
            <template slot-scope="scope">
              ￥{{
                $numFormat((scope.row.salePrice * scope.row.num).toFixed(2))
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="实付单价(元)"
            align="center"
            prop="actualPrice"
          >
            <template slot-scope="scope">
              ￥{{ $numFormat(scope.row.actualPrice) }}
            </template>
          </el-table-column>
          <el-table-column
            label="实付金额(元)"
            align="center"
            prop="actualAmount"
          >
            <template slot-scope="scope">
              ￥{{ $numFormat(scope.row.actualAmount) }}
            </template>
          </el-table-column>
          <el-table-column
            label="已申请售后数量"
            align="center"
            prop="alreadyAfterSalesNum"
          >
          </el-table-column>
          <el-table-column
            label="已申请售后金额"
            align="center"
            prop="alreadyAfterSalesAmount"
          >
            <template slot-scope="scope">
              ￥{{ $numFormat(scope.row.alreadyAfterSalesAmount) }}
            </template>
          </el-table-column>
          <el-table-column
            label="申请售后数量(件)"
            align="center"
            min-width="140"
            prop="requestedRefundQuantity"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.requestedRefundQuantity"
                :max="scope.row.requestedRefundQuantityCopy"
                @input="value=>changeNum(value, scope.row)"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="申请售后金额(元)"
            align="center"
            min-width="140"
            prop="requestedRefundAmount"
            v-if="orderDetail.afterSalesType!='EXCHANGE_GOOD'"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.requestedRefundAmount"
                :max="scope.row.requestedRefundAmountCopy"
                :class="(scope.row.requestedRefundAmount< (scope.row.actualPrice*scope.row.requestedRefundQuantity)) ? 'color-r': ''"
                @input="value=>changeAmount(value, scope.row)"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="120"
            align="center"
            prop="status"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="exChangeGoods(scope.row)"
                v-show="orderDetail.afterSalesType == 'EXCHANGE_GOOD'"
                >换货</el-button
              >
              <el-button
                size="mini"
                type="text"
                @click="deleteFnc(scope.$index)"
                v-if="
                  orderDetail.orderItems && orderDetail.orderItems.length > 1
                "
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="notice-box">
          <div class="notice-left">
            <!-- <i class="el-icon-bell"></i>
            申请售后的单件商品售后金额小于用户实付单价，需要流转到财务审核 -->
          </div>
          <div>
            <span style="margin-right: 10px">总售后件数：{{ totalNum }}件</span>
            <span v-show="orderDetail.afterSalesType != 'EXCHANGE_GOOD'">总售后金额：{{ `￥${$numFormat(totalAmount)}` }}元</span>
          </div>
        </div>
        <el-descriptions
          :column="2"
          labelClassName="all-class"
          v-if="
            orderDetail.afterSalesType == 'REFUND_MONEY_GOODS' ||
            orderDetail.afterSalesType == 'EXCHANGE_GOOD'
          "
        >
          <el-descriptions-item label="" labelClassName="else-form">
            <el-form-item label="是否代发:" prop="hasSupplier">
              <el-select
                filterable
                v-model="orderDetail.hasSupplier"
                placeholder="请选择"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in whetherShippingList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item
            label="代发供货商"
            v-if="
              orderDetail.afterSalesType == 'REFUND_MONEY_GOODS' ||
              (orderDetail.afterSalesType == 'EXCHANGE_GOOD' &&
                orderDetail.hasSupplier == '1')
            "
          >
            <el-select
              filterable
              v-model="orderDetail.supplierCode"
              placeholder="请选择"
              clearable
              size="mini"
              style="width: 240px"
              @change="supplierChange"
            >
              <el-option
                v-for="dict in shippingSupplierList"
                :key="dict.supplierCode"
                :label="dict.supplierName"
                :value="dict.supplierCode"
              />
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item
            label=""
            labelClassName="else-form"
            v-if="
              orderDetail.afterSalesType == 'REFUND_MONEY_GOODS' ||
              (orderDetail.afterSalesType == 'EXCHANGE_GOOD' &&
                orderDetail.hasSupplier == '1')
            "
          >
            <el-form-item
              label="退货包裹寄回地:"
              label-width="130px"
              :rules="[
                {
                  required: true,
                  message: '请选择退货包裹寄回地',
                  trigger: 'change',
                },
              ]"
              prop="refundAddressType"
            >
              <el-select
                filterable
                v-model="orderDetail.refundAddressType"
                placeholder="请选择"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in sendBackLandList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>

        <el-table
          :data="orderDetail.exchangeItems"
          v-show="orderDetail.afterSalesType == 'EXCHANGE_GOOD'"
          border
          stripe
          class="w100"
        >
          <el-table-column prop="skuName" min-width="160" label="换货商品信息">
            <template slot-scope="scope">
              {{ scope.row.skuNo }}/{{ scope.row.skuName }}
            </template>
          </el-table-column>
          <el-table-column prop="cost" label="成本价" align="center">
            <template slot-scope="scope">
              ￥{{ $numFormat(scope.row.cost) }}
            </template>
          </el-table-column>
          <el-table-column prop="num" label="换货数量(件)" align="center" />
          <el-table-column
            prop="diffPrice"
            label="补差价金额(元)"
            align="center"
          >
            <template slot-scope="scope">
              ￥{{ $numFormat(scope.row.diffPrice) }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="90"
            align="center"
            prop="status"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="deleteRow(scope.row, scope.$index)"
                type="text"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div
          class="notice-box"
          v-show="orderDetail.afterSalesType == 'EXCHANGE_GOOD'"
        >
          <div class="notice-left">
            <i class="el-icon-bell"></i>
            申请换货的商品成本价低于原商品成本价{{
              (orderDetail.minRate * 100).toFixed(0)
            }}%，需要流转到财务审核
          </div>
          <div>
            <span style="margin-right: 10px"
              >总补差价金额：{{ `￥${$numFormat(diffPrice)}` }}元</span
            >
          </div>
        </div>
      </el-card>
      <div class="btns-box">
        <el-button @click="goBack">取消</el-button>
        <el-button
          type="primary"
          :loading="submitOrderLoading"
          @click="submitOrder"
          >提交</el-button
        >
      </div>
    </el-form>

    <el-dialog
      title="输入换货商品编码"
      :visible.sync="confirmReview"
      width="550px"
      append-to-body
      :center="true"
    >
      <el-form
        ref="goodsFrom"
        size="small"
        :model="goodsFrom"
        label-width="150px"
      >
        <el-form-item label="输入换货商品编码:" prop="remark">
          <LoadMoreSelect
            :skuNo="goodsFrom.skuNo"
            @queryParams="(val) => (goodsFrom.skuNo = val)"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="confirmReview = false">取消</el-button>
        <el-button type="primary" @click="saveGoods" :loading="saveGoodsLoading"
          >确认</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="物流信息"
      width="600px"
      :visible.sync="showDeliveryExpressDialog"
      top="50px"
      :center="true"
      class="abdialog"
    >
      <el-timeline>
        <el-timeline-item
          placement="top"
          v-for="(express, index) in expressTimeLine"
          :key="index"
          type="success"
          :timestamp="express.time"
        >
          <el-card>
            <p style="margin: 0">{{ express.context }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="showDeliveryExpressDialog = false"
          >返回</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { orderAdd, afterSalesOrderDetail, orderQuery } from "@/api/afterSalesOrder/index";
import { getList } from "@/api/goods/index";
import { expressInfo, queryJulianSupplier } from "@/api/order/index";
import LoadMoreSelect from "@/components/LoadMoreSelect/index";

export default {
  name: "addAsOrder",
  props: {},
  components: {
    LoadMoreSelect,
  },
  data() {
    return {
      goodsFrom: {
        skuNo: "",
      },
      submitOrderLoading: false,
      confirmReview: false,
      saveGoodsLoading: false,
      totalNum: 0,
      totalAmount: 0,
      afterSalesResonsList: [
        { label: "7天无理由", value: "SEVEN_DAY_RETURN" },
        { label: "质量问题", value: "QUALITY_ISSUES" },
        { label: "换货", value: "EXCHANGE_GOOD" },
        { label: "退差价", value: "RETURN_PRICE_DIFFERENCE" },
        { label: "退运费", value: "RETURN_SHIPPING_FEE" },
      ],
      refundTypeList: [
        { label: "正常售后退款", value: "NORMAL_RETURN" },
        { label: "激活返现", value: "ACTIVATE_CASHBACK" },
        { label: "报备特殊补偿", value: "SPECIAL_COMPENSATION" },
        { label: "售后补款", value: "AFTER_SALES_COMPENSATION" },
        { label: "体验补偿", value: "TRIAL_COMPENSATION" },
      ],
      returnLogisticsCompanyList: [
        { label: "顺丰速运", value: "SF_EXPRESS" },
        { label: "圆通速递", value: "YTO_EXPRESS" },
        { label: "中通快递", value: "ZTO_EXPRESS" },
        { label: "申通快递", value: "STO_EXPRESS" },
      ],
      applicationTimeList: [],
      sendBackLandList: [
        { label: "自有仓库", value: "SELF_WAREHOUSE" },
        { label: "代发供货商", value: "SUPPLIER" },
      ],
      orderDetail: {
        exchangeItems: [],
        afterSalesNo: "",
        afterSalesPlatformCode: '',
        afterSalesStatus: "",
        afterSalesType: "",
        auditTime: "",
        changeItems: [],
        customerService: "",
        deliveryStatus: "",
        erpCode: "",
        hasRefundUser: "",
        hasSupplier: "",
        items: [],
        platformCode: "",
        platformName: "",
        platformNo: "",
        refundAddressType: "",
        refundAmount: "",
        refundExpressComName: "",
        refundExpressNo: "",
        refundReason: "",
        refundType: "",
        remark: "",
        returnLogisticsExpressComName: "",
        returnLogisticsExpressNo: "",
        shopCode: "",
        shopName: "",
        supplierCode: "",
        supplierName: "",
        userMobile: "",
        userName: "",
        vipName: "",
        orderItems: [],
      },
      diffPrice: 0,
      shippingSupplierList: [],
      orderTypeList: [
        // { label: "极速退款", value: "FIRST_REFUND" },
        { label: "仅退款", value: "ONLY_REFUND" },
        { label: "退货退款", value: "REFUND_MONEY_GOODS" },
        { label: "换货", value: "EXCHANGE_GOOD" },
        { label: "补偿退款", value: "COMPENSATION_REFUND" },
      ],
      whetherShippingList: [
        { label: "是聚链代发", value: "1" },
        { label: "不是聚链代发", value: "0" },
      ],
      whetherShippingList2: [
        { label: "是", value: 1 },
        { label: "否", value: 0 },
      ],
      orderStatusList2: [
        { label: "草稿", value: "-2" },
        { label: "待制单审核", value: "-1" },
        { label: "待平台风控审核", value: "10" },
        { label: "待审单", value: "0" },
        { label: "待配货", value: "4" },
        { label: "待发货", value: "1" },
        { label: "已发货", value: "2" },
        { label: "已签收", value: "5" },
        { label: "已取消", value: "3" },
      ],
      orderStatusList: [
        { label: "待客服主管复核", value: "AWAITING_SUPERVISOR_APPROVAL" },
        { label: "待接收退货包裹", value: "PENDING_RETURN_PACKAGES" },
        { label: "部分退货", value: "PART_SIGN" },
        { label: "待财务复核", value: "AWAITING_FINANCE_APPROVAL" },
        { label: "待换货", value: "PENDING_CHANGE" },
        { label: "已换货", value: "CONFIRM_SEND_CALLBACK" },
        { label: "待回传发货信息", value: "CONFIRM_SEND" },
        { label: "待退款", value: "PENDING_REFUNDS" },
        { label: "已退款/已处理", value: "REFUNDED" },
        { label: "打回退货包裹", value: "REJECT_PACKAGE" },
        { label: "取消", value: "CANCEL" },
      ],
      expressTimeLine: [],
      firstTime: true,
      exRow: {},
      afterSalesNo: "",
      editStatus: false,
      showDeliveryExpressDialog: false,
      deliveryStatusList: [
        { label: "未发货", value: 0 },
        { label: "部分发货", value: 1 },
        { label: "全部发货", value: 2 },
      ],
    };
  },

  created() {
    this.getSupplier();
    if (this.$route.query.afterSalesNo) {
      this.afterSalesNo = this.$route.query.afterSalesNo;
      this.editStatus = true;
      this.getDetail();
    } else {
      this.editStatus = false;
      const data = sessionStorage.getItem("addAsOrder-data");
      if (JSON.parse(data)) {
        
        Object.assign(this.$data.orderDetail, this.$options.data().orderDetail);
        this.orderDetail = Object.assign(this.orderDetail, JSON.parse(data));
        this.itemFormat();
        this.changeNum();
        this.changeAmount();
      }
      this.firstTime = false;
    }
  },
  activated() {
    if (this.$route.query.afterSalesNo) {
      if (this.afterSalesNo != this.$route.query.afterSalesNo) {
        this.getDetail();
      }
    } else {
      this.editStatus = false;
      if (this.firstTime) {
        return false;
      }
      const data = sessionStorage.getItem("addAsOrder-data");
      const cache_new = sessionStorage.getItem("addAsOrder-new");
      if(cache_new=='true'){
          sessionStorage.setItem("addAsOrder-new", 'false');
          this.orderDetail = {
            exchangeItems: [],
            afterSalesNo: "",
            afterSalesPlatformCode: '',
            afterSalesStatus: "",
            afterSalesType: "",
            auditTime: "",
            changeItems: [],
            customerService: "",
            deliveryStatus: "",
            erpCode: "",
            hasRefundUser: "",
            hasSupplier: "",
            items: [],
            platformCode: "",
            platformName: "",
            platformNo: "",
            refundAddressType: "",
            refundAmount: "",
            refundExpressComName: "",
            refundExpressNo: "",
            refundReason: "",
            refundType: "",
            remark: "",
            returnLogisticsExpressComName: "",
            returnLogisticsExpressNo: "",
            shopCode: "",
            shopName: "",
            supplierCode: "",
            supplierName: "",
            userMobile: "",
            userName: "",
            vipName: "",
            orderItems: [],
          }
          this.$nextTick(()=>{
            this.$refs.orderDetail.clearValidate();
          });
      }
      if (
        JSON.parse(data) && JSON.parse(data).erpCode!= this.orderDetail.erpCode
      ) {
        Object.assign(this.$data.orderDetail, this.$options.data().orderDetail);
        this.orderDetail = Object.assign(this.orderDetail, JSON.parse(data));
        this.itemFormat();
        this.$nextTick(()=>{
          this.$refs.orderDetail.clearValidate();
        });
        this.changeNum();
        this.changeAmount();
      }
    }
  },
  methods: {
    getSupplier() {
      queryJulianSupplier().then((res) => {
        if (res.status == 200) {
          this.shippingSupplierList = res.data;
        }
      });
    },
    getDetail() {
      afterSalesOrderDetail({
        afterSalesPlatformCode: this.afterSalesNo,
      }).then((res) => {
        if (res.status == 200) {
          res.data.orderItems = res.data.items;
          res.data.exchangeItems = res.data.changeItems;
          this.orderDetail = Object.assign(this.orderDetail, res.data);

          this.orderDetail.orderItems.forEach((item, index) => {
            this.$set(
              this.orderDetail.orderItems[index],
              "requestedRefundAmountCopy",
              Number(item.actualAmount - item.alreadyAfterSalesAmount)
            );
            this.$set(
              this.orderDetail.orderItems[index],
              "requestedRefundQuantityCopy",
              Number(item.num - item.alreadyAfterSalesNum)
            );
          });

          this.changeNum();
          this.changeAmount();
          orderQuery({
            erpCode: res.data.erpCode,
            platformCode: res.data.platformCode,
          }).then(res=>{
              if(res.status==200){
                this.orderDetail.orderStatus = res.data.orderStatus;
                this.orderDetail.deliveryStatus = res.data.deliveryStatus;
                this.orderDetail.userMobile = res.data.userMobile;
                this.orderDetail.userName = res.data.userName;
                this.orderDetail.orderPrice = res.data.orderPrice;
                this.orderDetail.payPrice = res.data.payPrice;
                this.orderDetail.deliveryInfos = res.data.deliveryInfos;
              }
          });
        }
      });
     
    },
    deleteRow(row, index) {
      this.$confirm("是否确定删除该商品记录？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.orderDetail.exchangeItems.splice(index, 1);
          this.diffPrice = 0;
          this.orderDetail.exchangeItems.forEach((item) => {
            this.diffPrice += Number(item.diffPrice);
          });
          this.diffPrice = this.diffPrice.toFixed(2);
        })
        .catch(() => {});
      
    },
    filterStatus(value) {
      const data = this.orderStatusList2.find((item) => {
        return value == item.value;
      });
      return data ? data.label : "";
    },
    supplierChange(value) {
      const data = this.shippingSupplierList.find((item) => {
        return value == item.supplierCode;
      });
      this.orderDetail.supplierName = data.supplierName || "";
    },
    itemFormat() {
      this.orderDetail.orderItems.forEach((item, index) => {
        this.$set(
          this.orderDetail.orderItems[index],
          "requestedRefundAmount",
          Number(item.actualAmount - item.alreadyAfterSalesAmount)
        );
        this.$set(
          this.orderDetail.orderItems[index],
          "requestedRefundAmountCopy",
          Number(item.actualAmount - item.alreadyAfterSalesAmount)
        );
        this.$set(
          this.orderDetail.orderItems[index],
          "requestedRefundQuantity",
          Number(item.num - item.alreadyAfterSalesNum)
        );
        this.$set(
          this.orderDetail.orderItems[index],
          "requestedRefundQuantityCopy",
          Number(item.num - item.alreadyAfterSalesNum)
        );
      });
    },
    showEx(row, item) {
      this.showDeliveryExpressDialog = true;
      expressInfo({
        expressNo: item,
        orderId: row.orderId,
      }).then((res) => {
        if (res.status == 200) {
          if (res.data) {
            this.expressTimeLine = res.data;
          } else {
            this.expressTimeLine = [{ time: "", context: "暂无物流信息" }];
          }
        }
      });
    },
    copyText(text) {
      window.navigator.clipboard
        .writeText(text)
        .then(() => {
          // this.$message.success("复制成功");
          this.$message({
            message: "复制成功",
            type: "success",
            customClass: "phone-message",
            center: true,
          });
        })
        .catch((error) => {
          // this.$message.warning("复制失败");
          this.$message({
            message: "复制失败",
            type: "warning",
            customClass: "phone-message",
            center: true,
          });
        });
    },
    typeChange(value) {
      this.orderDetail.exchangeItems = [];
      if (value != "COMPENSATION_REFUND") {
        this.orderDetail.refundAmount = "";
      }
    },
    submitOrder() {
      this.$refs.orderDetail.validate((valid, obj) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.orderDetail));
          let status = false,status2 = false,status3 = false,itemObj=null;
          if (data.orderItems && data.orderItems.length > 0) {
            data.items = data.orderItems.map((item) => {
              if(data.afterSalesType=='EXCHANGE_GOOD'||data.afterSalesType=='REFUND_MONEY_GOODS'){
                if(item.requestedRefundQuantity<=0){
                  status = true;
                }
              } 
              if(item.requestedRefundQuantity > item.requestedRefundQuantityCopy || item.requestedRefundAmount > item.requestedRefundAmountCopy){
                status2 = true;
              }
              if((item.requestedRefundAmount/item.requestedRefundQuantity) > item.actualPrice){
                status3 = true;
                itemObj = item;
              }
              return {
                requestedRefundAmount: data.afterSalesType=='EXCHANGE_GOOD'?'':item.requestedRefundAmount,
                requestedRefundQuantity: item.requestedRefundQuantity,
                skuNo: item.skuNo,
              };
            });
          } else {
            data.items = [];
          }
          if((data.afterSalesType=='REFUND_MONEY_GOODS'||data.afterSalesType=='EXCHANGE_GOOD')&&status){
            this.$message.warning('退货退款、换货的申请售后数量必须大于0');
            return false;
          }

          if(status2){
            this.$message.warning('申请数量：申请售后数量不能大于销售数量减去已申请售后数量，申请售后金额：申请售后金额不能大于实付金额减去已申请售后金额');
            return false;
          }
          if((data.afterSalesType=='REFUND_MONEY_GOODS'||data.afterSalesType=='ONLY_REFUND')&&status3){
            this.$message.warning(`${itemObj.skuName}商品单件申请售后金额不能大于实付单价${itemObj.actualPrice}元`);
            return false;
          }
          // refundAddressType
          if (
            data.afterSalesType == "EXCHANGE_GOOD" &&
            data.exchangeItems.length == 0
          ) {
            this.$message.warning("请选择换货商品");
            return false;
          }
          if (
            data.afterSalesType == "ONLY_REFUND" ||
            data.afterSalesType == "COMPENSATION_REFUND"
          ) {
            data.refundAddressType = "UNKNOWN";
            data.returnLogisticsExpressNo = "UNKNOWN";
            data.returnLogisticsExpressComName = "UNKNOWN";
          } else {
            if (!data.refundAddressType) {
              data.refundAddressType = "UNKNOWN";
            }
            if (!data.returnLogisticsExpressNo) {
              data.returnLogisticsExpressNo = "UNKNOWN";
            }
            if (!data.returnLogisticsExpressComName) {
              data.returnLogisticsExpressComName = "UNKNOWN";
            }
          }

          if (this.$route.query.afterSalesNo) {
            data.needUpdate = 1;
          }

          this.submitOrderLoading = true;
          orderAdd(data)
            .then((res) => {
              if (res.status == 200) {
                if(data.needUpdate == 1){
                  this.$message.success("编辑成功");
                }else{
                  this.$message.success("新增成功");
                }
                this.$tab.closeOpenPage('/afterSaleOrder/index');
              }
              this.submitOrderLoading = false;
            })
            .catch((_) => {
              this.submitOrderLoading = false;
            });
        } else {
          this.$message.error(obj[Object.keys(obj)[0]][0].message);
        }
      });
    },
    exChangeGoods(row) {
      let num = 0,
        rowNum = 0;
      this.orderDetail.exchangeItems.forEach((item) => {
        num += Number(item.num);
        if (item.sourceSkuNo == row.skuNo) {
          rowNum += Number(item.num);
        }
      });
      if (rowNum >= row.requestedRefundQuantity) {
        this.$message.warning("换货商品数超过售后件数");
        return false;
      }
      if (num >= this.totalNum) {
        this.$message.warning("换货商品数超过总售后件数");
        return false;
      }
      this.exRow = row;
      this.goodsFrom.skuNo = "";
      this.confirmReview = true;
    },
    saveGoods() {
      if (!this.goodsFrom.skuNo) {
        this.$message.warning("请输入商品编码");
        return false;
      }
      this.saveGoodsLoading = true;
      getList({ sku: this.goodsFrom.skuNo })
        .then((res) => {
          if (res.rows.length != 0) {
            console.log(res.rows);
            res.rows.forEach((item) => {
              let status = true;
              this.orderDetail.exchangeItems.forEach((it) => {
                if (it.skuNo == item.sku) {
                  status = false;
                }
              });
              if (status) {
                this.orderDetail.exchangeItems.push({
                  skuNo: item.sku,
                  skuName: item.skuName,
                  num: this.exRow.requestedRefundQuantity,
                  cost: item.costPrice || 0,
                  sourceSkuNo: this.exRow.skuNo,
                  diffPrice: Number(
                    (Number(item.costPrice) - Number(this.exRow.costPrice)) *
                      Number(this.exRow.requestedRefundQuantity)
                  ).toFixed(2),
                });

                this.diffPrice = (
                  Number(this.diffPrice) +
                  (Number(item.costPrice) - Number(this.exRow.costPrice)) *
                    Number(this.exRow.requestedRefundQuantity)
                ).toFixed(2);

                this.changeNum();
                this.changeAmount();
              } else {
                this.$message.warning("存在相同商品");
              }
            });
          }
          console.log(this.confirmReview);
          this.confirmReview = false;
          this.saveGoodsLoading = false;
        })
        .catch((err) => {
          this.saveGoodsLoading = false;
        });
    },
    changeNum(value, row) {
      if (value && (Number(value) > row.requestedRefundQuantityCopy)){
        this.$set(row, 'requestedRefundQuantity', row.requestedRefundQuantityCopy);
        // return false;
      }
      this.totalNum = 0;
      this.orderDetail.orderItems.forEach((item) => {
        this.totalNum += Number(item.requestedRefundQuantity);
      });
    },
    changeAmount(value, row) {
      if (value && (Number(value) > row.requestedRefundAmountCopy)){
        this.$set(row, 'requestedRefundAmount', row.requestedRefundAmountCopy);
        // return false;
      }
      this.totalAmount = 0;
      this.orderDetail.orderItems.forEach((item) => {
        this.totalAmount += Number(item.requestedRefundAmount);
      });
      this.totalAmount = this.totalAmount.toFixed(2);
    },
    typefilter(value, list) {
      const data = list.find((item) => {
        return item.value == value;
      });
      return data ? data.label : "";
    },
    deleteFnc(index) {
      this.$confirm("是否确定删除该商品记录？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.orderDetail.orderItems.splice(index, 1);
        })
        .catch(() => {});
    },
  },

  computed: {},

  mounted() {},

  watch: {},
};
</script>
<style lang='scss' scoped>
.new-after-sales-order {
  height: 100%;
  overflow-y: scroll;
  overflow-x: hidden;
  padding: 30px;
}
.box-card {
  margin-bottom: 16px;
}
.box-card1 {
  margin-top: 16px;
}
.main-container {
  .minHeight {
    // min-height: 330px;
    flex: 1;
  }
  .box-card2 {
    height: 95%;
  }
  .price-container {
    width: 20%;
    float: right;
    margin-top: 10px;
    div {
      margin-bottom: 8px;
      span {
        color: #f56c6c;
      }
    }
  }
}
h3 {
  font-weight: bold;
  display: flex;
  align-items: center;
  margin: 4px 0;
  // margin-top: 36px;
  span {
    display: block;
    width: 2px;
    height: 14px;
    background: #f56c6c;
    margin-right: 6px;
  }
}
.color-r {
  color: #f56c6c;
}
.color-y {
  color: #fbc576;
}
.mini-form {
  .el-form-item {
    margin-bottom: 0;
    margin-right: 0;
  }
}
.remarks-class {
  width: 100%;
  display: flex;
  ::v-deep .el-form-item__content {
    flex: 1;
  }
}
.notice-box {
  display: flex;
  justify-content: space-between;
  margin: 8px 0;
  .notice-left {
    color: #ffba00;
  }
}
.btns-box {
  text-align: center;
  margin: 16px 0;
}
.link-ex {
  cursor: pointer;
  color: #409eff !important;
}
.color-g {
  color: #67c23a;
}
</style>
<style lang="scss">
.new-after-sales-order {
  .el-descriptions--medium:not(.is-bordered) .el-descriptions-item__cell {
    padding-bottom: 16px;
  }
  .el-timeline-item__content {
    .el-card__body {
      padding: 0 16px;
    }
  }
  .el-descriptions-item__label {
    display: flex;
    align-items: center;
  }
  .all-class {
    width: 120px;
    padding-right: 12px;
  }
  .else-form {
    margin-right: 0 !important;
    &::after {
      content: "" !important;
    }
  }
  .el-descriptions-item {
    line-height: 28px !important;
  }
  .el-form-item__label {
    font-size: 14px !important;
  }
  .color-r {
    .el-input__inner {
      color: #f56c6c;
    }
  }
  .el-icon-document-copy {
    margin-left: 4px;
  }
}
.abdialog {
  .el-dialog__body {
    max-height: 70vh;
    overflow-y: scroll;
  }
}
</style>