<template>
  <div class="order-manage-wrapper">
    <bread-crumb
      :curmbFirst="curmbFirst"
      :curmbSecond="curmbSecond"
    ></bread-crumb>
    <div class="order-manage-content screenSet" id="screenSet">
      <div class="header-title">订单管理</div>
      <el-form
        ref="searchForm"
        :model="searchForm"
        label-width="80px"
        label-suffix=":"
        :inline="true"
      >
        <el-row :gutter="30" type="flex" style="margin-top: 10px">
          <el-col :span="24">
            <el-form-item label="商品名称">
              <el-input
                v-model="searchForm.goodsName"
                size="small"
                placeholder="请输入商品名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="订单号">
              <el-input
                v-model="searchForm.orderNo"
                size="small"
                placeholder="请输入订单号"
              ></el-input>
            </el-form-item>
            <el-form-item label="买家名称">
              <el-input
                v-model="searchForm.receiver"
                size="small"
                placeholder="请输入买家名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="创建人">
              <el-input
                v-model="searchForm.prescriberName"
                size="small"
                placeholder="请输入创建人名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30" type="flex" style="margin-top: 10px">
          <el-col :span="24">
            <el-form-item label="下单时间" class="t-b">
              <el-date-picker
                v-model="createRangeTime"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 90%"
                :picker-options="pickerOptions1"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="招募人">
              <el-select
                v-model="searchForm.ownerId"
                id="statusSelector"
                placeholder="请输入招募人"
                @change="changeOwner"
                clearable
              >
                <el-option
                  v-for="item in brokerOwnerList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="药代姓名">
              <el-select
                v-model="searchForm.brokerId"
                id="statusSelector"
                placeholder="请输入药代姓名"
                clearable
              >
                <el-option
                  v-for="item in brokerList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="订单类型">
              <el-select
                v-model="searchForm.saleType"
                placeholder="请选择订单类型"
                size="small"
                clearable
              >
                <el-option
                  v-for="item in saleTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right">
            <div class="button-container">
              <el-button type="primary" size="small" @click="searchFormOrder"
                >查询</el-button
              >
              <el-button
                type="default"
                size="small"
                @click="resetForm"
                style="margin-left: 0"
                >重置</el-button
              >
              <el-button type="primary" size="small" @click="exportOrder"
                >导出订单</el-button
              >
            </div>
            <!-- <div class="button-container">
              <el-button
                type="primary"
                size="small"
                @click="ShowExportDialog(1)"
                >导入物流单号</el-button
              >
              <el-button
                type="primary"
                size="small"
                @click="ShowExportDialog(2)"
                >批量取消订单</el-button
              >
            </div> -->
          </el-col>
        </el-row>
      </el-form>
      <!-- <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="全部" name="all"></el-tab-pane>
        <el-tab-pane label="等待买家付款" name="first"></el-tab-pane>
        <el-tab-pane label="等待发货" name="second"></el-tab-pane>
        <el-tab-pane label="已发货" name="third"></el-tab-pane>
        <el-tab-pane label="交易成功" name="fourth"></el-tab-pane>
        <el-tab-pane label="退款/关闭" name="five"></el-tab-pane>
      </el-tabs> -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="全部" name="all"></el-tab-pane>
        <el-tab-pane label="待支付" name="first"></el-tab-pane>
        <el-tab-pane label="待发货" name="second"></el-tab-pane>
        <el-tab-pane label="已发货" name="third"></el-tab-pane>
        <el-tab-pane label="已完成" name="fourth"></el-tab-pane>
        <el-tab-pane label="已取消" name="six"></el-tab-pane>
        <el-tab-pane label="退款/售后" name="five"></el-tab-pane>
    </el-tabs>
      <el-table
        :data="tableData"
        border
        max-height="1000"
        class="item-table"
        style="width: 100%; margin-top: 10px"
      >
        <el-table-column
          prop="id"
          label="订单号"
          min-width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="goodsNameList"
          label="商品名称"
          min-width="150"
          align="center"
        >
          <template slot-scope="scope">
            <!--<span>{{ scope.row.goodsName }}</span>-->
            <p
              v-for="(item, index) in scope.row.goodsNameList"
              :key="index"
              class="p-normal"
            >
              {{ item }}
            </p>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsShowStatusStrList"
          label="交易状态"
          min-width="100"
          align="center"
        >
        <template slot-scope="scope">
            <!--<span>{{ scope.row.goodsName }}</span>-->
            <p
              v-for="(item, index) in scope.row.goodsShowStatusStrList"
              :key="index"
              class="p-normal"
            >
              {{ item }}
            </p>
          </template>
        </el-table-column>
        <el-table-column
          prop="amount"
          label="订单实付"
          min-width="100"
          align="center"
        >
          <template slot-scope="scope">
            <span>￥{{ scope.row.amount | toFixed2 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="expressFee"
          label="运费"
          min-width="100"
          align="center"
        >
          <template slot-scope="scope">
            <span>￥{{ scope.row.expressFee | toFixed2 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="prescriberName"
          label="创建人"
          min-width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="receiver"
          label="买家"
          min-width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="goodsQuantityList"
          label="数量"
          min-width="100"
          align="center"
        >
          <template slot-scope="scope">
            <!--<span>{{ scope.row.goodsQuantity }}</span>-->
            <p
              v-for="(item, index) in scope.row.goodsQuantityList"
              :key="index"
              class="p-normal"
            >
              {{ item }}
            </p>
          </template>
        </el-table-column>
        <el-table-column
          prop="sizeList"
          label="规格"
          min-width="100"
          align="center"
        >
          <template slot-scope="scope">
            <!--<span>{{ scope.row.size }}</span>-->
            <p
              v-for="(item, index) in scope.row.sizeList"
              :key="index"
              class="p-normal"
            >
              {{ item }}
            </p>
          </template>
        </el-table-column>
        <el-table-column
          prop="priceList"
          label="单价"
          min-width="100"
          align="center"
        >
          <template slot-scope="scope">
            <!--<span>￥{{ scope.row.price }}</span>-->
            <p
              v-for="(item, index) in scope.row.priceList"
              :key="index"
              class="p-normal"
            >
              ￥{{ item | toFixed2 }}
            </p>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsTotalPrice"
          label="商品总额"
          min-width="100"
          align="center"
        >
          <template slot-scope="scope">
            <p
              v-for="(item, index) in scope.row.goodsTotalPriceList"
              :key="index"
              class="p-normal"
            >
              ￥{{ item | toFixed2 }}
            </p>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsRealPay"
          label="商品实付"
          min-width="100"
          align="center"
        >
          <template slot-scope="scope">
            <p
              v-for="(item, index) in scope.row.goodsRealPayList"
              :key="index"
              class="p-normal"
            >
              ￥{{ item | toFixed2 }}
            </p>
          </template>
        </el-table-column>

        <el-table-column
          prop="commissionAmount"
          label="返现"
          min-width="100"
          align="center"
        >
        <template slot-scope="scope">
            <p
              v-for="(item, index) in scope.row.goodsCommissionAmountList"
              :key="index"
              class="p-normal"
            >
              ￥{{ item | toFixed2 }}
            </p>
          </template>
        </el-table-column>

        <el-table-column
          prop="saleTypeStr"
          label="销售方式"
          width="170"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="下单时间"
          min-width="100"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="ownerName"
          label="招募人"
          min-width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="brokerName"
          label="药代姓名"
          min-width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="comments"
          label="备注"
          min-width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          label="操作"
          min-width="250"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <div>
              <!--<el-button @click="closeTrade(scope.row)" type="text" size="small">关闭交易</el-button>-->
              <!--<el-button @click="changePrice(scope.row)" type="text" size="small">修改价格</el-button>-->
              <!--              <el-button @click="sendGoods(scope.row)" type="text" size="small">发货</el-button>-->
              <!-- <el-button
                v-if="
                  scope.row.storeType == 1 &&
                  scope.row.showStatus == 3 &&
                  scope.row.refundStatus == 0
                "
                @click="sendGoods(scope.row)"
                type="text"
                size="small"
                >发货</el-button
              >
              <el-button
                v-if="
                  scope.row.storeType == 2 &&
                  scope.row.showStatus == 3 &&
                  scope.row.refundStatus == 0
                "
                @click="distribute(scope.row)"
                type="text"
                size="small"
                >配送</el-button
              >
              <el-button
                v-if="
                  (scope.row.storeType == 1 || scope.row.storeType == 2) &&
                  (scope.row.showStatus == 1 || scope.row.showStatus == 2)
                "
                @click="viewLogistics(scope.row)"
                type="text"
                size="small"
                >查看物流</el-button
              >
              <el-button
                v-if="scope.row.storeType == 2 && scope.row.showStatus == 2 && scope.row.expressType == 2"
                @click="distributeComplete(scope.row)"
                type="text"
                size="small"
                >配送完成</el-button
              > -->
              <el-button type="text" size="small" @click="goDetail(scope.row)">查看详情</el-button>
              <!-- <el-button
                v-if="
                  (scope.row.storeType == 1 || scope.row.storeType == 2) &&
                  scope.row.showStatus == 3 &&
                  scope.row.refundStatus == 0
                "
                @click="openTuiDialog(scope.row)"
                type="text"
                size="small"
                >退款退货</el-button
              > -->
              <!-- <el-button type="text" size="small">查看物流</el-button> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleNumChange"
          :current-page="searchForm.pageNo"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRows"
        ></el-pagination>
      </div>

      <!-- 关闭交易 -->
      <el-dialog
        title="确定关闭交易吗？"
        :visible="closeTradeDialog"
        @close="cancelTrade"
        :show-close="false"
        width="600px"
        center
      >
        <p style="text-align: center; margin-top: -25px; color: #9b9997">
          关闭后买家将不能再付款
        </p>
        <div style="text-align: center; margin-top: 30px">
          <el-input
            type="textarea"
            v-model="reasonTxt"
            maxlength="400"
            rows="5"
            placeholder="请输入备注内容"
            style="width: 80%"
          ></el-input>
          <span class="word-num"
            >{{ reasonTxt.replace(/\s+/g, "").length }}/400</span
          >
        </div>
        <!--<el-form ref="auditForm" :model="auditForm" label-width="120px">
          <el-form-item label="拒绝原因：">
            <el-radio-group v-model="auditForm.label">
              <div v-for="item in refuseReasonList" :key="item">
                <div style="padding-top: 12px;">
                  <el-radio :label="item"></el-radio>
                </div>
              </div>
              <div style="padding-top: 16px;">
                <el-radio label="其他"></el-radio>
              </div>
            </el-radio-group>
            <div v-if="auditForm.label == '其他'">
              <el-input type="textarea" v-model="auditForm.desc" maxlength="25" style="width: 310px;margin-top: 10px;"></el-input>
              <span class="word-num">{{(auditForm.desc).replace(/\s+/g,"").length}}/25</span>
            </div>
          </el-form-item>
        </el-form>-->
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="cancelTrade">取 消</el-button>
          <el-button size="small" type="primary" @click="submitTrade"
            >关闭交易</el-button
          >
        </span>
      </el-dialog>

      <!-- 修改价格 -->
      <el-dialog
        title="修改价格"
        :visible="changePriceDialog"
        @close="cancelPrice"
        width="600px"
        center
      >
        <el-form
          ref="changePriceForm"
          :model="changePriceForm"
          label-width="120px"
          label-suffix=":"
        >
          <el-form-item label="目前价格">
            <span>￥{{ changePriceForm.nowPrice }}</span>
          </el-form-item>
          <el-form-item label="修改价格">
            <el-input
              type="text"
              v-model="changePriceForm.updatePrice"
              placeholder="请输入修改后的价格"
              style="width: 70%"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" type="primary" @click="submitPrice"
            >完成</el-button
          >
        </span>
      </el-dialog>

      <!-- 配送信息 -->
      <send-set-dialog
        :sendGoodsDialog="sendGoodsDialog"
        :sendSetFormData="sendSetForm"
        :dtType="dtType"
        @closeSendSet="closeSendSet"
      >
      </send-set-dialog>


      <!-- 查看快递物流 -->
      <el-dialog
        title="查看物流"
        :visible="viewLogisticsDialog"
        @close="cancelView"
        :show-close="false"
        width="700px"
        center
      >
        <div class="view-content">
          <div>
            <i class="el-icon-truck" style="font-size: 18px"></i
            ><span class="send-status">已发货</span>
            <span class="view-number">{{ logisticeInfo.expressName }}  {{logisticeInfo.expressNo}}</span>
          </div>
          <div>
            <el-button type="text" @click="copyTxt">复制单号</el-button>
            <el-button type="text" @click="updateOrderNo" v-if="showStatus == 2"
              >修改物流单号</el-button
            >
          </div>
        </div>
        <div class="steps-logistics">
          <el-steps direction="vertical" :active="0">
            <el-step
              v-for="item in expressData"
              :title="item.time"
              :description="item.context"
              :key="item.time"
            >
              <div slot="icon">
                <div class="dot"></div>
              </div>
            </el-step>
          </el-steps>
        </div>
        <input type="text" id="copyInput" class="hidden-input" />
        <span slot="footer" class="dialog-footer">
          <el-button size="small" type="primary" @click="cancelView"
            >我知道了</el-button
          >
        </span>
      </el-dialog>


      <!-- 查看线下配送(云鹊配送)物流 -->
      <el-dialog
        title="查看物流"
        :visible="offlineDialog"
        :show-close="false"
        width="600px"
        center
      >
        <div class="offline-content">
          <p class="offline-title" v-if="offlinedata.showStatus == 1">云鹊配送完成</p>
          <p class="offline-title" v-if="offlinedata.showStatus == 2">云鹊配送中</p>
          <div class="offline-main">
            <p class="offline-msg">配送员： {{offlinedata.sender || '--'}} </p>
            <p class="offline-msg">手机号： {{offlinedata.senderMobile || '--'}}</p>
            <p class="offline-msg ">备 注： {{offlinedata.remark || '--'}}</p>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" type="primary" @click="()=>offlineDialog = false"
            >我知道了</el-button
          >
        </span>
      </el-dialog>

      <!-- 配送完成 -->
      <el-dialog
        title=""
        :visible="disCompleteDialog"
        @close="cancelDis"
        :show-close="false"
        width="600px"
        center
      >
        <div class="view-content">
          <p class="center-title">确认配送完成吗？</p>
          <p class="center-subtitle">请确认线下已将商品送达</p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="cancelDis">取消</el-button>
          <el-button size="small" type="primary" @click="submitDisComplete"
            >配送完成</el-button
          >
        </span>
      </el-dialog>
    </div>

    <!-- 退款退货 -->
    <el-dialog
      class="tui-dialog"
      title="退款退货"
      :visible="showTuiDialog"
      @close="showTuiDialog = false"
      width="385px"
    >
      <div style="margin-bottom: 20px; margin-top: -20px; text-align: center">
        <span style="color: red"
          >温馨提示：订单一旦退款，订单关联的预约单将被同步取消，请谨慎操作退款</span
        >
      </div>
      <el-form
        ref="tuiForm"
        :rules="rules"
        :model="tuiForm"
        label-width="120px"
      >
        <el-form-item label="退款退货方式：">
          <el-select v-model="tuiForm.type" placeholder="请选择退货方式">
            <el-option
              v-for="item in tuiTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="退款金额" prop="name">
          <el-input v-model="tuiForm.money" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="退款对象" prop="userName">
          <el-select v-model="userType" placeholder="请选择退款对象">
            <el-option
              v-for="item in userTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="退款理由" prop="">
          <el-input
            :maxlength="20"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入内容"
            v-model="tuiForm.refundReason"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="confirmTui"
          >完成</el-button
        >
      </span>
    </el-dialog>

    <!-- 修改物流单号 -->
    <el-dialog
      class="tui-dialog"
      title="修改物流单号"
      :visible="showOrderNoFlag"
      @close="showOrderNoFlag = false"
      width="600px"
    >
      <el-form
        ref="expressForm"
        :rules="rulesExpress"
        :model="expressForm"
        label-width="120px"
      >
        <el-form-item label="快递公司" prop="company">
          <el-input v-model="expressForm.company"></el-input>
        </el-form-item>
        <el-form-item label="快递单号" prop="no">
          <el-input v-model="expressForm.no"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="extendMessage">
          <el-input v-model="expressForm.extendMessage"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="confirmExpressNo"
          >完成</el-button
        >
      </span>
    </el-dialog>

    <!-- 导入物流单号 dialog-->
    <el-dialog
      class="exportlogistics-dialog"
      :title="ExportType == 1 ? '导入物流单号' : '批量取消订单'"
      :visible="exportDialog"
      @close="exportDialog = false"
      width="600px"
    >
      <el-form label-width="120px">
        <el-form-item label="导入文档：">
          <el-upload
            class="upload-excel"
            action="#"
            accept=".xlsx"
            multiple
            :limit="1"
            :show-file-list="false"
            :before-upload="uploadfile"
          >
            <div class="upload-container">
              <el-input
                class="file-name"
                v-model="fileData.fileName"
                size="mini"
                readonly
              ></el-input
              ><el-button type="primary" size="mini">选择文件</el-button>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="模板：">
          <a v-if="ExportType == 1" class="importUrl" :href="LogisticsUrl">
            物流单号修改模板.xlxs</a
          >
          <a v-else class="importUrl" :href="CancelOrderUrl">
            批量取消模板.xlxs</a
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancelExport">取消</el-button>
        <el-button
          size="small"
          :loading="isLoading"
          type="primary"
          @click="confirmExport"
          >确认</el-button
        >
      </div>
    </el-dialog>

    <!-- 导出进度loading -->
    <el-dialog
      class="exportlogistics-dialog"
      :visible="progressFlag"
      width="600px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div>
        <div class="progress-container">
          <div class="progress-tag">
            {{ ProgressData.doneNum }}/{{ ProgressData.totalNum }}
            <div class="popper__arrow"></div>
          </div>
          <div class="progress-content">正在导入...</div>
        </div>
      </div>
    </el-dialog>

    <!-- 结果统计 -->
    <el-dialog
      class="exportlogistics-dialog"
      title="导入完成"
      :visible="statFlg"
      @close="statFlg = false"
      width="600px"
    >
      <div class="stat-container">
        <div class="stat-title">模板数据共{{ ProgressData.totalNum }}条</div>
        <div class="stat-result">
          <div class="success">成功：{{ ProgressData.successNum }}条</div>
          <div class="repetition">重复：{{ ProgressData.repeatNum }}条</div>

          <div class="repetition">空行：{{ ProgressData.nullNum  }}条</div>

          <div class="failure">失败：{{ ProgressData.failNum }}条</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="statFlg = false">取消</el-button>
        <el-button size="small" type="primary" @click="showReasondialog"
          >查看失败原因</el-button
        >
      </div>
    </el-dialog>

    <!-- 失败原因 -->
    <el-dialog
      class="exportlogistics-dialog"
      title="失败记录"
      :visible="FailureReasonFlag"
      @close="FailureReasonFlag = false"
      width="1000px"
    >
      <div class="FailureReasonFlag-container" v-if="ExportType == 1">
        <el-table
          :data="ProgressData.errorList"
          border
          height="300"
          style="width: 100%"
        >
          <el-table-column
            prop="subOrderId"
            label="订单号"
            align="center"
            width="210"
          ></el-table-column>
          <el-table-column
            prop="expressName"
            label="快递公司"
            align="center"
          ></el-table-column>
          <el-table-column prop="expressNo" label="快递单号" align="center">
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center">
          </el-table-column>
          <el-table-column prop="failInfo" label="失败原因" align="center">
          </el-table-column>
          <el-table-column
            prop="operationGuide"
            label="操作指引"
            align="center"
          >
          </el-table-column>
        </el-table>
      </div>

      <div class="FailureReasonFlag-container" v-else>
        <el-table
          :data="ProgressData.errorList"
          border
          height="300"
          style="width: 100%"
        >
          <el-table-column
            prop="subOrderId"
            label="订单号"
            align="center"
            width="210"
          ></el-table-column>
          <el-table-column
            prop="refundReason"
            label="取消原因"
            align="center"
          ></el-table-column>
          <el-table-column prop="failInfo" label="失败原因" align="center">
          </el-table-column>
          <el-table-column
            prop="operationGuide"
            label="操作指引"
            align="center"
          >
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="FailureReasonFlag = false"
          >取消</el-button
        >
        <a :href="ProgressData.errorFileUrl">
          <el-button size="small" type="primary">导出失败记录</el-button>
        </a>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { openLoading, closeLoading } from "../../utils/utils";
import BreadCrumb from "@/components/breadcrumb.vue";
import SendSetDialog from "@/components/shop/send-set-dialog";
import {
  getOrdersExportUrl,
  uploadExpress,
  uploadRefund,
  getUploadExpressProgress,
  getUploadRefundProgress,
} from "@/utils/yqrange/yqrangeApi";
import {
  queryOrderList,
  updateExpress,
  refundApply,
  brokerListAll,
  brokerOwnerListAll,
  updateExpressNo,
  expressInfo,
} from "@/utils/shop";
import { toDecimal2 } from "@/utils";

export default {
  components: {
    SendSetDialog,
    BreadCrumb,
  },
  data() {
    return {
      createRangeTime: "",
      curmbFirst: "云鹊店铺",
      curmbSecond: "订单管理",
      activeName: "all",
      showStatus: -1,
      searchForm: {
        showStatus: -1,
        storeId: 0,
        goodsName: "",
        orderNo: "",
        receiver: "",
        prescriberName: "",
        orderTime: "",
        orderBeginTime: "",
        orderEndTime: "",
        brokerId: "",
        ownerId: "",
        pageNo: 1,
        pageSize: 10,
        saleType: 0,
      },
      // 确认物流
      statFlg: false,
      exportDialog: false,
      ExportType: 1, // 1导入物流信息 2、批量取消订单
      FailureReasonFlag: false,
      progressFlag: false,
      totalRows: 0,
      tableData: [],
      FailureTable: [],
      closeTradeDialog: false,
      reasonTxt: "",
      changePriceDialog: false,
      changePriceForm: {
        nowPrice: 45,
        updatePrice: "",
      },
      sendGoodsDialog: false,
      dtType: 1,
      sendSetForm: {},
      viewLogisticsDialog: false,
      logisticeInfo: {
        expressName: '',
        expressNo: ''
      }, //复制物流信息
      disCompleteDialog: false,
      offlineDialog: false, // 线下配送
      offlinedata:{ //线下配送的物流信息
        showStatus: 0,
        sender: '',
        senderMobile: '',
        remark: ''
      },
      disCompleteData: {},
      rules: {
        name: [{ required: true, message: "请输入快递公司", trigger: "blur" }],
        orderNum: [
          { required: true, message: "请输入快递单号", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "请选择退款对象", trigger: "blur" },
        ],
      },
      expressData: [
        {
          time: "",
          context: "待揽收",
        },
      ],
      showTuiDialog: false,
      tuiForm: {
        order: null,
        type: 0,
        refundReason: "",
        money: "",
      },
      expressForm: {
        order: null,
        company: "",
        no: "",
        extendMessage: "",
      },
      rulesExpress: {
        company: [
          { required: true, message: "请输入快递公司", trigger: "blur" },
        ],
        no: [{ required: true, message: "请输入快递单号", trigger: "blur" }],
      },
      tuiTypes: [
        {
          label: "仅退款，无需退货",
          value: 0,
          disabled: false,
        },
        {
          label: "仅退货，无需退款",
          value: 1,
          disabled: true,
        },
        {
          label: "退款退货",
          value: 2,
          disabled: true,
        },
      ],
      userType: "", // 1.开单医生, 2.支付用户
      userTypes: [
        {
          label: "开单医生",
          value: 1,
        },
        {
          label: "支付用户",
          value: 2,
        },
      ],
      saleTypeList: [
        {
          value: 0,
          label: "全部",
        },
        {
          value: 1,
          label: "零售",
        },
        {
          value: 2,
          label: "批发",
        },
      ],
      fileData: {
        fileBaseStr: "",
        fileName: "",
      },
      ownerId: "",
      brokerList: [],
      brokerOwnerList: [],
      showOrderNoFlag: false,
      LogisticsUrl:
        "https://pica-pro.oss-cn-shanghai.aliyuncs.com/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet/2021/08/12/20210812101318239-4c4e680b.xlsx",
      CancelOrderUrl:
        "https://pica-pro.oss-cn-shanghai.aliyuncs.com/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet/2021/08/12/2021081210125196-5a8743b1.xlsx",
      timer: null,
      pickerOptions1: {
        disabledDate: (time) => {
          return time.getTime() > new Date().getTime(); //减去一天的时间代表可以选择同一天;
        },
      },

      ProgressData: {
        totalNum: "", //总数
        nullNum:"",//空白行
        status: "", // 1完成 0进行中
        doneNum: "", // doneNum 完成数量
        successNum: "", // 成功数量
        failNum: "", //失败数量
        repeatNum: "",
        errorFileUrl: "", // 失败 原因文件
        errorList: [], // 失败列表
      },
      isLoading: false
      // errorFileUrl:"",
    };
  },
  created() {
    console.log("order created() : enter");
    (this.searchForm.storeId = this.$route.query.storeId || 0),
      this.searchList();
    this.brokerListAll();
    this.brokerOwnerListAll();
  },
  methods: {
    searchFormOrder(){
      this.searchForm.pageNo=1
      this.searchList();
    },
    //  确认导入
    confirmExport() {
      if (this.ExportType == 1) {
        this.uploadExpress();
      } else {
        this.uploadRefund();
      }
    },
    //
    ShowExportDialog(type) {
      this.ExportType = type;
      this.exportDialog = true;
      this.fileData = {
        fileBaseStr: "",
        fileName: "",
      };
    },
    // 批量更新物流操作
    uploadExpress() {
      this.isLoading = true;
      openLoading(this);
      uploadExpress(this.fileData)
        .then((res) => {
          if (res && res.code == "000000") {
            closeLoading(this);

            this.getUploadExpressProgressInterval(
              res.data.tradeBatchUploadLogId
            );
          } else {
            this.isLoading = false;
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          this.isLoading = false;
          closeLoading(this);
        });
    },
    // 批量取消退款操作
    uploadRefund() {
      this.isLoading = true;
      openLoading(this);
      uploadRefund(this.fileData)
        .then((res) => {
          console.log(res);
          if (res && res.code == "000000") {
            closeLoading(this);
            this.getUploadRefundProgressInterval(res.data.tradeBatchUploadLogId);
          } else {
            this.isLoading = false;
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          this.isLoading = false;
          closeLoading(this);
        });
    },
    // 获取物流上传进度
    async getUploadExpressProgressInterval(id) {
      clearInterval(this.timer);
      let status = await this.getUploadExpressProgress(id);
      if (status == 0) {
        console.log("status------", status);
        this.timer = setInterval(() => {
          this.getUploadExpressProgress(id);
        }, 2000);
      }
    },
    getUploadExpressProgress(id) {
      return getUploadExpressProgress(id).then((res) => {
        if (res && res.code == "000000") {
          this.isLoading = false;
          this.exportDialog = false;
          this.progressFlag = true;
          this.ProgressData = res.data;
          if (res.data.status == 1) {
            clearInterval(this.timer);
            setTimeout(() => {
              this.progressFlag = false;
              this.statFlg = true;
              this.searchList();

            }, 2000);
          }
          return res.data.status;
        } else {
          this.isLoading = false;
          this.$message.error(res.message);
          return;
        }
      });
    },
    // 获取批量取消进度
    async getUploadRefundProgressInterval(id) {
      clearInterval(this.timer);
      let status = await this.getUploadRefundProgress(id);
      if (status == 0) {
        this.timer = setInterval(() => {
          this.getUploadRefundProgress(id);
        }, 2000);
      }
    },
    getUploadRefundProgress(id) {
      return getUploadRefundProgress(id).then((res) => {
        if (res && res.code == "000000") {
          this.exportDialog = false;
          this.progressFlag = true;
          this.ProgressData = res.data;
          this.isLoading = false;
          if (res.data.status == 1) {
            clearInterval(this.timer);
            setTimeout(() => {
              this.progressFlag = false;
              this.statFlg = true;
              this.searchList()
            }, 2000);
          }
          return res.data.status;
        } else {
          this.isLoading = false;
          this.$message.error(res.message);
          return;
        }
      });
    },
    // 取消导入物流信息
    cancelExport() {
      (this.fileData = {
        fileBaseStr: "",
        fileName: "",
      }),
        (this.exportDialog = false);
    },
    // 导入物流单号
    uploadfile(file) {
      let _this = this;
      let arr = file.type.split("/");
      let ext = "." + arr[1];
      let name = file.name;
      let reader = new FileReader();
      reader.onload = function (e) {
        _this.fileData.fileName = name;
        _this.fileData.fileBaseStr = e.target.result.substr(
          e.target.result.indexOf("base64,") + 7
        );

        console.log("fileJson", _this.fileData);
      };
      reader.readAsDataURL(file);
    },
    // 确认取消订单
    showReasondialog() {
      this.statFlg = false;
      this.FailureReasonFlag = true;
    },
    searchList() {
      this.searchForm.orderBeginTime = this.createRangeTime[0];
      this.searchForm.orderEndTime = this.createRangeTime[1];
      console.log("searchList搜索开始");
      openLoading(this);
      queryOrderList(this.searchForm).then((res) => {
        closeLoading(this);
        if (res.code == "000000") {
          console.log("searchList搜索结束");
          this.tableData = res.data.orderSingleDtoList;
          this.totalRows = res.data.totalNum;
        }
      });
    },
    resetForm() {
      console.log("resetForm重置");
      this.activeName = "all";
      this.createRangeTime = "";
      this.searchForm = {
        showStatus: -1,
        storeId: this.$route.query.storeId,
        goodsName: "",
        prescriberName: "",
        orderBeginTime: "",
        orderEndTime: "",
        orderNo: "",
        receiver: "",
        orderDate: "",
        brokerId: "",
        ownerId: "",
        saleType: 0,
        pageNo: 1,
        pageSize: 10,
      };
      this.ownerId = "";
      this.searchList();
      this.brokerOwnerListAll();
      this.brokerListAll();
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.searchForm.pageNo = 1;
      this.searchList();
    },
    handleNumChange(val) {
      this.searchForm.pageNo = val;
      this.searchList();
    },
    handleClick(tab, event) {
      //-1全部，1已完成,2已发货,3待发货,4待支付,5交易关闭
      if (this.activeName == "all") {
        //全部
        this.searchForm.showStatus = -1;
      } else if (this.activeName == "first") {
        //等待买家付款
        this.searchForm.showStatus = 4;
      } else if (this.activeName == "second") {
        //待发货
        this.searchForm.showStatus = 3;
      } else if (this.activeName == "third") {
        //已发货
        this.searchForm.showStatus = 2;
      } else if (this.activeName == "fourth") {
        //交易成功
        this.searchForm.showStatus = 1;
      } else if (this.activeName == "five") {
        //交易关闭
        this.searchForm.showStatus = 5;
      } else if (this.activeName == "six") {
        //交易关闭
        this.searchForm.showStatus = 6;
      }
      this.searchForm.pageNo = 1;
      this.searchList();
    },
    //关闭交易
    closeTrade(row) {
      this.closeTradeDialog = true;
    },
    cancelTrade() {
      this.closeTradeDialog = false;
    },
    submitTrade() {
      this.closeTradeDialog = false;
    },
    //修改价格
    changePrice(row) {
      this.changePriceDialog = true;
    },
    cancelPrice() {
      this.changePriceDialog = false;
    },
    submitPrice() {
      this.changePriceDialog = false;
    },
    //发货
    sendGoods(row) {
      this.dtType = 1;
      this.sendGoodsDialog = true;
      this.sendSetForm = row;
    },
    closeSendSet(val) {
      console.log("关闭，val.type:" + val.type);
      //保存操作
      if (val.type == 2) {
        console.log("刷新列表resetForm");
        this.resetForm(); //更新列表
      }
      this.sendGoodsDialog = false;
    },
    //配送
    distribute(row) {
      this.dtType = 2;
      this.sendGoodsDialog = true;
      this.sendSetForm = row;
    },
    //查看物流
    viewLogistics(row) {
      console.log("row-----", row);
      // expressType 1为物流配送 2为线下
      if (row.expressType == 2) {
        this.showOffline(row);
        return;
      }
      expressInfo({ expressNo: row.expressNo,receiverMobile:row.receiverMobile }).then((res) => {
        if (res.code == "000000") {
          if (res.data.data && res.data.data.length) {
            this.expressData = res.data.data;
          } else {
            this.expressData[0].time = res.data.updateTime || '';
            this.expressData = this.expressData;
          }
          this.logisticeInfo = {
            expressName: row.expressName,
            expressNo: row.expressNo
          };
          this.expressForm.order = row;
          this.expressForm.company = `${row.expressName}`;
          this.expressForm.no = `${row.expressNo}`;
          this.expressForm.extendMessage = `${row.remark}`;
          this.showStatus = row.showStatus;
          this.viewLogisticsDialog = true;
        }
      });
    },
    // 展示线下物流信息
    showOffline(row) {
      const {sender, senderMobile, remark, showStatus} = row; 
      this.offlinedata = {sender, senderMobile, remark, showStatus};
      this.offlineDialog = true
    },
    cancelView() {
      this.viewLogisticsDialog = false;
    },
    copyTxt() {
      let txt = document.getElementById("copyInput");
      txt.value = this.logisticeInfo.expressNo;
      // if (navigator.userAgent.match(/(iPhone|iPod|iPad|Mac);?/i)) {
      if (
        navigator.userAgent.indexOf("Safari") > -1 &&
        navigator.userAgent.indexOf("Chrome") < 1
      ) {
        var el = document.createElement("input");
        el.value = txt.value; //要复制的内容
        el.style.opacity = "0";
        document.body.appendChild(el);
        var editable = el.contentEditable;
        var readOnly = el.readOnly;
        el.contentEditable = true;
        el.readOnly = false;
        const range = document.createRange();
        range.selectNodeContents(el);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
        el.setSelectionRange(0, 999999);
        el.contentEditable = editable;
        el.readOnly = readOnly;
        var ret = document.execCommand("copy");
        el.blur();
      } else {
        txt.select(); //选择对象
        document.execCommand("copy");
      }
      this.$message.success("复制成功");
    },
    //配送完成
    distributeComplete(row) {
      this.disCompleteDialog = true;
      this.disCompleteData = row;
    },
    cancelDis() {
      this.disCompleteDialog = false;
    },
    //确认配送完成
    submitDisComplete() {
      let para = this.disCompleteData;
      para.type = 3;
      updateExpress(para).then((res) => {
        if (res.code == "000000") {
          this.$message.success("操作成功");
          this.disCompleteDialog = false;
          this.resetForm(); //更新列表
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //查看详情
    goDetail(row) {
      this.$router.push({
        path: `/order-detail`,
        query: {
          id: row.id,
          storeId: this.searchForm.storeId,
          storeType: row.storeType,
        },
      });
    },
    openTuiDialog(item) {
      this.tuiForm.order = item;
      this.tuiForm.money = toDecimal2(item.amount);
      this.showTuiDialog = true;
    },
    confirmTui() {
      if (this.userType == null || this.userType == "") {
        this.$message.error("请选择退款对象");
        return;
      }
      refundApply({
        orderId: this.tuiForm.order.id,
        userType: this.userType,
        refundReason: this.tuiForm.refundReason,
      }).then((res) => {
        if (res.code == "000000") {
          this.$message.success("操作成功");
          this.showTuiDialog = false;
          this.searchList();
        } else {
          this.$message.success(`操作失败:${res.message}，请重试`);
        }
      });
    },
    // 修改物流单号
    updateOrderNo() {
      this.viewLogisticsDialog = false;
      this.showOrderNoFlag = true;
    },
    confirmExpressNo() {
      if (this.expressForm.company == null || this.expressForm.company == "") {
        this.$message.error("请填写快递公司");
        return;
      }
      if (this.expressForm.no == null || this.expressForm.no == "") {
        this.$message.error("请填写快递单号");
        return;
      }

      updateExpressNo({
        orderId: this.expressForm.order.id,
        expressName: this.expressForm.company,
        expressNo: this.expressForm.no,
        remark: this.expressForm.extendMessage,
      }).then((res) => {
        if (res.code == "000000") {
          this.$message.success("操作成功");
          this.showOrderNoFlag = false;
          this.searchList();
        } else {
          this.$message.success(`操作失败:${res.message}，请重试`);
        }
      });
    },
    exportOrder() {
      const {
        goodsName,
        orderNo,
        receiver,
        orderDate,
        storeId,
        brokerId,
        ownerId,
        prescriberName,
        orderBeginTime,
        orderEndTime,
        saleType,
      } = this.searchForm;

      getOrdersExportUrl({
        goodsName,
        orderNo,
        receiver,
        orderDate,
        storeId,
        brokerId,
        ownerId,
        prescriberName,
        orderBeginTime,
        orderEndTime,
        saleType,
      }).then((res) => {
        if (res.code != "000000") {
          this.$message({ message: res.message, type: "error" });
          return;
        }
        window.open(res.data);
      });
    },
    // 云鹊店铺-订单管理-药代列表
    brokerListAll() {
      brokerListAll({ ownerId: this.ownerId }).then((res) => {
        closeLoading(this);
        if (res.code == "000000") {
          this.brokerList = res.data;
        }
      });
    },
    //云鹊店铺-订单管理-招募人列表
    brokerOwnerListAll() {
      brokerOwnerListAll().then((res) => {
        closeLoading(this);
        if (res.code == "000000") {
          this.brokerOwnerList = res.data;
        }
      });
    },
    changeOwner(data) {
      this.ownerId = data;
      this.brokerListAll();
    },
  },
  filters: {
    toFixed2: function (value) {
      let val;
      if (value) {
        val = (value / 100).toFixed(2);
      } else {
        val = 0.0;
      }
      return val;
    },
  },
};
</script>
<style lang="scss">
.order-manage-wrapper {
  .el-step__icon {
    border: none;
    background: transparent;
  }
  .el-step__title {
    font-size: 14px;
  }

  .el-step:last-of-type .el-step__line {
    display: block !important;
    height: 30%;
  }
  .dot {
    border-radius: 50%;
    height: 8px;
    width: 8px;
    border: 1px solid #999999;
    background-color: #b8b8b8;
  }
  .order-manage-content {
    background: #fff;
    padding: 10px;
    .button-container {
      margin-bottom: 10px;
    }
    .header-title {
      padding: 10px 12px;
      font-size: 13px;
      color: #449284;
      border-bottom: 1px solid #efefef;
    }
  }
  .el-button--text {
    color: #449284;
    font-size: 14px;
    &::after {
      content: "";
      position: relative;
      height: 14px;
      /*border-right: 1px solid #EBEEF5;*/
      border-right: 1px solid #aaaaaa;
      padding-right: 10px;
    }
    &:last-of-type {
      &::after {
        content: "";
        position: relative;
        width: 1px;
        height: 14px;
        border-right: none;
      }
    }
  }
}
.el-tabs__item.is-active {
  color: #449284;
}
.el-tabs__active-bar {
  background-color: #449284;
}
.el-tabs__item:hover {
  color: #449284;
}

.view-content {
  display: flex;
  justify-content: space-between;
  .send-status {
    margin-left: 5px;
  }
  .view-number {
    color: #999999;
    margin-left: 15px;
    margin-right: 15px;
  }
  .center-title {
    text-align: center;
  }
  .center-subtitle {
    text-align: center;
    font-size: 13px;
    margin-top: 10px;
    color: #999999;
  }
}
.steps-logistics {
  height: 350px;
  overflow-y: scroll;
}
.hidden-input {
  height: 0;
}
.p-normal {
  line-height: 26px;
  border-bottom: 1px solid #e4e7ed;
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  margin: 10px 0;
  text-align: center;

  &:last-child {
    border-bottom: none;
  }
}
.tui-dialog {
  .el-dialog__header {
    text-align: center;
  }
  .is-disabled {
    width: 193px;
  }
}
.exportlogistics-dialog {
}
.upload-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .file-name {
    margin-right: 5px;
  }
}
.progress-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.progress-content {
  width: 150px;
  height: 40px;

  background: #449284;
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}
.progress-tag {
  width: 150px;
  height: 40px;
  border: 1px solid #ebeef5;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
  position: relative;
  .popper__arrow {
    position: absolute;
    bottom: 0px;
    left: 50%;

    margin-right: 3px;
    transform: translateX(-3px);

    border-bottom-width: 0;
    &::after {
      position: absolute;
      display: block;
      width: 0;
      height: 0;

      border-top-color: #fff;
      border-left-color: transparent;
      border-bottom-color: transparent;
      border-right-color: transparent;
      border-style: solid;
      content: " ";
      border-width: 6px;
    }
  }
}
.stat-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .stat-title {
    color: #333;
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
  }
  .stat-result {
    display: flex;
    justify-content: space-between;
    width: 360px;
    .failure {
      color: #e63c3c;
    }
  }
}
.importUrl {
  color: #449284;
}
.offline-content {
  .offline-title {
    padding: 10px 0;
    line-height: 24px;
    font-size: 18px;
    color: #303133;
    border-bottom: 1px solid #ddd;
  }
  .offline-main {
    .offline-msg {
      line-height: 30px;
    }
  }
}
</style>
