<template>
  <div class="conent">
    <el-card>
      <el-form ref="form" :inline="true" label-width="90px">
        <el-form-item label="所属店铺:">
          <el-select v-model="filter.shop_id" placeholder="店铺" @change="handleChoose()">
            <el-option v-for="item in shopsList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="发货状态:">
          <el-select v-model="filter.shipping_status" placeholder="发货状态" @change="handleChoose()">
            <el-option value="" label="全部"></el-option>
            <el-option value="0" label="未发货"></el-option>
            <el-option value="2" label="部分发货"></el-option>
            <el-option value="1" label="已发货"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="订单ID:">
          <el-input v-model="filter.id" placeholder="订单ID" @keyup.enter.native="handleChoose"></el-input>
        </el-form-item>

        <el-form-item label="订单编号:">
          <el-input v-model="filter.order_sn" placeholder="订单编号" @keyup.enter.native="handleChoose"></el-input>
        </el-form-item>

        <el-form-item label="订单类型:">
          <el-select v-model="filter.is_supplier" placeholder="订单类型" @change="handleChoose()">
            <el-option value="" label="全部订单"></el-option>
            <el-option :value="1" label="自卖团订单"></el-option>
            <el-option :value="0" label="帮卖团订单"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="订单状态:">
          <el-select v-model="filter.cancel_status" placeholder="订单状态" @change="handleChoose()">
            <el-option value="" label="全部"></el-option>
            <el-option :value="0" label="未取消"></el-option>
            <el-option :value="1" label="已取消"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="售后状态:">
          <el-select v-model="filter.after_sales_status" placeholder="售后状态" @change="handleChoose()">
            <el-option value="" label="全部"></el-option>
            <el-option :value="0" label="未售后"></el-option>
            <el-option :value="1" label="有售后"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品数量:">
          <el-select v-model="filter.goods_sku_num" placeholder="商品数量" @change="handleChoose()">
            <el-option value="" label="全部"></el-option>
            <el-option :value="1" label="1个商品"></el-option>
            <el-option :value="2" label="2-5个商品"></el-option>
            <el-option :value="6" label="6个以上商品"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="订单商品:">
          <el-select v-model="filter.external_sku_ids" multiple filterable remote reserve-keyword placeholder="订单商品"
            :remote-method="remoteMethod" :loading="searchLoading">
            <el-option v-for="item in options" :key="item.external_sku_id" :label="item.title"
                :value="item.external_sku_id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品编码:">
          <el-input v-model="filter.external_sku_id" placeholder="商品编码" @keyup.enter.native="handleChoose"></el-input>
        </el-form-item>

        <el-form-item label="跟团号:">
          <el-input v-model="filter.pno" placeholder="跟团号" @keyup.enter.native="handleChoose"></el-input>
        </el-form-item>

        <el-form-item label="打印状态:">
          <el-select v-model="filter.print_status" placeholder="请选择" @change="handleChoose()" clearable>
            <el-option :value="1" label="已打印"></el-option>
            <el-option :value="0" label="未打印"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="下单时间:">
          <el-date-picker v-model="confirmAt" type="datetimerange" range-separator="-" start-placeholder="起"
            end-placeholder="止" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" @change="handleChoose()">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleChoose">筛选</el-button>
          <el-button plain @click="handleReChoose">重置筛选</el-button>
          <el-button type="primary" @click="openPrint">打印</el-button>
          <!-- <el-button v-if="form.goods_sku_num === 2" type="primary">配货单导出</el-button> -->
          <el-button type="warning" :loading="exportLoading" @click="handleExport" icon="el-icon-download">数据导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 10px">
      <el-table v-loading="loading" ref="multipleTable" :data="orderList" style="width: 100%" border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" :selectable="selectable" />
        <el-table-column label="订单ID/订单编号" width="200">
          <template slot-scope="scope">
            {{ scope.row.id }}<br>
            {{ scope.row.order_sn }}
          </template>
        </el-table-column>
        <el-table-column label="店铺名称" prop="shop.name" />
        <el-table-column label="跟团号" align="center">
          <template slot-scope="scope">
            {{ scope.row.is_supplier ? '自卖团: ' : '帮卖团: ' }}
            {{ scope.row.is_supplier ? scope.row.participate_no : scope.row.supply_participate_no }}
          </template>
        </el-table-column>

        <el-table-column label="收件人信息" width="240">
          <template slot-scope="scope">
            <p>{{ scope.row.receiver_name }}&nbsp;&nbsp;{{ scope.row.receiver_mobile }}</p>
            <p>{{ scope.row.receiver_address_province }}/{{ scope.row.receiver_address_city }}/{{
                scope.row.receiver_address_district }}</p>
            <p>{{ scope.row.receiver_address_detail }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="shipping_status" label="发货状态" align="center"></el-table-column>
        <el-table-column prop="cancel_status" label="订单状态" align="center"></el-table-column>
        <el-table-column prop="after_sales_status" label="售后状态" align="center"></el-table-column>
        <el-table-column label="商品信息" min-width="150">
          <template slot-scope="scope">
            <div v-for="item in scope.row.items" :key="item.id">
              {{ item.goods_name }}
              <span style="color: red;">+{{ item.goods_number }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="面单信息" min-width="100" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.waybill">
              <el-tag type="info" v-if="scope.row.waybill.status == 0">待申请运单</el-tag>
              <el-tag type="primary" v-else-if="scope.row.waybill.status == 1">已申请运单</el-tag>
              <el-tag type="warning" v-else-if="scope.row.waybill.status == 2">待打印</el-tag>
              <el-tag type="success" v-else-if="scope.row.waybill.status == 3">打印成功</el-tag>
              <div style="line-height: 16px;margin-top: 10px;">运单号：{{ scope.row.waybill.waybill_code }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="打印状态" align="center" width="110">
          <template slot-scope="scope">
            <span v-if="scope.row.print_status == 1" style="color: rgb(4, 190, 2);">已打印</span>
            <span v-else>未打印</span>
          </template>
        </el-table-column>
        <el-table-column prop="confirm_at" label="下单时间" width="150" align="center"></el-table-column>
      </el-table>

      <div class="page-pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 50, 100, 500]"
          :page-size="per_page"
          layout="prev, pager, next, sizes, jumper, total"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog title="发货信息" width="960px" :visible.sync="showPrint" :close-on-click-modal="false" @close="closePrint">
      <div v-if="connectStatus == 1" style="margin: -20px 0 20px;">
        <el-alert title="已建立连接" type="success" show-icon></el-alert>
      </div>
      <el-table :data="tempList" style="width: 100%" border>
        <el-table-column label="订单ID" prop="id" width="80" align="center" />
        <el-table-column label="收件人信息" width="240">
          <template slot-scope="scope">
            <p>{{ scope.row.receiver_name }}&nbsp;&nbsp;{{ scope.row.receiver_mobile }}</p>
            <p>{{ scope.row.receiver_address_province }}/{{ scope.row.receiver_address_city }}/{{
                scope.row.receiver_address_district }}</p>
            <p>{{ scope.row.receiver_address_detail }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="shipping_status" label="发货状态" align="center"></el-table-column>
        <el-table-column prop="cancel_status" label="订单状态" align="center"></el-table-column>
        <el-table-column label="商品信息" width="220">
          <template slot-scope="scope">
            <div v-for="item in scope.row.items" :key="item.id">
              {{ item.goods_name }}
              <span style="color: red;">+{{ item.goods_number }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="打印状态" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.print_status == 0 || !scope.row.print_status">等待打印</span>
            <span v-else-if="scope.row.print_status == 1" style="color: rgb(4, 190, 2);">打印成功</span>
            <div v-else-if="scope.row.print_status == 2">
              <div style="color: #f00;">打印失败</div>
              <span style="font-size: 12px;color: #777;">{{ scope.row.fail_msg }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-form label-width="80px" style="margin-top: 20px;">
        <el-form-item label="打印机：">
          <el-select v-model="printName" placeholder="请选择打印机">
            <el-option v-for="(item, i) in printsList" :key="i" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="showPrint = false">取消</el-button>
        <el-button type="primary" @click="toPrint()" :loading="loading1">保存</el-button>
      </span>
  </el-dialog>
  </div>
</template>

<script>
import { platOrderList, printOrders, getPrintInfo, exportOrder, printSuccess } from "@/api/plat";
import { storeList } from "@/api/shop"
import { goodsSkusList } from "@/api/goods"
import dayjs from 'dayjs'

export default {
  data() {
    return {
      filter: {
        shop_id: '',
        shipping_status: '',
        is_supplier: '',
        cancel_status: 0,
        after_sales_status: 0,
        goods_sku_num: '',
        external_sku_ids: '',
        pno: '',
        order_sn: '',
        external_sku_id: ''
      },
      loading: false,
      searchLoading: false,
      options: [],
      orderList: [],
      total: 0,
      page: 1, //当前页
      per_page: 10, //每页显示数量
      shopsList: [],
      confirmAt: [],
      print_order_ids: '',
      print_documents: [],
      socket: null,
      lockReconnect: false, //是否真正建立连接
      timeout: 58 * 1000, //58秒一次心跳
      timeoutObj: null, //心跳心跳倒计时
      serverTimeoutObj: null, //心跳倒计时
      timeoutnum: null, //断开 重连倒计时
      defaultPrinter: null,
      taskIDArray: [],
      requestIDGetGlobalConfig: '',
      exportLoading: false,
      webSocket: null,
      chooseList: [],
      showPrint: false,
      printName: '',
      printsList: [],
      loading1: false,
      connectStatus: -1,
      tempList: []
    }
  },
  created() {
    let start = dayjs().format('YYYY-MM-DD') + ' 00:00:00'
    let end = dayjs().format('YYYY-MM-DD') + ' 23:59:59'
    this.confirmAt = [start, end]
    this.getOrderList()
    this.getShopsList()
  },
  methods: {
    getOrderList() {
      this.loading = true
      let params = {
        ...this.filter,
        page: this.page,
        per_page: this.per_page,
        confirm_at_start: this.confirmAt ? this.confirmAt[0] : '',
        confirm_at_end: this.confirmAt ? this.confirmAt[1] : ''
      }
      platOrderList(params).then((res) => {
        this.orderList = res.data.data
        this.total = res.data.meta.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getShopsList() {
      let params = {
        page: 0,
        per_page: 99
      }
      storeList(params).then((res) => {
        this.shopsList = res.data.data
      })
    },
    handleSizeChange(val) {
      this.page = 1
      this.per_page = val
      this.getOrderList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getOrderList()
    },
    handleChoose() {
      this.page = 1
      this.getOrderList()
    },
    handleReChoose() {
      this.filter = {
        shop_id: '',
        shipping_status: '',
        is_supplier: '',
        cancel_status: 0,
        after_sales_status: 0,
        goods_sku_num: '',
        external_sku_ids: '',
        pno: '',
        order_sn: ''
      }
      this.page = 1
      this.getOrderList()
    },
    remoteMethod(query) {
      if (query !== '') {
        this.searchLoading = true;
        setTimeout(() => {
          this.searchLoading = false;
          goodsSkusList(query).then((res) => {
            this.options = res.data.filter(item => {
              return item.title.toLowerCase().indexOf(query.toLowerCase()) > -1;
            });
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    print() {
      const print_loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
      });
      printOrders(this.filter).then((res) => {
          this.print_documents = res.data.documents;
          this.print_order_ids = res.data.order_ids;
          print_loading.close();
          this.doPrint();
      })
    },
    selectable(row, index) {
      if (row.shipping_status == '未发货' && row.cancel_status == '未取消' && row.print_status !== 1) {
        return true
      } else {
        return false
      }
    },
    handleSelectionChange(val) {
      this.chooseList = val
    },
    handleExport() {
      this.exportLoading = true
      let params = {
        ...this.form,
        page: 1,
        per_page: this.per_page,
        confirm_at_start: this.confirmAt[0] ? this.confirmAt[0] : '',
        confirm_at_end: this.confirmAt[1] ? this.confirmAt[1] : '',
        is_export: 1
      }
      // window.open("/api/plat_orders?" + this.objectToQueryString(params))

      exportOrder(params).then((res) => {
        this.downLoadXls(res.data)
        this.$message({ type: 'success', message: '导出成功！' })
        this.exportLoading = false
      }).catch(() => {
        this.exportLoading = false
      })
    },
    downLoadXls(response) {
      const content = response
      const blob = new Blob([content])
      const today = new Date().toLocaleDateString()
      const fileName = `订单列表${today}.xlsx`
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    },
    objectToQueryString(obj) {
      return Object.keys(obj)
        .map(key => encodeURIComponent(key) + '=' + (obj[key] ? encodeURIComponent(obj[key]) : ''))
        .join('&');
    },

    // https://open.jdl.com/#/open-business-document/access-guide/157/54222  京东云打印文档
    initWebSocket() {
      try {
        let State = new Array('正在连接', '已建立连接', '正在关闭连接', '已关闭连接')
        let host = 'ws://localhost:9113'
        const that = this
        that.webSocket = new WebSocket(host)
        that.webSocket.onopen = function() {
          console.log(that.webSocket)
          that.connectStatus = that.webSocket.readyState
          that.getPrintList()
        }
        that.webSocket.onmessage = function(msg) {
          let returnData = msg.data
          let json = eval('(' + returnData + ')')
          let content = json.content;
          if(json.code == '6'){ // 打印机返回消息
            that.printsList = content.split(',')
          } else if(json.success == 'true' && json.code == '2'){ // 打印成功
            console.log('0.0', json)
            that.getOrderList()
            if(json.message == 'print success all'){ // 全部打印成功
              let ids = []
              that.tempList.forEach((item, index) => {
                ids.push(item.id)
                that.$set(that.tempList[index], 'print_status', 1)
              })
              let params = {
                order_ids: ids.join(',')
              }
              printSuccess(params)
            } else if(json.message == 'print success, partly wrong.') { // 部分打印成功
              for (let i = 0; i < json.detailinfo.errors.length; i++) {
                const it = json.detailinfo.errors[i]
                that.$set(that.tempList[it.seq * 1 - 1], 'print_status', 2) // 打印失败
                that.$set(that.tempList[it.seq * 1 - 1], 'fail_msg', it.msg) // 失败信息
              }
              let ids = []
              that.tempList.forEach((item, index) => {
                if(!item.fail_msg) {
                  that.$set(that.tempList[index], 'print_status', 1)
                  ids.push(item.id)
                }
              })
              let params = {
                order_ids: ids.join(',')
              }
              printSuccess(params) // 将打印成功的执行特定接口
            }
          } else if(json.success == 'true' && json.code == '2') { // 打印失败
            for (let i = 0; i < json.detailinfo.detail.length; i++) {
              const it = json.detailinfo.detail[i]
              that.$set(that.tempList[it.seq * 1 - 1], 'print_status', 2)
              that.$set(that.tempList[it.seq * 1 - 1], 'fail_msg', it.msg)
            }
          } else if(json.code == "8"){
						console.log("data:image/png;base64, " + content) // 打印预览
					}
        }
        that.webSocket.onclose = function() {
          that.$message({ type: 'info', message: State[that.webSocket.readyState] })
        }
      } catch (error) {
        that.$message({ type: 'info', message: '连接失败' })
      }
    },
    getPrintList() {
			if(this.printsList.length){
				return
			}
			//打印机列表
			var text = "{\"orderType\":\"GET_Printers\",\"pin\":\"用户名\",\"parameters\":{		\"tempUrl\":\"\",		\"printName\":\"\",		\"printData\":\"\"	}}";
			this.webSocket.send(text)
		},
    openPrint() {
      if(this.chooseList.length) {
        this.initWebSocket()
        this.tempList = JSON.parse(JSON.stringify(this.chooseList))
        this.tempList.forEach((item) => {
          item.fail_msg = ''
        })
        this.showPrint = true
      } else {
        this.$message({ type: 'info', message: '请选择需要打印的订单' })
      }
    },
    toPrint() {
      if(!this.printName) {
        this.$message({ type: 'info', message: '请选择打印机' })
        return
      }
      this.loading1 = true
      let ids = []
      this.chooseList.forEach((item) => {
        ids.push(item.id)
      })
      let params = {
        ids: ids.join(',')
      }
      getPrintInfo(params).then((res) => {
        let printObject = res.data.data
        console.log(printObject)
        let parameters = {
          "orderType": "print", // PRE_View 预览，print 打印
          "version": "2",
          "parameters": {
            "printName": this.printName,
            "contents": []
          }
        }
        for(let key in printObject) {
          console.log(key)
          parameters.parameters.contents.push({
            "tempUrl": printObject[key].templateUrl,
            "printData": printObject[key].encryptedData,
            "customTempUrl": printObject[key].customer_temp_url,
            "customData": printObject[key].customer_temp_data
          })
        }
        this.webSocket.send(JSON.stringify(parameters))
        this.loading1 = false
      }).catch(() => {
        this.loading1 = false
      })
    },
    toPrint1() {
      let printCmd = 'print'
      let temp = 'https://template-content.jd.com/template-oss?tempCode=jdkd76x130'
      let tempUser = ''
      let printDataUser = ''
      let printData = '[encoded data, 4524 characters]'
      let text = "{\"orderType\": \""+ printCmd +"\", \"parameters\": {\"printName\": \""+ this.printName +"\", 		\"tempUrl\": \""+ temp +"\", \"customTempUrl\": \""+ tempUser +"\", \"customData\": [" + printDataUser +"], 	\"printData\": [\""+ printData +"\"] } }";
      this.webSocket.send(text)
    },
    closePrint() {
      this.$refs.multipleTable.clearSelection()
      this.chooseList = []
      this.printName = ''
      this.webSocket.close()
    }
  }
}
</script>

<style lang="scss" scoped>
  
</style>
