<template>
    <div style="background-color: #f0f2f5; padding-bottom: 20px; min-height: 100%; " >
      <div style="padding: 20px; background-color: #fff;">
        售后详情
      </div>
<div class="content" v-if="item!=null" style="padding-bottom: 20px;">
  <div class="desct"></div>
<div class="order-status" v-if="item!=null" >
          <el-steps  :active="item.status==4?item.status+1:item.status" align-center>
            <el-step title="待审核"></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>
           <el-card shadow="never" style="margin-top: 15px">
             <div class="operate-container"  v-if="item!=null">
               <span style="margin-left: 20px" class="color-danger">售后状态：
                  <el-tag prop="status" v-for="(ite, index) in salesStatusOptions"    v-if="item.status==ite.dictValue">{{ite.dictLabel}}</el-tag>
               </span>
               <div class="operate-button-container"  >
                 <el-button size="mini"  @click="showOrder">查看订单</el-button>
               </div>
              <div class="operate-button-container"  >
                 <el-button size="mini" @click="editDelivery()" >编辑物流</el-button>
              </div>
              <div class="operate-button-container" v-if="item && item.deliverySn">
                 <el-button size="mini" @click="showShipBack()">查看寄回物流</el-button>
              </div>
              <div class="operate-button-container"  v-if="item.status==0 && item.salesStatus==0">
                  <el-button size="mini" @click="handleAudit1()" >平台审核</el-button>
               </div>
               <div class="operate-button-container"  v-if="item.status==2 && item.salesStatus==0">
                  <el-button size="mini" @click="depotAuditing(3)" >仓库审核</el-button>
               </div>
               <div class="operate-button-container"  v-if="item.status==3 && item.salesStatus==0">
                  <el-button size="mini" @click="tuimoney(4)" v-hasPermi="['his:storeAfterSales:finance']">财务审核</el-button>
               </div>
               <div class="operate-button-container" v-if="item.salesStatus==0  &&( (item.status<4 && item.orderStatus==2) ||(item.status<2 && item.orderStatus==3) ||(item.deliverySn!=null &&item.deliverySn!='' && item.orderStatus==4)) "  >
                  <el-button size="mini" @click="NoAuditing(5)" >撤销</el-button>
               </div>
             </div>

     <div style="margin: 20px 0px">
       <span class="font-small">基本信息</span>
     </div>
     <el-descriptions   :column="3" border  >
         <el-descriptions-item label="订单编号"> <span v-if="item!=null">{{item.orderCode}}</span></el-descriptions-item>
         <el-descriptions-item label="会员"  ><span>{{nickName}} </span></el-descriptions-item>
         <el-descriptions-item label="退款金额"  ><span v-if="item!=null"> {{item.refundAmount}}</span></el-descriptions-item>
         <el-descriptions-item label="申请类型"  > <dict-tag :options="refundTypeOptions" :value="item.refundType"/></el-descriptions-item>
         <el-descriptions-item label="申请原因"  > <span v-if="item!=null"> {{item.reasons}}</span> </el-descriptions-item>
         <el-descriptions-item label="说明"  >  <span v-if="item!=null"> {{item.explains}}</span></el-descriptions-item>
         <el-descriptions-item label="状态"  ><dict-tag :options="salesStatusOptions" :value="item.status"/> </el-descriptions-item>
         <el-descriptions-item label="订单状态"  ><dict-tag :options="orderOptions" :value="item.orderStatus"/> </el-descriptions-item>
         <el-descriptions-item label="售后状态"  ><dict-tag :options="afterSalesStatusOptions" :value="item.salesStatus"/> </el-descriptions-item>
         <el-descriptions-item label="物流单号"  ><span>{{item.deliverySn}} </span></el-descriptions-item>
         <el-descriptions-item label="物流名称"  ><span>{{item.deliveryName}} </span></el-descriptions-item>
<!--          <el-descriptions-item label="溯源码" align="center"><span>{{item.verifyCode}}</span></el-descriptions-item>-->
<!--          <el-descriptions-item label="产品批次号" align="center"><span>{{item.batchNumber}}</span></el-descriptions-item>-->
     </el-descriptions>
</el-card>
</div>



<div class="content" v-if="item!=null">
     <div class="desct">
       商品信息
     </div>
   <el-table
          border
          :data="prod"
          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).barCode}}</p>
       </template>
     </el-table-column>

<!--     <el-table-column label="商品组合编码" width="300" align="center">-->
<!--       <template slot-scope="scope">-->
<!--         <p>{{JSON.parse(scope.row.jsonInfo).groupBarCode}}</p>-->
<!--       </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="180" align="center">
       <template slot-scope="scope">
         {{scope.row.commonName}}
       </template>
     </el-table-column>

     <el-table-column label="生产许可证或备案凭证编号" width="180" align="center">
       <template slot-scope="scope">
         {{scope.row.prodLicenseNo || '-' }}
       </template>
     </el-table-column>

     <el-table-column label="生产企业" width="180" align="center">
       <template slot-scope="scope">
         {{scope.row.manufacturer || '-' }}
       </template>
     </el-table-column>


     <el-table-column label="溯源码/有效期" width="300" align="center">
       <template slot-scope="scope">
         <p>{{scope.row.verifyCode}}</p>
       </template>
     </el-table-column>
     <el-table-column label="生产批次号/序列号" width="300" align="center">
       <template slot-scope="scope">
         <p>{{scope.row.batchNumber}}</p>
       </template>
     </el-table-column>
     <el-table-column label="单价" width="240" align="center">
       <template slot-scope="scope">
         <p>￥{{JSON.parse(scope.row.jsonInfo).price.toFixed(2)}}</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">
         {{scope.row.dosageForm}}
       </template>
     </el-table-column>

     <el-table-column label="注册证书编号" width="180" align="center">
       <template slot-scope="scope">
         {{scope.row.drugRegCertNo}}
       </template>
     </el-table-column>
     <el-table-column label="上市许可持有人" width="180" align="center">
       <template slot-scope="scope">
         {{scope.row.mah}}
       </template>
     </el-table-column>
     <el-table-column label="处方药" width="240" align="center">
       <template slot-scope="scope">
         {{scope.row.isPrescribe!=null&&scope.row.isPrescribe==1?'是':'否'}}
       </template>
     </el-table-column>
          <el-table-column label="小计"  align="center">
            <template slot-scope="scope">
              ￥{{JSON.parse(scope.row.jsonInfo).num*JSON.parse(scope.row.jsonInfo).price}}
            </template>
          </el-table-column>
        </el-table>
  </div>

<!--      <div class="content" v-if="item != null">
        <div class="desct">费用信息</div>
        <el-descriptions :column="4" border>
          <el-descriptions-item label="商品合计">
            <span v-if="order != null">
              ￥{{ order.totalPrice.toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="应付金额">
            <span v-if="order != null">
              ￥{{ order.payPrice.toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="运费">
            <span v-if="order != null">
              ￥{{ order.payPostage.toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="优惠券">
            <span v-if="order != null">
              ￥{{ order.couponPrice.toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="活动名称" v-if="orderPromotion != null">
            <span>{{ orderPromotion.activityTitle }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="活动类型" v-if="orderPromotion != null">
            <span>{{ orderPromotion.tierTypeLabel }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="活动档位" v-if="orderPromotion != null">
            <span>{{ orderPromotion.matchedTierDesc }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="活动优惠" v-if="orderPromotion != null">
            <span class="color-danger">
              ￥{{ formatPromotionDiscount(orderPromotion.promotionDiscountAmount) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="积分抵扣">
            <span v-if="order != null">
              ￥{{ order.deductionPrice.toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="实付金额">
            <span v-if="order != null">
              ￥{{ order.payMoney.toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="代收金额">
            <span v-if="order != null">
              ￥{{ order.payDelivery.toFixed(2) }}
            </span>
          </el-descriptions-item>
        </el-descriptions>
      </div>-->

      <div class="content" v-if="item!=null">
           <div class="desct">
             操作信息
           </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>
      <div style="margin-top: 20px">
        <span class="font-small">积分明细</span>
      </div>
      <el-table
        border
        :data="integralLogs"
        size="small"
        style="width: 100%;margin-top: 20px"
        empty-text="该订单暂无积分变动记录">
        <el-table-column label="类型" align="center" min-width="160">
          <template slot-scope="scope">
            <el-tag size="mini" :type="scope.row.integral >= 0 ? 'success' : 'danger'">
              {{ formatLogType(scope.row.logType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="积分变动" align="center" width="120">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.integral >= 0 ? '#67C23A' : '#F56C6C', fontWeight: 'bold' }">
              {{ scope.row.integral >= 0 ? '+' + scope.row.integral : scope.row.integral }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="变动后余额" align="center" prop="balance" width="120" />
        <el-table-column label="业务订单ID" align="center" prop="businessId" width="140" />
        <el-table-column label="时间" align="center" prop="createTime" width="160" />
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      </el-table>
</div>
<el-dialog :title="edit.title" :visible.sync="edit.open" width="500px" append-to-body>
  <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="100px">
    <el-form-item label="快递公司" prop="deliveryName">
      <el-input v-model="editForm.deliveryName" placeholder="请输入"  />
    </el-form-item>
    <el-form-item label="运单号" prop="deliverySn">
      <el-input v-model="editForm.deliverySn" placeholder="请输入"  />
    </el-form-item>
  </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
<el-drawer
    :with-header="false"
    :append-to-body="true"
     size="75%"
      :title="show.title" :visible.sync="show.open"
      >
      <storeOrderDetails  ref="Details" />
    </el-drawer>

    <el-dialog title="用户寄回快递信息" :visible.sync="ship.open" width="720px" append-to-body>
      <el-descriptions :column="1" border v-if="item!=null">
        <el-descriptions-item label="物流公司编码">{{ item.shipperCode }}</el-descriptions-item>
        <el-descriptions-item label="物流名称">{{ item.deliveryName }}</el-descriptions-item>
        <el-descriptions-item label="物流单号">{{ item.deliverySn }}</el-descriptions-item>
        <el-descriptions-item label="商家手机号">{{ item.phoneNumber }}</el-descriptions-item>
      </el-descriptions>
      <div style="margin-top: 20px; font-weight: bold;">物流流转信息</div>
      <div v-loading="expressLoading">
        <el-table v-if="traces && traces.length > 0"
                  style="margin-top: 10px;width: 100%"
                  :data="traces" border size="small">
          <el-table-column label="时间" width="170" align="center">
            <template slot-scope="scope">{{ scope.row.AcceptTime }}</template>
          </el-table-column>
          <el-table-column label="位置" align="center">
            <template slot-scope="scope">{{ scope.row.Location }}</template>
          </el-table-column>
          <el-table-column label="描述" align="center">
            <template slot-scope="scope">{{ scope.row.AcceptStation }}</template>
          </el-table-column>
        </el-table>
        <div v-else-if="!expressLoading"
             style="margin-top: 10px; padding: 24px 0; text-align: center; color: #909399;">
          暂无信息
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="ship.open = false">关 闭</el-button>
      </div>
    </el-dialog>


    </div>
</template>

<script>
import {tuiMoney,noAuditing,depotAuditing, auditing, codeId, logList,getRelatedProducts, itemList,listSales, getSales, delSales, addSales, updateSales, exportSales, getExpress, cancelSales, audit1 } from "@/api/store/storeAfterSales";
import { getStoreOrder } from "@/api/store/storeOrder";
import { getOrderPromotionDetail } from "@/api/store/storePromotion";
import { getIntegralLogsByOrderId } from "@/api/store/userIntegralLogs";
import storeOrderDetails from '../store/storeOrderDetails.vue';
  export default {
    name: "orderDet",
    components: { storeOrderDetails },
    props:["data"],
    data() {
      return {
        edit:{
          open:false,
          title:"添加物流"
        },
        editForm:{
          id:null,
          deliveryName:null,
          deliverySn:null
        },
        editRules:{
          deliveryName: [
            { required: true, message: "物流名称不能为空", trigger: "blur" }
          ],
          deliverySn: [
            { required: true, message: "物流单号不能为空", trigger: "blur" }
          ],
        },
        show:{
          open:false,
          title:"订单详情"
        },
        ship:{
          open:false
        },
        traces:[],
        expressLoading:false,
        logs:[],
        nickName:null,
        storeName:null,
        orderOptions:[],
        refundTypeOptions:[],
        salesStatusOptions:[],
        afterSalesStatusOptions:[],
        item:null,
        prod:null,
        order: null,
        orderPromotion: null,
        // 积分明细列表
        integralLogs: [],
        // 积分日志类型字典（字典 + 本地兜底，与 FsUserIntegralLogTypeEnum 对齐）
        integralLogTypeOptions: [],
        form: {
          sreason: '',
        }
      }
    },
    created() {
    this.getDicts("sys_order_status").then(response => {
        this.orderOptions = response.data;
      });
    this.getDicts("sys_refund_type").then(response => {
        this.refundTypeOptions = response.data;
      });
    this.getDicts("sys_sales_status").then(response => {
        this.salesStatusOptions = response.data;
      });
    this.getDicts("sys_after_sales_status").then(response => {
        this.afterSalesStatusOptions = response.data;
      });
    // 加载积分日志类型字典（合并本地兜底，确保所有已知 logType 都有中文名称）
    this.getDicts("sys_integral_log_type").then((response) => {
      this.integralLogTypeOptions = this.mergeLogTypeOptions(response.data || []);
    });
    },
    methods: {
      formatPromotionDiscount(amount) {
        if (amount == null || amount === '') {
          return '0.00';
        }
        return Number(amount).toFixed(2);
      },
      submitForm() {
        var id=this.item.id;
        this.editForm.id = id;
        updateSales(this.editForm).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("编辑成功");
                  this.edit.open = false;
                  getSales(id).then(response => {
                      this.item = response.data;
                      this.getitemList();
                      this.getlogList();
                  });
                }
              });
      },
      getlist(){
      getSales(this.item.id).then(response => {
          this.item = response.data;
          this.getitemList();
          this.getlogList();
          this.$parent.$parent.getList();
        });
      },
      tuimoney(row){
      var that=this;
       this.$confirm('是否确认财务审核?', "财务审核", {
         confirmButtonText: "确定",
         cancelButtonText: "取消",
         type: "warning"
       }).then(function() {
        var data={
          id:that.item.id,
          status:row,
        }
         return tuiMoney(data);
       }).then(() => {
         this.msgSuccess("操作成功");
          this.getlist();
       }).catch(function() {});
      },
      NoAuditing(row){
        var that=this;
        var id = this.item.id;
        this.$prompt('是否确定取消订单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          var data = { salesId: id, remark: value };
          return cancelSales(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getlist();
        }).catch(function() {});
      },
      goAuditing(row){
        var that=this;
        this.$confirm('是否确认审核通过?', "审核", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={
            id:that.item.id,
            status:row,
          }
          return auditing(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getlist();
        }).catch(function() {});
      },

      /** 平台审核，与 admin 总后台一致 */
      handleAudit1(){
        var id = this.item.id;
        this.$confirm('确定审请通过?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data = { salesId: id };
          return audit1(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getlist();
        }).catch(function() {});
      },

      depotAuditing(row){
        var that=this;
        this.$confirm('是否确认审核通过?', "审核", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={
            id:that.item.id,
            status:row,
          }
          return depotAuditing(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getlist();
        }).catch(function() {});
      },


      showOrder(row){
            this.show.open=true;
            codeId(this.item.orderId).then(response => {
              setTimeout(() => {
                   this.$refs.Details.getDetails(this.item.orderId,this.nickName,this.storeName);
              }, 1);
            });
      },
      getDetails(orderId,nickName,storeName) {
        this.nickName=nickName;
        this.storeName=storeName;
        this.item=null;
        this.order=null;
        this.orderPromotion=null;
        this.integralLogs=[];
          getSales(orderId).then(response => {
              this.item = response.data;
              this.getitemList();
              this.getlogList();
              this.loadOrderFeeInfo(this.item.orderId);
              this.loadIntegralLogs(this.item.orderId);
          });
      },
      loadOrderFeeInfo(orderId) {
        if (!orderId) {
          return;
        }
        getStoreOrder(orderId).then(response => {
          this.order = response.order || null;
        }).catch(() => {
          this.order = null;
        });
        getOrderPromotionDetail(orderId).then(response => {
          this.orderPromotion = response.data || null;
        }).catch(() => {
          this.orderPromotion = null;
        });
      },
      // 加载积分明细
      loadIntegralLogs(orderId) {
        console.log("-------------》加载明细积分--->"+orderId);
        if (!orderId) {
          this.integralLogs = [];
          return;
        }
        getIntegralLogsByOrderId(orderId).then(response => {
          console.log("-------------》请求接口---------》")
          this.integralLogs = response.data || [];
        }).catch(() => {
          this.integralLogs = [];
        });
      },
      /** 合并字典与本地兜底类型，确保所有已知 logType 都有对应名称 */
      mergeLogTypeOptions(dictOptions) {
        const localMap = {
          1: '签到获得积分', 2: '消费获得积分', 3: '分享获得积分', 4: '退款扣除积分',
          5: '购买积分商品', 6: '平台取消售后', 7: '积分过期', 8: '螳螂同步积分',
          9: '购买课程小节扣除', 10: '观看课程获取积分', 11: '新用户完善就诊人获得积分',
          12: '新用户填写收货地址获取积分', 13: '浏览商品获得积分', 14: '浏览视频获得积分',
          15: '首次下单疗法获得积分', 16: '点播看课获得积分', 17: '点播答题获得积分',
          18: '邀请新用户获取积分', 19: '填写邀请码获取积分', 20: '首次完成手机号绑定注册',
          21: '首次完成专家咨询', 22: '首次完成积分商城下单', 23: '管理员添加',
          24: '付费课程订阅', 25: '下单使用积分抵扣', 26: '取消订单退回积分', 27: '退款订单退回积分'
        };
        const result = [...dictOptions];
        const existValues = new Set(dictOptions.map(o => Number(o.dictValue)));
        Object.keys(localMap).forEach(key => {
          const val = Number(key);
          if (!existValues.has(val)) {
            result.push({ dictValue: String(val), dictLabel: localMap[val] });
          }
        });
        return result;
      },
      /** 将 logType 数值转换为中文名称 */
      formatLogType(logType) {
        if (logType == null) return '-';
        const item = this.integralLogTypeOptions.find(o => Number(o.dictValue) === Number(logType));
        return item ? item.dictLabel : ('类型' + logType);
      },
      editDelivery(){
        this.edit.open = true;
        this.editForm.deliveryName = this.item.deliveryName;
        this.editForm.deliverySn = this.item.deliverySn;
      },

      showShipBack(){
        this.ship.open = true;
        this.traces = [];
        if (this.item && this.item.deliverySn) {
          this.expressLoading = true;
          getExpress(this.item.id).then(response => {
            if (response && response.data && response.data.Traces) {
              this.traces = response.data.Traces;
            } else {
              this.traces = [];
            }
          }).finally(() => {
            this.expressLoading = false;
          });
        }
      },

      cancel1(){
        this.edit.open = false;
        this.editForm.deliveryName = null;
        this.editForm.deliverySn = null;
      },
      getitemList(){
        getRelatedProducts(this.item.id).then(response => {
            this.prod = response.data;
        });
      },
      getlogList(){
        logList(this.item.id).then(response => {
            this.logs = response.data;
        });
      }
    }
  }
</script>
<style>
  .content{
      height: 100%;
      background-color: #fff;
      padding: 0px 20px 20px;

      margin: 20px;
  }
  .el-descriptions-item__label.is-bordered-label{
    font-weight: normal;
  }
  .el-descriptions-item__content {
    max-width: 150px;
    min-width: 100px;
  }
  .desct{
      padding-top: 20px;
      padding-bottom: 20px;
      color: #524b4a;
      font-weight: bold;
    }

</style>

<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>
