<template>
  <div class="app-container" :style="{'--q-height':qHeight}">
    <div class="app-container-query" ref="queryFormBox">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="订单号">
          <el-input
            v-model="queryParams.orderId"
            placeholder="请输入订单号"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="购票人手机号" label-width="100px">
          <el-input
            v-model="queryParams.memberMobile"
            placeholder="请输入购票人手机号"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="剧目名称">
          <el-input
            v-model="queryParams.performName"
            placeholder="请输入剧目名称"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="票务名称">
          <el-input
            v-model="queryParams.goodsName"
            placeholder="请输入票务名称"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="是否成功开票" label-width="100">
          <el-select
            v-model="queryParams.ifSuccessInvoice"
            placeholder="请选择"
            clearable
            style="width: 100%"
          >
            <el-option label="否" value="0" />
            <el-option label="是" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="queryParams.status"
            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 label="支付方式">
          <el-select
            v-model="queryParams.payWay"
            placeholder="支付方式"
            clearable
            style="width: 100%"
          >
              <el-option
                v-for="dict in dict.type.pay_way_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
          </el-select>
        </el-form-item>
        <el-form-item label="购票渠道">
          <el-select
            v-model="queryParams.source"
            placeholder="购票渠道"
            clearable
            style="width: 100%"
          >
            <!-- <el-option
              v-for="dict in sourceMapList"
              :key="dict.value"
              :label="dict.name"
              :value="dict.value"
            /> -->
            <el-option
              v-for="dict in dict.type.order_form_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="支付时间">
          <el-date-picker
            style="width: 230px;"
            v-model="queryParams.time"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            style="width: 230px;"
            v-model="queryParams.createTime"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="场次时间">
          <el-date-picker
            style="width: 230px;"
            v-model="queryParams.performDate"
            @change="pagePerformTimeListFun"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="场次时间" label-width="70px">
          <el-date-picker
            style="width: 250px;"
            v-model="queryParams.performDate"
            @change="pagePerformTimeListFun"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="场次" v-if="!multiPerformDate">
          <el-select
            v-model="queryParams.performTimeId"
            placeholder="场次"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in pagePerformTimeList"
              :key="dict.id"
              :label="dict.timeSnapshot+'('+dict.performTimeStart+'-'+dict.performTimeEnd+')'"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开票时间">
          <el-date-picker
            style="width: 230px;"
            v-model="queryParams.invoiceTime"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </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>
    </div>
    
    <div class="app-container-table-box">
      <el-row :gutter="10" class="mb8">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-download"
          v-hasPermi="['order:orderMr:downloadExcel']"
          @click="handleExport"
          v-loading.fullscreen.lock="handleExportLoading"
          element-loading-text="正在拼命生成数据中..."
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.5)"
        >导出excel</el-button>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <div class="app-container-table-info">
        <el-table ref="tables" height="100%" v-loading="loading" :data="dataList" border>
          <el-table-column label="序号" align="center" :fixed="fixed" type="index" width="60"></el-table-column>
          <el-table-column label="订单号" align="center" :fixed="fixed" prop="id" />
          <el-table-column label="购票人手机号" align="center" :fixed="fixed" prop="memberMobile" />
          <el-table-column label="剧目名称" align="center" :fixed="fixed" prop="performName" />
          <el-table-column label="票务名称" align="center" :fixed="fixed" prop="goodsName" />
          <el-table-column label="座位类型" align="center" :fixed="fixed" prop="seatTypeName" />
          <el-table-column label="购票渠道" align="center" :fixed="fixed" 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="performDate" />
          <el-table-column label="场次" width="120" align="center" prop="timeSnapshot">
            <template slot-scope="scope">
              <span>{{ scope.row.timeSnapshot }} <br /> ({{ scope.row.performTimeStart + '-' + scope.row.performTimeEnd }})</span>
            </template>
          </el-table-column>
          <el-table-column label="下单时间" align="center" prop="createTime" />
          <el-table-column label="购票数量" align="center" prop="quantity" />
          <el-table-column label="应收金额" align="center" prop="orderPrice">
            <template slot-scope="scope">
              <span>￥{{ scope.row.orderPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column label="实收金额" align="center" prop="realPrice">
            <template slot-scope="scope">
              <span>￥{{ scope.row.realPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column label="支付方式" align="center" prop="payWay">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.pay_way_type" :value="scope.row.payWay"/>
            </template>
          </el-table-column>
          
          <el-table-column label="支付时间" align="center" prop="payTime" width="160" >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.payTime) }}</span>
            </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="usedTotal">
            <template slot-scope="scope">
              <span>{{ scope.row.usedTotal }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已核销金额" align="center" prop="usedPriceTotal">
            <template slot-scope="scope">
              <span>{{ scope.row.usedPriceTotal }}</span>
            </template>
          </el-table-column>
          <el-table-column label="退票数量" align="center" prop="refundTotal">
            <template slot-scope="scope">
              <span>{{ scope.row.refundTotal }}</span>
            </template>
          </el-table-column>
          <el-table-column label="退票金额" align="center" prop="refundPriceTotal">
            <template slot-scope="scope">
              <span>{{ scope.row.refundPriceTotal }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否成功开票" align="center">
            <template slot-scope="scope">
              <el-tag type="danger" v-if="scope.row.ifSuccessInvoice  == '0'">否</el-tag>
              <el-tag type="success" v-else-if="scope.row.ifSuccessInvoice  == '1'">是</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="开票时间" align="center" prop="invoiceTime">
            <template slot-scope="scope">
              <span>{{ scope.row.invoiceTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark">
            <template slot-scope="scope">
              <span>{{ scope.row.remark }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="openDetails(scope.row)"
                v-hasPermi="['orderMr:orderMr:details']"
              >详情</el-button>
              <el-button
                v-if="scope.row.status === 0"
                size="mini"
                type="text"
                @click="handleCancelOrder(scope.row)"
                v-hasPermi="['orderMr:orderMr:cancel']"
              >关闭订单</el-button>
              <el-button
                  v-if="scope.row.status == 3 || scope.row.status == 7"
                  size="mini"
                  type="text"
                  @click="handleOpen([scope.row])"
                  v-hasPermi="['orderMr:orderMr:print']"
                >打印小票</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    

    <!-- 详情 -->
    <details-dia ref="detailsDia" @getList="getList"></details-dia>

    <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,downOrderListXls, printApi } from '@/api/order/orderMr';
import { orderInfoCancel } from '@/api/windowTicketSales/ticketingSales';
import detailsDia from "./dialog/details";
import { pagePerformTimeList } from "@/api/schedulingMr/schedulingMr"
import { exportExcel } from '@/utils/exportexcel'
import { pageList as getPrintListApi } from "@/api/device/pda";
const https = require('https');
const axios = require('axios');
import moment from "moment"
export default {
  name: "agreement",
  dicts: ['order_form_type','order_status_type','pay_way_type'],
  components: { detailsDia },
  data() {
    return {
      qHeight: '0px',
      resizeObserver: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      dataList: null,
      // 弹出层标题
      title: "",

      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      visibleStatus: false,
      newObj: {},
      visibleType: '',

      pagePerformTimeList: [], // 场次列表

      handleExportLoading: false,

      viewerList: [],
        printList: [],
        dialogVisible: false,
        ruleForm: {},
        rules: {
          region: [
            { required: true, message: '请选择打印机', trigger: ['change','blur' ]}
          ],
        },
        dialogVisibleLoading: false,
        multiPerformDate:false,
        fixed: 'left',
    };
  },
  created() {
    this.$set(this.queryParams,'performDate',[moment().format("yyyy-MM-DD"),moment().format("yyyy-MM-DD")])
    this.pagePerformTimeListFun(this.queryParams.performDate)
    this.getList();
  },
  mounted() {
    this.resizeObserver = new ResizeObserver(entries => {
      for (let entry of entries) {
        const { width, height } = entry.contentRect;
        this.qHeight = height + 'px'
      }
      if(document.body.clientWidth<765) {
        this.fixed = false
      }else {
        this.fixed = 'left'
      }
    });
    this.resizeObserver.observe(this.$refs.queryFormBox);
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      let params = {...this.addDateRange(this.queryParams, this.dateRange)};
      delete params.performDate;
      delete params.invoiceTime
      pageList(params)
      .then(response => {
          this.dataList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(this.queryParams.time){
        this.queryParams.payBeginTime = this.queryParams.time[0];
        this.queryParams.payEndTime = this.queryParams.time[1];
      }else {
        this.queryParams.payBeginTime = null
        this.queryParams.payEndTime = null
      }
      if(this.queryParams.createTime&&this.queryParams.createTime.length>0){
        this.queryParams.createBeginTime = this.queryParams.createTime[0];
        this.queryParams.createEndTime = this.queryParams.createTime[1];
      }else {
        this.queryParams.createBeginTime = null
        this.queryParams.createEndTime = null
      }
      if(this.queryParams.performDate){
        this.queryParams.performDateStart   = this.queryParams.performDate[0];
        this.queryParams.performDateEnd = this.queryParams.performDate[1];
      }else {
        this.queryParams.performDateStart   = null
        this.queryParams.performDateEnd = null
      }
      if(this.queryParams.invoiceTime&&this.queryParams.invoiceTime.length==2){
       this.queryParams.invoiceBeginTime =this.queryParams.invoiceTime[0];
       this.queryParams.invoiceEndTime =this.queryParams.invoiceTime[1];
      }else {
       this.queryParams.invoiceBeginTime = null
       this.queryParams.invoiceEndTime = null
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.$set(this.queryParams, 'orderId', '');
      this.$set(this.queryParams, 'status', '');
      this.$set(this.queryParams, 'memberMobile', '');
      this.$set(this.queryParams, 'source', '');
      this.$set(this.queryParams, 'performName', '');
      this.$set(this.queryParams, 'payBeginTime', '');
      this.$set(this.queryParams, 'payEndTime', '');
      this.$set(this.queryParams, 'time', '');
      this.$set(this.queryParams, 'createTime', '');
      this.$set(this.queryParams, 'createBeginTime', '');
      this.$set(this.queryParams, 'createEndTime', '');
      this.$set(this.queryParams, 'goodsName', '');
      this.$set(this.queryParams, 'performDate', '');
      this.$set(this.queryParams, 'timeSnapshot', '');
      this.$set(this.queryParams, 'performTimeId', '');
      this.$set(this.queryParams, 'payWay', '');
      this.$set(this.queryParams, 'invoiceTime', '');
      this.queryParams.pageNum = 1;
      this.handleQuery();
    },
    /** 详情按钮操作 */
    openDetails(row, type) {
      this.$refs["detailsDia"].openDialog("详情", row, type);
    },
    async pagePerformTimeListFun(value) {
      // console.log('value',value);
      try {
        this.pagePerformTimeList = []
        this.$set(this.queryParams,'performTimeId',null)
        if(!value){
          return
        }
        if(value.length==2&&value[0]==value[1]){
          this.multiPerformDate = false
        }else{
          this.multiPerformDate = true
          return
        }
        let { data,code } = await pagePerformTimeList({
          performDate: value[0],
          pageNum: 1,
          pageSize: 999
        })
        this.pagePerformTimeList = [].concat(data.rows)
      } catch (error) {
        
      }
    },
    /**
     * 导出报表
     * @date 2022-10-24
     * @returns {any}
     */
     handleExport() {
      this.$confirm('您确定要导出当前查询的数据吗？', '提示', {
        confirmButtonText: '确定 ',
        cancelButtonText: '取消 ',
        type: 'warning'
      })
        .then(() => {
          this.handleExportLoading = true;
          // const { pageNum, pageSize} = this.params;
          let postMap = {}
          
          if(this.queryParams.time){
            this.queryParams.payBeginTime = this.queryParams.time[0];
            this.queryParams.payEndTime = this.queryParams.time[1];
          }else {
            this.queryParams.payBeginTime = null
            this.queryParams.payEndTime = null
          }
          if(this.queryParams.createTime&&this.queryParams.createTime.length>0){
            this.queryParams.createBeginTime = this.queryParams.createTime[0];
            this.queryParams.createEndTime = this.queryParams.createTime[1];
          }else {
            this.queryParams.createBeginTime = null
            this.queryParams.createEndTime = null
          }
          if(this.queryParams.performDate){
            this.queryParams.performDateStart   = this.queryParams.performDate[0];
            this.queryParams.performDateEnd = this.queryParams.performDate[1];
          }else {
            this.queryParams.performDateStart   = null
            this.queryParams.performDateEnd = null
          }
          if(this.queryParams.invoiceTime&&this.queryParams.invoiceTime.length==2){
            this.queryParams.invoiceBeginTime =this.queryParams.invoiceTime[0];
            this.queryParams.invoiceEndTime =this.queryParams.invoiceTime[1];
          }else {
            this.queryParams.invoiceBeginTime = null
            this.queryParams.invoiceEndTime = null
          }
          let params = JSON.parse(JSON.stringify(this.queryParams))
          for (let key in params) {
            if(key != 'pageNum' && key != 'pageSize' && key != 'time' && key != 'createTime' && key != 'performDate' && key != 'invoiceTime'){
              postMap[key] = params[key]
            }
          }
          downOrderListXls(postMap)
            .then((res) => {
              exportExcel(res, '订单管理', '.xlsx');
              this.handleExportLoading = false;
            })
            .catch((error) => {
              console.log("error===",error)
              this.handleExportLoading = false;
            });
        })
        .catch(() => {
          this.$message.info('您已取消导出！');
        });
    },
    

    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;
            }
          );
        },
        /**  选择打印机  */
        selectPrint(){

        },
        // 打印 
        async print(list = []){
          this.$refs.ruleForm.validate(async (valid) => {
            if (valid) {
              this.dialogVisibleLoading = true
              try {
                let res = await printApi({
                  //viewerList:list,
                  orderId: list[0],
                  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.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.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
          })

        },
        /** 关闭订单 */
        handleCancelOrder(row) {
          this.$confirm("是否关闭" + row.id + "的订单?", '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            orderInfoCancel({ orderId: row.id}).then((res) => {
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                });
                this.getList();
              }
            });
          }).catch(() => {});
        },
  },
  beforeDestroy() {
    this.resizeObserver.unobserve(this.$refs.queryFormBox);
    this.resizeObserver.disconnect();
  },
};
</script>
<style scoped lang="scss"> 
.app-container {
  height: calc( 100vh - 110px );
  box-sizing: border-box;
}
.app-container-query {
  
}
.app-container-table-box {
  height: calc( 100% - var(--q-height) );
  .app-container-table-info {
    height: calc( 100% - 100px );
  }
}
</style>