<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="取票码" label-width="100px">
          <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-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="handleOpen(multipleSelection)"
                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="qrcodeNo" />
        <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" 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>

      <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: "distributionapplication",
    dicts: ['order_form_type','order_status_type'],
    data() {
      return {
        // 遮罩层
        loading: false,
        // 选中数组
        multipleSelection: [],
        // 显示搜索条件
        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,
      };
    },
    created() {
      //this.getList();
      //this.getPrintListApi()
    },
    methods: {
      /** 查询列表 */
      getList() {
        this.loading = true;
        pageList(this.queryParams,)
        .then(response => {
            this.dataList = response.data.list;
            //this.total = response.data.total;
            this.loading = false;
          }
        );
      },
      
      // 取消按钮
      cancel() {
        this.open = false;
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.$set(this.queryParams, 'qrcodeNo', '');
        this.$set(this.queryParams, 'idcard', '');
        this.$set(this.queryParams, 'mobile', '');
        this.$set(this.queryParams, 'orderStatus', '');
        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) {
          console.log("val====",val)
          this.multipleSelection = val;
        },
        handleOpen(list=[]){
          if(!list||list.length==0) return
          let idList = []
          list.forEach((item,index)=>{
            idList.push(item.id)
          }) 
          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({
                  viewerList: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
          // })
        }
    }
  };
  </script>
  