<template>
  <div class="app-container app-container-scheduling" :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 v-if="queryShow.orderId" label="订单号">
          <el-input v-model="queryParams.orderId" placeholder="请输入订单号" clearable style="width: 240px;"
            @keyup.enter.native="handleQuery" />
            <span @click="clearQuery('orderId')" class="query_clear"><i class="el-icon-circle-close"></i></span>
        </el-form-item>
        <el-form-item v-if="queryShow.orderStatus" 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" />
              <span @click="clearQuery('orderStatus')" class="query_clear"><i class="el-icon-circle-close"></i></span>
          </el-select>
        </el-form-item>
        <el-form-item v-if="queryShow.seatTypeId" label="座位类型">
          <el-select v-model="queryParams.seatTypeId" placeholder="座位类型" clearable style="width: 100%">
            <el-option v-for="(item, index) in seatTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <span @click="clearQuery('seatTypeId')" class="query_clear"><i class="el-icon-circle-close"></i></span>
        </el-form-item>
        <el-form-item v-if="queryShow.source" label="购票渠道">
          <el-select v-model="queryParams.source" placeholder="购票渠道" clearable style="width: 100%">
            <el-option v-for="dict in dict.type.order_form_type" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
          <span @click="clearQuery('source')" class="query_clear"><i class="el-icon-circle-close"></i></span>
        </el-form-item>
        <el-form-item v-if="queryShow.qrcodeNo" label="取票码">
          <el-input v-model="queryParams.qrcodeNo" placeholder="请输入取票码" clearable style="width: 240px;"
            @keyup.enter.native="handleQuery" />
            <span @click="clearQuery('qrcodeNo')" class="query_clear"><i class="el-icon-circle-close"></i></span>
        </el-form-item>
        <el-form-item v-if="queryShow.payTime" label="支付时间">
          <!-- <el-date-picker style="width: 230px;" v-model="queryParams.payTime" type="date" value-format="yyyy-MM-dd"
            placeholder="支付时间">
          </el-date-picker> -->
          <el-date-picker
            v-model="queryParams.payTime"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
          <span @click="clearQuery('payTime')" class="query_clear"><i class="el-icon-circle-close"></i></span>
        </el-form-item>
        <el-form-item v-if="queryShow.performDate" 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>
          <span @click="clearQuery('performDate')" class="query_clear"><i class="el-icon-circle-close"></i></span>
        </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="场次" v-if="!multiPerformDate && queryShow.performDate">
          <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>
          <span @click="clearQuery('performDate')" class="query_clear"><i class="el-icon-circle-close"></i></span>
        </el-form-item>
        <el-form-item>
          <el-dropdown @command="openQuery">
            <el-button size="mini" type="primary" icon="el-icon-plus"></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="orderId">订单号</el-dropdown-item>
              <el-dropdown-item command="orderStatus">订单状态</el-dropdown-item>
              <el-dropdown-item command="seatTypeId">座位类型</el-dropdown-item>
              <el-dropdown-item command="source">购票渠道</el-dropdown-item>
              <el-dropdown-item command="qrcodeNo">取票码</el-dropdown-item>
              <el-dropdown-item command="payTime">支付时间</el-dropdown-item>
              <el-dropdown-item command="performDate">场次时间/场次</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button style="margin-left: 10px;" 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:viewers:excel']"
          @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>
        <el-button
        type="primary"
        size="mini"
        v-hasPermi="['order:viewers:tuikuai']"
        :disabled="multipleSelection.length==0"
          @click="openRefundSubmitModel(multipleSelection)">批量退款</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%" @selection-change="handleSelectionChange" v-loading="loading" :data="dataList" border>
          <el-table-column
          :selectable="isSelectableFun"
          type="selection"
          :fixed="fixed"
          width="55"></el-table-column>
          <el-table-column label="订单号" :fixed="fixed" align="center" prop="orderId" />
          <el-table-column label="观影人名称" :fixed="fixed" align="center" prop="name" />
          <el-table-column label="身份证号" :fixed="fixed" align="center" prop="idcard" />
          <el-table-column label="票务名称" :fixed="fixed" align="center" prop="goodsName" />
          <el-table-column label="座位类型" :fixed="fixed" align="center" prop="seatTypeName" />
          <el-table-column label="购买渠道" :fixed="fixed" 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="performDate" />
          <el-table-column label="场次" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.performTimeStart + '-' + scope.row.performTimeEnd }}</span>
            </template>
          </el-table-column>
          <el-table-column label="购票人" align="center" prop="memberName" />
          <el-table-column label="取票码" align="center" prop="qrcodeNo" width="100" />
          <el-table-column label="购票人手机号" align="center" prop="memberMobile" />
          <el-table-column label="订单应收总额" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.priceTotal || scope.row.priceTotal == 0  ? '￥' + scope.row.priceTotal : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单实收总额" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.realPriceTotal || scope.row.realPriceTotal == 0 ? '￥' + scope.row.realPriceTotal : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="观影人单价" align="center" prop="realPrice">
            <template slot-scope="scope">
              <span>{{ scope.row.realPrice || scope.row.realPrice == 0 ? '￥' + 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">
            <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="deviceName" />
          <el-table-column label="人员类别" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.personnel_type" :value="scope.row.identity" />
            </template>
          </el-table-column>
          <el-table-column label="打印次数/次" align="center" prop="ticketPrintTotal" />
          <el-table-column label="备注" align="center" prop="remark" />
          <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="['order:viewers:details']">详情</el-button>
              <span v-hasPermi="['order:viewers:print']" style="display: inline-block;">
                <el-button 
                style="margin-left: 10px;"
                v-if="scope.row.status == 3 || scope.row.status == 7" size="mini" type="text"
                @click="handleOpen([scope.row])"
                >打印</el-button>
              </span>
              <span v-hasPermi="['order:viewers:tuikuai']" style="display: inline-block;">
                <el-button
                style="margin-left: 10px;"
                v-if="(scope.row.status == 3 || scope.row.status == 6 || scope.row.status == 7 || scope.row.status == 8) && scope.row.source != 1 && scope.row.source != 6" size="mini" type="text"
                @click="openRefundSubmitModel([scope.row])"
                >退款</el-button>
              </span>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </div>
    </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>
    <!-- 退款   -->
    <el-dialog
    title="退款提示"
    :visible.sync="tkDialogVisible"
    width="80%"
    :before-close="handleCloseTk"
    :modal-append-to-body="false"
    :show-close="!tkDialogVisibleLoading"
    >
      <div style="width: 100%;height: calc( 100vh - 30vh );overflow: hidden;overflow-y: auto;">

        <div style=" width: 100%;box-sizing: border-box;padding-left: 40px;">
          <el-table
          :data="tkSelectList"
          style="width: 100%">
          <el-table-column
            type="index"
            label="序号"
            >
          </el-table-column>
          <el-table-column
            prop="orderId"
            label="订单号"
            >
          </el-table-column>
          <el-table-column
            label="退款人数"
            >
            <template slot-scope="scope">
              <span>{{ scope.row.viewerList.length }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="refundAmount"
            label="退款金额"
            >
          </el-table-column>
          <el-table-column
            label="原订单金额"
            >
            <template slot-scope="scope">
              <span>{{ scope.row.orgRealPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="状态">
            <template slot-scope="scope">
              <span
              :style="{
                color: refundSubmitAction == scope.row.orderId?'#409eff':
                  refundSubmitSuccess.includes(scope.row.orderId)?'#67c23a':
                  refundSubmitError.includes(scope.row.orderId)?'#f56c6c':
                  '#000'
              }"
              >
                {{
                  refundSubmitAction == scope.row.orderId?'退款提交中...':
                  refundSubmitSuccess.includes(scope.row.orderId)?'退款提交成功':
                  refundSubmitError.includes(scope.row.orderId)?'退款提交失败':
                  '等待退款提交...'  }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="errorRemark"
            label="退款失败原因"
            >
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                v-if="!tkDialogVisibleLoading"
                type="danger"
                size="mini"
                @click="deleteSelect(scope.$index, scope.row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
        </div>
        <div style="width: 100%;box-sizing: border-box;">
          <el-form :disabled="tkDialogVisibleLoading" :model="tkRuleForm" :rules="tkRules" ref="tkRuleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="" label-width="0">
              <span style="font-weight: 600;margin-left: 40px;">订单合计{{ tkSelectList.length }}笔，</span>
              <span style="font-weight: 600;">退款人数合计{{ tkRuleForm.refundPeople }}人，</span>
              <span style="font-weight: 600;">退款金额合计￥{{ tkRuleForm.refundAmountAll }}</span>
            </el-form-item>
            <el-form-item label="退款原因" prop="refundReason">
              <el-input
              type="textarea"
              :rows="3"
              v-model="tkRuleForm.refundReason"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
              type="textarea"
              :rows="3"
              v-model="tkRuleForm.remark"></el-input>
            </el-form-item>
            
          </el-form>
        </div>
      </div>


      <span slot="footer" class="dialog-footer">
        <el-button :loading="tkDialogVisibleLoading" @click="handleCloseTk('tkRuleForm')">取 消</el-button>
        <el-button
        :loading="tkDialogVisibleLoading"
        type="primary"
        @click="tkSubmitForm('tkRuleForm')"
        v-if="refundSubmitSuccess.length != tkSelectList.length && tkSelectList.length>0"
        >{{
        tkDialogVisibleLoading ? '退款中...':
        refundSubmitError.length > 0? '继续提交失败订单':
        '确定退款'
         }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

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

      // 是否显示弹出层
      open: false,
      // 查询参数
      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,

      seatTypeList: [],
      multipleSelection: [],
      tkDialogVisible: false,
      tkDialogVisibleLoading: false,
      tkSelectList: [],
      tkRuleForm: {
        "orderId": null,
        "refundReason": null,
        "remark": null,
        "refundAmount": 0,
        "ifDirectRefund": 1,
        "refundPeople": 0,
        "errorRemark": '',
        "viewerList": [
          {
            "viewerId": "1111",
            "salePrice": 0.01
          }
        ]
      },
      tkRules: {
        refundReason: [{ required: true, message: '请输入退款原因', trigger: ['blur', 'change'] }],
        remark: [{ required: false, message: '请输入备注', trigger: ['blur', 'change'] }],
      },
      refundSubmitAction: null,
      refundSubmitSuccess:[], // 成功条数
      refundSubmitError: [], // 失败条数
      refundSubmitErrorList: [], //
      multiPerformDate:false,
      fixed: 'left',

      queryShow: {
        orderId: true,
        orderStatus: true,
        seatTypeId: false,
        source: false,
        qrcodeNo: false,
        payTime: false,
        performDate: true
      },
    };
  },
  created() {
    //this.$set(this.queryParams,'performDate',[moment().format("yyyy-MM-DD"),moment().format("yyyy-MM-DD")])
    this.getSeatTypeListFun()
    //this.$set(this.queryParams,'performDate',moment().format("yyyy-MM-DD"))
    this.$set(this.queryParams,'performDate',[moment().format("yyyy-MM-DD"),moment().format("yyyy-MM-DD")])
    this.pagePerformTimeListFun(this.queryParams.performDate)
    this.getList();
  },
  activated(){
    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)};
      if(params.performDate&&params.performDate.length==2){
        params.performBeginDate = params.performDate[0];
        params.performEndDate = params.performDate[1];
      }
      delete params.performDate;
      pageList(this.addDateRange(params))
        .then(response => {
          this.dataList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
        }).catch(()=>{
          this.dataList = []
          this.total = 0
          this.loading = false;
        })
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.time) {
        this.queryParams.beginTime = this.queryParams.time[0];
        this.queryParams.endTime = this.queryParams.time[1];
      }else {
        this.queryParams.beginTime = null
        this.queryParams.endTime = 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.payTime && this.queryParams.payTime.length > 0) {
        this.queryParams.payBeginTime = this.queryParams.payTime[0];
        this.queryParams.payEndTime = this.queryParams.payTime[1];

      }else {
        this.queryParams.payBeginTime = null
        this.queryParams.payEndTime = null

      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }

      // 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.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.beginTime = this.queryParams.time[0];
            this.queryParams.endTime = this.queryParams.time[1];
          }else {
            this.queryParams.beginTime = null
            this.queryParams.endTime = 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.payTime && this.queryParams.payTime.length > 0) {
            this.queryParams.payBeginTime = this.queryParams.payTime[0];
            this.queryParams.payEndTime = this.queryParams.payTime[1];

          }else {
            this.queryParams.payBeginTime = null
            this.queryParams.payEndTime = null

          }

          if(this.queryParams.performDate){
            this.queryParams.performBeginDate   = this.queryParams.performDate[0];
            this.queryParams.performEndDate = this.queryParams.performDate[1];
          }else {
            this.queryParams.performBeginDate   = null
            this.queryParams.performEndDate = null
          }

          let params = JSON.parse(JSON.stringify(this.queryParams))
          for (let key in params) {
            if(key != 'pageNum' && key != 'pageSize' && key != 'time' && key != 'createTime' && key != 'payTime' && key != 'performDate'){
              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,
              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) {
      // 创建忽略 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
      })

    },
    /** 获取座位类型  */
    async getSeatTypeListFun() {
      try {
        let res = await getSeatTypeList({
          pageNum: 1, pageSize: 999
        })
        this.seatTypeList = res.data.rows
      } catch (error) {

      }
    },
    /**  打开弹窗  */
    openRefundSubmitModel(data, type) {
      // 判断是否需要弹出确认框
      let needsConfirmation = data.some(item => item.source === 20 || item.source === 3);

      // 弹出确认框的逻辑
      const showConfirmationDialog = () => {
        return this.$confirm(`请确认在OTA平台中已完成对应订单的退款操作流程，否则修改后无法恢复，请谨慎修改！`, '警告', {
          confirmButtonText: '确认退款',
          cancelButtonText: '取消',
          type: 'warning'
        });
      };

      // 构建订单列表的逻辑
      const buildOrderList = (data) => {
        let list = [];
        data.forEach(item => {
          let existingOrder = list.find(order => order.orderId === item.orderId);
          if (!existingOrder) {
            list.push({
              orderId: item.orderId,
              refundReason: null,
              remark: null,
              refundAmount: 0,
              refundPeople: 0,
              ifDirectRefund: 1,
              errorRemark: '',
              viewerList: [
                {
                  viewerId: item.id,
                  salePrice: item.realPrice ? item.realPrice : 0
                }
              ]
            });
          } else {
            existingOrder.viewerList.push({
              viewerId: item.id,
              salePrice: item.realPrice ? item.realPrice : 0
            });
          }
        });
        return list;
      };

      // 计算退款总额和人数的逻辑
      const calculateRefunds = (list) => {
        let refundAmountAll = 0;
        let refundPeople = 0;

        list.forEach(item => {
          let refundAmount = 0;
          item.viewerList.forEach(viewer => {
            refundAmount = mathM.format(Number(refundAmount) + Number(viewer.salePrice), 10);
            refundAmountAll = mathM.format(Number(refundAmountAll) + Number(viewer.salePrice), 10);
            if(viewer.orgRealPrice) {
              refundAmountAll = mathM.format(Number(refundAmountAll) + Number(viewer.orgRealPrice), 10);
            }
          });
          item.refundAmount = refundAmount;
          refundPeople += item.viewerList.length;
        });

        return { refundAmountAll, refundPeople };
      };

      // 更新表单数据和列表数据的逻辑
      const updateFormAndList = (refundAmountAll, refundPeople, list) => {
        this.tkRuleForm['refundAmountAll'] = refundAmountAll;
        this.tkRuleForm['refundPeople'] = refundPeople;
        this.tkSelectList = JSON.parse(JSON.stringify(list));
        console.log("Updated list:", this.tkSelectList);
        this.tkDialogVisible = true;
      };

      const executeRefundProcess = () => {
        this.refundSubmitSuccess = [];
        this.refundSubmitError = [];
        let orderList = buildOrderList(data);
        let { refundAmountAll, refundPeople } = calculateRefunds(orderList);
        updateFormAndList(refundAmountAll, refundPeople, orderList);
      };

      if (needsConfirmation) {
        showConfirmationDialog()
          .then(() => {
            // 用户点击了确认退款，执行以下逻辑
            executeRefundProcess();
          })
          .catch(() => {
            // 用户点击了取消，给出取消信息
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
      } else {
        // 不需要确认退款，直接执行退款流程
        executeRefundProcess();
      }
    },
    deleteSelect(index,row){
      let refundAmountAll = 0
      let refundPeople = 0
      let list = JSON.parse(JSON.stringify(this.tkSelectList))
      /** 清除成功 */
      let listCopy = JSON.parse(JSON.stringify(this.refundSubmitSuccess))
      this.refundSubmitSuccess.forEach((item,index1)=>{
        if(item == row.orderId) {
          listCopy.splice(index1,1)
        }
      })
      this.refundSubmitSuccess = listCopy
      /** 清除失败 */
      let listCopy1 = JSON.parse(JSON.stringify(this.refundSubmitError))
      this.refundSubmitError.forEach((item,index1)=>{
        if(item == row.orderId) {
          listCopy1.splice(index1,1)
        }
      })
      this.refundSubmitError = listCopy1
      list.splice(index,1)
      list.forEach((item,index)=>{
        if(item.viewerList && item.viewerList.length > 0){
          let refundAmount = 0
          refundPeople = refundPeople + item.viewerList.length
          item.viewerList.forEach((item1,index1)=>{
            refundAmount = mathM.format(Number(refundAmount) + Number(item1.salePrice),10)
            refundAmountAll = mathM.format(Number(refundAmountAll) + Number(item1.salePrice),10)
          })
          list[index].refundAmount = refundAmount
        }
      })
      this.tkRuleForm['refundAmountAll'] = refundAmountAll
      this.tkRuleForm['refundPeople'] = refundPeople
      this.tkSelectList = JSON.parse(JSON.stringify(list))
    },
    /**  提交退款   */
    tkSubmitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let listCopy = JSON.parse(JSON.stringify(this.tkSelectList))
            this.tkSelectList.forEach((item,index)=>{
              listCopy[index] = {
                ...item,
                refundReason: this.tkRuleForm.refundReason?this.tkRuleForm.refundReason:'',
                remark: this.tkRuleForm.remark?this.tkRuleForm.remark:''
              }
            })
            this.tkSelectList = listCopy
            //this.refundSubmitFun(0)
            if(this.refundSubmitError && this.refundSubmitError.length>0) {
              let list = []
              this.refundSubmitError.forEach((item,index)=>{
                this.tkSelectList.forEach((item1,index1)=>{
                  if(item == item1.orderId){
                    list.push(item1)
                  }
                })
              })
              this.refundSubmitError = []
              this.refundSubmitErrorList = list
              console.log("this.refundSubmitErrorList===",list)
              this.moreRefundSubmitFun(0)
            }else {
              this.refundSubmitFun(0)
            }

          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    /** 批量退票 */
    async refundSubmitFun(index) {
      try {
        this.tkDialogVisibleLoading = true
        this.refundSubmitAction = this.tkSelectList[index].orderId
        let res = await refundSubmitApi({
          ...this.tkSelectList[index]
        })
        this.refundSubmitAction = null
        if(res.code == 200) {
          this.$set(this.tkSelectList[index],'errorRemark','')
          this.refundSubmitSuccess.push(this.tkSelectList[index].orderId)
        }else {
          this.refundSubmitError.push(this.tkSelectList[index].orderId)
          this.$message.error(`订单号:${this.tkSelectList[index].orderId}，退款提交失败`);
          this.$set(this.tkSelectList[index],'errorRemark',res.msg)
        }
        if((index+1) < this.tkSelectList.length) {
          this.refundSubmitAction = this.tkSelectList[index+1].orderId
          setTimeout(() => {
            this.refundSubmitFun(index+1)
          }, 3000);
        }else {
          this.tkDialogVisibleLoading = false
          if(this.refundSubmitError.length == 0) {
            this.$message({
              message: '全部退款提交成功!!!',
              type: 'success'
            });
            // this.handleCloseTk()
          }
        }
      } catch (error) {
        console.error(index+"===error====",error)
        this.refundSubmitAction = null
        this.refundSubmitError.push(this.tkSelectList[index].orderId)
        this.$message.error(`订单号:${this.tkSelectList[index].orderId}，退款提交失败`);
        this.$set(this.tkSelectList[index],'errorRemark',error?error.message||error.title||error.msg||error:'系统问题')
        if((index+1) < this.tkSelectList.length) {
          this.refundSubmitAction = this.tkSelectList[index+1].orderId
          setTimeout(() => {
            this.refundSubmitFun(index+1)
          }, 3000);
        }else {
          this.tkDialogVisibleLoading = false
        }
      }
    },
    /** 再次 批量退票 */
    async moreRefundSubmitFun(index) {
      try {
        this.tkDialogVisibleLoading = true
        this.refundSubmitAction = this.refundSubmitErrorList[index].orderId
        let res = await refundSubmitApi({
          ...this.refundSubmitErrorList[index]
        })
        this.refundSubmitAction = null
        if(res.code == 200) {
          this.tkSelectList.forEach((item1,index1)=>{
            if(this.refundSubmitErrorList[index].orderId == item1.orderId){
              this.$set(this.tkSelectList[index1],'errorRemark','')
            }
          })
          this.refundSubmitSuccess.push(this.refundSubmitErrorList[index].orderId)
        }else {
          this.refundSubmitError.push(this.refundSubmitErrorList[index].orderId)
          this.$message.error(`订单号:${this.refundSubmitErrorList[index].orderId}，退款提交失败`);
          this.tkSelectList.forEach((item1,index1)=>{
            if(this.refundSubmitErrorList[index].orderId == item1.orderId){
              this.$set(this.tkSelectList[index1],'errorRemark',res.msg)
            }
          })
        }
        if((index+1) < this.refundSubmitErrorList.length) {
          this.refundSubmitAction = this.refundSubmitErrorList[index+1].orderId
          setTimeout(() => {
            this.moreRefundSubmitFun(index+1)
          }, 3000);
        }else {
          this.tkDialogVisibleLoading = false
          if(this.refundSubmitErrorList.length == 0) {
            this.$message({
              message: '全部退款成功!!!',
              type: 'success'
            });
            // this.handleCloseTk()
          }
        }
      } catch (error) {
        console.error(index+"===error====",error)
        console.error("dsfsdfds===",(index+1) < this.refundSubmitErrorList.length
        )
        this.refundSubmitAction = null
        this.refundSubmitError.push(this.refundSubmitErrorList[index].orderId)
        this.$message.error(`订单号:${this.refundSubmitErrorList[index].orderId}，退款提交失败`);
        this.tkSelectList.forEach((item1,index1)=>{
          if(this.refundSubmitErrorList[index].orderId == item1.orderId){
            this.$set(this.tkSelectList[index1],'errorRemark', error?error.message||error.title||error.msg||error:'系统问题')
          }
        })
        if((index+1) < this.refundSubmitErrorList.length) {
          this.refundSubmitAction = this.refundSubmitErrorList[index+1].orderId
          setTimeout(() => {
            this.moreRefundSubmitFun(index+1)
          }, 3000);
        }else {
          this.tkDialogVisibleLoading = false
        }
      }
    },
    /**  退款状态  */
    refundSubmitStatus(row){

    },
    /**  选择 */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /**  是否可用 */
    isSelectableFun(row, index){
      return row.status == 3 || row.status == 6 || row.status == 7 || row.status == 8
    },
    handleCloseTk(formName){
      console.log('dsfsdfsdf')
      this.tkDialogVisible = false
      if(this.$refs.tkRuleForm) {
        this.$refs.tkRuleForm.resetFields()
      }
      this.getList();
    },
    clearQuery(key) {
      this.$set(this.queryShow,key,false)
      this.$set(this.queryParams,key,'')
      if(key == 'performDate') {
        this.$set(this.queryParams,'performTimeId','')
      }
    },
    openQuery(key) {
      this.$set(this.queryShow,key,true)
    }
  },
  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 );
  }
}

.app-container-scheduling ::v-deep .el-select__tags {
    flex-wrap: inherit !important;
    overflow-x: auto !important;
}
.app-container-scheduling ::v-deep .el-form-item__content {
  position: relative;
}
.app-container-scheduling ::v-deep .el-form-item__content .query_clear{
  position: absolute;
  top: -15px;
  right: -10px;
  display: none;
  cursor: pointer;
  z-index: 99;
}
.app-container-scheduling ::v-deep .el-form-item__content:hover .query_clear {
  display: block;
}
</style>