<template>
  <div class="app-container mod-order-order">
    <!-- 筛选条件 -->
    <div class="screen-container">
      <el-form ref="screenForm" :model="screenForm" label-width="70px" size="small" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="订单号" prop="orderId">
              <el-input v-model="screenForm.orderId" placeholder="请输入订单号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="screenForm.goodsName" placeholder="请输入商品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="会员昵称" prop="memberName">
              <el-input v-model="screenForm.memberName" placeholder="请输入会员昵称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="screenForm.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="网点名称" prop="websitId">
              <el-select v-model="screenForm.websitId" placeholder="全部" filterable>
                <el-option label="全部" value=""></el-option>
                <el-option :label="item.name" :value="item.id" v-for="(item, index) in websiteList" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="兑换码" prop="exchangeCode">
              <el-input v-model="screenForm.exchangeCode" placeholder="请输入兑换码"></el-input>
            </el-form-item>
          </el-col>

<!--          <el-col :xs="24" :sm="12" :lg="6">-->
<!--            <el-form-item label="当前状态" prop="orderStatus">-->
<!--              <el-select v-model="screenForm.orderStatus" placeholder="全部">-->
<!--                <el-option label="全部" value=""></el-option>-->
<!--                <el-option :label="item.label" :value="item.value" v-for="(item, index) in screen_status" :key="index"></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->

          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="创建时间" prop="createDate" style="height: 33px;">
              <el-date-picker
                v-model="screenForm.createDate"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="支付时间" prop="payDate" style="height: 33px;">
              <el-date-picker
                v-model="screenForm.payDate"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="评价状态" prop="evaluateStatus">
              <el-select v-model="screenForm.evaluateStatus" placeholder="全部">
                <el-option label="全部" value=""></el-option>
                <el-option label="未评价订单" :value="0"></el-option>
                <el-option label="已评价订单" :value="3"></el-option>
                <el-option label="差评订单" :value="1"></el-option>
                <el-option label="好评订单" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="派单异常" prop="sendStatus">
              <el-select v-model="screenForm.sendStatus" placeholder="全部">
                <el-option label="全部" value=""></el-option>
                <el-option label="派单异常订单" :value="true"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="信息编号" prop="workerOrderNo">
              <el-input v-model="screenForm.workerOrderNo" placeholder="请输入信息编号"></el-input>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :lg="6" class="tr">
            <el-form-item label="">
              <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
              <el-button size="small" @click="resetScreenForm">清空</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="tabs-container order-tabs-container clearfix">
      <div class="fl">
        <el-tabs v-model="tabCurrent" type="card" @tab-click="changeTabs" class="fl" style="margin-right: 20px">
          <el-tab-pane label="全部" name="ALL"></el-tab-pane>
          <el-tab-pane label="待付款" name="NOPAY"></el-tab-pane>
          <el-tab-pane label="待发货" name="DFH"></el-tab-pane>
          <el-tab-pane label="已发货" name="YFH"></el-tab-pane>
          <el-tab-pane label="已完成" name="OVER"></el-tab-pane>
          <el-tab-pane label="已关闭" name="CLOSE"></el-tab-pane>
          <el-tab-pane label="已超时" name="TIMEOUT"></el-tab-pane>
        </el-tabs>
        <el-button class="fl" type="primary" size="small" @click="batchRemark">批量备注</el-button>
        <el-button class="fl" type="primary" size="small" @click="batchShipmentVisible = true" v-show="tabCurrent == 'DFH'">批量发货</el-button>
        <el-button class="fl" size="small" @click="downloadTemplate" v-show="tabCurrent == 'DFH'">下载批量发货模版</el-button>
      </div>
      <div class="fr">
        <el-button size="small" type="primary" @click="handleExport">导出报表</el-button>
      </div>
    </div>
    <div class="order-main-container">
      <div class="table-top">
        <el-row style="width:100%">
          <el-col :span="6">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="allChange" style="margin-left: 10px"></el-checkbox>
            <span class="item product">商品信息</span>
          </el-col>
          <el-col :span="3" style="text-align: right"><span class="item">单价(元)/数量</span></el-col>
          <el-col :span="3" style="text-align: center"><span class="item">买家信息</span></el-col>
          <el-col :span="3" style="text-align: center"><span class="item">收货信息</span></el-col>
          <el-col :span="2" style="text-align: center"><span class="item">实付金额</span></el-col>
          <el-col :span="2" style="text-align: center"><span class="item">订单状态</span></el-col>
          <el-col :span="2" style="text-align: center"><span class="item">评价状态</span></el-col>
          <el-col :span="3" style="text-align: center"><span class="item">操作</span></el-col>
        </el-row>
      </div>
      <div class="order-item" v-for="order in dataList" :key="order.orderId">
        <div class="order-top">
          <el-checkbox v-model="order.selected"></el-checkbox>
          <span><b>订单号</b>：{{order.orderId}}</span>
          <span><b>下单时间</b>：{{order.createTime}}</span>
          <span><b>商户</b>：{{order.companyWechatName || '无'}}</span>
          <span><b>网点</b>：{{order.websitName || '无'}}</span>
          <div class="fr">
            <el-link type="primary" :underline="false" @click="showRemark(order.orderId, order.remark)">订单备注</el-link>
            <el-link type="primary" :underline="false" @click="queryDetail(order.orderId)">查看详情</el-link>
          </div>
        </div>
        <div class="order-content">
          <el-row style="width:100%;">
            <el-col :span="9" style="height: 100%;">
              <div class="col-item-pro">
                <div class="pro-item" v-for="orderItem in order.orderDetails" :key="orderItem.orderDetailId">
                  <div class="left">
                    <div class="image">
                      <img :src="orderItem.imgUrl" style="height:80px;width: 80px;">
                    </div>
                    <div class="main">
                      <span><el-tag type="danger" effect="plain" size="mini" style="margin-right: 4px" v-if="orderItem.promotionFullPieceId">满件打折</el-tag>{{orderItem.goodsName}}</span>
                      <span class="spec" v-if="orderItem.goodsSpecName === '默认' && orderItem.goodsSpecValue === '默认'">默认</span>
                      <span class="spec" v-else>{{orderItem.goodsSpecName}}-{{orderItem.goodsSpecValue}}</span>
                    </div>
                  </div>
                  <div class="right">
                    <span>￥{{orderItem.price}}</span>
                    <span>x{{orderItem.num}}</span>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="3" style="height: 100%;">
              <div class="col-item">
                <div>{{ order.userName }}</div>
                <div>{{ order.phone }}</div>
                <div style="color: #409EFF;">{{ order.isAddCorp ? '（已入驻企微）':'' }}</div>
              </div>
            </el-col>
            <el-col :span="3" style="height: 100%;">
              <div class="col-item">
                <div>{{ order.receUserName }}/{{ order.recePhone }}</div>
                <div class="ellipsis-2">{{ order.province + order.city + order.area + order.street + order.receAddress + order.houseNo }}</div>
              </div>
            </el-col>
            <el-col :span="2" style="height: 100%;">
              <div class="col-item">
                <div class="totalprice">￥{{order.payAmount}}</div>
                <div style="font-size: 12px" v-if="order.discountAmount">(已优惠<span>￥{{order.discountAmount}}</span>)</div>
                <div style="color: #409EFF;">{{ order.hasNoshareCoupon ? '（不分佣）':'' }}</div>
              </div>
            </el-col>
            <el-col :span="2" style="height: 100%;">
              <div class="col-item">
                <div style="display: flex; align-items: center;">
                  <img src="@/assets/order/CLOSE.png" style="width: 16px; flex-shrink: 0;" v-if="order.orderStatus == 'CLOSE'">
                  <img src="@/assets/order/DFH.png" style="width: 16px; flex-shrink: 0;" v-if="order.orderStatus == 'DFH'">
                  <img src="@/assets/order/NOPAY.png" style="width: 16px; flex-shrink: 0;" v-if="order.orderStatus == 'NOPAY'">
                  <img src="@/assets/order/OVER.png" style="width: 16px; flex-shrink: 0;" v-if="order.orderStatus == 'OVER'">
                  <img src="@/assets/order/TIMEOUT.png" style="width: 16px; flex-shrink: 0;" v-if="order.orderStatus == 'TIMEOUT'">
                  <img src="@/assets/order/YFH.png" style="width: 16px; flex-shrink: 0;" v-if="order.orderStatus == 'YFH'">
                  <span style="margin-left: 4px">{{ order.orderStatus | ORDER_CURRENT_STATUS_FILTER }}</span>
                </div>
                <div>({{ order.toWorkOrder ? '已派单':'未派单' }})</div>
              </div>
            </el-col>
            <el-col :span="2" style="height: 100%;">
              <div class="col-item">
                <el-popover placement="top" width="220" trigger="hover" v-if="order.commentService">
                  <div class="rate-list">
                    <div style="display: flex; align-items: center; margin-bottom: 5px;">商品质量：<el-rate :value="order.commentGoods" disabled></el-rate></div>
                    <div style="display: flex; align-items: center; margin-bottom: 5px;">服务质量：<el-rate :value="order.commentService" disabled></el-rate></div>
                    <div style="display: flex; align-items: center;">配送质量：<el-rate :value="order.commentExpress" disabled></el-rate></div>
                  </div>
                  <el-button type="text" slot="reference">已评价</el-button>
                </el-popover>
                <div v-else>未评价</div>
              </div>
            </el-col>
            <el-col :span="3" style="height: 100%;">
              <div class="col-item">
                <div class="operate">
                  <el-popconfirm title="确定取消订单吗？" @onConfirm="cancelOrder(order.orderId)" v-if="order.orderStatus === 'NOPAY'">
                    <el-button slot="reference" type="text" size="small">取消订单</el-button>
                  </el-popconfirm>
                  <el-button type="text" size="small" v-if="order.orderStatus === 'DFH'" @click="showLogistics(order, 'add')">发货</el-button>
                  <el-button type="text" size="small" @click="openAddressForm(order)">修改收货地址</el-button>
                  <el-button 
                    type="text" 
                    size="small" 
                    v-if="order.orderStatus === 'YFH' && order.orderDetails.some(i => i.workOrderType === 'INSTALL')" 
                    @click="showLogistics(order, 'edit')">
                    修改快递单号
                  </el-button>
                  <el-button 
                    type="text" 
                    size="small" 
                    v-if="(order.orderStatus === 'YFH' || order.orderStatus === 'OVER') && order.orderDetails.some(i => i.workOrderType === 'INSTALL')" 
                    @click="queryLogistics(order.logisticsNo, order.companyCode)">
                    查看物流
                  </el-button>
                  <el-button type="text" size="small" v-if="order.toWorkOrder" @click="toWorkOrderDetail(order.orderId)">查看工单</el-button>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="order-remark time" v-if="order.expectVisitTime">期望上门时间：{{order.expectVisitTime.slice(0, 10)}} {{order.expectDayFlag === 1 ? '上午':'下午'}}</div>
        <div class="order-remark buyer" v-if="order.buyerMsg">买家留言：{{order.buyerMsg}}</div>
        <div class="order-remark saler" v-if="order.remark">商家备注：{{order.remark}}</div>
      </div>
      <div class="no-data" v-if="dataList.length <= 0">暂无订单</div>
    </div>
    <div class="pagination clearfix">
      <div class="fr">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="listTotal">
        </el-pagination>
      </div>
    </div>
    <el-dialog :title="'订单备注'" :visible.sync="remarkVisible" :show-close="false" width="50%" :close-on-click-modal="false">
      <el-input
        type="textarea"
        :autosize="{ minRows: 8, maxRows: 16}"
        placeholder="请输入备注内容"
        v-model="remark"
        maxlength="100"
        show-word-limit>
      </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveRemark">保 存</el-button>
        <el-button @click="cancelRemark">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="'物流信息'" :visible.sync="logisticsVisible" :show-close="false" width="80%" :close-on-click-modal="false">
      <el-table
        v-loading="logisticsLoading"
        :data="logistics"
        style="width: 100%"
        size="mini">
        <el-table-column prop="comName" label="物流公司" align="center"></el-table-column>
        <el-table-column prop="areaName" label="地区名称" align="center"></el-table-column>
        <el-table-column prop="time" label="物流时间" align="center"></el-table-column>
        <el-table-column prop="state" label="物流状态" align="center">
          <template slot-scope="scope">
            {{ scope.row.state | EXPRESS_CURRENT_STATE_FILTER }}
          </template>
        </el-table-column>
        <el-table-column prop="context" label="物流详情" align="center"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="logisticsVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 发货弹窗 -->
    <el-dialog :title="logisticsType == 'add' ? '发货':'修改单号'" :visible.sync="logisticsIdVisible" :show-close="false" width="50%" :close-on-click-modal="false">
      <el-form :model="logisticsForm" ref="logisticsForm" label-width="80px" label-position="left">
        <el-form-item label="快递单号" prop="logisticsNo"
          :rules="[{ required: true, message: '快递单号不能为空', trigger: 'blur' }]" >
          <el-input v-model="logisticsForm.logisticsNo" placeholder="请输入快递单号"></el-input>
        </el-form-item>
        <el-form-item label="物流公司" prop="companyCode"
          :rules="[{ required: true, message: '请选择物流公司', trigger: 'change' }]" >
          <el-select v-model="logisticsForm.companyCode" placeholder="请选择物流公司" style="width: 100%;">
            <el-option :label="item.name" :value="item.code" v-for="(item, index) in companyList" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓储" prop="storageId" v-if="logisticsType === 'add'"
          :rules="[{ required: true, message: '请选择仓储', trigger: 'change' }]" >
          <el-select v-model="logisticsForm.storageId" placeholder="请选择仓储" style="width: 100%;">
            <el-option :label="item.storageName" :value="item.storageId" v-for="(item, index) in storageList" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否派单" prop="workOrder" v-if="logisticsType === 'add'">
          <el-radio-group v-model="logisticsForm.workOrder">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveLogistics">保 存</el-button>
        <el-button @click="cancelLogistics">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改收货地址 -->
    <el-dialog title="修改收货地址" :visible.sync="addressFormVisible" :show-close="false" width="50%" :close-on-click-modal="false">
      <el-form :model="addressForm" :rules="addressFormRules" ref="addressForm" label-width="80px" label-position="left">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addressForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="省" prop="province">
          <el-select v-model="addressForm.province" placeholder="请选择省" @change="changeProvince" style="width: 100%">
            <el-option v-for="item in provinceList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select v-model="addressForm.city" placeholder="请选择市" @change="changeCity" style="width: 100%">
            <el-option v-for="item in cityList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区" prop="area">
          <el-select v-model="addressForm.area" placeholder="请选择区" @change="changeArea" style="width: 100%">
            <el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="街道" prop="street">
          <el-select v-model="addressForm.street" placeholder="请选择街道" @change="changeStreet" style="width: 100%">
            <el-option v-for="item in streetList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addressForm.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="门牌号" prop="house">
          <el-input v-model="addressForm.house" placeholder="请输入门牌号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddressForm">保 存</el-button>
        <el-button @click="cancelAddressForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量发货 -->
    <el-dialog title="批量发货" :visible.sync="batchShipmentVisible" :show-close="false" width="30%" :close-on-click-modal="false">
      <el-form ref="batchShipmentForm" label-position="top" label-width="120px" style="height: 194px;">
        <el-form-item label="上传发货表格" prop="fileUrl">
          <el-upload
            ref="upload"
            class="upload-demo"
            :action="baseURL + 'order/goods/batch/deliver'"
            :headers="myHeaders"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :before-upload="beforeUpload"
            :auto-upload="false"
            :file-list="fileList">
            <el-button size="small" type="primary">{{fileList.length == 0 ? '点击上传':'重新上传'}}</el-button>
            <div slot="tip" class="el-upload__tip">只支持上传excel表格文件</div>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelBatchShipmentForm">取 消</el-button>
        <el-button type="primary" @click="submitBatchShipmentForm">发 货</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import {cancelOrder, getList, goodsDeliver, saveRemark, batchShipment, batchRemark, getWebsiteList, editLogistics, getRegion, editAddress} from "@/api/order";
import {getExpress, getCompanyList} from "@/api/common";
import {downloadFiles, handleImport, findElem} from '@/utils/util'
import * as Storage from "@/api/storage";
import '@/styles/order-list.scss'

export default {
  name: "order_list",
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: {'x-token': getToken()},
      screenForm: { // 筛选表单数据
        orderId: '', // 订单号
        goodsName: '', // 商品名称
        memberName: '', // 会员昵称
        phone: '', // 手机号
        websitId: '', // 网点名称
        orderStatus: '', // 状态
        createDate: '', // 创建时间
        payDate: '', // 支付时间
        exchangeCode: '', // 兑换码
        evaluateStatus: '', // 评价状态
        sendStatus: '', // 派单异常
        workerOrderNo: '', // 信息编号
      },
      screen_status: [ // 筛选字段 - 状态
        { label: '待付款', value: 'NOPAY' },
        { label: '待发货', value: 'DFH' },
        { label: '已发货', value: 'YFH' },
        { label: '已完成', value: 'OVER' },
        { label: '已关闭', value: 'CLOSE' }
      ],
      tabCurrent: 'ALL',
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: [],
      remarkVisible: false,
      editOrderId: '',
      remark: '', // 订单备注
      logisticsVisible: false,
      logistics: [],
      prodVisible: false,
      logisticsType: 'add',
      logisticsIdVisible: false,
      logisticsLoading: false,
      logisticsForm: {
        logisticsNo: '',
        storageId: '',
        companyCode: '',
        workOrder: true,
      },
      storageList: [],
      companyList: [],
      websiteList: [],
      batchShipmentVisible: false,
      fileList: [],
      canClickSave: true,

      addressFormOrder: null,
      addressFormVisible: false,
      addressForm: {
        name: '',
        phone: '',
        province: '',
        city: '',
        area: '',
        street: '',
        address: '',
        house: '',
      },
      addressFormRules: {
        name: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请填写电话', trigger: 'blur' }],
        province: [{ required: true, message: '请选择省', trigger: 'change' }],
        city: [{ required: true, message: '请选择市', trigger: 'change' }],
        area: [{ required: true, message: '请选择区', trigger: 'change' }],
        street: [{ required: true, message: '请选择街道', trigger: 'change' }],
        address: [{ required: true, message: '请填写地址', trigger: 'blur' }],
      },
      provinceList: [],
      cityList: [],
      areaList: [],
      streetList: [],
    }
  },
  computed: {
    checkAll: {
      get() {
        return this.dataList.every(item => item.selected === true)
      },
      set() {}
    },
    isIndeterminate() {
      return !this.dataList.every(item => item.selected !== true) && !this.dataList.every(item => item.selected !== false)
    }
  },
  created() {
    this.getList();
    this.getStorageList();
    this.getCompanyList();
    this.getWebsiteList();
  },
  methods: {
    changeTabs(tab, event) {
      // this.$refs.screenForm.resetFields();
      this.screenForm.orderStatus = this.tabCurrent === 'ALL' ? '' : tab.$options.propsData.name
      this.currentPage = 1;
      this.getList();
    },
    // 获取数据列表
    getList () {
      // this.listLoading = true;

      let params = {
        orderId: this.screenForm.orderId, // 订单号
        productName: this.screenForm.goodsName, // 商品名称
        userName: this.screenForm.memberName, // 会员昵称
        phone: this.screenForm.phone, // 手机号
        websitId: this.screenForm.websitId,
        exchangeCode: this.screenForm.exchangeCode,
        orderStatus: this.screenForm.orderStatus, // 状态
        startCreateTime: this.screenForm.createDate[0] ? this.screenForm.createDate[0] : null, // 创建时间
        endCreateTime: this.screenForm.createDate[1] ? this.screenForm.createDate[1] : null, // 创建时间
        startPayTime: this.screenForm.payDate[0] ? this.screenForm.payDate[0] : null, // 支付时间
        endPayTime: this.screenForm.payDate[1] ? this.screenForm.payDate[1] : null, // 支付时间
        isNegative: this.screenForm.evaluateStatus, // 评价状态
        abnormalDispatch: this.screenForm.sendStatus, // 派单异常
        workerOrderNo: this.screenForm.workerOrderNo, // 信息编号
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };

      getList(params).then(res => {
        res.data.records.forEach(item => {
          item.selected = false;
          // item.websitName = this.handleText(item.websitName);
        });
        this.dataList = res.data.records;
        this.listTotal = res.data.total;
        // this.listLoading = false;
      })
    },
    // 查看详情
    queryDetail (orderId) {
      let {href} = this.$router.resolve({path: `/order/detail?orderId=${orderId}`});
      window.open(href, '_blank');

      // this.$router.push({
      //   path: '/order/detail',
      //   query: {
      //     orderId
      //   }
      // })
    },
    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getList();
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },
    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1;
      this.getList();
    },
    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields();
      this.currentPage = 1;
      this.getList();
    },
    showRemark(orderId, remark) {
      this.remarkVisible = true
      this.editOrderId = orderId
      this.remark = remark
    },
    cancelRemark() {
      this.remarkVisible = false
      this.editOrderId = ''
      this.remark = ''
    },
    saveRemark() {
      const params = {
        orderId: this.editOrderId,
        remark: this.remark
      }
      saveRemark(params).then(() => {
        this.cancelRemark();
        this.getList();
        this.$successMsg('保存成功');
      })
    },
    // 取消订单
    cancelOrder(orderId) {
      cancelOrder({ orderId }).then(() => {
        this.getList();
        this.$successMsg('取消成功');
      })
    },
    // 查看物流
    queryLogistics(logisticsNo, companyCode) {
      this.logisticsVisible = true
      this.logisticsLoading = true
      getExpress({ logisticsNo, companyCode }).then(res => {
        this.logistics = res.data
        this.logisticsLoading = false
      })
    },
    // 显示快递信息填写
    showLogistics(item, type) {
      this.logisticsType = type;
      this.logisticsIdVisible = true;
      this.editOrderId = item.orderId;
      if(type === 'edit') {
        this.logisticsForm.logisticsNo = item.logisticsNo;
        this.logisticsForm.companyCode = item.companyCode;
      }
      
    },
    // 取消快递信息填写
    cancelLogistics() {
      this.logisticsIdVisible = false
      this.editOrderId = ''
      this.$refs.logisticsForm.resetFields()
    },
    // 提交快递信息填写
    saveLogistics() {
      this.$refs.logisticsForm.validate((valid) => {
        if (valid) {
          // 发货
          if(this.logisticsType === 'add') {
            goodsDeliver({
              orderId: this.editOrderId,
              logisticsNo: this.logisticsForm.logisticsNo,
              storageId: this.logisticsForm.storageId,
              companyCode: this.logisticsForm.companyCode,
              workOrder: this.logisticsForm.workOrder,
            }).then(() => {
              this.cancelLogistics();
              this.getList();
              this.$successMsg('发货成功');
            })
          }
          // 修改单号
          else {
            editLogistics({
              orderId: this.editOrderId,
              logisticsNo: this.logisticsForm.logisticsNo,
              companyCode: this.logisticsForm.companyCode,
            }).then(() => {
              this.cancelLogistics();
              this.getList();
              this.$successMsg('修改成功');
            })
          }
        }
      })
    },
    getStorageList() {
      Storage.getList({ pageNum: 1, pageSize: 100 }).then(res => {
        this.storageList = res.data.records
      })
    },

    // 获取物流公司列表
    getCompanyList() {
      getCompanyList().then(res => {
        this.companyList = res.data;
      })
    },

    // 网点列表
    getWebsiteList() {
      getWebsiteList({
        pageNum: 1,
        pageSize: 1000
      }).then(res => {
        this.websiteList = res.data.records;
      })
    },

    // 取消 批量发货
    cancelBatchShipmentForm(){
      this.batchShipmentVisible = false;
      this.fileList = [];
    },

    handleRemove(file, fileList) {
      this.fileList = [];
    },

    handleChange(file, fileList) {
      this.fileList = fileList.slice(fileList.length - 1);
    },

    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ['xls', 'xlsx', 'xlsm'];
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$errorMsg('只支持上传excel表格文件!');
        return false;
      }
    },

    // 批量发货
    async submitBatchShipmentForm() {
      if (!this.canClickSave) return false;
      this.canClickSave = false;
      setTimeout(() => { this.canClickSave = true }, 3000)
      if(this.fileList.length <= 0) {
        return this.$errorMsg('请上传发货表格');
      }
      const loading = this.$loading({
        lock: true,
        text: '上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      console.log(this.fileList[0].raw);
      const file = this.fileList[0].raw;
      const formData = new FormData();
      formData.append("file", file);
      let result = await handleImport('order/goods/batch/deliver', formData);
      this.importFileList = [];
      if(result.code == 200) {
        loading.close();
        this.$successMsg('批量发货成功');
        this.getList();
      }else {
        loading.close();
        this.$alert(result.message, '批量发货失败', {
          confirmButtonText: '确定'
        });
      }
    },

    // 获取省市区街道
    getRegion(level=0, id=0) {
      getRegion({pid: id}).then(res => {
        if(level === 0) {
          this.provinceList = res.data;
        }else if(level === 1) {
          this.cityList = res.data;
        }else if(level === 2) {
          this.areaList = res.data;
        }else if(level === 3) {
          this.streetList = res.data;
        }
      })
    },

    // 切换省
    changeProvince(value) {
      this.addressForm.city = '';
      this.addressForm.area = '';
      this.addressForm.street = '';
      this.cityList = [];
      this.areaList = [];
      this.streetList = [];
      this.getRegion(1, value);
    },

    // 切换市
    changeCity(value) {
      this.addressForm.area = '';
      this.addressForm.street = '';
      this.areaList = [];
      this.streetList = [];
      this.getRegion(2, value);
    },

    // 切换区
    changeArea(value) {
      this.addressForm.street = '';
      this.streetList = [];
      this.getRegion(3, value);
    },

    // 切换街道
    changeStreet(value) {

    },

    // 初始化省市区街道
    initRegion(level, item, id=0) {
      let { province, city, area, street } = item;
      let nextId = null;
      getRegion({pid: id}).then(res => {
        if(level === 0) {
          this.provinceList = res.data;
          nextId = this.addressForm.province = this.provinceList[findElem(this.provinceList, 'name', province)].id;
        }else if(level === 1) {
          this.cityList = res.data;
          nextId = this.addressForm.city = this.cityList[findElem(this.cityList, 'name', city)].id;
        }else if(level === 2) {
          this.areaList = res.data;
          nextId = this.addressForm.area = this.areaList[findElem(this.areaList, 'name', area)].id;
        }else if(level === 3) {
          this.streetList = res.data;
          nextId = this.addressForm.street = this.streetList[findElem(this.streetList, 'name', street)].id;
        }
        if(level < 3) {
          level = level + 1;
          this.initRegion(level, item, nextId);
        }
      })
    },

    // 打开 修改收货地址 表单
    openAddressForm(item) {
      console.log(item);
      this.addressFormVisible = true;
      this.initRegion(0, item);
      this.addressForm.name = item.receUserName;
      this.addressForm.phone = item.recePhone;
      this.addressForm.address = item.receAddress;
      this.addressForm.house = item.houseNo;
      this.addressFormOrder = item;
    },

    // 取消 修改收货地址 表单
    cancelAddressForm() {
      this.addressFormVisible = false;
      this.$refs.addressForm.resetFields();
    },

    // 保存 修改收货地址 表单
    submitAddressForm() {
      this.$refs.addressForm.validate((valid) => {
        if (valid) {
          let province = this.provinceList[findElem(this.provinceList, 'id', this.addressForm.province)].name;
          let city = this.cityList[findElem(this.cityList, 'id', this.addressForm.city)].name;
          let area = this.areaList[findElem(this.areaList, 'id', this.addressForm.area)].name;
          let street = this.streetList[findElem(this.streetList, 'id', this.addressForm.street)].name;
          editAddress({
            orderId: this.addressFormOrder.orderId,
            orderStatus: this.addressFormOrder.orderStatus,
            receUserName: this.addressForm.name,
            recePhone: this.addressForm.phone,
            province,
            city,
            area,
            street,
            receAddress: this.addressForm.address,
            houseNo: this.addressForm.house,
          }).then(() => {
            this.cancelAddressForm();
            this.getList();
            this.$successMsg('修改成功');
          })
        }
      })
    },

    // 下载模版
    downloadTemplate() {
      downloadFiles('order/goods/deliver/excel');
    },

    // 导出
    handleExport() {
      let screenData = {
        orderId: this.screenForm.orderId, // 订单号
        productName: this.screenForm.goodsName, // 商品名称
        userName: this.screenForm.memberName, // 会员昵称
        phone: this.screenForm.phone, // 手机号
        websitId: this.screenForm.websitId,
        exchangeCode: this.screenForm.exchangeCode,
        orderStatus: this.screenForm.orderStatus, // 状态
        startCreateTime: this.screenForm.createDate[0] ? this.screenForm.createDate[0] : null, // 创建时间
        endCreateTime: this.screenForm.createDate[1] ? this.screenForm.createDate[1] : null, // 创建时间
        startPayTime: this.screenForm.payDate[0] ? this.screenForm.payDate[0] : null, // 支付时间
        endPayTime: this.screenForm.payDate[1] ? this.screenForm.payDate[1] : null, // 支付时间
        isNegative: this.screenForm.evaluateStatus, // 评价状态
        abnormalDispatch: this.screenForm.sendStatus, // 派单异常
        workerOrderNo: this.screenForm.workerOrderNo, // 信息编号
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };
      downloadFiles('order/export', screenData);
    },

    // 切换全选/全不选
    allChange(val) {
      // 如果有其中一个false，那就全选
      if(this.dataList.some((item) => { return item.selected === false })) {
        let dataList = this.dataList;
        dataList.forEach(item => {
          item.selected = true;
        })
        this.$set(this, 'dataList', dataList);
      }
 
      // 如果全是true，那就全不选
      else {
        let dataList = this.dataList;
        dataList.forEach(item => {
          item.selected = false;
        })
        this.$set(this, 'dataList', dataList);
      }
    },

    batchRemark() {
      if(this.dataList.every((item) => { return item.selected === false })) {
        return this.$errorMsg('至少选择一个订单');
      }
      this.$prompt('请输入备注', '批量备注', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: function(value) {
          if(!value) return '请输入备注'
        },
      }).then(({ value }) => {
        let selectedlist = [];
        this.dataList.forEach(item => {
          if(item.selected) {
            selectedlist.push(item.orderId);
          }
        });
        batchRemark({
          orderIds: selectedlist,
          remark: value
        }).then(res => {
          this.getList();
          this.$successMsg();
        })
      }).catch(() => {});
    },

    handleText(text){
      if(!text) {
        return '';
      }
      if(text.length>10){
        return text.slice(0, 10) + "...";
      }else {
        return text
      }
    },

    // 查看工单
    toWorkOrderDetail(orderId) {
      let {href} = this.$router.resolve({path: `/order/workOrder_detail?orderId=${orderId}`});
      window.open(href, '_blank');
    },

  }
}

</script>

