<template>
  <div class="order-content">
      <div class="order-status" v-if="afterSales!=null" >
          <el-steps  :active="afterSales.status==4?afterSales.status+1:afterSales.status" align-center>
            <el-step title="待审核(24小时自动审核)"></el-step>
            <el-step title="平台已审核等待用户发货"></el-step>
            <el-step title="用户已发货待仓库审核"></el-step>
            <el-step title="财务审核"></el-step>
            <el-step title="退款成功"></el-step>
          </el-steps>
      </div>
      <div v-if="afterSales!=null">
      <el-card shadow="never" style="margin-top: 15px">
        <div class="operate-container">
          <span style="margin-left: 20px" class="color-danger">售后状态：
            <el-tag prop="status" v-for="(item, index) in salesStatusOptions"    v-if="afterSales.salesStatus==item.dictValue">{{item.dictLabel}}</el-tag>
            <el-tag v-if="afterSales.erpExceptionStatus === 1" type="danger" size="mini" style="margin-left: 8px;">erp订单状态异常</el-tag>
          </span>
          <div class="operate-button-container"  >
            <el-button size="mini"  v-hasPermi="['store:storeAfterSales:edit']" v-show="afterSales.salesStatus==0&&afterSales.status===1"  @click="addDelivery">编辑物流</el-button>
            <el-button size="mini"  v-hasPermi="['store:storeAfterSales:edit']" v-show="afterSales.salesStatus==0&&afterSales.status===0&&afterSales.erpExceptionStatus===1" @click="handleConfirmErpStatus">ERP订单状态确认</el-button>
            <el-button size="mini"  v-hasPermi="['store:storeAfterSales:audit1']" v-show="afterSales.salesStatus==0&&afterSales.status===0" @click="handleAudit1">平台审核</el-button>
            <el-button size="mini"  v-hasPermi="['store:storeAfterSales:audit2']" v-show="afterSales.salesStatus==0&&afterSales.status===2" @click="handleAudit2">仓库审核</el-button>
            <el-button size="mini"  v-hasPermi="['store:storeAfterSales:refund']" @click="handleRefund"  v-show="afterSales.salesStatus==0&&afterSales.status===3">财务审核</el-button>
            <el-button size="mini"  v-hasPermi="['store:storeAfterSales:cancel']" @click="cancel"  v-show="afterSales.salesStatus==0">撤销</el-button>
            <el-button size="mini"  @click="showOrder">查看订单</el-button>
         </div>
        </div>

        <div style="margin: 20px 0px" >
          <span class="font-small">基本信息</span>
        </div>
        <el-descriptions   :column="4" border  >
            <el-descriptions-item label="订单编号"  >
                <span v-if="afterSales!=null">
                  {{afterSales.orderCode}}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="会员"  >
                <span v-if="user!=null">
                  {{user.nickname}}({{user.phone}})
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="退款金额"  >
                <span v-if="afterSales!=null">
                  {{afterSales.refundAmount}}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="实付金额"  >
                <span v-if="order!=null && order.payMoney!=null">
                  ￥{{ Number(order.payMoney).toFixed(2) }}
                </span>
                <span v-else-if="order!=null && order.payPrice!=null">
                  ￥{{ Number(order.payPrice).toFixed(2) }}
                </span>
                <span v-else>￥0.00</span>
            </el-descriptions-item>
            <el-descriptions-item label="优惠券"  >
                <span v-if="order!=null && order.couponPrice!=null">
                  ￥{{ Number(order.couponPrice).toFixed(2) }}
                </span>
                <span v-else>￥0.00</span>
            </el-descriptions-item>
            <el-descriptions-item label="运费"  >
                <span v-if="order!=null">
                  {{order.payPostage}}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="申请类型"  >
                <span v-if="afterSales!=null">
                  <el-tag  v-for="(item, index) in serviceTypeOptions"    v-if="afterSales.serviceType==item.dictValue" >{{item.dictLabel}}</el-tag>
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="申请原因"  >
                <span v-if="afterSales!=null">
                  {{afterSales.reasons}}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="说明"  >
                <span v-if="afterSales!=null">
                  {{afterSales.explains}}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="状态"  >
                <span v-if="afterSales!=null">
                  <el-tag   v-for="(item, index) in statusOptions"    v-if="afterSales.status==item.dictValue" >{{item.dictLabel}}</el-tag>
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="售后状态"  >
                <span v-if="afterSales!=null">
                  <el-tag  v-for="(item, index) in salesStatusOptions"    v-if="afterSales.salesStatus==item.dictValue" >{{item.dictLabel}}</el-tag>
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="财务审核原因"  v-if="afterSales!=null && afterSales.status >= 4">
                <span>
                  {{afterSales.auditReasonName}}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="财务审核备注"  v-if="afterSales!=null && afterSales.status >= 4">
                <span>
                  {{afterSales.auditRemark}}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="售后一级原因" v-if="afterSales!=null">
              <span>{{ afterSales.reasonValue1 || afterSales.reasonLevel1Text || '-' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="售后二级原因" v-if="afterSales!=null">
              <span>{{ afterSales.reasonValue2 || afterSales.reasonLevel2Text || '-' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="ERP异常状态" v-if="afterSales!=null">
              <span>{{ erpExceptionStatusText(afterSales.erpExceptionStatus) }}</span>
            </el-descriptions-item>

        </el-descriptions>
        <div style="margin: 20px 0px">
          <span class="font-small">收货信息</span>
        </div>
        <el-descriptions   :column="4" border  >
            <el-descriptions-item label="收货人"  >
                <span v-if="afterSales!=null">
                  {{afterSales.consignee}}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="收货人"  >
                <span v-if="afterSales!=null">
                  {{afterSales.consignee}}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="手机号码"  >
                <span v-if="afterSales!=null">
                  {{afterSales.phoneNumber}}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="收货地址"  >
                <span v-if="afterSales!=null">
                  {{afterSales.address}}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="快递公司"  >
                <span v-if="afterSales!=null">
                  {{afterSales.deliveryName}}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="运单号"  >
                <span v-if="afterSales!=null">
                  {{afterSales.deliverySn}}
                </span>
            </el-descriptions-item>
        </el-descriptions>
        <div style="margin-top: 20px">
          <span class="font-small">商品信息</span>
        </div>
        <el-table
          border
          :data="items"
          size="small"
          style="width: 100%;margin-top: 20px" >
          <el-table-column label="商品图片" width="150" align="center">
            <template slot-scope="scope">
              <img :src="JSON.parse(scope.row.jsonInfo).image" style="height: 80px">
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="300" align="center">
            <template slot-scope="scope">
              <p>{{JSON.parse(scope.row.jsonInfo).productName}}</p>
            </template>
          </el-table-column>
          <el-table-column label="价格" width="240" align="center">
            <template slot-scope="scope">
              <p>价格：￥{{JSON.parse(scope.row.jsonInfo).price}}</p>

            </template>
          </el-table-column>
          <el-table-column label="属性" width="240" align="center">
            <template slot-scope="scope">
              {{JSON.parse(scope.row.jsonInfo).sku}}
            </template>
          </el-table-column>
          <el-table-column label="数量" width="180" align="center">
            <template slot-scope="scope">
                {{scope.row.num}}
            </template>
          </el-table-column>
<!--          <el-table-column label="运费金额" width="180" align="center">
            <template slot-scope="scope">
              ￥{{ (order.payPostage || 0).toFixed(2) }}
            </template>
          </el-table-column>-->
          <el-table-column label="小计"  align="center">
            <template slot-scope="scope">
<!--              ￥{{scope.row.num*JSON.parse(scope.row.jsonInfo).price}}-->
<!--              {{ (goodsTotal + (order.payPostage || 0)).toFixed(2) }}-->
              ￥{{order.payPrice}}
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 12px; text-align: right;" v-if="order">
          <div>订单金额：￥{{ goodsTotal.toFixed(2) }}</div>
          <div>运费金额：￥{{ (order.payPostage || 0).toFixed(2) }}</div>
          <div>实付金额：￥{{ Number(order.payMoney != null ? order.payMoney : (order.payPrice || 0)).toFixed(2) }}</div>
        </div>
        <div style="margin-top: 20px">
          <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
          <span class="font-small">操作信息</span>
        </div>
        <el-table style="margin-top: 20px;width: 100%"
                  ref="orderHistoryTable"
                  :data="logs" border>
          <el-table-column label="操作时间"  width="160" align="center">
            <template slot-scope="scope">
              {{scope.row.changeTime}}
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template slot-scope="scope">
              {{scope.row.changeMessage}}
            </template>
          </el-table-column>
          <el-table-column label="操作员" align="center">
            <template slot-scope="scope">
              {{scope.row.operator}}
            </template>
          </el-table-column>
        </el-table>
      </el-card>

    </div>
    <el-dialog :title="audit.title" :visible.sync="audit.open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="退款金额" prop="refundAmount"  >
          <el-input-number v-model="form.refundAmount" :min="0"  />
        </el-form-item>
        <el-form-item label="一级原因" prop="reasonId1">
          <el-select v-model="form.reasonId1" placeholder="请选择一级原因" @change="handleReason1Change" style="width: 100%">
            <el-option
              v-for="item in reasonList"
              :key="item.id"
              :label="item.reasonName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级原因" v-if="form.reasonId1 != null" prop="reasonId2">
          <el-select v-model="form.reasonId2" placeholder="请选择二级原因" style="width: 100%">
            <el-option
              v-for="item in reason2List"
              :key="item.id"
              :label="item.reasonName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input
            type="textarea"
            :rows="3"
            maxlength="200"
            placeholder="请输入审核备注"
            v-model="form.auditRemark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAuditForm">确 定</el-button>
        <el-button @click="audit.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer
    :append-to-body="true"
     size="75%"
      :title="show.title" :visible.sync="show.open"
      >
      <product-order  ref="productOrder" />
    </el-drawer>
    <el-dialog :title="add.title" :visible.sync="add.open" width="500px" append-to-body>

      <div slot="footer" class="dialog-footer">
        <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="100px">
          <el-form-item label="id" prop="id" v-if="false">
            <el-input v-model="addForm.id" placeholder="请输入"  />
          </el-form-item>
          <el-form-item label="快递公司" prop="deliveryName">
            <el-input v-model="addForm.deliveryName" placeholder="请输入"  />
          </el-form-item>
          <el-form-item label="运单号" prop="deliverySn">
            <el-input v-model="addForm.deliverySn" placeholder="请输入"  />
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getStoreAfterSales,cancel,refund,audit1,audit2,updateStoreAfterSales,listRefundReason,confirmErpStatus} from "@/api/hisStore/storeAfterSales";

import productOrder from "./productOrder";
export default {
  components: { productOrder },
  name: "order",
  data() {
    return {
      show:{
        open:false,
        title:"订单详情"
      },
      audit:{
          title:"财务审核",
          open:false,
      },
      add:{
        open:false,
        title:"添加物流"
      },
      addForm:{
        id:null,
        deliveryName:null,
        deliverySn:null
      },
      addRules:{
        deliveryName: [
          { required: true, message: "物流名称不能为空", trigger: "blur" }
        ],
        deliverySn: [
          { required: true, message: "物流单号不能为空", trigger: "blur" }
        ],
      },
      order:null,
      user:null,
      serviceTypeOptions:[],
      salesStatusOptions:[],
      statusOptions:[],
      afterSales:null,
      items:[],
      logs:[],
      form:{
        refundAmount:0,
        reasonId1: null,
        reasonId2: null,
        auditRemark: ''
      },
      rules: {
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
        refundAmount: [
          { required: true, message: "退款金额不能为空", trigger: "blur" }
        ],
        // 新增一级原因必填
        // reasonId1: [
        //   { required: true, message: "请选择一级原因", trigger: "change" }
        // ],
        // reasonId2: [
        //   {
        //     validator: (rule, value, callback) => {
        //       if (this.form.reasonId1 && !value) {
        //         callback(new Error("请选择二级原因"));
        //       } else {
        //         callback();
        //       }
        //     },
        //     trigger: "change"
        //   }
        // ],
        // auditRemark: [
        //   { required: true, message: "请输入审核备注", trigger: "blur" }
        // ]
      },
      reasonList: [],
      reason2List: []
    };
  },
  computed: {
    goodsTotal() {
      if (!this.items || this.items.length === 0) return 0;
      return this.items.reduce((sum, it) => {
        const info = JSON.parse(it.jsonInfo || "{}");
        const num = Number(it.num != null ? it.num : info.num) || 0;
        const price = Number(info.price) || 0;
        return sum + num * price;
      }, 0);
    }
  },
  created() {
    this.getDicts("store_after_sales_sales_status").then((response) => {
        this.salesStatusOptions = response.data;
    });
    this.getDicts("store_after_sales_status").then((response) => {
        this.statusOptions = response.data;
    });
     this.getDicts("store_after_sales_service_type").then((response) => {
        this.serviceTypeOptions = response.data;
    });
  },
  methods: {
    submitForm() {
      var id=this.afterSales.id;
      this.addForm.id = id;
      updateStoreAfterSales(this.addForm).then(response => {
              if (response.code === 200) {
                this.msgSuccess("编辑成功");
                this.add.open = false;
                this.getStoreAfterSales(id);
              }
            });
    },
    cancel1(){
      this.add.open = false;
    },
    addDelivery(){
      this.add.open = true;
      this.addForm.deliveryName = this.afterSales.deliveryName;
      this.addForm.deliverySn = this.afterSales.deliverySn;
    },
    showOrder(){
      this.show.open=true;
      const orderId = this.order.id ;
      setTimeout(() => {
        this.$refs.productOrder.getOrder(orderId);
      }, 500);
    },
    erpExceptionStatusText(status) {
      if (status === 1) {
        return '异常';
      }
      if (status === 2) {
        return '已处理';
      }
      return '-';
    },
    handleConfirmErpStatus() {
      const id = this.afterSales.id;
      this.$confirm('请选择ERP订单状态确认结果', 'ERP订单状态确认', {
        confirmButtonText: '通过',
        cancelButtonText: '不通过',
        distinguishCancelAndClose: true,
        type: 'warning'
      }).then(() => {
        return confirmErpStatus({ salesId: id, erpExceptionStatus: 2 });
      }).catch(action => {
        if (action === 'cancel') {
          return confirmErpStatus({ salesId: id, erpExceptionStatus: 1 });
        }
        return Promise.reject();
      }).then(() => {
        this.getStoreAfterSales(id);
        this.msgSuccess('操作成功');
      }).catch(() => {});
    },
    handleAudit1(){
      var id=this.afterSales.id;
      this.$confirm('确定审请通过?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={salesId:id}
          return audit1(data);
        }).then(() => {
          this.getStoreAfterSales(id);
          this.msgSuccess("操作成功");
        }).catch(function() {});

    },
    handleAudit2(){
      var id=this.afterSales.id;
      this.$confirm('确定审请通过?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={salesId:id}
          return audit2(data);
        }).then(() => {
          this.getStoreAfterSales(id);
          this.msgSuccess("操作成功");
        }).catch(function() {});

    },
    handleRefund(){
        this.form.salesId=this.afterSales.id;
        this.form.refundAmount=this.order.payMoney;
        this.form.reasonId1 = null;
        this.form.reasonId2 = null;
        this.form.auditRemark = '';
        this.reason2List = [];
        this.audit.open=true;
        this.getReasonList();
    },
    getReasonList() {
      listRefundReason({ typeLevel: 1 }).then(response => {
        this.reasonList = response.rows.map(item => {
          return {
            ...item,
            children: []
          };
        });
        this.reasonList.forEach(item => {
          if (item.childrenCount > 0) {
            this.getReason2List(item.id, item);
          }
        });
      });
    },
    getReason2List(parentId, parent) {
      listRefundReason({ parentId: parentId, typeLevel: 2 }).then(response => {
        parent.children = response.rows;
      });
    },
    handleReason1Change(val) {
        this.form.reasonId2 = null;
        this.reason2List = [];
        if (val) {
          const selected = this.reasonList.find(item => item.id === val);
          if (selected && selected.children) {
            this.reason2List = selected.children;
          }
        }
    },
    submitAuditForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          refund(this.form).then(response => {
              if (response.code === 200) {
                this.audit.open = false;
                this.getStoreAfterSales(this.afterSales.id);
                this.msgSuccess("操作成功");
              }
            });
        }
      });
    },
    cancel(){
      var id=this.afterSales.id;
      this.$prompt('是否确定取消订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        var data={salesId:id,remark:value};
        return cancel(data);
      }).then(() => {
        this.getStoreAfterSales(id);
        this.msgSuccess("操作成功");
      }).catch(() => {

      });
    },
    getStoreAfterSales(id){
        getStoreAfterSales(id).then(response => {
            this.afterSales = response.afterSales;
            this.logs = response.logs;
            this.items = response.items;
            this.user=response.user;
            this.order=response.order;
        });
     },
  }
};
</script>
<style scoped>
.order-content{
  margin: 10px;
}

.operate-container {
  background: #F2F6FC;
  height: 60px;
  margin: -20px -20px 0;
  line-height: 60px;
}

.operate-button-container {
  float: right;
  margin-right: 20px
}

</style>
