<template>
    <div class="app-container app-container-me">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="订单号" label-width="80px">
          <el-input
            v-model="queryParams.orderId"
            placeholder="请输入订单号"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="取票码" label-width="80px">
          <el-input
            v-model="queryParams.qrcodeNo"
            placeholder="请输入取票码"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input
            v-model="queryParams.mobile"
            placeholder="请输入手机号"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="身份证号:" label-width="120px" prop="idcard">
          <el-input
            v-model="queryParams.idcard"
            placeholder="请输入身份证号"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          >
            <el-button slot="append" :loading="idcardLoading" size="mini" type="primary" @click="readCert">{{ idcardLoading ? '识别中':'识别' }}</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="座位号" label-width="80px">
          <el-input
            v-model="queryParams.seatName"
            placeholder="请输入座位号"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="queryParams.orderStatus"
            placeholder="订单状态"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.order_status_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
                :disabled="multipleSelection.length == 0"
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="openMultipleSelectionVisible"
                v-hasPermi="['windowTicketSales:ticketingCollection:print']"
              >批量打印门票</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table 
      ref="tables" 
      v-loading="loading" 
      :data="dataList" 
      @selection-change="handleSelectionChange"
      border>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" align="center" type="index" width="50"></el-table-column>
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="身份证号" align="center" prop="idcard" />
        <el-table-column label="手机号" align="center" prop="mobile" />
        <el-table-column label="取票码" align="center" prop="qrcodeNo" />
        <el-table-column label="订单号" align="center" prop="orderId" />
        <el-table-column label="剧目名称" align="center" prop="performName" />
        <el-table-column label="票务名称" align="center" prop="goodsName" />
        <el-table-column label="座位信息" align="center" prop="seatName" />
        <el-table-column label="座位类型" align="center" prop="seatTypeName" />
        <el-table-column label="节目播出日期" align="center" prop="performDate" />
        <el-table-column label="下单时间" align="center" prop="createTime" />
        <el-table-column label="购票渠道" align="center" prop="source">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.order_form_type" :value="scope.row.source"/>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_status_type" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="打印次数" align="center" prop="printNum" />
        <el-table-column label="操作" align="center" fixed="right" width="80" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleOpen([scope.row])"
              v-hasPermi="['windowTicketSales:ticketingCollection:print']"
            >打印门票</el-button>
          </template>
        </el-table-column>
        <template slot="empty">
            <div>
                <span>未查询到相关订单，请重新输入！</span>
            </div>
        </template>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <!--  批量打印顺序  -->
      <el-dialog
        title="批量打印顺序"
        :visible.sync="multipleSelectionVisible"
        width="90%"
        :before-close="()=>{ multipleSelectionVisible = false}">
        <el-table 
          ref="tabless" 
          v-loading="loading" 
          :data="multipleSelectionTabel" 
          border>
            <el-table-column label="打印顺序" align="center" type="index" width="50"></el-table-column>
            <el-table-column label="姓名" align="center" prop="name" />
            <el-table-column label="身份证号" align="center" prop="idcard" />
            <el-table-column label="手机号" align="center" prop="mobile" />
            <el-table-column label="取票码" align="center" prop="qrcodeNo" />
            <el-table-column label="订单号" align="center" prop="orderId" />
            <el-table-column label="剧目名称" align="center" prop="performName" />
            <el-table-column label="票务名称" align="center" prop="goodsName" />
            <el-table-column label="座位信息" align="center" prop="seatName" />
            <el-table-column label="座位类型" align="center" prop="seatTypeName" />
            <el-table-column label="节目播出日期" align="center" prop="performDate" />
            <el-table-column label="下单时间" align="center" prop="createTime" />
            <el-table-column label="购票渠道" align="center" prop="source">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.order_form_type" :value="scope.row.source"/>
              </template>
            </el-table-column>
            <el-table-column label="订单状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.order_status_type" :value="scope.row.status"/>
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="multipleSelectionVisible = false">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="handleOpen(multipleSelection)">{{ dialogVisibleLoading?'打印中...':'打印' }}</el-button>
        </span>
      </el-dialog>

      <!--  选择打印机  -->
      <el-dialog
        title="选择打印机"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="打印机" prop="region">
            <el-select v-model="ruleForm.region" placeholder="选择打印机">
              <el-option :label="item.deviceName" :key="item.id" :value="item.id" v-for="(item,index) in printList"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="dialogVisibleLoading" @click="print(viewerList)">{{ dialogVisibleLoading?'打印中...':'打印' }}</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  
  import { pageList,printApi } from '@/api/windowTicketSales/ticketingCollection'
  import { pageList as getPrintListApi } from "@/api/device/pda";
  const https = require('https');
  const axios = require('axios');
  export default {
    name: "TicketingCollectionfsd",
    dicts: ['order_form_type','order_status_type'],
    data() {
      return {
        // 遮罩层
        loading: false,
        // 选中数组
        multipleSelection: [],
        multipleSelectionTabel: [],
        multipleSelectionVisible: false,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 用户表格数据
        dataList: null,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          // type: undefined
          //orderStatus: "3"
        },
        visibleStatus: false,
        visibleStatusLoading: false,
        ruleForm: {},
        rules: {
          remark: [
            { required: true, message: '请输入备注', trigger: ['blur','change'] },
            { min: 0, max: 50, message: '长度在 0 到 50 个字符', trigger: ['blur','change'] }
          ]
        },
        
        viewerList: [],
        printList: [],
        dialogVisible: false,
        ruleForm: {},
        rules: {
          region: [
            { required: true, message: '请选择打印机', trigger: ['change','blur' ]}
          ],
        },
        dialogVisibleLoading: false,

        idcardLoading: false,
      };
    },
    created() {
      console.log("params====",this.$route)
      if(this.$route.query&&this.$route.query.orderId) {
        this.$set(this.queryParams,'orderId',this.$route.query.orderId)
        this.getList()
      }
      //this.getList();
      //this.getPrintListApi()
    },
    methods: {
      /** 查询列表 */
      getList() {
        this.loading = true;
        pageList(this.queryParams)
        .then(response => {
            this.dataList = response.data.rows;
            this.total = response.data.total;
            this.loading = false;
            console.log("this.multipleSelection=====",this.multipleSelection)
          }
        ).catch(()=>{
          this.dataList = []
          this.total = 0
          this.loading = false
        })
      },
      
      // 取消按钮
      cancel() {
        this.open = false;
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.$set(this.queryParams, 'orderId', '');
        this.$set(this.queryParams, 'qrcodeNo', '');
        this.$set(this.queryParams, 'idcard', '');
        this.$set(this.queryParams, 'mobile', '');
        this.$set(this.queryParams, 'orderStatus', '');
        this.$set(this.queryParams, 'seatName', '');
        this.handleQuery();
      },
      setRemark(data) {
        this.visibleStatus = true
        this.resetForm.id = data.id
      },
      submitForm(formName) {
          this.$refs[formName].validate(async (valid) => {
            if (valid) {
              try { 
                this.visibleStatusLoading = true
                let res = await setRemark({
                  id: this.resetForm.id,
                  "remark": this.ruleForm.remark
                })
                this.visibleStatus = false
                this.visibleStatusLoading = false
                this.resetForm('ruleForm')
                this.queryParams.pageNum = 1;
                this.getList()
              } catch (error) {
                this.visibleStatusLoading = false
              }
              
            } else {
              this.visibleStatusLoading = false
              return false;
            }
          });
        },
        resetForm(formName) {
          this.$refs[formName].resetFields();
        },
        handleSelectionChange(val,row) {
          console.log("val====",val,row)
          this.multipleSelection = val;
        },

        openMultipleSelectionVisible(){
          console.log("sdfasgadfgadfgadfgadfg")
          this.multipleSelectionTabel = JSON.parse(JSON.stringify(this.multipleSelection))
          this.multipleSelectionVisible = true
        },
        handleOpen(list=[]){
          if(!list||list.length==0) return
          let idList = []
          list.forEach((item,index)=>{
            idList.push({
              viewerId: item.id,
              index: index
            })
          }) 
          this.viewerList = idList
          this.getPrintListApi()
          this.$set(this.ruleForm, 'region', '');
          this.$nextTick(()=>{
            this.$refs.ruleForm.clearValidate('region')
          })
          this.dialogVisible = true
        },
        handleClose(){
          
          this.dialogVisible = false
        },
        /** 查询打印机列表 */
        getPrintListApi() {
          getPrintListApi({deviceType:5,pageNum: 1,
          pageSize: 999,})
          .then(response => {
              this.printList = response.data.rows;
          }).catch((error)=>{
            console.log("error===",error)
          }
          );
        },
        /**  选择打印机  */
        selectPrint(){

        },
        // 打印 
        async print(list = []){
          this.$refs.ruleForm.validate(async (valid) => {
            if (valid) {
              this.dialogVisibleLoading = true
              try {
                let res = await printApi({
                  viewerList2:list,
                  source: 2,
                  deviceId: this.ruleForm.region
                })
                if(res.code == 200) {
                  let url = res.data.linkIp
                  let printInfo = res.data.printInfo
                  this.connectPrint(url,printInfo)
                }else {
                  throw new Error(res)
                }
              } catch (error) {
                this.dialogVisible = false
                this.dialogVisibleLoading = false
                console.error("error=====",error)
              }
            } else {
              console.log('error submit!!');
              return false;
            }
          });
          
        },
        /**  连接打印机  */
        connectPrint(url,data){
          // let xhr = new XMLHttpRequest();
          // xhr.withCredentials = true
          
          // xhr.onreadystatechange = ()=>{
          // if(xhr.readyState == 4){ // 监听请求完成
          //     if((xhr.status >=200 && xhr.status <300) || xhr.status == 304){
          //       console.log(xhr.responseText)
          //       this.dialogVisible = false
          //       this.dialogVisibleLoading = false
          //     }else{
          //       console.log('请求失败')
          //       this.dialogVisible = false
          //       this.dialogVisibleLoading = false
          //     }
          //   }
          // }
         
          // xhr.open("post", url, true); // 异步请求
          // xhr.setRequestHeader('Content-Type', 'application/json')
          // xhr.send(JSON.stringify(data));

          

          // 创建忽略 SSL 的 axios 实例
          const ignoreSSL = axios.create({
            httpsAgent: new https.Agent({  
              rejectUnauthorized: false
            }),
            withCredentials: true, // 跨域请求时发送Cookie
            timeout: 60000, // 请求超时
            headers: {
              "Content-Type": "application/json; charset=UTF-8;"
            }
          });
          ignoreSSL.post(url, 
            { ...data }
            ).then(()=>{
            this.dialogVisible = false
            this.dialogVisibleLoading = false
          }).catch(()=>{
            this.dialogVisible = false
            this.dialogVisibleLoading = false
          })
          // 在 axios 请求时，选择性忽略 SSL
          // const agent = new https.Agent({  
          //   rejectUnauthorized: false
          // });
          // axios.post(
          //   url, 
          //   { httpsAgent: agent,...data }
          //   ).then(()=>{
          //   this.dialogVisible = false
          //   this.dialogVisibleLoading = false
          // })
          // .catch(()=>{
          //   this.dialogVisible = false
          //   this.dialogVisibleLoading = false
          // })
        },
        /**  读取身份证 */
        readCert(){
          this.idcardLoading = true
          var result = "";
          try {
              let xmlHttp = new XMLHttpRequest();
              let Protocol = window.location.protocol.split(':')[0];
              //获取当前协议，并且分割字符串，得到http或者https
              if (Protocol === 'https'){
                //创建请求 第一个参数是代表以post方式发送；第二个是请求端口和地址；第三个表示是否异步
                xmlHttp.open("POST", "http://127.0.0.1:18889/api/readCert?ReadSN=" + 0, false);	  //readCert读卡，生成正反面仿复印件	
              }else {
                //创建请求 第一个参数是代表以post方式发送；第二个是请求端口和地址；第三个表示是否异步
                xmlHttp.open("POST", "http://127.0.0.1:18889/api/readCert?ReadSN=" + 0, false);	  //readCert读卡，生成正反面仿复印件	
              }
              //发送请求
              xmlHttp.send();
              if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                  result = xmlHttp.responseText;
                  xmlHttp.readyState = 1;
              }
          } catch (e) {
            console.error("e====",e)
          }
          let obj = JSON.parse(result)
          if(obj.resultContent && obj.resultContent.certNumber){
            this.$set(this.queryParams,"idcard",obj.resultContent.certNumber)
          }else {
            this.$message.error('读取失败!!!');
          }
          
          this.idcardLoading = false
          //return result;
            console.log(result,obj)
          }
        }
        
  };
  </script>