<template>
  <zj-page-container>
    <zj-page-fill>
      <zj-tab-page
        ref="tabPage"
        :defaultActives="[{ key: 'list', label: $route.meta.title + '-列表', essential: true }]"
      >
        <template slot-scope="{ activeKey, data }">
          <div
            :style="{ height: activeKey == 'list' ? '100%' : '0px' }"
            style="width: 100%; height: 100%; overflow: hidden"
          >
            <div style="width: 100%; height: 100%; box-sizing: border-box; padding: 10px">
              <zj-page-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="esGoodsName">
                          <el-input v-model="screenForm.esGoodsName" placeholder="请输入商品名称"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :xs="24" :sm="12" :lg="6">
                        <el-form-item label="会员昵称" prop="userName">
                          <el-input v-model="screenForm.userName" placeholder="请输入会员昵称"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :xs="24" :sm="12" :lg="6">
                        <el-form-item label="手机号" prop="userMobile">
                          <el-input v-model="screenForm.userMobile" placeholder="请输入手机号"></el-input>
                        </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" class="tr">
                        <el-form-item label="" label-width="0px">
                          <div style="text-align: left">
                            <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
                            <el-button size="small" @click="resetScreenForm">清空</el-button>
                          </div>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </div>
                <div class="tabs-container order-tabs-container clearfix" style="margin: 10px 0 !important">
                  <div class="fl">
                    <el-tabs
                      v-model="tabCurrent"
                      type="card"
                      @tab-click="changeTabs"
                      class="fl"
                      size="small"
                      style="margin-right: 10px"
                    >
                      <el-tab-pane label="全部" name="ALL"></el-tab-pane>
                      <el-tab-pane label="待付款" name="SAVE"></el-tab-pane>
                      <el-tab-pane label="待确认" name="WAIT"></el-tab-pane>
                      <el-tab-pane label="待发货" name="PAID"></el-tab-pane>
                      <el-tab-pane label="已发货" name="SEND"></el-tab-pane>
                      <el-tab-pane label="已完成" name="OVER"></el-tab-pane>
                      <el-tab-pane label="已售后/取消" name="CANCEL"></el-tab-pane>
                      <el-tab-pane label="已超时" name="TIME_OUT"></el-tab-pane>
                    </el-tabs>
                    <el-button class="fl" type="primary" size="small" @click="add(1)">新增</el-button>
                  </div>
                  <div class="fr">
                    <el-button size="small" type="primary" @click="handleExport">导出</el-button>
                  </div>
                </div>
                <zj-page-fill>
                  <div class="order-main-container">
                    <div class="table-top">
                      <el-row style="width: 100%">
                        <el-col :span="3">
                          <span class="item product">商品信息</span>
                        </el-col>
                        <el-col :span="3" style="text-align: right"><span class="item">单价(元)/数量</span></el-col>
                        <el-col :span="4" style="text-align: center"><span class="item">买家信息</span></el-col>
                        <el-col :span="4" style="text-align: center"><span class="item">收货信息</span></el-col>
                        <el-col :span="4" 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="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">
                        <span><b>订单号</b>：{{ order.esOrderId }}</span>
                        <span><b>下单时间</b>：{{ order.createTime }}</span>
                        <el-tag v-if="~[2, '2'].indexOf(order.saleType)">线下销售</el-tag>
                        <el-tag v-if="~[1, '1'].indexOf(order.saleType)">线上销售</el-tag>
                        <el-tag v-if="order.saleType == 1 && order.payType == 'WECHAT'">在线支付</el-tag>
                        <el-tag v-if="(order.saleType == 1 && order.payType != 'WECHAT') || order.saleType == 2"
                          >到店支付</el-tag
                        >
                        <el-tag v-if="~[0].indexOf(order.totalAmount)">面议</el-tag>
                        <div class="fr"></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">
                                <div class="left">
                                  <div class="image">
                                    <img :src="$showImgUrl(order.goodsUrl)" style="height: 80px; width: 80px" />
                                  </div>
                                  <div class="main">
                                    <span>{{ order.esGoodsName }}</span>
                                  </div>
                                </div>
                                <div class="right">
                                  <span>￥{{ order.goodsPrice }}</span>
                                  <span>x{{ order.num }}</span>
                                </div>
                              </div>
                            </div>
                          </el-col>
                          <el-col :span="4" style="height: 100%">
                            <div class="col-item">
                              <div>{{ order.userName }}</div>
                              <div>{{ order.userMobile }}</div>
                            </div>
                          </el-col>
                          <el-col :span="4" style="height: 100%">
                            <div class="col-item">
                              <div>{{ order.userName }}/{{ order.userMobile }}</div>
                              <div class="ellipsis-2">
                                {{ order.province + order.city + order.area + order.street + order.receAddress }}
                              </div>
                            </div>
                          </el-col>
                          <el-col :span="4" style="height: 100%">
                            <div class="col-item">
                              <div class="totalprice">￥{{ order.totalAmount }}</div>
                            </div>
                          </el-col>
                          <el-col :span="3" style="height: 100%">
                            <div class="col-item">
                              <div style="display: flex; align-items: center">
                                <span style="margin-left: 4px">{{
                                  {
                                    SAVE: '待支付',
                                    WAIT: '待确认',
                                    PAID: '待发货',
                                    SEND: '卖家发货',
                                    OVER: '已完成',
                                    TIME_OUT: '超时',
                                    CANCEL: '已售后/取消',
                                    WAIT_REFUND: '售后中',
                                    REFUND: '已退'
                                  }[order.status]
                                }}</span>
                              </div>
                            </div>
                          </el-col>
                          <el-col :span="3" style="height: 100%">
                            <div class="col-item">
                              <div class="operate">
                                <el-popconfirm
                                  v-if="~['WAIT'].indexOf(order.status)"
                                  title="确认订单吗？"
                                  @confirm="quedingesOrderPayOk(order)"
                                >
                                  <el-button slot="reference" type="text" size="small">确认订单</el-button>
                                </el-popconfirm>
                                <el-popconfirm
                                  v-if="~['SAVE', 'WAIT'].indexOf(order.status)"
                                  title="确认取消订单吗？"
                                  @confirm="quedingesOrderCancel(order)"
                                >
                                  <el-button slot="reference" type="text" size="small">取消订单</el-button>
                                </el-popconfirm>
                                <el-button
                                  v-if="~['SEND', 'OVER'].indexOf(order.status)"
                                  @click="viewMaterialFlow(order)"
                                  type="text"
                                  size="small"
                                  >查看物流</el-button
                                >
                                <el-button
                                  v-if="
                                    ~['SAVE', 'WAIT', 'PAID', 'SEND', 'OVER', 'CANCEL', 'TIME_OUT'].indexOf(
                                      order.status
                                    )
                                  "
                                  @click="viewDetails(order, 0)"
                                  type="text"
                                  size="small"
                                  >查看详情</el-button
                                >
                                <el-button
                                  v-if="~['CASH'].indexOf(order.payType) && ~['SAVE'].indexOf(order.status)"
                                  @click="viewDetails(order, 1)"
                                  type="text"
                                  size="small"
                                  >确认收款</el-button
                                >
                                <el-button
                                  v-if="~['SEND', 'OVER', 'CANCEL'].indexOf(order.status) && order.payStatus == 'PAID'"
                                  @click="viewDetails(order, 2)"
                                  type="text"
                                  size="small"
                                  >发起退货</el-button
                                >
                                <el-button
                                  v-if="~['PAID'].indexOf(order.status)"
                                  type="text"
                                  @click="gofahuo(order)"
                                  size="small"
                                  >发货</el-button
                                >
                                <el-button
                                  v-if="~['PAID', 'SEND'].indexOf(order.status)"
                                  type="text"
                                  size="small"
                                  @click="toPrint(order)"
                                  >打印</el-button
                                >
                              </div>
                            </div>
                          </el-col>
                        </el-row>
                      </div>
                    </div>
                    <div class="no-data" v-if="dataList.length <= 0">暂无订单</div>
                  </div>
                </zj-page-fill>
                <div class="pagination clearfix" style="margin-top: 10px">
                  <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>
              </zj-page-container>
            </div>
          </div>
          <!-- 新增 -->
          <div v-if="activeKey == 'add'" style="width: 100%; height: 100%">
            <add
              :detailsId="detailsId"
              :detailsType="detailsType"
              @removeTab="
                () => {
                  getList()
                  data.removeTab()
                }
              "
            />
          </div>
          <!-- 查看详情 / 确认收款 / 退货-->
          <div v-if="~activeKey.indexOf('details_')" style="width: 100%; height: 100%">
            <detailsV
              :detailsId="detailsId"
              :detailsType="detailsType"
              @viewMaterialFlow="viewMaterialFlow"
              @removeTab="
                () => {
                  getList()
                  data.removeTab()
                }
              "
            />
          </div>
          <!-- 查看物流 -->
          <div v-if="activeKey == 'materialFlow'" style="width: 100%; height: 100%">
            <materialFlow :detailsId="detailsId" />
          </div>
          <!-- 发货 -->
          <div v-if="activeKey == 'fahuo'" style="width: 100%; height: 100%">
            <deliverGoods
              :detailsId="detailsId"
              @removeTab="
                () => {
                  getList()
                  data.removeTab()
                }
              "
            />
          </div>
        </template>
      </zj-tab-page>
    </zj-page-fill>
    <print-preview ref="preView" @initPrint="handleInitPrint" @refreshList="handleRefreshList" />
  </zj-page-container>
</template>

<script>
import { esOrderList, esOrderListExcel, esOrderPayOk, esOrderCancel, esOrderDetail } from '@/api/orderManagement'
import add from './add.vue'
import detailsV from './details.vue'
import materialFlow from './materialFlow.vue'
import deliverGoods from './deliverGoods.vue'
import '@/styles/order-list.scss'
import { downloadFiles } from '@/utils/util'
import { disAutoConnect, hiprint } from 'vue-plugin-hiprint'
import printPreview from '../components/preview.vue'
export default {
  components: { add, detailsV, materialFlow, deliverGoods, printPreview },
  data() {
    return {
      pageType: this?.$route?.params?.pageType,
      pageCode: this?.$route?.params?.pageCode,
      pagePam: this?.$route?.params?.pagePam,
      screenForm: {
        // 筛选表单数据
        orderId: '', // 订单号
        esGoodsName: '', // 商品名称
        userName: '', // 会员昵称
        userMobile: '', // 手机号
        websitId: '', // 网点名称
        status: '', // 状态
        createDate: '', // 创建时间
        payDate: '', // 支付时间
        exchangeCode: '', // 兑换码
        evaluateStatus: '', // 评价状态
        sendStatus: '', // 派单异常
        workerOrderNo: '' // 信息编号
      },
      tabCurrent: 'ALL',
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: [],
      detailsId: '',
      detailsType: ''
    }
  },
  created() {
    this.getList()
    if (this.pageType === 'detail' && this.pageCode) {
      this.$nextTick(() => {
        this.viewDetails({ esOrderId: this.pageCode }, 0)
      })
    }
    if (this.pageType === 'materialFlow' && this.pageCode) {
      this.$nextTick(() => {
        this.viewMaterialFlow({ esOrderId: this.pageCode })
      })
    }
    if (this.pageType === 'add' && this.pageCode) {
      this.$nextTick(() => {
        this.add(0)
      })
    }
  },
  methods: {
    quedingesOrderPayOk(row) {
      esOrderPayOk({
        esOrderId: row.esOrderId
      }).then(res => {
        this.$message({ type: 'success', message: `确定成功!` })
        this.getList()
      })
    },
    quedingesOrderCancel(row) {
      esOrderCancel({
        esOrderId: row.esOrderId
      }).then(res => {
        this.$message({ type: 'success', message: `取消成功!` })
        this.getList()
      })
    },
    add(type) {
      this.$refs.tabPage.addTab({
        // 对应显示的模块
        activeKey: 'add',
        // 唯一标识
        key: 'add',
        // 页签名称
        label: '新增订单',
        // 打开时事件
        triggerEvent: () => {
          this.detailsType = type
        },
        // 关闭时事件
        closeEvent: () => {}
      })
    },
    viewDetails(row, type) {
      this.$refs.tabPage.addTab({
        // 对应显示的模块
        activeKey: 'details_' + type,
        // 唯一标识
        key: 'details_' + type,
        // 页签名称
        label: ['订单详情', '确认收款', '退货退款'][type],
        // 打开时事件
        triggerEvent: () => {
          this.detailsId = row.esOrderId
          this.detailsType = type
        },
        // 关闭时事件
        closeEvent: () => {}
      })
    },
    viewMaterialFlow(row) {
      this.$refs.tabPage.addTab({
        // 对应显示的模块
        activeKey: 'materialFlow',
        // 唯一标识
        key: 'materialFlow',
        // 页签名称
        label: '查看物流',
        // 打开时事件
        triggerEvent: () => {
          this.detailsId = row.esOrderId
        },
        // 关闭时事件
        closeEvent: () => {}
      })
    },
    gofahuo(row) {
      this.$refs.tabPage.addTab({
        // 对应显示的模块
        activeKey: 'fahuo',
        // 唯一标识
        key: 'fahuo',
        // 页签名称
        label: '发货',
        // 打开时事件
        triggerEvent: () => {
          this.detailsId = row.esOrderId
        },
        // 关闭时事件
        closeEvent: () => {}
      })
    },
    changeTabs(tab, event) {
      this.screenForm.status = this.tabCurrent === 'ALL' ? '' : tab.$options.propsData.name
      this.currentPage = 1
      this.getList()
    },
    // 获取数据列表
    getList() {
      let params = {
        orderId: this.screenForm.orderId, // 订单号
        esGoodsName: this.screenForm.esGoodsName, // 商品名称
        userName: this.screenForm.userName, // 会员昵称
        userMobile: this.screenForm.userMobile, // 手机号
        status: this.screenForm.status, // 状态
        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, // 支付时间
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      esOrderList(params).then(res => {
        res.data.records.forEach(item => {
          item.selected = false
        })
        this.dataList = res.data.records
        this.listTotal = res.data.total
      })
    },
    // 更改每页数量
    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()
    },
    // 导出
    handleExport() {
      let params = {
        orderId: this.screenForm.orderId, // 订单号
        esGoodsName: this.screenForm.esGoodsName, // 商品名称
        userName: this.screenForm.userName, // 会员昵称
        userMobile: this.screenForm.userMobile, // 手机号
        status: this.screenForm.status, // 状态
        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, // 支付时间
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      downloadFiles('esOrder/listExcel', params)
    },
    // 点击打印
    async toPrint(row) {
      const { data } = await esOrderDetail({
        esOrderId: row.esOrderId
      })
      // 初始化模板，否则生成的模板叠加
      hiprint.init()
      this.hiprintTemplate = new hiprint.PrintTemplate()
      // 使用 i-- 提升for效率
      this.$startLoading()
      try {
        let num = data.num
        let totalAmount = Number(data.num) * Number(data.goodsPrice)
        let html = `
          <tr align="center">
          <td>${data.esGoodsName || ''}</td>
          <td>${data.unit || ''}</td>
          <td>${data.num}</td>
          <td>${data.goodsPrice}</td>
          <td>${totalAmount}</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, 1, 0)
          }
        })
      } catch (error) {
        this.$endLoading()
        return
      }
      this.$endLoading()
      // 预览打印内容
      this.$refs.preView.show(this.hiprintTemplate, this.panel)
    },
    // 打印模板
    setTableDom(data, html, totalAmount, num, length, page) {
      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 = `打印日期: ${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;">${
            JSON.parse(localStorage.getItem('greemall_user'))?.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.esOrderId}</div>
        </div>
        <div style="display: flex;justify-content: space-between;font-size: 16px;margin: 10px 0;">
          <div>客户: ${data.userName}</div>
          <div>摘要: ${{ TRANSFER: '在线支付', WECHAT: '在线支付', CASH: '到店支付' }[data.payType]}</div>
        </div>
        <div style="display: flex;font-size: 16px;margin-bottom: 10px;">
          <div style="flex-shrink: 0;">联系电话: ${data.userMobile}</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>
            </tr>
            ${html}
            <tr align="center" align="center">
              <td>小计: </td>
              <td></td>
              <td>${num}</td>
              <td>${totalAmount}</td>
              <td>金额总计: ${totalAmount}</td>
              <td></td>
            </tr>
          </table>
        </div>
        <div style="display: flex;justify-content: space-between;font-size: 16px;margin: 10px 0;">
          <div>制单人: ${data.createBy || ''}</div>
          <div>审核人: ${JSON.parse(localStorage.getItem('greemall_user'))?.nickName || ''}</div>
          <div>业务员: ${data.saleName || ''}</div>
          <div>签收人: </div>
        </div>
        <div style="display: flex;justify-content: flex-end;">
        </div>
        <div style="margin:100px 0 0 0">
          <div></div>
        </div>
	   </div>
	  `
    },
    handleRefreshList() {
      this.getList()
    },
    handleInitPrint() {
      this.$nextTick(() => {
        this?.initPrint()
      })
    }
  }
}
</script>
