<template>
  <div style="background-color: #f0f2f5; padding-bottom: 20px; min-height: 100%; " >
    <div style="padding: 20px; background-color: #fff;">
      订单详情
    </div>
  <div class="contentx" 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-1" 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" 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 orderOptions"    v-if="item.status==ite.dictValue">{{ite.dictLabel}}</el-tag>
      </span>
      <div class="operate-button-container" v-if="item.packageOrderId!=null&&item.packageOrderId!=''" v-hasPermi="['his:storeOrder:package']" >
         <el-button size="mini" @click="getPackageOrder()" >套餐包订单</el-button>
      </div>
     <div class="operate-button-container"   v-if="item.deliverySn!=null" v-hasPermi="['his:storeOrder:express']">
       <el-button size="mini" @click="showExpress()" >查看物流</el-button>
     </div>
     <div class="operate-button-container"  v-hasPermi="['his:storeOrder:edit']">
       <el-button size="mini" @click="editOrder()" >修改订单</el-button>
     </div>
     <div class="operate-button-container" v-if="shouldShowRefundButton">
         <el-button size="mini" @click="refund()" v-hasPermi="['his:storeOrder:afterSales']">申请退款</el-button>
     </div>
     <div class="operate-button-container"  v-if="item.followTime!=null&&item.followTime!=''"   v-hasPermi="['store:storeOrder:msgList']"  >
         <el-button size="mini" @click="followMsg()" >随访记录</el-button>
     </div>
     <div class="operate-button-container"  v-if="item.customerId==null||item.customerId==''"   v-hasPermi="['his:storeOrder:bindCustomer']"  >
         <el-button size="mini"  @click="handleBindCustomer()">关联客户</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="会员ID"  ><span v-if="item!=null">{{item.userId}}</span></el-descriptions-item>
      <el-descriptions-item label="支付方式"  ><dict-tag :options="PayOptions" :value="item.payType"/></el-descriptions-item>
      <el-descriptions-item label="药品类型"  ><dict-tag :options="orderTypeOptions" :value="item.orderType"/></el-descriptions-item>
      <el-descriptions-item label="医生名称"  ><span v-if="item!=null">{{item.doctorName}}</span></el-descriptions-item>
      <el-descriptions-item label="患者姓名"  > <span v-if="item!=null">{{item.patientName}}</span></el-descriptions-item>
      <el-descriptions-item label="患者年龄"  ><span v-if="item!=null">{{item.patientAge}}</span></el-descriptions-item>
      <el-descriptions-item label="患者性别"  >  <dict-tag :options="sexOptions" :value="item.patientGender"/>  </el-descriptions-item>
      <el-descriptions-item label="诊断"  ><span v-if="item!=null">{{item.diagnose}}</span> </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 type="text" size="mini" @click="callNumber(0,0,item.orderId,null)"  v-hasPermi="['store:storeOrder:callNumber']">拨号</el-button>
        <el-button type="text" size="mini" @click="handleSms(item.userPhone)" v-hasPermi="['store:storeOrder:sendSms']">短信</el-button>
        <el-button icon="el-icon-search" size="mini" @click="handlePhone()" style="margin-left: 20px;" circle v-hasPermi="['store:storeOrder: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()" style="margin-left: 20px;" circle v-hasPermi="['store:storeOrder: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!=null">{{item.deliveryCode}}</span></el-descriptions-item>
      <el-descriptions-item label="快递名称" ><span v-if="item!=null">{{item.deliveryName}}</span></el-descriptions-item>
      <el-descriptions-item label="快递单号" ><span v-if="item!=null">{{item.deliverySn}}</span></el-descriptions-item>
      <el-descriptions-item label="ERP编号" ><span v-if="item!=null">{{item.extendOrderId}}</span></el-descriptions-item>
      <el-descriptions-item label="物流状态" ><dict-tag :options="deliveryStatusOptions" :value="item.deliveryStatus"/></el-descriptions-item>
      <el-descriptions-item label="物流结算状态" ><dict-tag :options="deliveryPayStatusOptions" :value="item.deliveryPayStatus"/></el-descriptions-item>
      <el-descriptions-item label="物流结算时间" ><span v-if="item!=null">{{item.deliveryPayTime}}</span></el-descriptions-item>
      <el-descriptions-item label="物流结算金额" ><span v-if="item!=null">{{item.deliveryPayMoney}}</span></el-descriptions-item>
      <el-descriptions-item label="物流跟踪状态" ><span v-if="item!=null"><dict-tag :options="deliveryTypeOptions" :value="item.deliveryType"/> </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" v-if="item!=null" style="padding-bottom: 70px;">
  <div class="desct">
      商品信息
     </div>
     <el-tooltip class="item" effect="dark" :content="showList ? '显示全部' : '隐藏'" placement="top" style="float: right;">
       <el-button size="mini" circle icon="el-icon-search" @click="showListD()" />
     </el-tooltip>
  <el-table border v-if="showProd!=null" :data="showProd" 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).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.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="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" >
             ￥{{(scope.row.num*JSON.parse(scope.row.jsonInfo).price).toFixed(2)}}
           </template>
         </el-table-column>
       </el-table>
       <div style="float: right;margin: 20px" v-if="item.totalPrice!=null">
         合计：<span class="color-danger">￥{{item.totalPrice.toFixed(2)}}</span>
       </div>
       <div style="float: right;margin: 20px" v-if="item.orderType==2">
         剂数：<span class="color-danger">{{counts}}</span>
       </div>
  </div>
   <div class="contentx" v-if="item!=null">
  <div class="desct">
    费用信息
  </div>
  <el-descriptions   :column="3" border  >
     <el-descriptions-item label="商品合计"  ><span v-if="item.totalPrice!=null">￥{{item.totalPrice.toFixed(2)}} </span></el-descriptions-item>
     <el-descriptions-item label="处方定价"  ><span v-if="item.prescribePrice!=null"> ￥{{item.prescribePrice.toFixed(2)}}</span></el-descriptions-item>
     <el-descriptions-item label="处方应付金额"  ><span v-if="item.payPrice!=null"> ￥{{item.payPrice.toFixed(2)}}</span></el-descriptions-item>
     <el-descriptions-item label="运费" ><span v-if="item.payDelivery!=null">￥{{item.payDelivery.toFixed(2)}}</span></el-descriptions-item>
     <el-descriptions-item label="优惠劵" ><span v-if="item.discountMoney!=null">￥{{item.discountMoney.toFixed(2)}}</span></el-descriptions-item>
     <el-descriptions-item label="实付金额"  ><span v-if="item.payMoney!=null">￥{{item.payMoney.toFixed(2)}}</span></el-descriptions-item>
     <el-descriptions-item label="代收金额" ><span v-if="item.deliveryStatu!=null">￥{{item.deliveryStatus.toFixed(2)}}</span></el-descriptions-item>
  </el-descriptions>
   </div>
       <div class="contentx" v-if="item!=null">
        <div class="desct">
          支付信息
        </div>
      <el-table
        border
        :data="pay"
        size="small"
        style="width: 100%;margin-top: 20px" >
          <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" 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>
   <el-dialog
    width="50%"
    title="发货"
    :visible.sync="sendVisible"
    append-to-body @close="sendCancel">
  <el-form ref="form" :model="form" :rules="rules" label-width="120px">
     <el-form-item label="快递公司编号" prop="deliveryCode">
       <el-input v-model="form.deliveryCode" placeholder="请输入快递公司编号" />
     </el-form-item>
     <el-form-item label="快递名称" prop="deliveryName">
       <el-input v-model="form.deliveryName" placeholder="请输入快递名称" />
     </el-form-item>
     <el-form-item label="快递单号" prop="deliverySn">
       <el-input v-model="form.deliverySn" placeholder="请输入快递单号" />
     </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
     <el-button type="primary" @click="sendGoods">确 定</el-button>
     <el-button @click="sendCancel">取 消</el-button>
  </div>
  </el-dialog>
     <el-dialog :title="expressDialog.title" :visible.sync="expressDialog.open" width="600px" append-to-body>
       <div  v-hasPermi="['his:storeOrder:syncExpress']"  >
         <el-button size="mini" @click="syncExpress()" >同步快递鸟物流状态</el-button>
       </div>
       <el-table style="margin-top: 20px;width: 100%" 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>
      <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">
          <el-form-item label="物流单号" prop="deliverySn"  >
            <el-input v-model="editDyForm.deliverySn" 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="erpDialog.title" :visible.sync="erpDialog.open" width="600px" append-to-body>
      <div v-if="item!=null&&item.extendOrderId!=null&&item.status==2" style="position: absolute; top: 50px;right: 20px;">
        <el-button size="mini" @click="updateExpress()" v-hasPermi="['his:storeOrder:updateExpress']" >同步物流发货</el-button>
      </div>
       <div class="table-layout"  v-if="erpOrder!=null" >
        <el-descriptions direction="vertical"   :column="4" border >
            <el-descriptions-item label="订单编号" > <span v-if="item!=null"> {{erpOrder.code}}</span></el-descriptions-item>
            <el-descriptions-item label="是否代收" ><span v-if="item!=null">{{erpOrder.cod?'是':'否'}}</span></el-descriptions-item>
            <el-descriptions-item label="快递编号" ><span v-if="item!=null">{{erpOrder.express_code}}</span></el-descriptions-item>
            <el-descriptions-item label="快递名称" ><span v-if="item!=null"> {{erpOrder.express_name}}</span></el-descriptions-item>
            <el-descriptions-item label="收货人" ><span v-if="item!=null">{{erpOrder.receiver_name}}</span></el-descriptions-item>
            <el-descriptions-item label="电话" ><span v-if="item!=null"> {{erpOrder.receiver_mobile}}</span></el-descriptions-item>
            <el-descriptions-item label="地址" ><span v-if="item!=null"> {{erpOrder.receiver_address}}</span></el-descriptions-item>
            <el-descriptions-item label="运单号" ><span v-if="item!=null"> {{erpOrder.deliverys!=null&&erpOrder.deliverys.length>0?erpOrder.deliverys[0].mail_no:''}}</span></el-descriptions-item>
        </el-descriptions>
       </div>
     </el-dialog>
    <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="orderBuyType"  >
          <el-select style="width: 200px" v-model="editForm.orderBuyType" placeholder="请选择订单购买类型" clearable size="small" >
            <el-option
               v-for="item in orderBuyTypeOptions"
               :key="item.dictValue"
               :label="item.dictLabel"
               :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="档期归属" prop="scheduleId"  >
            <el-select filterable style="width: 200px" v-model="editForm.scheduleId" placeholder="请选择档期" clearable size="small" >
              <el-option
                 v-for="item in scheduleOptions"
                   :key="item.id"
                   :label="item.name"
                   :value="item.id"
                 />
            </el-select>
          </el-form-item>
        <el-form-item label="渠道" prop="channel"  >
          <el-select filterable style="width: 200px" v-model="editForm.orderChannel" placeholder="请选择渠道" clearable size="small" >
            <el-option
              v-for="item in channelOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否首次进线" prop="isFirst"  >
          <el-select filterable style="width: 200px" v-model="editForm.isFirst" placeholder="请选择渠道" clearable size="small" >
            <el-option
              v-for="item in orOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="企微主体" prop="qwSubject"  >
          <el-select filterable style="width: 200px" v-model="editForm.qwSubject" placeholder="请选择企微体" clearable size="small" >
            <el-option
              v-for="item in qwSubjectOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark"  >
          <el-input v-model="editForm.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="详情地址" prop="userAddress">
          <el-cascader
            ref="citySelect"
            v-model="cityIds"
            :options="citys"
            :props="{ checkStrictly: true }"
            @change="handleCityChange"
            clearable
          />
          <el-input v-model="editForm.userAddress" placeholder="请输入详细地址(不含省/市/区)" />
        </el-form-item>
        <el-form-item label="收货人电话" prop="userPhone"  >
          <el-input v-model="editForm.userPhone" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
      <el-drawer
            :with-header="false"
            :append-to-body="true"
            size="75%"
            :title="show.title" :visible.sync="show.open">
        <inquiryOrderDetails  ref="Details" />
      </el-drawer>
      <el-drawer
            :with-header="false"
            :append-to-body="true"
            size="75%"
            :title="pack.title" :visible.sync="pack.open">
        <packageOrderDetails  ref="packDetails" />
      </el-drawer>
      <el-dialog :title="addSms.title" :visible.sync="addSms.open" width="800px" append-to-body>
        <add-sms ref="sms" @close="closeSms()"></add-sms>
    </el-dialog>
    <el-dialog
      title="聊天记录"
      :visible.sync="dialogVisible"
      width="80%"
      :before-close="msgDialogClose" append-to-body >
      <msgDetails  ref="msgDetails" :msgDialogClose="msgDialogClose" /><strong></strong>
      <span slot="footer" class="dialog-footer">
        <el-button @click="msgDialogClose">取 消</el-button>
        <el-button type="primary" @click="msgDialogClose">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="bindCustomerDialog.title" :visible.sync="bindCustomerDialog.open" width="800px" append-to-body>
      <el-form ref="bindCustomerForm" :model="bindCustomerForm" :rules="bindCustomerRules" label-width="100px">
        <el-form-item label="客户查询">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-input v-model="bindCustomerForm.mobile"   placeholder="请输入客户手机号"/>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" @click="searchCustomer">查看</el-button>
            </el-col>
          </el-row>

        </el-form-item>
        <el-form-item label="客户选择"  prop="customerIds">
          <el-table   @selection-change="handleSelectionChange"
                :data="customers" border>
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" align="center" prop="customerId" />
            <el-table-column label="客户编号"  width="160" align="center">
              <template slot-scope="scope">
                {{scope.row.customerCode}}
              </template>
            </el-table-column>
            <el-table-column label="客户名称"  width="160" align="center">
              <template slot-scope="scope">
                {{scope.row.customerName}}
              </template>
            </el-table-column>
            <el-table-column label="客户手机号"  width="160" align="center">
              <template slot-scope="scope">
                {{scope.row.mobile}}
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBindCustomerForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {bindCustomer, msgList,getMsgFollow,updateMoney,getGoods,getEroOrder,editTuiMoney,updateDelivery,createErpOrder,updateExpress, afterSales,sendgoods,logList,listOrder,getExpress,syncExpress, listOrderitem,getOrder,getOrderAddress,getUserPhone, delOrder, addOrder, updateStoreOrder, exportOrder,payment,tuiOrder ,getPrescribe} from "@/api/store/storeOrder";
import packageOrderDetails from '../components/packageOrderDetails2.vue';
import {getCustomerListBySearch } from "@/api/crm/customer";
import { getTcmScheduleList } from "@/api/company/tcmScheduleReport";
import addSms from '../../crm/components/addSms.vue';
import msgDetails from '../../store/components/followMsgDetails.vue';
import {getCitys} from "@/api/store/city";
  export default {
    name: "orderDe",
    props:["data"],
    components: { packageOrderDetails,addSms,msgDetails },
    data() {
      return {
        followDialogVisible:false,
        dialogVisible:false,
        messageFollowList:null,
        msgTotal:0,
        msg:[],
        msgDialog:{
          open:false,
          title:"随访记录"
        },
        customers:[],
        bindCustomerDialog:{
          title:"关联客户",
          open:false,
        },
        bindCustomerForm:{
          mobile:null,
          customerIds:null,
        },
        msgForm:{
          pageNum: 1,
          pageSize: 10,
          userId:null,
          followDoctorId:null,
        },
        currentTime: new Date(),
        expressDialog:{
          title:"物流信息",
          open:false,
        },
        editDy:{
          title:"修改物流单号",
          open:false,
        },
        addSms:{
        open:false,
        title:"发短信"
      },
        editDyForm:{
          orderId:null,
          deliveryId:null,
        },
        showList:true,
        edit:{
          title:"修改订单",
          open:false,
        },
        erpDialog:{
          title:"ERP订单信息",
          open:false,
        },
        show:{
          title:"问诊详情",
          open:false,
        },
        pack:{
          title:"套餐包",
          open:false,
        },
        counts:null,
        money:null,
        moneyVisible:false,
        rules:{},
        sendVisible:false,
        logs:[],
        pay:[],
        nickName:null,
        storeName:null,
        PayOptions:[],
        orderOptions:[],
        payStatusOptions:[],
        express:null,
        traces:[],
        sexOptions:[],
        refundOptions:[],
        tuiOptions:[],
        orOptions:[],
        storeOPtions:[],
        deliveryStatusOptions:[],
        deliveryPayStatusOptions:[],
        deliveryTypeOptions:[],
        orderTypeOptions:[],
        orderBuyTypeOptions:[],
        channelOptions:[],
        qwSubjectOptions:[],
        scheduleOptions:[],
        item:null,
        erpOrder:null,
        prod:null,
        showProd:null,
        editForm:{
          orderId:null,
          orderBuyType:null,
          scheduleId:null,
          orderChannel:null,
          qwSubject:null,
          remark:"",
          isFirst:null,
          userAddress: "",
          userPhone: ""
        },
        editDyRules:{
          deliverySn: [
            { required: true, message: "物流单号不能为空", trigger: "blur" }
          ],
        },
        editRules:{
          userAddress: [
            { required: true, message: "收货地址不能为空", trigger: "blur" }
          ],

        },
        mrules:{

        },
        bindCustomerRules:{
          customerIds: [
              { required: true, message: "客户不能为空", trigger: "change" }
          ],

        },
        form: {
          deliveryCode: null,
          deliveryName:null,
          deliverySn:null,
          orderId:null,
        },
        cityIds:[],
        citys:[],
        userAddress:null,
        originalAddress: null,
        originalDetail: "",
      }
    },
    computed: {
      shouldShowRefundButton() {
        const finishTimeInMilliseconds = this.item.finishTime ? new Date(this.item.finishTime).getTime() : null;
        const currentTimeInMilliseconds = this.currentTime.getTime();

        const timeDifferenceInMilliseconds = currentTimeInMilliseconds - finishTimeInMilliseconds;
        const timeDifferenceInDays = timeDifferenceInMilliseconds / (1000 * 60 * 60 * 24);
        if(this.item.orderType===2){
          return false
        }
        if(this.item.payType===3 && this.item.status>2){
          return false
        }

        if (this.item.finishTime === null && this.item.status > 1 && this.item.status < 4) {
          return true; // finishTime为空，item.status > 1，item.status < 4
        }

        console.log(finishTimeInMilliseconds);
        console.log(currentTimeInMilliseconds);
        console.log(timeDifferenceInDays);
        if (this.item.status === 4 && finishTimeInMilliseconds !== null && timeDifferenceInDays <= 3) {
          return true; // item.status === 4，finishTime存在，且当前时间与finishTime之间的时间差小于等于三天
        }

        return false;
      }
    },

    created() {
      getTcmScheduleList().then(response => {
        this.scheduleOptions = response.data;
      });
      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_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("sys_store_order_delivery_status").then(response => {
             this.deliveryStatusOptions = response.data;
           });
        this.getDicts("sys_delivery_type").then(response => {
              this.deliveryTypeOptions = response.data;
            });

    },
    methods: {
      getCitys() {
        return getCitys().then(res => {
          this.citys = res.data || [];
          return this.citys;
        });
      },
      // 新增：切换省市区
      handleCityChange(val) {
        this.cityIds = Array.isArray(val) ? val : [];
      },

      getCityLabelsByIds() {
        if (!this.cityIds || this.cityIds.length === 0) return [];
        const [pVal, cVal, aVal] = this.cityIds;
        const p = this.citys.find(p => p.value === pVal);
        const c = p?.children?.find(c => c.value === cVal);
        const a = c?.children?.find(a => a.value === aVal);
        return [p?.label, c?.label, a?.label].filter(Boolean);
      },
      buildFullAddress() {
        const region = this.getCityLabelsByIds().join(' ');
        const detail = (this.editForm.userAddress || '').trim();
        return region && detail ? `${region} ${detail}` : (region || detail || '');
      },
      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;
      },
      handleBindCustomer() {
        this.customers=[];
        this.bindCustomerDialog.open = true;
        this.bindCustomerForm.mobile=null;
        this.bindCustomerForm.orderId=this.item.orderId;
        this.bindCustomerForm.customerIds=null;
      },


      handleSelectionChange(selection) {
        this.bindCustomerForm.customerIds = selection.map(item => item.customerId)

      },
      submitBindCustomerForm() {
        this.$refs["bindCustomerForm"].validate(valid => {
          if (valid) {

            bindCustomer(this.bindCustomerForm).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.bindCustomerDialog.open = false;
                }
              });
          }
        });
      },
      closeSms(){
        this.addSms.open=false;
      },
      handleSms(mobile){
        this.addSms.open=true;
        var that=this;
        setTimeout(() => {
            that.$refs.sms.getOrderId(this.item.orderId,mobile,2);
        }, 500);

      },
      handlePhone(){
        const orderId = this.item.orderId;
        return getUserPhone(orderId).then(response =>{
            this.item.userPhone = response.userPhone;
        })
      },
      handleAddress(){
        const orderId = this.item.orderId;
        return getOrderAddress(orderId).then(response =>{
            this.item.userAddress = response.address;
        })
      },
      searchCustomer(){
        if(this.bindCustomerForm.mobile==null||this.bindCustomerForm.mobile==""){
          this.msgError("请输入手机号");
          return;
        }
        var data={mobile:this.bindCustomerForm.mobile};
        getCustomerListBySearch(data).then(response => {
            this.customers=response.data;
        });
      },
      editDelivery(){
        this.editDy.open = true;
        this.editDyForm.orderId = this.item.orderId;
        this.editDyForm.deliverySn = this.item.deliverySn;
      },
      showListD(){
        if(this.showList){
          this.showProd=this.prod
        }else{
          this.showProd=[this.prod[0]]
        }
        this.showList=this.showList?false:true;
      },

    showExpress(){
      this.expressDialog.open=true;
      getExpress(this.item.orderId).then(response => {
          this.express = response.data;
          if(this.express!=null&&this.express.Traces!=null){
              this.traces=this.express.Traces
          }
      });
    },
    //修改订单状态
    submitEditForm() {
      this.$refs["editForm"].validate(valid => {
        if (!valid) return;

        // 判断是否修改了地址：选了更深层级 或 详细地址有改动
        const regionChanged = Array.isArray(this.cityIds) && this.cityIds.length > 1;
        const detailChanged = (this.editForm.userAddress || '').trim() !== (this.originalDetail || '');
        const addressModified = regionChanged || detailChanged;

        // 若修改了地址，要求省市区都选到（3级）
        if (addressModified) {
          if (!this.cityIds || this.cityIds.length < 3) {
            this.msgError("请完整选择省/市/区");
            return;
          }
        }

        const payload = {
          ...this.editForm,
          userAddress: addressModified ? this.buildFullAddress() : (this.originalAddress || this.item.userAddress || ''),
        };

        updateStoreOrder(payload).then(response => {
          if (response.code === 200) {
            this.msgSuccess("操作成功");
            this.edit.open = false;
            getOrder(this.item.orderId).then(response => {
              this.item = response.data;
              this.getlogList(this.item.orderId);
              this.$parent.$parent.getList();
            });
          }
        });
      });
    },
    editOrder() {
      this.handlePhone().then(res=>{
        return this.handleAddress()
      }).then(res=>{
        this.edit.open = true;
        this.editForm.orderId = this.item.orderId;
        this.editForm.remark = this.item.remark;
        this.editForm.userPhone = this.item.userPhone != null ? this.item.userPhone.toString() : "";
        if (this.item.orderBuyType != null) {
          this.editForm.orderBuyType = this.item.orderBuyType.toString();
        }
        this.editForm.orderChannel = this.item.orderChannel;
        this.editForm.qwSubject = this.item.qwSubject;
        this.editForm.scheduleId = this.item.scheduleId;

        const currentAddress = (this.item.userAddress || "").toString().trim();
        // 记录原始完整地址
        this.originalAddress = currentAddress;

        this.getCitys().then(() => {
          if (!currentAddress) {
            this.cityIds = [];
            this.editForm.userAddress = "";
            this.originalDetail = "";
            return;
          }
          // 按“省 市 区 详细地址（空格分隔）”进行拆分。若无区或无市也不报错。
          const parts = currentAddress.split(/\s+/);
          const detail = parts.pop() || "";           // 末尾作为详细地址
          const provLabel = parts[0];
          const cityLabel = parts[1];
          const areaLabel = parts[2];

          const province = this.citys.find(p => p.label === provLabel);
          if (province) {
            // 只回显省，不预选市/区
            this.cityIds = [province.value];
          } else {
            console.warn("未匹配到省:", { provLabel });
            this.cityIds = [];
          }
          // 输入框只放“详细地址（不含省市区）”
          this.editForm.userAddress = detail;
          // 记录原始详细地址（用于判断有无修改）
          this.originalDetail = detail;
        });
      })
    },
    updateExpress(){
      var that=this;
      this.$confirm('定同步物流信息吗，同步后将自动发货?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        var data=that.item.orderId
        return updateExpress(data);
      }).then(() => {
        this.msgSuccess("操作成功");
      getOrder(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.orderId
            return createErpOrder(data);
          }).then(() => {
            this.msgSuccess("操作成功");
          getOrder(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(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("操作成功");
           getOrder(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("操作成功");
            getOrder(this.item.orderId).then(response => {
              this.item=response.data
              that.getlogList(this.item.orderId);
              that.$parent.$parent.getList();
            });
          }).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 afterSales(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          getOrder(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 getGoods(data);
         }).then(() => {
           this.msgSuccess("操作成功");
           getOrder(this.item.orderId).then(response => {
               this.item = response.data;
                this.getlistOrderitem(this.item.orderId);
               this.getlogList(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
         getOrder(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("操作成功");
          getOrder(this.item.orderId).then(response => {
              this.item = response.data;
              this.getlogList(this.item.orderId);
              this.$parent.$parent.getList();
          });
        }).catch(function() {});
    },
    sendCancel(){
     this.sendVisible = false;
     this.form={
       deliveryCode: null,
       deliveryName:null,
       deliverySn:null,
       orderId:null,
     }
},
    sendGoods(){
        this.form.orderId=this.item.orderId;
        sendgoods(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.sendVisible = false;
              getOrder(this.item.orderId).then(response => {
                  this.item = response.data;
                  this.getlogList(this.item.orderId);
                  this.$parent.$parent.getList();
              });
              this.form={
              deliveryCode: null,
              deliveryName:null,
              deliverySn:null,
              orderId:null,
            }
        });
      },

      getDetails(orderId,nickName,storeName) {
        this.nickName=nickName;
        this.storeName=storeName;
        this.item=null;
          getOrder(orderId).then(response => {
              this.item = response.data;
              this.getlistOrderitem(orderId);
              this.getlogList(orderId);
              this.getPayment(orderId);
              this.msgForm.userId=response.data.userId;
              this.msgForm.followDoctorId=response.data.followDoctorId;
              if(this.item.orderType==2){
                this.getCount(this.item.prescribeId);
              }
          });
      },
      getCount(id){
        getPrescribe(id).then(response => {

            this.counts =  JSON.parse(response.data.usageJson).counts
        });
      },
      getOrder(){
        getOrder(this.item.orderId).then(response => {
            this.item = response.data;
            this.getlistOrderitem(this.item.orderId);
            this.getlogList(this.item.orderId);
            this.getPayment(this.item.orderId);
            if(this.item.orderType==2){
              this.getCount(this.item.prescribeId);
            }
        });
      },
      submitEditDyForm(){
          this.$refs["editDyForm"].validate(valid => {
          if (valid) {
            console.log(this.editDyForm)
            updateDelivery(this.editDyForm).then(response => {
              if (response.code === 200) {
                this.msgSuccess("操作成功");
                this.editDy.open = false;
                  getOrder(this.item.orderId).then(response => {
                      this.item = response.data;
                      this.getlogList(this.item.orderId);
                      this.$parent.$parent.getList();
                  });
              }
            });
          }
        });
      },

      getlistOrderitem(orderId){
        listOrderitem(orderId).then(response => {
            this.prod = response.rows;
            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>

  .content{
      height: 100%;
      background-color: #fff;
      padding: 0px 20px;

  }
</style>
<style>

  .contentx{
      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>

<style scoped>
.chat-records {

  overflow-y: auto;
}
.timestamp {
  font-size: 12px;
  color: #A9A9A9;
}
.chat-record {
  margin: 10px;
  flex-direction: column;
  align-items: flex-start;
}
.sent {
  background-color: #fbfdff;
  color: #000839;
}
.sent .timestamp {
  float: right;
}
.right{
  float: right;
}
.received {
  background-color: #fbfdff;
  color: #000000;
}

.el-descriptions-item__content {
    max-width: 150px;
    min-width: 100px;
}
.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>
