<template>
  <div class="live-page live-order-detail">
    <div class="live-page__header">
      <h2 class="live-page__title">订单详情</h2>
    </div>
    <div class="contentx live-panel" v-if="item!=null">
      <div class="desct"></div>
      <div class="order-status" v-if="item!=null" >
        <el-steps  :active="item.status==4?item.status:item.status" align-center finish-status="success">
          <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" class="detail-card">
        <div class="operate-container"  v-if="item!=null">
               <span class="operate-status color-danger">订单状态：
                  <el-tag prop="status" v-for="(ite, index) in orderOptions"    v-if="item.status==ite.dictValue">{{ite.dictLabel}}</el-tag>
               </span>
          <div class="operate-button-container" v-if="item.status==3">
            <el-button size="mini" @click="finishOrder()" v-hasPermi="['live:liveOrder:finishOrder']">确认收货</el-button>
          </div>
          <div class="operate-button-container"  v-if="item.status==2&&item.orderType==1">
            <el-button size="mini" @click="sendVisible=true" v-hasPermi="['live:liveOrder:sendGoods']">发货</el-button>
          </div>
          <div class="operate-button-container"  v-if="item.status==2&&item.orderType==2">
            <el-button size="mini" @click="tuiOrder()" v-hasPermi="['live:liveOrder:sendHisGoods']" >推送订单</el-button>
          </div>
          <div class="operate-button-container"   v-if="item.deliverySn!=null" v-hasPermi="['live:liveOrder:express']">
            <el-button size="mini" @click="showExpress()" >查看物流</el-button>
          </div>
          <div class="operate-button-container" >
            <el-button size="mini" @click="editDelivery()"  v-hasPermi="['live:liveOrder:updateDelivery']" >修改物流单号</el-button>
          </div>

          <div class="operate-button-container" >
            <el-button size="mini" @click="editOrder()"  v-hasPermi="['live:liveOrder:edit']" >修改订单</el-button>
          </div>
          <div class="operate-button-container" v-if="item.extendOrderId == null"  >
            <el-button size="mini" @click="addErpOrder()" v-hasPermi="['live:liveOrder:createErpOrder']">创建ERP订单信息</el-button>
          </div>
          <div class="operate-button-container" v-if="item.extendOrderId!=null"  >
            <el-button size="mini" @click="showErpOrder()" v-hasPermi="['live:liveOrder:getEroOrder']">ERP订单信息</el-button>
          </div>
          <div class="operate-button-container" v-if="item.status>1">
            <el-button size="mini" @click="refund()" v-hasPermi="['live:liveOrder:refundOrderMoney']">退款</el-button>
          </div>
        </div>
        <div class="desct">
          基本信息
        </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 v-if="item.nickName!=null">{{item.nickName}}({{item.phone}})</span></el-descriptions-item>
          <el-descriptions-item label="支付方式"  ><dict-tag :options="PayOptions" :value="item.payType"/></el-descriptions-item>
          <el-descriptions-item label="收货人" >  <span v-if="item!=null">{{item.userName}}</span>  </el-descriptions-item>
          <el-descriptions-item label="手机号码" > <span v-if="item!=null">{{item.userPhone}}</span>
            <el-button icon="el-icon-search" size="mini" @click="handlePhone()" class="inline-search-btn" circle v-hasPermi="['live:liveOrder:queryPhone']"></el-button>
          </el-descriptions-item>
          <el-descriptions-item label="收货地址" > <span v-if="item!=null">{{item.userAddress}}</span>
            <el-button icon="el-icon-search" size="mini" @click="handleAddress()" class="inline-search-btn" circle v-hasPermi="['live:liveOrder:queryAddress']"></el-button>
          </el-descriptions-item>
          <el-descriptions-item label="所属公司"><span v-if="item!=null">{{item.companyName}}</span></el-descriptions-item>
          <el-descriptions-item label="员工"><span v-if="item!=null">{{item.companyUserName}}</span></el-descriptions-item>
          <el-descriptions-item label="推广佣金" ><span v-if="item.tuiMoney!=null">{{item.tuiMoney.toFixed(2)}}</span></el-descriptions-item>
          <el-descriptions-item label="推广佣金状态" ><span v-if="item!=null"><dict-tag :options="tuiOptions" :value="item.tuiMoneyStatus"/> </span></el-descriptions-item>
          <el-descriptions-item label="ERP编号" ><span v-if="item!=null">{{item.extendOrderId}}</span></el-descriptions-item>
          <el-descriptions-item label="用户备注" ><span v-if="item!=null">{{item.remark}}</span></el-descriptions-item>
          <el-descriptions-item label="档期归属" >
            <el-tag prop="scheduleId" v-for="(schedule, index) in scheduleOptions"    v-if="item!=null&&item.scheduleId==schedule.id">{{schedule.name}}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单购买类型" ><span v-if="item!=null"><dict-tag :options="orderBuyTypeOptions" :value="item.orderBuyType"/></span></el-descriptions-item>
<!--          <el-descriptions-item label=" 公众号/渠道" ><span v-if="item!=null">{{item.channel}}</span></el-descriptions-item>-->
          <el-descriptions-item label=" 渠道" ><span v-if="item!=null"><dict-tag :options="channelOptions" :value="item.orderChannel"/></span></el-descriptions-item>
          <el-descriptions-item label=" 企微主体" ><span v-if="item!=null"><dict-tag :options="qwSubjectOptions" :value="item.qwSubject"/></span></el-descriptions-item>
        </el-descriptions>
      </el-card>
    </div>
    <div class="contentx live-panel contentx--pad" v-if="item!=null">
      <div class="section-head">
        <div class="desct">
          物流信息
        </div>
        &nbsp;
        <el-link  type="primary" @click="editDelivery(null)">添加物流信息</el-link>
      </div>
      <el-table
        border
        :data="deliverList"
        size="small"
        class="detail-table" >
        <el-table-column label="物流公司编码" width="150" align="center">
          <template slot-scope="scope">
            <p>{{scope.row.deliverSn}}</p>
          </template>
        </el-table-column>
        <el-table-column label="物流公司名称" width="300" align="center">
          <template slot-scope="scope">
            <p>{{scope.row.deliverName}}</p>
          </template>
        </el-table-column>
        <el-table-column label="物流单号" width="300" align="center">
          <template slot-scope="scope">
            <p>{{scope.row.deliverId}}</p>
          </template>
        </el-table-column>
        <el-table-column label="物流状态" width="300" align="center">
          <template slot-scope="scope">
              <span>
              <el-tag v-for="(item, index) in deliveryStatusOptions"    v-if="scope.row!=null&&scope.row.status==item.dictValue">
              {{item.dictLabel}}
              </el-tag>
              </span>
          </template>
        </el-table-column>
        <el-table-column label="发货时间" width="240" align="center">
          <template slot-scope="scope">
            {{scope.row.deliverySendTime}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template slot-scope="scope">
            <el-link  type="primary" @click="showExpress(scope)">查看物流跟踪</el-link>
            &nbsp;&nbsp;
            <el-link  type="primary" @click="editDelivery(scope)">修改物流</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="contentx live-panel contentx--pad" v-if="item!=null">
      <div class="desct">
        商品信息
      </div>
      <el-tooltip class="item toggle-tip" effect="dark" :content="showList ? '显示全部' : '隐藏'" placement="top">
        <el-button size="mini" circle icon="el-icon-search" @click="showListD()" />
      </el-tooltip>
      <el-table border v-if="showProd!=null" :data="showProd" size="small" class="detail-table" >
        <el-table-column label="商品图片" width="150" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.imgUrl" class="goods-thumb">
          </template>
        </el-table-column>
        <el-table-column label="商品编码" width="300" align="center">
          <template slot-scope="scope">
            <p>{{scope.row.barCode}}</p>
          </template>
        </el-table-column>
        <el-table-column label="仓库代码" width="300" align="center">
          <template slot-scope="scope">
            <p>{{scope.row.warehouseCode}}</p>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" width="300" align="center">
          <template slot-scope="scope">
            <p>{{scope.row.productName}}</p>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="240" align="center">
          <template slot-scope="scope">
            <p>￥{{scope.row.price.toFixed(2)}}</p>
          </template>
        </el-table-column>
        <el-table-column label="出库价" width="240" align="center">
          <template slot-scope="scope">
            <p>￥{{(scope.row.netPrice != null ? scope.row.netPrice : getOutboundPrice(scope.$index, scope.row)).toFixed(2)}}</p>
          </template>
        </el-table-column>
        <el-table-column label="市场价" width="240" align="center">
          <template slot-scope="scope">
            {{scope.row.otPrice}}
          </template>
        </el-table-column>
        <el-table-column label="产品数量" width="240" align="center">
          <template slot-scope="scope">
            {{scope.row.totalNum}}
          </template>
        </el-table-column>
      </el-table>
      <div class="section-total" v-if="item.totalPrice!=null">
        商品总价：<span class="color-danger">￥{{(parseFloat(item.totalPrice)).toFixed(2)}}</span>
      </div>
    </div>
    <div class="contentx live-panel contentx--pad" v-if="item!=null">
      <div class="desct">
        费用信息
      </div>
      <el-tooltip class="item toggle-tip" effect="dark" :content="showList ? '显示全部' : '隐藏'" placement="top">
        <el-button size="mini" circle icon="el-icon-search" @click="showListD()" />
      </el-tooltip>
      <el-descriptions :column="3" border  >
        <el-descriptions-item label="商品合计"  ><span v-if="item!=null">{{(parseFloat(item.totalPrice || 0)).toFixed(2)}}</span></el-descriptions-item>
        <el-descriptions-item label="应付金额"><span v-if="item!=null">{{(parseFloat(item.payPrice || 0)).toFixed(2)}}</span></el-descriptions-item>
        <el-descriptions-item label="邮费"><span v-if="item!=null">{{(parseFloat(item.payPostage || 0)).toFixed(2)}}</span></el-descriptions-item>
        <el-descriptions-item label="优惠券"  ><span v-if="item.discountMoney!=null">{{item.discountMoney}}</span></el-descriptions-item>
        <el-descriptions-item label="积分抵扣" >  <span v-if="item!=null">{{item.payIntegral}}</span>  </el-descriptions-item>
        <el-descriptions-item label="实付金额" >  <span v-if="item!=null">{{(parseFloat(item.payMoney || 0)).toFixed(2)}}</span>  </el-descriptions-item>
        <el-descriptions-item label="代收金额" >  <span v-if="item!=null">{{item.payRemain}}</span>  </el-descriptions-item>
        <el-descriptions-item label="服务费" >  <span v-if="item!=null">{{0.00}}</span>  </el-descriptions-item>
        <el-descriptions-item label="折扣率"  >
          <span v-if="item!=null && productTotal > 0">{{ discountRatePercent }}%</span>
          <span v-else-if="item!=null">0.00%</span>
        </el-descriptions-item>
        <el-descriptions-item label="产品合计"  >
          <span v-if="item!=null && showProd!=null && showProd.length > 0">￥{{productTotal.toFixed(2)}}</span>
          <span v-else-if="item!=null">￥0.00</span>
        </el-descriptions-item>
        <el-descriptions-item label=""/>
      </el-descriptions>
      <div class="section-total" v-if="item.payMoney!=null">
        实付合计：<span class="color-danger">￥{{(parseFloat(item.payMoney)).toFixed(2)}}</span>
      </div>
    </div>

    <div class="contentx live-panel contentx--pad" v-if="payments!=null">
      <div class="desct">
        支付信息
      </div>
    <el-table
      border
      :data="payments"
      size="small"
      class="detail-table" >
      <el-table-column label="支付单号" align="center" prop="payCode" width="120px" />
      <el-table-column label="支付金额" align="center" prop="payMoney" />
      <el-table-column label="类型" align="center" prop="payTypeCode" />
      <el-table-column label="交易单号" align="center" prop="bankTransactionId" />
      <el-table-column label="银行单号" align="center" prop="bankSerialNo" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="支付时间" align="center" prop="payTime" />
    </el-table>
    </div>

    <div class="contentx live-panel contentx--pad" v-if="logs!=null">

      <div class="desct">
        操作信息
      </div>
    <el-table class="detail-table"
              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>

    <div class="contentx live-panel contentx--pad" v-if="tuiMoneyLogs!=null">

      <div class="desct">
        分佣信息
      </div>
    <el-table
      border
      :data="tuiMoneyLogs"
      size="small"
      class="detail-table" >
      <el-table-column label="公司名称" align="center" prop="companyName" width="120px" />
      <el-table-column label="金额" align="center" prop="money" />
      <el-table-column label="余额" align="center" prop="balance" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="备注" align="center" prop="remark" />
    </el-table>
    </div>

    <el-dialog :title="edit.title" :visible.sync="edit.open" width="600px" append-to-body>
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="100px">

        <el-form-item label="订单状态" prop="status" >
          <el-select v-model="editForm.status" placeholder="请选择状态" clearable size="small" filterable>
            <el-option
              v-for="dict in orderOptions "
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物流状态" prop="deliveryStatus" >
          <el-select v-model="editForm.deliveryStatus" placeholder="请选择物流状态" clearable size="small" filterable>
            <el-option
              v-for="dict in deliveryStatusOptions "
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物流跟踪状态" prop="deliveryType" >
          <el-select v-model="editForm.deliveryType" placeholder="请选择状态" clearable size="small" filterable>
            <el-option
              v-for="dict in deliveryTypeOptions "
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详情地址" prop="userAddress"  >
          <el-input v-model="editForm.userAddress" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="备注" prop="remark"  >
          <el-input v-model="editForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="erpDialog.title" :visible.sync="erpDialog.open" width="600px" append-to-body>
      <div v-if="item!=null&&item.extendOrderId!=null&&item.status==1"  v-hasPermi="['live:liveOrder:updateExpress']"  >
        <el-button size="mini" @click="updateExpress()" >同步物流发货</el-button>
      </div>
      <div class="table-layout"  v-if="erpOrder!=null">
        <el-row>
          <el-col :span="6" class="table-cell-title">订单编号</el-col>
          <el-col :span="6" class="table-cell-title">是否代收</el-col>
          <el-col :span="6" class="table-cell-title">快递编号</el-col>
          <el-col :span="6" class="table-cell-title">快递名称</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell">
            {{erpOrder.code}}
          </el-col>
          <el-col :span="6" class="table-cell">
            {{erpOrder.cod?'是':'否'}}
          </el-col>
          <el-col :span="6" class="table-cell">
            {{erpOrder.express_code}}
          </el-col>
          <el-col :span="6" class="table-cell">
            {{erpOrder.express_name}}
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell-title">收货人</el-col>
          <el-col :span="6" class="table-cell-title">电话</el-col>
          <el-col :span="6" class="table-cell-title">地址</el-col>
          <el-col :span="6" class="table-cell-title">运单号</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell">
            {{erpOrder.receiver_name}}
          </el-col>
          <el-col :span="6" class="table-cell">
            {{erpOrder.receiver_mobile}}
          </el-col>
          <el-col :span="6" class="table-cell">
            {{erpOrder.receiver_address}}
          </el-col>
          <el-col :span="6" class="table-cell">
            {{erpOrder.deliverys!=null&&erpOrder.deliverys.length>0?erpOrder.deliverys[0].mail_no:''}}
          </el-col>

        </el-row>
      </div>
    </el-dialog>

    <el-dialog :title="editDy.title" :visible.sync="editDy.open" width="600px" append-to-body>
      <el-form ref="editDyForm" :model="editDyForm" :rules="editDyRules" label-width="100px">
        <div  v-hasPermi="['live:liveOrder:updateErpOrder']"  class="dialog-action-bar" >
          <el-button size="mini" @click="updateErpOrder" >同步物流单号信息</el-button>
        </div>
        <el-form-item label="物流公司" prop="deliveryCode" >
          <el-select class="delivery-select" v-model="editDyForm.deliveryCode" placeholder="请选择" clearable size="small" filterable>
            <el-option
              v-for="dict in deliveryOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="deliveryId"  >
          <el-input v-model="editDyForm.deliveryId" placeholder="请输入物流单号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditDyForm">确 定</el-button>
        <el-button @click="editDy.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="expressDialog.title" :visible.sync="expressDialog.open" width="600px" append-to-body>
      <div  v-hasPermi="['live:liveOrder:syncExpress']"  >
        <el-button size="mini" @click="syncExpress()" >同步快递鸟物流状态</el-button>
      </div>
      <el-table class="detail-table"
                ref="orderHistoryTable"
                :data="traces" border>
        <el-table-column label="操作时间"  width="160" 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>
    </el-dialog>


  </div>
</template>


<script>
import {
  getLiveOrder,
  syncExpress,
  updateLiveOrder,
  updateErp,
  getExpress,
  listOrderitem,
  tuiOrder,
  refundOrderMoney,
  editDeliveryId,
  finishOrder,
  getOrderExpress,
  getOrderPayments,
  getOrderLog,
  tuiMoneyLogs,
  updateExpress,
  createErpOrder, getEroOrder, getUserPhone, getLiveOrderAddress
} from "@/api/live/liveOrder";
import {getStoreOrderLive} from "@/api/store/storeOrder";


export default {
  props:["data"],
  data() {
    return {
      expressDialog:{
        title:"物流信息",
        open:false,
      },
      editDy:{
        title:"修改物流单号",
        open:false,
      },
      sourceOptions:[],
      payments: [],
      followDialogVisible:false,
      dialogVisible:false,
      total: 0,
      msgForm:{
        pageNum: 1,
        pageSize: 10,
        userId:null,
        followDoctorId:null,
      },
      deliveryOptions: [],
      editDyForm:{
        id: null,
        orderId: null,
        deliveryId: null,
        deliveryCode: null,
      },
      showList:true,
      edit:{
        title:"修改订单",
        open:false,
      },
      erpDialog:{
        title:"ERP订单信息",
        open:false,
      },
      show:{
        title:"问诊详情",
        open:false,
      },
      pack:{
        title:"套餐包",
        open:false,
      },
      followList:[],
      money:null,
      moneyVisible:false,
      rules:{},
      sendVisible:false,
      logs:[],
      pay:[],
      nickName:null,
      storeName:null,
      PayOptions:[],
      orderOptions:[],
      payStatusOptions:[],
      express:null,
      traces:[],
      msg:[],
      deliverList: [],
      sexOptions:[],
      refundOptions:[],
      channelOptions:[],
      qwSubjectOptions:[],
      tuiOptions:[],
      orOptions:[],
      storeOPtions:[],
      deliveryStatusOptions:[],
      deliveryPayStatusOptions:[],
      deliveryTypeOptions:[],
      orderTypeOptions:[],
      orderBuyTypeOptions:[],
      scheduleOptions:[],
      item:null,
      tuiMoneyLogs:[],
      erpOrder:null,
      prod:null,
      showProd:null,
      editForm:{
        orderId:null,
        status:null,
        userAddress:null,
        deliveryStatus:null,
        deliveryType:null,
        remark:"",
      },
      editDyRules:{
        deliveryId: [
          { required: true, message: "物流单号不能为空", trigger: "blur" }
        ],
        deliveryCode: [
          { required: true, message: "物流公司不能为空", trigger: "blur" }
        ],
      },
      editRules:{
        userAddress: [
          { required: true, message: "收货地址不能为空", trigger: "blur" }
        ],
      },
      mrules:{
      },
      form: {
        deliveryCode: null,
        deliveryName:null,
        deliverySn:null,
        orderId:null,
      }
    }
  },

  computed: {
    /** 产品合计：每个产品单价*数量之和（基于 showProd） */
    productTotal() {
      if (!this.showProd || this.showProd.length === 0) {
        return 0;
      }
      let total = 0;
      for (let i = 0; i < this.showProd.length; i++) {
        const row = this.showProd[i];
        const price = parseFloat(row.price) || 0;
        const num = parseFloat(row.totalNum) || 0;
        total += price * num;
      }
      return total;
    },
    /** 折扣率百分比：实付 / 商品总价（totalPrice） */
    discountRatePercent() {
      if (!this.item || !this.item.totalPrice || parseFloat(this.item.totalPrice) <= 0) {
        return '0.00';
      }
      const payMoney = parseFloat(this.item.payMoney) || 0;
      const totalPrice = parseFloat(this.item.totalPrice) || 0;
      const rate = parseFloat((payMoney / totalPrice).toFixed(2));
      return (rate * 100).toFixed(2);
    }
  },

  created() {
    this.getDicts("sys_store_pay_type").then(response => {
      this.PayOptions = response.data;
    });
    this.getDicts("sys_order_status").then(response => {
      this.orderOptions = response.data;
    });
    this.getDicts("sys_order_pay").then(response => {
      this.payStatusOptions = response.data;
    });
    this.getDicts("sys_order_source").then(response => {
      this.sourceOptions = response.data;
    });
    this.getDicts("sys_store_order_type").then(response => {
      this.orderTypeOptions = response.data;
    });
    this.getDicts("sys_store_order_buy_type").then(response => {
      this.orderBuyTypeOptions = response.data;
    });
    this.getDicts("sys_refund_status").then(response => {
      this.refundOptions = response.data;
    });
    this.getDicts("sys_store_channel").then(response => {
      this.channelOptions = response.data;
    });
    this.getDicts("sys_store_qw_subject").then(response => {
      this.qwSubjectOptions = response.data;
    });
    this.getDicts("sys_tui_money_status").then(response => {
      this.tuiOptions = response.data;
    });
    this.getDicts("sys_company_or").then(response => {
      this.orOptions = response.data;
    });
    this.getDicts("sys_patient_sex").then(response => {
      this.sexOptions = response.data;
    });
    this.getDicts("sys_store_delivery_pay_status").then(response => {
      this.deliveryPayStatusOptions = response.data;
    });
    this.getDicts("store_order_delivery_status").then(response => {
      this.deliveryStatusOptions = response.data;
    });
    this.getDicts("logistics_status").then(response => {
      this.deliveryTypeOptions = response.data;
    });
    this.getDicts("sys_express_company").then(response => {
      this.deliveryOptions = response.data || [];
    });

  },
  methods: {

    getOrderLive(orderId){
      getLiveOrder(orderId).then(response => {
        this.item=response.data
      });
      this.getlistOrderitem(orderId);
    },
    followMsg(row){
      const userId = this.item.userId;
      const followDoctorId =this.item.followDoctorId;
      const doctorName = this.item.doctorName;
      const patientName = this.item.patientName;

      setTimeout(() => {
        this.$refs.msgDetails.getDetails(userId,followDoctorId,doctorName,patientName);
      }, 500);
      this.dialogVisible = true;
    },
    msgDialogClose(){
      this.dialogVisible = false;
    },
    handlePhone(){
      const orderId = this.item.orderId;
      getUserPhone(orderId).then(response =>{
        this.item.userPhone = response.userPhone;
      })
    },
    handleAddress(){
      const orderId = this.item.orderId;
      getLiveOrderAddress(orderId).then(response =>{
        this.item.userAddress = response.address;
      })
    },
    fmt(val) {
      return val != null ? Number(val).toFixed(2) : '0.00'
    },
    editDelivery(scope){
      this.editDy.open = true;
      this.editDyForm.orderId = this.item.orderId;
      if (scope && scope.row) {
        this.editDyForm.id = scope.row.id;
        this.editDyForm.deliveryCode = scope.row.deliverSn;
        this.editDyForm.deliveryId = scope.row.deliverId;
      } else {
        this.editDyForm.id = null;
        this.editDyForm.deliveryCode = null;
        this.editDyForm.deliveryId = '';
      }
    },
    showListD(){
      if(this.showList){
        this.showProd=this.prod
      }else{
        this.showProd=[this.prod[0]]
      }
      this.showList=this.showList?false:true;
    },
    /**
     * 计算出库价（与 productOrder 一致：折扣率四舍五入保留两位小数）
     */
    getOutboundPrice(index, row) {
      if (!this.item || !this.showProd || this.showProd.length === 0) {
        return 0;
      }
      const price = parseFloat(row.price) || 0;
      const num = parseFloat(row.totalNum) || 0;
      const payMoney = parseFloat(this.item.payMoney) || 0;
      if (this.productTotal <= 0) {
        return 0;
      }
      const discountRate = parseFloat((payMoney / this.productTotal).toFixed(2));
      if (this.showProd.length === 1) {
        return price * discountRate;
      }
      const isLastItem = index === this.showProd.length - 1;
      if (isLastItem) {
        let previousTotal = 0;
        for (let i = 0; i < index; i++) {
          const prevRow = this.showProd[i];
          const prevPrice = parseFloat(prevRow.price) || 0;
          const prevNum = parseFloat(prevRow.totalNum) || 0;
          const prevOutboundPrice = prevPrice * discountRate;
          previousTotal += prevOutboundPrice * prevNum;
        }
        return num > 0 ? (payMoney - previousTotal) / num : 0;
      }
      return price * discountRate;
    },

    showExpress(){
      this.expressDialog.open=true;
      getExpress({
        orderId: this.item.orderId,
        deliverId: this.item.deliverySn,
        deliverSn: this.item.deliveryCode,
      }).then(response => {
        this.express = response.data;
        if(this.express!=null&&this.express.Traces!=null){
          this.traces=this.express.Traces
        }
      });
    },
    updateErpOrder(){
      var that=this;
      this.$confirm('确定同步物流单号信息吗', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        var data={orderId:that.item.orderId}
        return updateErp(data);
      }).then(() => {
        this.msgSuccess("操作成功");
        getLiveOrder(this.item.orderId).then(response => {
          this.item=response.data
          that.getlogList(this.item.orderId);
          that.$parent.$parent.getList();
        });
        this.editDy.open = false
      }).catch(function() {});

    },
    sendFollowMsg(){
      var that=this;
      this.$confirm('是否确认发送消息?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return sendMsg(that.item.orderId);
      }).then(() => {
        this.msgSuccess("操作成功");
      }).catch(function() {});
    },
    handleClose1(){
      this.dialogVisible=false;
    },
    handleClose2(){
      this.followDialogVisible=false;
    },
    follow(row){
      getMsgFollow(row).then(response => {
        if(response.data.formJson!=null&&response.data.formJson!=''&&response.data.writeStatus==1){
          this.messageFollowList=JSON.parse(response.data.formJson );
          this.followDialogVisible=true;
        }else{
          this.$message({
            message: '未填写随访单',
            type: 'info'
          });
          return
        }
      });
    },

    //修改订单状态
    submitEditForm(){
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          updateLiveOrder(this.editForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("操作成功");
              this.edit.open = false;
              getLiveOrder(this.item.orderId).then(response => {
                this.item=response.data
                that.getlogList(this.item.orderId);
                that.$parent.$parent.getList();
              });
            }
          });
        }
      });
    },
    editOrder(){
      this.edit.open=true;
      this.editForm.orderId=this.item.orderId;
      this.editForm.remark=this.item.remark;
      this.editForm.userAddress = this.item.userAddress == null ? '' : this.item.userAddress.toString();
      this.editForm.status = this.item.status == null ? '' : this.item.status.toString();
      this.editForm.deliveryType = this.item.deliveryType == null ? '' : this.item.deliveryType.toString();
      this.editForm.deliveryStatus = this.item.deliveryStatus == null ? '' : this.item.deliveryStatus.toString();

    },
    updateExpress(){
      var that=this;
      this.$confirm('确定同步物流信息吗，同步后将自动发货?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        var data=that.item.orderId
        return updateExpress(data);
      }).then(() => {
        this.msgSuccess("操作成功");
        getLiveOrder(this.item.orderId).then(response => {
          this.item=response.data
          that.getlogList(this.item.orderId);
          that.$parent.$parent.getList();
        });
      }).catch(function() {});
    },
    addErpOrder(){
      var that=this;
      this.$confirm('是否确认推送管易?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        var data=that.item.orderCode
        return createErpOrder({
          orderCode: data
        });
      }).then(() => {
        this.msgSuccess("操作成功");
        getLiveOrder(this.item.orderId).then(response => {
          this.item=response.data
          that.getlogList(this.item.orderId);
          that.$parent.$parent.getList();
        });
      }).catch(function() {});
    },
    showErpOrder(){
      this.erpDialog.open=true;
      var data=this.item.extendOrderId;
      getEroOrder({
        extendOrderId: data
      }).then(response => {
        this.erp = response.data;
        if(response.data.orders!=null&&response.data.orders.length==1){
          this.erpOrder=response.data.orders[0]
        }
      });
    },

    editTuiMoney1(){
      var that=this;
      this.$confirm('是否解冻此订单推广佣金吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        var data=that.item.orderId;
        return editTuiMoney(data);
      }).then(() => {
        this.msgSuccess("操作成功");
        getLiveOrder(this.item.orderId).then(response => {
          this.item=response.data
          that.getlogList(this.item.orderId);
          that.$parent.$parent.getList();
        });
      }).catch(function() {});
    },
    editTuiMoney2(){
      var that=this;
      this.$confirm('是否冻结此订单推广佣金吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        var data=that.item.orderId;
        return editTuiMoney(data);
      }).then(() => {
        this.msgSuccess("操作成功");
        getLiveOrder(this.item.orderId).then(response => {
          this.item=response.data
          that.getlogList(this.item.orderId);
          that.$parent.$parent.getList();
        });
      }).catch(function() {});
    },
    returnCost(){
      var that=this;
      this.$confirm('是否退还此订单成本吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        var data=that.item.orderId;
        return returnCost(data);
      }).then(() => {
        this.msgSuccess("操作成功");
        this.getDetails(this.item.orderId,null,null)
      }).catch(function() {});
    },
    moneyCancel(){
      this.money=null;
      this.moneyVisible=false;
    },
    refund(){
      var that=this;
      this.$confirm('是否确认申请退款?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        var data={
          orderId:that.item.orderId
        }
        return refundOrderMoney(data);
      }).then(() => {
        this.msgSuccess("操作成功");
        getLiveOrder(this.item.orderId).then(response => {
          this.item = response.data;
          // this.getlogList(this.item.orderId);
          this.$parent.$parent.getList();
        });
      }).catch(function() {});
    },
    finishOrder(){
      var that=this;
      this.$confirm('是否确认客户已收货?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        var data={
          orderId:that.item.orderId
        }
        return finishOrder(data);
      }).then(() => {
        this.msgSuccess("操作成功");
        getLiveOrder(this.item.orderId).then(response => {
          this.item = response.data;
          this.getlistOrderitem(this.item.orderId);
          this.$parent.$parent.getList();
        });
      }).catch(function() {});
    },


    syncExpress(){
      var that=this;
      this.$confirm('确定同步物流状态吗', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        var data=that.item.orderId
        return syncExpress(data);
      }).then(() => {
        this.msgSuccess("操作成功");
        this.expressDialog.open=false
        getLiveOrder(this.item.orderId).then(response => {
          this.item=response.data
          that.getlogList(this.item.orderId);
          that.$parent.$parent.getList();
        });
      }).catch(function() {});
    },
    getInquiryOrder(){

      this.show.open=true;
      setTimeout(() => {
        this.$refs.Details.getDetails(this.item.inquiryOrderId);
      }, 1);
    },
    getPackageOrder(){
      this.pack.open=true;
      console.log(this.item.packageOrderId)
      setTimeout(() => {
        this.$refs.packDetails.getDetails(this.item.packageOrderId);
      }, 1);
    },
    tuiOrder(){
      var that=this;
      this.$confirm('是否确认推送订单?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        var data={
          orderId:that.item.orderId
        }
        return tuiOrder(data);
      }).then(() => {
        this.msgSuccess("操作成功");
        getLiveOrder(this.item.orderId).then(response => {
          this.item = response.data;
          this.getlogList(this.item.orderId);
          this.$parent.$parent.getList();
        });
      }).catch(function() {});
    },
    getDetails(orderId,nickName,storeName) {
      this.nickName=nickName;
      this.storeName=storeName;
      this.item=null;
      this.tuiMoneyLogs=null;
      getLiveOrder(orderId).then(response => {
        this.item = response.data;
        console.log(this.tuiMoneyLogs)
        this.tuiMoneyLogs = response.tuiMoneyLogs;
        this.msgForm.userId=response.data.userId;
        this.msgForm.followDoctorId=response.data.followDoctorId;
        this.getlistOrderitem(this.item.orderId);
        getOrderExpress(orderId).then(response => {
          this.deliverList = response.data;
          console.log(this.deliverList)
        });

        getOrderPayments(this.item.orderId).then(response => {
          this.payments = response.payments;
        });

        getOrderLog(this.item.orderId).then(response => {
          this.logs = response.logs
        });

        tuiMoneyLogs(this.item.orderId).then(response => {
          this.tuiMoneyLogs = response.data
        })
      });

    },
    getOrder(){
      getLiveOrder(this.item.orderId).then(response => {
        this.item = response.data;
        this.getlistOrderitem(this.item.orderId);
      });
    },
    submitEditDyForm(){
      this.$refs["editDyForm"].validate(valid => {
        if (valid) {
          const params = {
            orderId: this.editDyForm.orderId,
            deliverSn: this.editDyForm.deliveryCode,
            deliverId: this.editDyForm.deliveryId,
            type: 1
          };
          if (this.editDyForm.id != null) {
            params.id = this.editDyForm.id;
          }
          if (!params.deliverName) {
            const selectedOption = this.deliveryOptions.find(option => option.dictValue === params.deliverSn);
            params.deliverName = selectedOption ? selectedOption.dictLabel : null;
          }
          editDeliveryId(params).then(response => {
            if (response.code === 200) {
              this.msgSuccess("操作成功");
              this.editDy.open = false;
              getLiveOrder(this.item.orderId).then(response => {
                this.item = response.data;
                this.$parent.$parent.getList();
              });
              getOrderExpress(this.item.orderId).then(response => {
                this.deliverList = response.data || [];
              });
            }
          })
        }
      });
    },
    getlistOrderitem(orderId){
      this.prod = null
      this.showProd=[]
      this.showList = true
      listOrderitem(orderId).then(response => {
        this.prod = response.rows;
        if (this.prod.length > 0) {
          this.showProd=[this.prod[0]];
        }
      });
    },
    // getlogList(orderId){
    //   logList(orderId).then(response => {
    //     this.logs = response.rows;
    //   });
    // },
    // getPayment(orderId){
    //   payment(orderId).then(response => {
    //     console.log(response)
    //     this.pay = response.data;
    //   });
    // }
  }
}

</script>


<style scoped>
.live-order-detail {
  min-height: 100%;
  padding-bottom: 20px;
  background-color: #f4f6f8;
}

.live-order-detail .live-page__header {
  margin: 0 0 16px;
  padding: 16px 20px;
  background: #fff;
  border: 1px solid #e8eaed;
  border-radius: 10px;
}

.contentx {
  margin: 0 0 14px;
  padding: 14px 16px 16px;
}

.contentx--pad {
  padding-bottom: 24px;
}

.detail-card {
  margin-top: 15px;
  border: 1px solid #e8eaed;
  border-radius: 10px;
}

.desct {
  padding: 12px 0;
  color: #1f2329;
  font-size: 15px;
  font-weight: 600;
}

.section-head {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 4px;
}

.section-head .desct {
  padding: 12px 0;
}

.operate-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px 10px;
  background: #f4f6f8;
  margin: -20px -20px 0;
  padding: 12px 16px;
  border-bottom: 1px solid #e8eaed;
  min-height: auto;
  line-height: 1.4;
}

.operate-status {
  margin-right: auto;
}

.operate-button-container {
  float: none;
  margin: 0;
}

.inline-search-btn {
  margin-left: 12px;
}

.toggle-tip {
  float: right;
}

.detail-table {
  width: 100%;
  margin-top: 16px;
}

.goods-thumb {
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.section-total {
  float: right;
  margin: 20px 0;
  color: #1f2329;
}

.dialog-action-bar {
  margin-bottom: 20px;
}

.delivery-select {
  width: 220px;
}

.el-descriptions-item__label.is-bordered-label {
  font-weight: normal;
  color: #8a919f;
}

.el-descriptions-item__content {
  max-width: 150px;
  min-width: 100px;
  color: #1f2329;
}

.chat-records {
  overflow-y: auto;
}

.timestamp {
  font-size: 12px;
  color: #8a919f;
}

.chat-record {
  margin: 10px;
  flex-direction: column;
  align-items: flex-start;
}

.sent {
  background-color: #fbfdff;
  color: #1f2329;
}

.sent .timestamp {
  float: right;
}

.right {
  float: right;
}

.received {
  background-color: #fbfdff;
  color: #1f2329;
}
</style>
