<template>
  <div>
    <zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title+'-列表', essential: true }]">
      <template slot-scope="{activeKey, data}">
        <div v-if="activeKey == 'list'" class="app-container">
          <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 clearable>
                      <el-option :label="item.name" :value="item.websitId" 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="DQR"></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 v-if="$restrict('batchNote')" 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' && $restrict('batchDelivery')">批量发货</el-button>
              <el-button class="fl" size="small" @click="downloadTemplate" v-show="tabCurrent == 'DFH' && $restrict('template')">下载批量发货模版</el-button>
            </div>
            <div class="fr">
              <el-button v-if="$restrict('exp')" 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="3">
                  <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="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-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>
                <el-tag>{{order.saleType | saleTypeFilter}}</el-tag>
                <el-tag>{{order.payType}}</el-tag>
                <div class="fr">
                  <el-link type="primary" v-if="$restrict('orderNote')" :underline="false" @click="showRemark(order)">订单备注</el-link>
                  <el-link type="primary" v-if="$restrict('detail')" :underline="false" @click="queryDetail(order.orderId)">查看详情</el-link>
                  <!-- <el-link type="primary" :underline="false" @click="queryWorkOrder(order.orderId)">订单工单</el-link> -->
                </div>
              </div>
              <div class="order-content">
                <el-row style="width:100%;">
                  <el-col :span="6" 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><span
                          v-if="order.promotionDiscountRate">/{{ order.promotionDiscountRate * 10 }}折</span>)</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="2" style="height: 100%;">
                    <div class="col-item">
                      <div>{{order.saleName}}</div>
                    </div>
                  </el-col>
                  <el-col :span="2" style="height: 100%;">
                    <div class="col-item">
                      <div>{{order.workerName}}</div>
                    </div>
                  </el-col>
                  <el-col :span="2" style="height: 100%;">
                    <div class="col-item">
                      <div class="operate">
                        <el-popconfirm title="确定确认订单吗？" @confirm="confirmOrder(order.orderId)"
                          v-if="order.orderStatus === 'DQR' && $restrict('confirmOrder')">
                          <el-button slot="reference" type="text" size="small">确认订单</el-button>
                        </el-popconfirm>
                        <el-popconfirm title="确定取消发货吗？" @confirm="cancelOrder(order.orderId)"
                          v-if="order.orderStatus === 'DQR' && $restrict('cancelOrder')">
                          <el-button slot="reference" type="text" size="small">取消发货</el-button>
                        </el-popconfirm>
                        <el-popconfirm title="确定取消订单吗？" @confirm="cancelOrder(order.orderId)"
                          v-if="order.orderStatus === 'NOPAY' && $restrict('cancelOrder')">
                          <el-button slot="reference" type="text" size="small">取消订单</el-button>
                        </el-popconfirm>
                        <el-button type="text" size="small" v-if="order.orderStatus === 'DFH' && $restrict('deliver')"
                          @click="showLogistics(order, 'add')">发货</el-button>
                        <el-button type="text" size="small" v-if="order.orderStatus === 'DFH' && $restrict('changeShippingaddress')"
                          @click="openAddressForm(order)">修改收货地址</el-button>
                        <el-button type="text" size="small"
				                v-if="order.orderStatus === 'YFH' && $restrict('changeDeliverynumber') && order.orderDetails.some(i => i.workOrderType === 'INSTALL') && order.pickType == 'NO'"
                          @click="showLogistics(order, 'edit')">
                          修改快递单号
                        </el-button>
                        <el-button type="text" size="small"
                          v-if="(order.orderStatus === 'YFH' || order.orderStatus === 'OVER') && $restrict('viewLogistics') && order.orderDetails.some(i => i.workOrderType === 'INSTALL')"
                          @click="queryLogistics(order)">
                          查看物流
                        </el-button>
                        <el-button type="text" size="small"
                          v-if="(order.orderStatus === 'YFH' || order.orderStatus === 'OVER')" @click="showLogistics(order, 'detail')">
                          查看发货条码
                        </el-button>
                        <!-- toWorkOrderDetail(order.orderId) -->
                        <el-button type="text" size="small" v-if="order.toWorkOrder && $restrict('workOrder_detail')"
                          @click="queryWorkOrder(order.orderId)">查看工单</el-button>
                        <el-button type="text" size="small"
                          v-if="(order.orderStatus === 'DFH' || order.orderStatus === 'YFH')"
                          @click="toPrint(order)">
                          打印{{order.printRecordCount ? `(${order.printRecordCount}次)` : ''}}
                        </el-button>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </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>
        </div>
        <!-- 订单备注 -->
        <div v-if="activeKey == 'remark'" class="app-container">
          <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(data.removeTab)">保 存</el-button>
            <el-button @click="data.removeTab();cancelRemark">取 消</el-button>
          </div>
        </div>
        <!-- 物流信息 -->
        <div v-if="activeKey == 'materialDetail'" class="app-container">
          <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;data.removeTab()">关 闭</el-button>
          </div>
        </div>
        <!-- 发货弹窗 -->
			<div v-if="activeKey == 'deliverGoods' || activeKey == 'editExpressage' || activeKey == 'deliverGoodsDetail'" class="app-container">
				<el-form :model="logisticsForm" ref="logisticsForm" label-width="100px" label-position="left">
					<el-row :gutter="20">
						<el-col :span="6">
							<el-form-item label="发货方式" prop="pickType" v-if="logisticsType != 'edit'">
							  <el-radio-group v-model="logisticsForm.pickType">
							    <el-radio :disabled="logisticsType == 'detail'" label="YES">自提/自送</el-radio>
							    <el-radio :disabled="logisticsType == 'detail'" label="NO">快递物流</el-radio>
							  </el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="6" v-if="logisticsForm.pickType == 'YES'">
							<el-form-item label="提货人" prop="pickName" :rules="[{ required: true, message: '提货人不能为空', trigger: 'blur' }]">
							  <el-input v-model="logisticsForm.pickName" :disabled="logisticsType == 'detail'" placeholder="请输入提货人"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="6" v-if="logisticsForm.pickType == 'YES'">
							<el-form-item label="提货人电话" prop="pickPhone" :rules="[{ required: true, message: '提货人电话不能为空', trigger: 'blur' },{ pattern:/^((1[3456789]\d{9}))$/, message: '电话号码格式不正确', trigger: 'blur' }]">
							  <el-input v-model="logisticsForm.pickPhone" :disabled="logisticsType == 'detail'" placeholder="请输入提货人电话"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="6" v-if="logisticsForm.pickType == 'NO'">
							<el-form-item label="快递单号" prop="logisticsNo" :rules="[{ required: true, message: '快递单号不能为空', trigger: 'blur' }]">
							  <el-input v-model="logisticsForm.logisticsNo" :disabled="logisticsType == 'detail'" placeholder="请输入快递单号"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="6" v-if="logisticsForm.pickType == 'NO'">
							<el-form-item label="物流公司" prop="companyCode"
							  :rules="[{ required: true, message: '请选择物流公司', trigger: 'change' }]">
							  <el-select v-model="logisticsForm.companyCode" :disabled="logisticsType == 'detail'" 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-col>
						<el-col :span="6">
							<el-form-item label="仓储" prop="storageId" v-if="logisticsType != 'edit'"
							  :rules="[{ required: true, message: '请选择仓储', trigger: 'change' }]">
							  <el-input v-if="logisticsType == 'detail'" v-model="logisticsForm.storageName" :disabled="true" placeholder="请输入提货人"></el-input>
							  <el-select v-else 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-col>
						<el-col :span="6">
							<el-form-item label="是否派单" prop="workOrder" v-if="logisticsType != 'edit'">
							  <el-radio-group v-model="logisticsForm.workOrder">
							    <el-radio :disabled="logisticsType == 'detail'" :label="true">是</el-radio>
							    <el-radio :disabled="logisticsType == 'detail'" :label="false">否</el-radio>
							  </el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="是否退换单" prop="exchange" v-if="logisticsType != 'edit'">
							  <el-radio-group v-model="logisticsForm.exchange">
							    <el-radio :disabled="logisticsType == 'detail'" :label="true">是</el-radio>
							    <el-radio :disabled="logisticsType == 'detail'" :label="false">否</el-radio>
							  </el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-card class="box-card">
								<el-tabs v-model="typeIndex" @tab-click="changeType">
								    <el-tab-pane label="发货数量" name="1"></el-tab-pane>
								    <el-tab-pane v-if="joinCode" label="发货条码" name="2"></el-tab-pane>
								</el-tabs>
								<br/>
								<el-button size="small" v-show="typeIndex == 2 && logisticsType == 'add' && joinCode" type="primary" @click="addCode()">新增</el-button>
								<el-button size="small" v-show="typeIndex == 1 && logisticsType == 'add' && joinCode" type="primary" @click="handleDownload('导入条码模板')">导入条码模板下载</el-button>
								<div class="table">
									<!-- 发货数量 -->
									<el-form v-show="typeIndex == 1" ref="formData1" :model="formData1" label-width="0" size="small" label-position="left">
										<el-table :data="formData1.list" element-loading-text="Loading" border fit highlight-current-row stripe>
											<el-table-column prop="brandName" align="center" label="品牌"></el-table-column>
											<el-table-column prop="mainName" align="center" label="大类"></el-table-column>
											<el-table-column prop="smallName" align="center" label="小类"></el-table-column>
											<el-table-column prop="goodsName" align="center" label="商品名称"></el-table-column>
											<el-table-column prop="goodsMaterialName" align="center" label="物料名称"></el-table-column>
											<el-table-column prop="goodsMaterialSpecsName" align="center" label="规格型号"></el-table-column>
											<el-table-column prop="goodsMaterialUnit" align="center" label="单位">
												<template slot-scope="scope">
													{{scope.row.goodsMaterialUnit == 'C'?'整套':scope.row.goodsMaterialUnit == 'I'?"单个":''}}
												</template>
											</el-table-column>
											<el-table-column prop="num" align="center" label="数量"></el-table-column>
											<el-table-column prop="insideNum" align="center" label="内机数量"></el-table-column>
											<el-table-column prop="outNum" align="center" label="外机数量"></el-table-column>
											<el-table-column prop="partNum" align="center" label="配件数量"></el-table-column>
											<el-table-column prop="insideCodeQty" align="center" label="导入内机条码数量" width="140"></el-table-column>
											<el-table-column prop="outCodeQty" align="center" label="导入外机条码数量" width="140"></el-table-column>
											<el-table-column prop="partsCodeQty" align="center" label="导入配件条码数量" width="140"></el-table-column>
											<el-table-column label="操作" align="center" width="140" fixed="right">
												<template slot-scope="scope" v-if="formType != 2 && joinCode && logisticsType == 'add'">
													<el-upload
													  action='_'
													  :show-file-list='false'
													  :http-request="importCode"
													>
														<el-button @click="orderDetailId = scope.row.orderDetailId" size="mini" type="text">导入条码</el-button>
													</el-upload>
												</template>
											</el-table-column>
										</el-table>
									</el-form>
									<!-- 发货条码 -->
									<el-form ref="formData2" :model="formData2">
										<el-table v-show="typeIndex == 2" :data="formData2.list" element-loading-text="Loading" border fit highlight-current-row stripe>
											<el-table-column label="品牌" align="center">
												<template slot-scope="scope">
													<el-form-item>
														<el-input type="text" v-model="scope.row.brandName" :disabled="true" placeholder="请输入"></el-input>
													</el-form-item>
												</template>
											</el-table-column>
											<el-table-column label="商品大类" align="center">
												<template slot-scope="scope">
													<el-form-item>
														<el-input type="text" v-model="scope.row.mainName" :disabled="true" placeholder="请输入"></el-input>
													</el-form-item>
												</template>
											</el-table-column>
											<el-table-column label="商品小类" align="center">
												<template slot-scope="scope">
													<el-form-item>
														<el-input type="text" v-model="scope.row.smallName" :disabled="true" placeholder="请输入"></el-input>
													</el-form-item>
												</template>
											</el-table-column>
											<el-table-column prop="" align="center" label="商品名称">
												<template slot-scope="scope">
													<el-form-item>
														<el-input type="text" v-model="scope.row.goodsMaterialName" :disabled="true" placeholder="请输入"></el-input>
													</el-form-item>
												</template>
											</el-table-column>
											<el-table-column label="规格型号" align="center">
												<template slot-scope="scope">
													<el-form-item :prop="'list.' + scope.$index + '.specs'" :rules="[{ required: true, message: `请选择规格型号`, trigger: 'blur' }]">
														<el-select v-model="scope.row.specs" @change="(e)=>{changeSpecs(e,scope.row)}" value-key="orderDetailId" :disabled="isEdit2 != scope.$index || formType == 2 || logisticsType == 'detail'" placeholder="请选择" style="width: 100%;">
														    <el-option
														      v-for="(item,ind) in formData1.list"
														      :key="ind"
														      :label="item.goodsMaterialSpecsName"
														      :value="item">
														    </el-option>
														</el-select>
													</el-form-item>
												</template>
											</el-table-column>
											<el-table-column label="物料类型" align="center">
												<template slot-scope="scope">
													<el-form-item :prop="'list.' + scope.$index + '.goodsMaterialItemType'" :rules="[{ required: true, message: `请选择物料类型`, trigger: 'blur' }]">
														<el-select v-model="scope.row.goodsMaterialItemType" @change="(e)=>{changeMaterial(e,scope.row)}" 
															:disabled="isEdit2 != scope.$index || formType == 2 || logisticsType == 'detail'" placeholder="请选择" style="width: 100%;">
														    <el-option
														      v-for="(item,ind) in [{name: '内机',id: 'INSIDE'},{name: '外机',id: 'OUT'},{name: '配件',id: 'PARTS'}]"
														      :key="ind"
														      :label="item.name"
														      :value="item.id">
														    </el-option>
														</el-select>
													</el-form-item>
												</template>
											</el-table-column>
											<el-table-column label="物料名称" align="center">
												<template slot-scope="scope">
													<el-form-item :prop="'list.' + scope.$index + '.material'" :rules="[{ required: true, message: `请选择物料名称`, trigger: 'blur' }]">
														<el-select v-model="scope.row.material" @focus="(e)=>{
															if(!scope.row.goodsMaterialItemType){
																return $message.warning('请先选择物料类型！');
															}
														}" @change="(e)=>{
															scope.row.materialName = e.name
															scope.row.stockQty = (e.uniqueCode=='YES'?1:null)
															scope.row.uniqueCode = e.uniqueCode
															scope.row.goodsMaterialItemId = e.itemId
														}" value-key="name" :disabled="isEdit2 != scope.$index || formType == 2 || logisticsType == 'detail'" placeholder="请选择" style="width: 100%;">
														    <el-option
														      v-for="(item,ind) in scope.row.materialList"
														      :key="ind"
														      :label="item.name"
														      :value="item">
														    </el-option>
														</el-select>
													</el-form-item>
												</template>
											</el-table-column>
											<el-table-column prop="" align="center" label="是否一物一码" >
												<template slot-scope="scope">
													<el-form-item>
														{{scope.row.uniqueCode=='YES'?'是':scope.row.uniqueCode=='NO'?'否':''}}
													</el-form-item>
												</template>
											</el-table-column>
											<el-table-column prop="" align="center" label="条码" >
												<template slot-scope="scope">
													<el-form-item :prop="'list.' + scope.$index + '.materialCode'" :rules="[{ required: true, message: `请输入条码`, trigger: 'blur' }]">
														<el-input type="text" v-model="scope.row.materialCode" :disabled="isEdit2 != scope.$index || formType == 2 || logisticsType == 'detail'" placeholder="请输入"></el-input>
													</el-form-item>
												</template>
											</el-table-column>
											<el-table-column prop="" align="center" label="数量">
												<template slot-scope="scope">
													<el-form-item :prop="'list.' + scope.$index + '.stockQty'" :rules="[{ required: true, message: `请输入数量`, trigger: 'blur' }]">
														<el-input type="number" v-model="scope.row.stockQty" :disabled="isEdit2 != scope.$index || formType == 2 || scope.row.uniqueCode=='YES' || logisticsType == 'detail'" placeholder="请输入"></el-input>
													</el-form-item>
												</template>
											</el-table-column>
											<el-table-column label="操作" align="right" width="140" fixed="right">
												<template slot-scope="scope" v-if="logisticsType == 'add'">
													<el-button size="mini" type="primary" v-if="scope.$index == isEdit2" @click="saveCode(scope.row)">保存</el-button>
													<el-button size="mini" type="primary" v-if="scope.$index != isEdit2" @click="isEdit2 = scope.$index">编辑</el-button>
													<el-popconfirm title="确定删除吗？" @confirm="delCode(scope.row.orderDetailCodeId,scope.$index)">
														<el-button slot="reference" size="mini" type="danger">删除</el-button>
													</el-popconfirm>
												</template>
											</el-table-column>
										</el-table>
									</el-form>
								</div>
							</el-card>
						</el-col>
					</el-row>
				</el-form>
				<br/>
				<div slot="footer" class="dialog-footer">
				  <el-button type="primary" v-if="logisticsType != 'detail'" @click="saveLogistics(data.removeTab)">{{logisticsType === 'add'?'发 货':'保 存'}}</el-button>
				  <el-button @click="cancelLogistics;data.removeTab()">取 消</el-button>
				</div>
			</div>
        <!-- 修改收货地址 -->
        <div v-if="activeKey == 'editAddress'" class="app-container">
          <el-form :model="addressForm" :rules="addressFormRules" ref="addressForm" label-width="80px" label-position="left">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="addressForm.name" placeholder="请输入姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="电话" prop="phone">
                  <el-input v-model="addressForm.phone" placeholder="请输入电话"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <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-col>
              <el-col :span="6">
                <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-col>
              <el-col :span="6">
                <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-col>
              <el-col :span="6">
                <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-col>
              <el-col :span="6">
                <el-form-item label="详细地址" prop="address">
                  <el-input v-model="addressForm.address" placeholder="请输入详细地址"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="门牌号" prop="house">
                  <el-input v-model="addressForm.house" placeholder="请输入门牌号"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitAddressForm(data.removeTab)">保 存</el-button>
            <el-button @click="cancelAddressForm;data.removeTab()">取 消</el-button>
          </div>
        </div>
      </template>
      <!-- 批量发货 -->
      <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>

    </zj-tab-page>
    
    <print-preview ref="preView" :printOrderId="printOrderId" @initPrint="handleInitPrint" @refreshList="handleRefreshList" />
  </div>
	
</template>

<script>
import { getToken } from '@/utils/auth'
import { cancelOrder, confirm2Order, getList, goodsDeliver, saveRemark, batchShipment, batchRemark, getWebsiteList, editLogistics, getRegion, editAddress, getOrderDetail, getCodeDetail, getMaterialList, listImport, saveCode, delCode } from "@/api/order";
import { getExpress, getCompanyList } from "@/api/common";
import { downloadFiles, handleImport } from '@/utils/util'
import { commonTemplateDownload } from '@/api/common.js'
import printPreview from '../components/preview.vue'
import { disAutoConnect, hiprint } from 'vue-plugin-hiprint'
import import_mixin from '@/components/template/import_mixin.js'
import * as Storage from "@/api/storage";
import '@/styles/order-list.scss'

export default {
  name: "order_list",

	components: { 
    printPreview
  },
  
  filters: {
    saleTypeFilter(val) {
      const MAP = {
        1: '商城销售',
        2: '线下销售',
      }
      return MAP[val];
    }
  },

  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: {
        pickType: 'YES',
        pickName: '',
        pickPhone: '',
        logisticsNo: '',
        storageId: '',
		storageName: '',
        companyCode: '',
        workOrder: true,
        exchange: false,
		pickType: 'YES',
		pickName: '',
		pickPhone: ''
      },
      logisticsTab: 'first',
      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: [],
		formType: 'add',
		formVisible: false,
		typeIndex: '1',
		formData1: {
			list: [],
		},
		formData2: {
			list: [],
		},
		isEdit1: 0,
		isEdit2: 0,
		joinCode: JSON.parse(localStorage.getItem('greemall_user')).joinCode,
		orderDetailId: '',

    printOrderId: '',
		payQrcode: JSON.parse(localStorage.getItem('greemall_user')).payQrcode,
		billTitle: JSON.parse(localStorage.getItem('greemall_user')).billTitle,//打印名称
    }
  },
  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)
    },

    filterArr() {
			return function (arr, size) {
				//判断如果不是数组(就没有length)，或者size没有传值，size小于1，就返回空数组
				if (!arr.length || !size || size < 1) return []
				let [start, end, result] = [null, null, []]
				for (let i = 0; i < Math.ceil(arr.length / size); i++) {
					start = i * size
					end = start + size
					result.push(arr.slice(start, end))
				}
				return result
			}
		}
  },
  created() {
    this.getList();
    this.getStorageList();
    this.getCompanyList();
    this.getWebsiteList();
    if(this.$route.query.id){
      this.queryDetail(this.$route.query.id)
    }
  },
  methods: {
    queryWorkOrder(id) {
		this.$router.push({
	  		name: 'workOrderPool',
	  		params: {
          pageName: id,
	  			pageType: 'saleOrderId',
	  			pageCode: id,
	  		},
	  	})
    },
    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;
      })
    },
	getOrderDetail(){
		getOrderDetail({orderId: this.editOrderId}).then(res => {
			let arr = []
			res.data.orderDetails.forEach(item=>{
				if(item.goodsMaterialId){
					arr.push(item)
				}
			})
			this.formData1.list = arr
		})
	},
	changeType(){
		this.getOrderDetail()
		this.getCodeDetail()
	},
	async getCodeDetail(){
		getCodeDetail({orderId: this.editOrderId}).then(async res => {
			for(var item of res.data){
				item.specs = {goodsMaterialSpecsName: item.specsName,orderDetailId: item.orderDetailId}
				item.material = {name: item.materialName}
				item.materialList = await this.getMaterialList(item.specsName,item.goodsMaterialItemType)
			}
			this.formData2.list = res.data
		})
	},
	async getMaterialList(specsName,type){
		return new Promise((resolve, reject) => {
			getMaterialList({
				pageNum: 1,
				pageSize: -1,
				specsName,
				type
			}).then(async res => {
				resolve(res.data.records) 
			})
		})
		
	},
	async changeSpecs(e,row){
		row.brandName = e.brandName
		row.brandId = e.brandId
		row.mainName = e.mainName
		row.mainId = e.mainNumber
		row.smallName = e.smallName
		row.smallId = e.smallNumber
		row.specsName = e.goodsMaterialSpecsName
		row.goodsMaterialName = e.goodsName
		row.goodsMaterialId = e.goodsMaterialId
		row.material = null
		row.materialName = ''
		row.stockQty = ''
		row.uniqueCode = ''
		row.materialList = await this.getMaterialList(row.specsName,row.goodsMaterialItemType)
		row.orderDetailId = e.orderDetailId
	},
	async changeMaterial(e,row){
		if(!row.specs){
			return this.$message.warning('请先选择规格型号！');
		}
		row.material = null
		row.materialName = ''
		row.stockQty = ''
		row.uniqueCode = ''
		row.materialList = await this.getMaterialList(row.specsName,row.goodsMaterialItemType)
	},
	//发货新增条码
	addCode(){
		this.$refs.formData2.validate((valid) => {
			if (valid) {
				this.isEdit2 = 0
				this.formData2.list.unshift({
					brandId: '',
					brandName: '',
					mainId: '',
					mainName: '',
					stockQty: '',
					smallId: '',
					smallName: '',
					goodsMaterialItemType: '',
					goodsMaterialName: '',
					goodsMaterialId: '',
					materialCode: '',
					uniqueCode: '',
					specs: null,
					specsName: '',
					materialName: '',
					material: null,
					materialList: [],
					orderDetailId: '',
					goodsMaterialItemId: ''
				})
			}
		});
	},
	delCode(orderDetailCodeId,index){
		if(orderDetailCodeId){
			delCode({
			  orderDetailCodeId
			}).then(res => {
			  if (res.code == 200) {
			    this.$message({ type: 'success', message: '删除成功!' })
			    this.getOrderDetail()
			    this.getCodeDetail()
			  } else {
			    this.$message.error(res.msg);
			  }
			})
		}else{
			this.formData2.list.splice(index,1)
		}
	},
	saveCode(orderDetailCodes){
		const that = this
		let params = [{
			...orderDetailCodes,
			orderId: this.editOrderId,
		}]
		delete params[0].material;
		delete params[0].specs;
		this.$refs.formData2.validate((valid, invalidFields, errLabels) => {
			if (valid) {
				saveCode(params).then(res=>{
					if(res.code == 200){
						that.$message.success('保存成功!')
						this.getOrderDetail()
						this.getCodeDetail()
					}
				})
			}
		})
	},
    // 查看详情
    queryDetail(orderId) {
      // let {href} = this.$router.resolve({path: `/order/detail?orderId=${orderId}`});
      // window.open(href, '_blank');
      this.$router.push({
        name: "order_detail",
        query: {
          orderId
        }
      })
    },
	openForm(type,order){
		this.$refs.tabPage.addTab({
			// 对应显示的模块
			activeKey: type,
			// 唯一标识
			key: type,
			// 页签名称
			label: ({ remark: "订单备注", editExpressage: "修改快递单号",editAddress: "修改收货地址", materialDetail: "查看物流", deliverGoods: "发货", deliverGoodsDetail: '查看发货条码' })[type],
			// 打开时事件
			triggerEvent: () => {
				
				this.$nextTick(()=>{
					this.formType = type
					this.formVisible = true
					if(type == 'remark'){
						this.remarkVisible = true
						this.editOrderId = order.orderId
						this.remark = order.remark
					}
					if(type == 'editExpressage'){
						this.logisticsForm.logisticsNo = order.logisticsNo;
						this.logisticsForm.companyCode = order.companyCode;
					}
					if(type == 'materialDetail'){
						getExpress({ logisticsNo: order.logisticsNo, companyCode: order.companyCode }).then(res => {
						  this.logistics = res.data
						  this.logisticsLoading = false
						})
					}
					if(type == 'editAddress'){
						this.addressFormVisible = true;
						this.initRegion(0, order);
						this.addressForm.name = order.receUserName;
						this.addressForm.phone = order.recePhone;
						this.addressForm.address = order.receAddress;
						this.addressForm.house = order.houseNo;
						this.addressFormOrder = order;
					}
				})
			},
			// 关闭时事件
			closeEvent: () => {
				
			}
		})
	},
    // 更改每页数量
    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(order) {
		this.openForm('remark',order)
    },
    cancelRemark() {
      this.remarkVisible = false
      this.editOrderId = ''
      this.remark = ''
    },
    saveRemark(cancel) {
      const params = {
        orderId: this.editOrderId,
        remark: this.remark
      }
      saveRemark(params).then(() => {
		  cancel('list')
        this.cancelRemark();
        this.getList();
        this.$successMsg('保存成功');
      })
    },
    // 取消订单
    cancelOrder(orderId) {
      cancelOrder({ orderId }).then(() => {
        this.getList();
        this.$successMsg('取消成功');
      })
    },
    // 确认订单
    confirmOrder(orderId) {
      confirm2Order({ orderId }).then(() => {
        this.getList();
        this.$successMsg('确认成功');
      })
    },
    // 查看物流
    queryLogistics(order) {
      this.logisticsVisible = true
      this.logisticsLoading = true
			this.openForm('materialDetail',order)
    },
    // 显示快递信息填写
    showLogistics(item, type) {
			this.logisticsType = type;
			this.logisticsIdVisible = true;
			this.editOrderId = item.orderId;
			if(type == 'add'){
				this.getOrderDetail()
				this.getCodeDetail()
				this.openForm('deliverGoods',item)
			}else if(type == 'edit'){
				this.openForm('editExpressage',item)
			}else{
				this.logisticsForm.logisticsNo = item.logisticsNo
				this.logisticsForm.storageId = item.storageId
				this.logisticsForm.storageName = item.storageName
				this.logisticsForm.companyCode = item.companyCode
				this.logisticsForm.workOrder = item.workOrder
				this.logisticsForm.exchange = item.exchangeOrder
				this.logisticsForm.pickType = item.pickType
				this.logisticsForm.pickName = item.pickName
				this.logisticsForm.pickPhone = item.pickPhone
				this.getOrderDetail()
				this.getCodeDetail()
				this.openForm('deliverGoodsDetail',item)
			}
    },
    // 取消快递信息填写
    cancelLogistics() {
      this.logisticsIdVisible = false
      this.editOrderId = ''
      this.$refs.logisticsForm.resetFields()
    },
    // 提交快递信息填写
    saveLogistics(cancel) {
      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,
              exchange: this.logisticsForm.exchange,
			  pickName: this.logisticsForm.pickName,
			  pickPhone: this.logisticsForm.pickPhone,
			  pickType: this.logisticsForm.pickType,
            }).then(() => {
				cancel('list')
              this.cancelLogistics();
              this.getList();
              this.$successMsg('发货成功');
            })
          }
          // 修改单号
          else {
            editLogistics({
              orderId: this.editOrderId,
              logisticsNo: this.logisticsForm.logisticsNo,
              companyCode: this.logisticsForm.companyCode,
            }).then(() => {
				cancel('list')
              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,
		type: 'C'
      }).then(res => {
        this.websiteList = res.data;
      })
    },

    // 取消 批量发货
    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);

      handleImport('order/goods/batch/deliver', formData).then(result=>{
        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[this.$findElem(this.provinceList, 'name', province)].id;
        } else if (level === 1) {
          this.cityList = res.data;
          nextId = this.addressForm.city = this.cityList[this.$findElem(this.cityList, 'name', city)].id;
        } else if (level === 2) {
          this.areaList = res.data;
          nextId = this.addressForm.area = this.areaList[this.$findElem(this.areaList, 'name', area)].id;
        } else if (level === 3) {
          this.streetList = res.data;
          nextId = this.addressForm.street = this.streetList[this.$findElem(this.streetList, 'name', street)].id;
        }
        if (level < 3) {
          level = level + 1;
          this.initRegion(level, item, nextId);
        }
      })
    },

    // 打开 修改收货地址 表单
    openAddressForm(item) {
		this.openForm('editAddress',item)
    },

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

    // 保存 修改收货地址 表单
    submitAddressForm(cancel) {
      this.$refs.addressForm.validate((valid) => {
        if (valid) {
          let province = this.provinceList[this.$findElem(this.provinceList, 'id', this.addressForm.province)].name;
          let city = this.cityList[this.$findElem(this.cityList, 'id', this.addressForm.city)].name;
          let area = this.areaList[this.$findElem(this.areaList, 'id', this.addressForm.area)].name;
          let street = this.streetList[this.$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(() => {
			  cancel('list')
            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');

      this.$router.push({
        name: "workOrder_detail",
        query: {
          orderId
        }
      })

    },
	
	importCode(data){
		const loading = this.$loading({
		  lock: true,
		  text: '正在导入',
		  spinner: 'el-icon-loading',
		  background: 'rgba(0, 0, 0, 0.7)'
		})
		var formdata = new FormData()
		formdata.append('file', data.file)
		let params = {
			orderDetailId: this.orderDetailId
		}
		if (!!params) {
		  for (const key in params) {
		    if (Object.hasOwnProperty.call(params, key)) {
		      formdata.append(key, params[key])
		    }
		  }
		}
		listImport({ formdata })
		  .then(res => {
		    this.getOrderDetail()
			this.getCodeDetail()
		    loading.close()
		    this.$message({
		      type: 'success',
		      message: '导入成功!'
		    })
		  })
		  .catch(err => {
		    loading.close()
		    this.$message({
		      type: 'error',
		      message: err.message || '导入失败'
		    })
		  })
	},
	
	// 下载导入模版
	handleDownload(title) {
		commonTemplateDownload({ name: '导入条码.xlsx' }, title).then(res => {
			this.$message({
				message: '下载成功',
				type: 'success'
			})
		}).catch(err => {
			this.$message.error('下载失败')
		})
	},


    // 点击打印
		async toPrint(row) {
      this.printOrderId = row.orderId;
			let pagingData = []
			const { data } = await getOrderDetail({
				orderId: row.orderId
			})
			pagingData = this.filterArr(data.orderDetails, 4)
			// 初始化模板，否则生成的模板叠加
			hiprint.init()
			this.hiprintTemplate = new hiprint.PrintTemplate()
			// 兼容批量打印
			let len = pagingData.length
			let loadingLen = len
			// 使用 i-- 提升for效率
			this.$startLoading()
      let unitMap = {
        C: '整套',
        I: '单个'
      }

			for (let i = 0; i < len; i++) {
				try {
					let html = ''
					let num = 0
					let totalAmount = 0
					pagingData[i].forEach(item => {
						totalAmount = (Number(item.payAmount) * 100 + totalAmount * 100) / 100
						num += Number(item.num)
						html += `
              <tr align="center">
              <td>${item.goodsName || ''}</td>
              <td>${item.goodsSpecName || ''}</td>
              <td>${item.goodsMaterialUnit ? unitMap[item.goodsMaterialUnit] : ''}</td>
              <td>${item.num}</td>
              <td>${item.price}</td>
              <td>${item.payAmount}</td>
              <td>${data.storageName || ''}</td>
              <td>${data.remark || ''}</td>
              </tr>
            `
					})
					// 模板基础配置
					this.panel = this.hiprintTemplate.addPrintPanel({
						height: 140,
						width: 241,
						fontFamily: '黑体',
						fontSize: 13,
						paperFooter: 340,
						paperHeader: 10,
						paperNumberDisabled: true
					})

					// 获取收款单模板和基础配置
					this.panel.addPrintHtml({
						options: {
							width: 633,
							top: 30,
							left: 20,
							fontFamily: '黑体',
							fontSize: 13,
							content: this.setTableDom(data, html, totalAmount, num, len, i, row.printRecordCount)
						}
					})

					loadingLen--
				} catch (error) {
					console.log(999, error)
					this.$endLoading()
					return
				}
			}
			if (loadingLen === 0) {
				this.$endLoading()
			}
			console.log(333)
			// 预览打印内容
			this.$refs.preView.show(this.hiprintTemplate, this.panel)
		},

		// 打印模板
		setTableDom(data, html, totalAmount, num, length, page, printRecordCount) {
      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1; // 月份是从 0 开始计数的，所以要加 1
      let day = now.getDate();
      let hours = now.getHours();
      let minutes = now.getMinutes();
      let seconds = now.getSeconds();
      let nowTime = `${year}-${month < 10 ? '0'+month : month}-${day < 10 ? '0'+day : day} ${hours < 10 ? '0'+hours : hours}:${minutes < 10 ? '0'+minutes : minutes}:${seconds < 10 ? '0'+seconds : seconds}`

      let showpPrintCount = '';
      if(printRecordCount) {
        showpPrintCount = `重打日期: ${nowTime}`
      }else {
        showpPrintCount = `打印日期: ${nowTime}`
      }

			return `
	   <div style="font-family:'黑体';font-size: 16px;">
			<div style="display: flex;justify-content: center;align-items: center;position: relative;">
				<h1 style="text-align:center;margin: 10px 0;">${this.billTitle?this.billTitle:data.companyWechatName}销售单</h1>
				<div style="position: absolute;right:0;">共 ${length}页 第 ${page+1} 页</div>
			</div>
		  <div style="display: flex;justify-content: space-between;">
			<div>${showpPrintCount}</div>
			<div>单据日期: ${data.createTime}</div>
			<div>单据编号: ${data.orderId}</div>
		  </div>
		  <div style="display: flex;justify-content: space-between;font-size: 16px;margin: 10px 0;">
		  	<div>客户: ${data.receUserName}</div>
		  	<div>摘要: ${data.payType}</div>
		  </div>
		  <div style="display: flex;font-size: 16px;margin-bottom: 10px;">
		  	<div style="flex-shrink: 0;">联系电话: ${data.recePhone}</div>
		  	<div style="margin-left: 50px;">收货地址: ${data.province}${data.city}${data.area}${data.street}${data.receAddress}</div>
		  </div>
	      <div >
	        <table border=".5" cellspacing="0" width="856"
	         style="border-color: rgb(0,0,0);
	          border-collapse: collapse;
	          border-style: none;
	          border: 1px solid rgb(0,0,0);
	          font-weight: normal;
	          
	          text-decoration: none;
	          vertical-align: middle;
	          box-sizing: border-box;
	          word-wrap: break-word;
	          word-break: break-all;">
				<tr align="center">
					<td>商品名称</td>
					<td>规格</td>
					<td>单位</td>
					<td>数量</td>
					<td>单价</td>
					<td>金额</td>
					<td>仓库</td>
					<td>备注</td>
				</tr>
	            ${html}
				<tr align="center" align="center">
				  <td>小计: </td>
				  <td colspan="2"></td>
				  <td>${num}</td>
				  <td></td>
				  <td>${totalAmount}</td>
				  <td colspan="2">金额总计: ${totalAmount}</td>
				</tr>
	        </table>
	      </div>
		  <div style="display: flex;justify-content: space-between;font-size: 16px;margin: 10px 0;">
		  	<div>制单人: ${data.createBy || ''}</div>
		  	<div>审核人: ${data.companyWechatName || ''}</div>
			<div>业务员: ${data.saleName || ''}</div>
			<div>签收人: </div>
		  </div>
				<div style="display: flex;justify-content: flex-end;">
					${(data.payTypeId == 'CASH' && this.payQrcode)?`<div style="">
						<img style="width: 80px;height: 80px;" src="${this.payQrcode}"/>
					</div>`:''}
				</div>
	      <div style="margin:100px 0 0 0">
	        <div></div>
	      </div>
	   </div>
	  `
		},

		handleRefreshList() {
      this.getList();
			// this.recordSelected = []
			// this.$refs.pageRef.refreshList()
		},

		handleInitPrint() {
			this.$nextTick(() => {
				this.initPrint()
			})
		},

  }
}

</script>

