<template>
  <div class="form-wrap">
    <el-form
      class="searchBox"
      ref="form"
      :model="form"
      :inline="true"
      label-width="100px"
    >
      <div class="block-title">
        查询条件
      </div>
      <el-form-item
        label="订单号"
        prop="orderNo"
      >
        <el-input v-model="form.orderNo"></el-input>
      </el-form-item>
      <el-form-item
        label="合作方订单号"
        prop="partnerOrderNo"
      >
        <el-input v-model="form.partnerOrderNo"></el-input>
      </el-form-item>
      <el-form-item
        label="票号"
        prop="ticketNo"
      >
        <el-input v-model="form.ticketNo"></el-input>
      </el-form-item>
      <el-form-item
        label="下单时间"
        prop="createTime">
        <el-date-picker
          v-model="form.createTime"
          style="width:240px"
          type="daterange"
          format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="游玩时间"
        prop="playDate">
        <el-date-picker
          v-model="form.playDate"
          style="width:240px"
          type="daterange"
          format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="支付方式"
        prop="payChannelList">
        <el-select
          v-model="form.payChannelList"
          multiple
          filterable>
          <el-option
            v-for="item in payChannelOptions"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="销售来源"
        prop="otaSourceNameList">
        <el-select
          v-model="form.otaSourceNameList"
          multiple
          filterable>
          <el-option
            v-for="item in otaSourceList"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="游客姓名"
        prop="visitorName"
      >
        <el-input v-model="form.visitorName"></el-input>
      </el-form-item>
      <el-form-item
        label="游客电话"
        prop="visitorPhone">
        <el-input v-model="form.visitorPhone"></el-input>
      </el-form-item>
      <el-form-item
        label="游客证件号"
        prop="visitorIdentify">
        <ReaderInput v-model="form.visitorIdentify"></ReaderInput>
      </el-form-item>
      <el-form-item
        label="订单状态"
        prop="orderStatus"
      >
        <el-select
          v-model="form.orderStatus"
          clearable
          placeholder="请选择"
        >
          <el-option
            label="全部"
            value=""></el-option>
          <el-option
            v-for="item in orderStatusDic"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="门票状态"
        prop="ticketStatus"
      >
        <el-select
          v-model="form.ticketStatus"
          clearable
          placeholder="请选择"
        >
          <el-option
            label="全部"
            value=""></el-option>
          <el-option
            v-for="item in ticketStatusDic"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="订单类型"
        prop="orderCategory"
      >
        <el-select
          v-model="form.orderCategory"
          placeholder="请选择"
          filterable>
          <el-option
            v-for="item in orderCategories"
            :key="item.id"
            :value="item.id"
            :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="票种列表"
        prop="ticketTypeIdList"
      >
        <el-select
          v-model="form.ticketTypeIdList"
          placeholder="请选择"
          multiple
          filterable>
          <el-option
            v-for="item in ticketTypeList"
            :key="item.id"
            :value="item.id"
            :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="售票员"
        prop="adminIdList"
      >
        <el-select
          v-model="form.adminIdList"
          multiple
          placeholder="请选择"
          filterable>
          <el-option
            v-for="item in accountList"
            :key="item.id"
            :value="item.id"
            :label="item.loginName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="售卖自助机"
        prop="saleTermIdList"
      >
        <el-select
          v-model="form.saleTermIdList"
          multiple
          placeholder="请选择"
          filterable>
          <el-option
            v-for="item in termList"
            :key="item.id"
            :value="item.id"
            :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <div class="btn-wrap">
        <el-button
          @click="reset"
        >
          重置
        </el-button>
        <el-button
          :disabled="loading"
          type="primary"
          @click="getOrderList(true)"
        >
          搜索
        </el-button>
      </div>
    </el-form>

    <div class="tableBox">
      <div class="block-title">
        统计信息
      </div>
      <el-table
        stripe
        border
        v-loading="loading"
        :data="tableData">
        <el-table-column
          min-width="200"
          prop="orderNo"
          label="订单号"
          fixed="left"
        >
        </el-table-column>
        <el-table-column
          width="120"
          prop="partnerOrderNo"
          label="线上订单号"
        >
        </el-table-column>
        <el-table-column
          width="120"
          prop="orderCategory"
          label="订单类型"
        >
          <template slot-scope="scope">
            {{ scope.row.orderCategory | filterOrderCategory }}
          </template>
        </el-table-column>
        <el-table-column
          width="120"
          prop="otaSourceName"
          label="订单来源渠道"
        >
        </el-table-column>
        <el-table-column
          label="支付渠道"
          width="120"
          prop="payChannel">
        </el-table-column>
        <el-table-column
          label="支付状态"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-tag
              :type="getPayStatus(scope.row.payStatus, 'type')"
              size="normal"
            >
              {{ getPayStatus(scope.row.payStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="支付时间"
          width="140"
          prop="payTime">
        </el-table-column>
        <!-- <el-table-column
          label="票种"
          min-width="120">
          <template slot-scope="scope">
            <Ellipsis
              type="tooltip"
              :content="scope.row.ticketsName"
              :length="15"></Ellipsis>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="saleAdminName"
          width="120"
          label="售票员"
        >
        </el-table-column>
        <el-table-column
          width="140"
          label="售票时间"
        >
          <template slot-scope="scope">
            {{ scope.row.createTime | formatTime }}
          </template>
        </el-table-column>
        <el-table-column
          width="120"
          prop="buyerName"
          label="购买方名称"
        ></el-table-column>
        <el-table-column
          width="110"
          prop="buyerPhone"
          label="购买方手机">
        </el-table-column>
        <el-table-column
          width="140"
          prop="buyerIdentify"
          label="购买方证件号">
        </el-table-column>
        <el-table-column
          width="80"
          prop="ticketNum"
          label="所含票数"
        >
        </el-table-column>
        <!-- <el-table-column
          width="80"
          label="人数"
        >
          <template slot-scope="scope">
            {{ reduceCheckNum(scope.row.ticketList) }}
          </template>
        </el-table-column> -->
        <!-- <el-table-column
          width="80"
          label="游客信息"
          prop="guestName">
        </el-table-column> -->
        <!-- <el-table-column
          width="80"
          label="使用状态"
          prop="ticketStatus">
        </el-table-column> -->
        <el-table-column
          width="80"
          label="总价(￥)"
        >
          <template slot-scope="scope">
            {{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column
          width="90"
          label="状态"
          fixed="right"
        >
          <template slot-scope="scope">
            <OrderStatusTag :value="scope.row.status"></OrderStatusTag>
          </template>
        </el-table-column>
        <el-table-column
          width="80"
          label="备注"
        >
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          width="220"
        >
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click="showOrderDetail(scope.row)">
              详情
            </el-link>
            <el-link
              type="primary"
              v-if="scope.row.status !== 'CANCELED'"
              @click="editOrder(scope.row)">
              修改
            </el-link>
            <el-link
              type="primary"
              v-if="scope.row.status !== 'CANCELED'"
              @click="printOrder(scope.row)">
              网络取票
            </el-link>
            <br>
            <el-link
              type="primary"
              v-if="scope.row.status !== 'CANCELED'"
              @click="checkOrder(scope.row)">
              核销
            </el-link>
            <el-link
              type="primary"
              v-if="scope.row.status !== 'CANCELED'"
              @click="refundOrder(scope.row)">
              退单
            </el-link>
            <el-link
              type="primary"
              v-if="scope.row.status !== 'CANCELED'"
              @click="secondPrint(scope.row)">
              补打
            </el-link>
            <!--
            <el-link
              type="primary"
              v-if="scope.row.tickets.some(v=>v.is_invoice_picked===0&&v.status==='USED')&&scope.row.otaName!=='自营售票'"
              @click="showPickInvoice(scope.row)">
              开票
            </el-link>
            -->
            <!-- <el-link
              type="primary"
              v-if="scenicName==='昭苏' && scope.row.ticketList.some(v=>v.is_invoice_picked===0&&v.status==='USED')&&scope.row.otaName!=='自营售票'"
              @click="showPickInvoice(scope.row)">
              开票
            </el-link>
            <el-link
              type="primary"
              v-if="scenicName!=='昭苏' && scope.row.ticketList.some(v=>v.is_invoice_picked===0&&v.status==='USED')"
              @click="showPickInvoice(scope.row)">
              开票
            </el-link> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page.sync="form.pageNum"
        @current-change="getOrderList()"
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>

    <OrderDetail ref="orderDetail"></OrderDetail>

    <el-dialog
      title="开票"
      :visible.sync="visible"
      width="80%"
      @close="visible=false">
      <el-table
        ref="multipleTable"
        :data="currentOrder.ticketList"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          :selectable="selectable"
          width="55">
        </el-table-column>
        <el-table-column
          prop="ticketNo"
          label="票号"
        >
        </el-table-column>

        <el-table-column
          prop="ticketTypeName"
          label="票种"
        >
        </el-table-column>

        <el-table-column
          width="80"
          label="票价(￥)"
        >
          <template slot-scope="scope">
            {{ scope.row.price/scope.row.checkNum }}
          </template>
        </el-table-column>
        <el-table-column
          prop="guestIdentifyType"
          label="证件类型"
        >
          <template slot-scope="scope">
            {{ papersType[scope.row.guestIdentifyType] }}
          </template>
        </el-table-column>

        <el-table-column
          width="100"
          prop="checkNum"
          label="检票人数"
        >
        </el-table-column>

        <el-table-column
          width="100"
          prop="payDateBegin"
          label="游玩时间"
        >
          <template slot-scope="scope">
            {{ scope.row.playDateBegin || scope.row.playDateEnd ? `${scope.row.playDateBegin || ''} - ${scope.row.playDateEnd || ''}` : "无限制" }}
          </template>
        </el-table-column>
        <el-table-column
          width="80"
          label="取票状态"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.isPrint?'success':'info'">
              {{ scope.row.isPrint?'已取票':'未取票' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          width="80"
          label="状态"
        >
          <template slot-scope="scope">
            <OrderStatusTag :value="scope.row.status"></OrderStatusTag>
          </template>
        </el-table-column>
        <el-table-column
          width="80"
          label="是否已开票"
        >
          <template slot-scope="scope">
            {{ scope.row.is_invoice_picked===1?'已开':'未开' }}
          </template>
        </el-table-column>
        <el-table-column
          width="80"
          prop="price"
          label="小计"
        >
        </el-table-column>
      </el-table>
      {{ formEl.invoiceType }}
      <el-form
        class="searchBox"
        ref="formEl"
        :model="formEl"
        :inline="true"
        label-width="200px"
        style="background: transparent"
      >
        <!-- 九龙湖只能固定一种开票方式 -->
        <el-form-item
          v-if="['九龙湖','demo'].includes(scenicName)"
          label="开票方式"
          prop="invoiceType"
        >
          <!-- <el-radio
            v-if="false"
            v-model="formEl.invoiceType"
            :label="1">
            扫码开票
          </el-radio> -->
          <el-radio
            v-model="formEl.invoiceType"
            :label="0">
            普通开票
          </el-radio>
        </el-form-item>

        <el-form-item
          v-else
          verify
          label="开票方式"
          prop="invoiceType"
        >
          <el-radio
            v-model="formEl.invoiceType"
            :label="1">
            扫码开票
          </el-radio>
          <el-radio
            v-model="formEl.invoiceType"
            :label="0">
            普通开票
          </el-radio>
        </el-form-item>
        <el-form-item
          v-if="!formEl.invoiceType"
          verify
          label="购买方"
          prop="invoiceBuyer"
        >
          <el-input
            v-model="formEl.invoiceBuyer"
            style="width:100%"></el-input>
        </el-form-item>
        <el-form-item
          v-if="!formEl.invoiceType"
          label="纳税⼈识别号"
          prop="invoiceBuyerTaxNum"
          :rules="rules.invoiceBuyerTaxNum"
        >
          <el-input
            v-model="formEl.invoiceBuyerTaxNum"
            style="width:100%"></el-input>
        </el-form-item>
        <el-form-item
          v-if="!formEl.invoiceType"
          label="纳税⼈邮箱"
          prop="invoiceBuyerEmail"
          :rules="[
            { required: false, message: '请输入邮箱', trigger: 'blur' },
            { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
          ]"
        >
          <el-input
            v-model="formEl.invoiceBuyerEmail"
            style="width:100%"></el-input>
        </el-form-item>
        <el-form-item
          v-if="!formEl.invoiceType"
          label="纳税⼈手机号"
          prop="invoiceBuyerPhone"
          :rules="[
            { required: false, message: '请输入手机号', trigger: 'blur' },
            { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
          ]"
        >
          <el-input
            v-model="formEl.invoiceBuyerPhone"
            style="width:100%"></el-input>
        </el-form-item>
        <el-form-item
          v-if="!formEl.invoiceType"
          label="购买方地址"
          prop="invoiceBuyerAddress"
        >
          <el-input
            v-model="formEl.invoiceBuyerAddress"
            style="width:100%"></el-input>
        </el-form-item>
        <el-form-item
          v-if="!formEl.invoiceType"
          label="购买方银行开户行及账号"
          prop="invoiceBuyerBankAccount"
        >
          <el-input
            v-model="formEl.invoiceBuyerBankAccount"
            style="width:100%"></el-input>
        </el-form-item>
        <el-form-item
          v-if="!formEl.invoiceType"
          label="备注"
          prop="remark"
        >
          <el-input
            v-model="formEl.remark"
            style="width:100%"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitPickInvoice">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="核销"
      :visible.sync="checkOrderDialogVisible"
      width="80%"
      @close="checkOrderDialogVisible=false">
      <div style="margin: 20px">
        <el-checkbox label="强制核销" v-model="checkOrderInfo.force"></el-checkbox>
      </div>
      <el-table
        border
        :data="currentOrder.ticketList"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          :selectable="selectable"
          width="55">
        </el-table-column>
        <el-table-column prop="ticketNo" label="票号"> </el-table-column>

        <el-table-column prop="ticketTypeName" label="票种"> </el-table-column>
        <el-table-column prop="guestName" label="游客姓名">
        </el-table-column>
        <el-table-column prop="guestPhone" label="游客手机号">
        </el-table-column>
        <el-table-column prop="guestIdentifyType" label="证件类型">
          <template slot-scope="scope">
            {{ papersType[scope.row.guestIdentifyType] }}
          </template>
        </el-table-column>
        <el-table-column prop="guestIdentify" label="证件号码">
          <template slot-scope="scope">
            {{ scope.row.guestIdentify }}
          </template>
        </el-table-column>

        <el-table-column width="100" prop="checkNum" label="检票人数">
        </el-table-column>

        <el-table-column width="100" prop="payDateBegin" label="游玩时间">
          <template slot-scope="scope">
            {{ scope.row.playDateBegin || scope.row.playDateEnd ? `${scope.row.playDateBegin || ''} - ${scope.row.playDateEnd || ''}` : "无限制" }}
          </template>
        </el-table-column>
        <el-table-column width="80" label="取票状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isPrint ? 'success' : 'info'">
              {{ scope.row.isPrint ? "已取票" : "未取票" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column width="80" label="状态">
          <template slot-scope="scope">
            <OrderStatusTag :value="scope.row.status"></OrderStatusTag>
          </template>
        </el-table-column>
        <el-table-column width="80" prop="price" label="小计">
        </el-table-column>
        <el-table-column width="80" label="检票景点">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.ticketListScenic"
              @click="showDetail(scope.row)"
            >
              明细
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer">
        <el-button @click="checkOrderDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitCheckOrder">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="退单"
      :visible.sync="refundOrderDialogVisible"
      width="80%"
      @close="refundOrderDialogVisible=false">
      <div style="margin: 20px">
        <el-checkbox label="强制取消" v-model="refundOrderInfo.force"></el-checkbox>
      </div>
      <!-- <div class="">
        <div class="tag">退票金额</div>
        <el-input-number
          v-model="refundOrderInfo.cancelPrice"
          :min="0"
          :precision="0.01"></el-input-number>
      </div> -->
      <el-table
        border
        :data="currentOrder.ticketList"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          :selectable="selectable"
          width="55">
        </el-table-column>
        <el-table-column prop="ticketNo" label="票号"> </el-table-column>
        <el-table-column prop="ticketTypeName" label="票种"> </el-table-column>
        <el-table-column prop="guestName" label="游客姓名">
        </el-table-column>
        <el-table-column prop="guestPhone" label="游客手机号">
        </el-table-column>
        <el-table-column prop="guestIdentifyType" label="证件类型">
          <template slot-scope="scope">
            {{ papersType[scope.row.guestIdentifyType] }}
          </template>
        </el-table-column>
        <el-table-column prop="guestIdentify" label="证件号码">
          <template slot-scope="scope">
            {{ scope.row.guestIdentify }}
          </template>
        </el-table-column>

        <el-table-column width="100" prop="checkNum" label="检票人数">
        </el-table-column>

        <el-table-column width="100" prop="payDateBegin" label="游玩时间">
          <template slot-scope="scope">
            {{ scope.row.playDateBegin || scope.row.playDateEnd ? `${scope.row.playDateBegin || ''} - ${scope.row.playDateEnd || ''}` : "无限制" }}
          </template>
        </el-table-column>
        <el-table-column width="80" label="取票状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isPrint ? 'success' : 'info'">
              {{ scope.row.isPrint ? "已取票" : "未取票" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column width="80" label="状态">
          <template slot-scope="scope">
            <OrderStatusTag :value="scope.row.status"></OrderStatusTag>
          </template>
        </el-table-column>
        <el-table-column width="80" prop="price" label="小计">
        </el-table-column>
        <el-table-column width="80" label="检票景点">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.ticketListScenic"
              @click="showDetail(scope.row)"
            >
              明细
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer">
        <el-button @click="refundOrderDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitRefundOrder">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="补打"
      :visible.sync="secondPrintDialogVisible"
      width="80%"
      @close="secondPrintDialogVisible=false">
      <!-- <div class="">
        <div class="tag">退票金额</div>
        <el-input-number
          v-model="refundOrderInfo.cancelPrice"
          :min="0"
          :precision="0.01"></el-input-number>
      </div> -->
      <el-table
        border
        :data="currentOrder.ticketList"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          :selectable="selectable"
          width="55">
        </el-table-column>
        <el-table-column prop="ticketNo" label="票号"> </el-table-column>
        <el-table-column prop="ticketTypeName" label="票种"> </el-table-column>
        <el-table-column prop="guestName" label="游客姓名">
        </el-table-column>
        <el-table-column prop="guestPhone" label="游客手机号">
        </el-table-column>
        <el-table-column prop="guestIdentifyType" label="证件类型">
          <template slot-scope="scope">
            {{ papersType[scope.row.guestIdentifyType] }}
          </template>
        </el-table-column>
        <el-table-column prop="guestIdentify" label="证件号码">
          <template slot-scope="scope">
            {{ scope.row.guestIdentify }}
          </template>
        </el-table-column>

        <el-table-column width="100" prop="checkNum" label="检票人数">
        </el-table-column>

        <el-table-column width="100" prop="payDateBegin" label="游玩时间">
          <template slot-scope="scope">
            {{ scope.row.playDateBegin || scope.row.playDateEnd ? `${scope.row.playDateBegin || ''} - ${scope.row.playDateEnd || ''}` : "无限制" }}
          </template>
        </el-table-column>
        <el-table-column width="80" label="取票状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isPrint ? 'success' : 'info'">
              {{ scope.row.isPrint ? "已取票" : "未取票" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column width="80" label="状态">
          <template slot-scope="scope">
            <OrderStatusTag :value="scope.row.status"></OrderStatusTag>
          </template>
        </el-table-column>
        <el-table-column width="80" prop="price" label="小计">
        </el-table-column>
        <el-table-column width="80" label="检票景点">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.ticketListScenic"
              @click="showDetail(scope.row)"
            >
              明细
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer">
        <el-button @click="secondPrintDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitSecondPrint">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="网络取票"
      :visible.sync="printOrderDialogVisible"
      width="80%"
      @close="printOrderDialogVisible=false">
      <el-table
        border
        :data="currentOrder.ticketList"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          :selectable="selectable"
          width="55">
        </el-table-column>
        <el-table-column prop="ticketNo" label="票号"> </el-table-column>
        <el-table-column prop="ticketTypeName" label="票种"> </el-table-column>
        <el-table-column prop="guestName" label="游客姓名">
        </el-table-column>
        <el-table-column prop="guestPhone" label="游客手机号">
        </el-table-column>
        <el-table-column prop="guestIdentifyType" label="证件类型">
          <template slot-scope="scope">
            {{ papersType[scope.row.guestIdentifyType] }}
          </template>
        </el-table-column>
        <el-table-column prop="guestIdentify" label="证件号码">
          <template slot-scope="scope">
            {{ scope.row.guestIdentify }}
          </template>
        </el-table-column>

        <el-table-column width="100" prop="checkNum" label="检票人数">
        </el-table-column>

        <el-table-column width="100" prop="payDateBegin" label="游玩时间">
          <template slot-scope="scope">
            {{ scope.row.playDateBegin || scope.row.playDateEnd ? `${scope.row.playDateBegin || ''} - ${scope.row.playDateEnd || ''}` : "无限制" }}
          </template>
        </el-table-column>
        <el-table-column width="80" label="取票状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isPrint ? 'success' : 'info'">
              {{ scope.row.isPrint ? "已取票" : "未取票" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column width="80" label="状态">
          <template slot-scope="scope">
            <OrderStatusTag :value="scope.row.status"></OrderStatusTag>
          </template>
        </el-table-column>
        <el-table-column width="80" prop="price" label="小计">
        </el-table-column>
        <el-table-column width="80" label="检票景点">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.ticketListScenic"
              @click="showDetail(scope.row)"
            >
              明细
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer">
        <el-button @click="printOrderDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitPrintOrder">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改"
      :visible.sync="editOrderDialogVisible"
      mini-height="500"
      @close="cancelEdit">
      <el-form
        class="searchBox"
        ref="formEl"
        :model="editOrderInfo"
        :inline="true"
        label-width="100px">
        <el-form-item
          label="修改类型"
          prop="updateType"
        >
          <el-select
            v-model="editOrderInfo.updateType"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in updateTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="editOrderInfo.updateType === 'updateOrderPayChannel'"
          label="原支付方式"
          prop="payChannel"
        >
          {{ currentOrder.payChannel }}
        </el-form-item>
        <el-form-item
          v-if="editOrderInfo.updateType === 'updateOrderPayChannel'"
          label="支付方式"
          prop="payChannel"
        >
          <el-radio-group
            border
            fill="#379143"
            class="tags-btn"
            v-model="editOrderInfo.payChannel">
            <el-radio
              border
              v-for="val in payChannelOptions"
              :key="val"
              :value="val"
              :label="val"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="editOrderInfo.updateType === 'updatePlayDate'"
          label="选择门票"
          prop="playDateBegin">
          <el-select
            v-model="editOrderInfo.ticketIds"
            multiple>
            <el-option
              v-for="item in currentOrder.ticketList"
              :key="item.id"
              :label="item.ticketNo"
              :value="item.id">
              <span style="">{{ item.ticketNo }}</span>-
              <span style="color: #8492a6; font-size: 13px">{{ item.ticketTypeName }}</span>
              (<span style="color: #849822; font-size: 13px">
                {{ item.playDateBegin || item.playDateEnd ? `${item.playDateBegin || ''} - ${item.playDateEnd || ''}` : "无限制" }}
              </span>)
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="editOrderInfo.updateType === 'updatePlayDate'"
          label="起始时间"
          prop="playDateBegin">
          <el-date-picker
            v-model="editOrderInfo.playDateBegin"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item
          v-if="editOrderInfo.updateType === 'updatePlayDate'"
          label="截止时间"
          prop="playDateEnd">
          <el-date-picker
            default-time="23:59:59"
            v-model="editOrderInfo.playDateEnd"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <div class="tableBox" v-if="editOrderInfo.updateType === 'updateScenicTimes'">
          <div class="tips">
            <i class="el-icon-info"></i>
            -1代表不限制 如果当前景点为群组景点 该次数为群组景点的检票次数总和
          </div>
          <el-table
            border
            stripe
            height="500"
            :data="editOrderInfo.ticketList">
            <el-table-column type="expand">
              <template slot-scope="props">
                <div class="title">检票景点明细</div>
                <el-table :data="props.row.ticketCheckScenicList" :max-height="200">
                  <el-table-column
                    prop="scenicName"
                    label="景点"
                  ></el-table-column>
                  <el-table-column
                    prop="checkLimitTimes"
                    label="可检票次数"
                  >
                    <template slot-scope="scope">
                      {{ scope.row.checkLimitTimes === -1 ? "无限制" : scope.row.checkLimitTimes }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="checkedTimes"
                    label="已检票次数"
                  ></el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column width="160" prop="ticketNo" label="票号"> </el-table-column>
            <el-table-column width="100" prop="ticketTypeName" label="票种"> </el-table-column>
            <el-table-column min-width="180" label="检票景点">
              <template slot-scope="scope">
                {{ scope.row.ticketCheckScenicList.map(item => item.scenicName).join(',') }}
              </template>
            </el-table-column>
            <el-table-column
              label="景点的限制检票次数"
              min-width="90">
              <template slot-scope="scope">
                <el-input-number
                  controls-position="right"
                  :min="-1"
                  :precision="0"
                  v-model="scope.row.checkLimitTimes"
                ></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <span slot="footer">
        <el-button @click="cancelEdit">取消</el-button>
        <el-button
          type="primary"
          @click="submitEditOrder">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable no-unused-vars */
import { apiOrderList, pickInvoice, getInvoice, cancelOrder, reprintTicket, checkTickets, updateOrder, getSaleChannelList, getSingleOrder, printTickets } from '@/api/order'
import { orderStatusDic, ticketStatusDic, channelList, papersType, orderCategories } from '@/assets/staticData'
import { getPayStatus } from '@/utils/index'
// import Ellipsis from '@/components/Ellipsis'
import moment from 'moment'
import { payPOS } from '@/api/pay'
import { getSelf } from '@/api/systemSetting/account'
import { getSystemConfigList } from '@/api/systemConfig'
import { get } from 'core-js/core/dict'

const Store = require('electron-store')
const localStore = new Store()

export default {
  name: 'salesQuery',
  computed: {
    scenicName () {
      return this.$localStore.get('scenicName') || this.$store.state.user.scenicName
    },
    salesList () {
      return this.$store.state.user.salesList
    },
    accountList () {
      return this.$store.state.app.accountList
    },
    termList () {
      return this.$store.state.app.termList
    },
    saleChannel () {
      return this.$store.state.app.saleChannel
    },
    payChannelOptions () {
      return this.$store.getters.payChannelOptions
    },
    ticketTypeList () {
      const { ticketTypeList } = this.$store.state.app
      const { orderCategory } = this.form
      return orderCategory ? ticketTypeList.filter(item => item.category === orderCategory) : ticketTypeList
    },
    scenicList () {
      return this.$store.state.app.scenicList
    }
  },
  components: {
    // ReaderInput,
    // Ellipsis
  },
  data () {
    return {
      projecticketTypeName: process.env.VUE_APP_PROJECT,
      channelList,
      otaSourceList: [],
      orderStatusDic,
      ticketStatusDic,
      papersType,
      isDev: process.env.NODE_ENV === 'development',
      orderCategories,
      form: {
        partnerOrderNo: '', // OTA订单号
        otaOrderNo: '', // 渠道订单号
        orderNo: '', // 订单号
        createTime: [new Date(moment().subtract(7, 'day').format('YYYY-MM-DD')), new Date(moment().format('YYYY-MM-DD'))], // 下单时间
        createTimeBegin: '',
        createTimeEnd: '',
        orderCategory: '',
        playDate: ['', ''], // 游玩时间
        playDateBegin: '',
        playDateEnd: '',
        payChannelList: [], // 支付方式
        otaSourceNameList: [], // 销售来源
        adminIdList: [], // 售票员
        saleTermIdList: [], // 售卖自助机
        orderStatus: '', // 订单状态
        ticketStatus: '', // 门票状态
        visitorName: '', // 游客姓名
        visitorPhone: '', // 游客手机
        visitorIdentify: '', // 游客身份证
        ticketTypeIdList: [], // 票种列表
        pageNum: 1,
        pageSize: 10
      },
      tableData: [],
      total: 0,
      loading: false,
      invoiceType: 0,
      formEl: {
        invoiceType: 1,
        invoiceBuyer: '',
        invoiceBuyerTaxNum: '',
        invoiceBuyerEmail: '',
        invoiceBuyerPhone: '',
        invoiceBuyerAddress: '',
        invoiceBuyerBankAccount: '',
        remark: ''
      },
      rules: {
        invoiceBuyerTaxNum: [
          { required: false, message: '请输入纳税人识别号', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9]{15,20}$/, message: '纳税人识别号格式不正确', trigger: 'blur' }
        ]
      },
      currentOrder: {},
      multipleSelection: [],
      order_tag_list: [],
      visible: false,
      refundOrderDialogVisible: false,
      refundOrderInfo: {
        force: false,
        orderId: '',
        ticketCancelRequestList: []
      },
      checkOrderDialogVisible: false,
      checkOrderInfo: {
        force: false,
        orderId: '',
        ticketIdList: []
      },
      printOrderDialogVisible: false,
      secondPrintDialogVisible: false,
      secondPrintInfo: {
        orderId: '',
        ticketIdList: []
      },
      updateTypes: [
        { value: 'updateOrderPayChannel', label: '支付方式' },
        { value: 'updatePlayDate', label: '游玩日期' },
        { value: 'updateScenicTimes', label: '检票次数' }
      ],
      editOrderDialogVisible: false,
      editOrderInfo: {
        orderId: '',
        updateType: '',
        payChannel: '',
        playDateBegin: '',
        playDateEnd: '',
        ticketIds: [],
        ticketList: [],
        ticketCheckScenicUpdateRequestList: []
      }
    }
  },
  filters: {
    filterChannel (n) {
      switch (n) {
        case 1:
          return '线下'
        case 2:
          return '线上'
        case 3:
          return '自助机'
      }
    },
    filterOrderCategory (n) {
      return orderCategories.find(item => item.id === n).name
    }
  },
  async created () {
    const searchParams = JSON.parse(sessionStorage.getItem('统计表-售票记录-查询条件'))
    if (searchParams) {
    // 如果存在查询条件，则设置到组件的数据中
      this.form = searchParams // 记住上次搜索条件
    }
    this.getSaleChannelList()
    this.getOrderList()
  },
  methods: {
    getPayStatus,
    reset () {
      this.$refs.form.resetFields()
      this.getOrderList(true)
    },
    // 取票状态
    checkPrintStatus (ticketList) {
      let tempArr = ticketList.filter(i => i.isPrint)
      if (tempArr.length) {
        if (tempArr.length === ticketList.length) {
          return { type: 'success', text: '已取票' }
        } else {
          return { type: 'warning', text: '部分取票' }
        }
      } else {
        return { type: 'info', text: '未取票' }
      }
    },
    toggleSelection (rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    selectable (row, index) {
      return true
    },
    showPickInvoice (order) {
      this.visible = true
      this.currentOrder = order
      if (['九龙湖', 'demo'].includes(this.scenicName)) {
        this.formEl.invoiceType = 0 // 九龙湖只能普通开票
      }
    },
    submitPickInvoice () {
      if (!this.multipleSelection.length) return this.$message.error('请选择门票')
      this.$refs.formEl.validate(valid => {
        if (!valid) return
        if (this.formEl.invoiceType) {
          this.formEl.invoiceBuyer = ''
          this.formEl.invoiceBuyerTaxNum = ''
          this.formEl.invoiceBuyerEmail = ''
          this.formEl.invoiceBuyerPhone = ''
          this.formEl.invoiceBuyerAddress = ''
          this.formEl.invoiceBuyerBankAccount = ''
          this.formEl.remark = ''
        }
        pickInvoice([this.currentOrder.id], this.multipleSelection.map(v => v.id), this.formEl.invoiceType, this.formEl.invoiceBuyer, this.formEl.invoiceBuyerTaxNum, this.formEl.invoiceBuyerEmail, this.formEl.invoiceBuyerPhone, this.formEl.invoiceBuyerAddress, this.formEl.invoiceBuyerBankAccount, this.formEl.remark).then(res => {
          this.$message.success('操作成功')
          this.getOrderList()
          this.visible = false
          this.currentOrder = {}
          this.formEl = {
            invoiceType: 1,
            invoiceBuyer: '',
            invoiceBuyerTaxNum: '',
            invoiceBuyerEmail: '',
            invoiceBuyerPhone: '',
            invoiceBuyerAddress: '',
            invoiceBuyerBankAccount: '',
            remark: ''
          }
          this.$confirm('发票已生成，是否跳转到发票下载页？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$router.push('/queryReport/invoiceRecord')
          })
        })
      })
    },
    confirmPOS (record) {
      this.$confirm('请确认该订单已付款,将手动更新订单状态为已支付', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        getSelf().then(response => {
          const params = {
            managerId: response.id,
            id: record.id,
            payChannel: record.payChannel,
            posId: localStore.get('termId'),
            tradeInfo: '',
            type: 'TICKET'
          }
          payPOS(params).then(res => {
            this.$message.success('操作成功')
            this.getOrderList()
            this.$confirm('门票状态已修改,是否跳转补打门票页面？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$router.push({ name: 'printTicket' })
            }).catch(() => {
            })
          })
        })
      }).catch(() => {
      })
    },
    getSaleChannelList () {
      getSaleChannelList().then(res => {
        this.otaSourceList = res.data
      })
    },
    getOrderList (goFirst) {
      this.loading = true
      goFirst && (this.form.pageNum = 1)

      const [s, e] = this.form.createTime || []
      this.form.createTimeBegin = s ? moment(s).startOf('day').format('YYYY-MM-DD HH:mm:ss') : ''
      this.form.createTimeEnd = e ? moment(e).endOf('day').format('YYYY-MM-DD HH:mm:ss') : ''

      const [s1, e1] = this.form.playDate || []
      this.form.playDateBegin = s1 ? moment(s1).format('YYYY-MM-DD') : ''
      this.form.playDateEnd = e1 ? moment(e1).format('YYYY-MM-DD') : ''

      apiOrderList(this.form).then(res => {
        this.total = res.data.total

        // const list = []
        res.data.records.forEach(item => {
          let ticketsName = []
          item.ticketsName = ticketsName.join('，')
        })

        this.tableData = res.data.records
        this.tableData.forEach(v => {
          if (v.price === 0 && v.payChannel === '现金') {
            v.payChannel = '免票'
          }
        })

        console.log(this.tableData, 'tableData')
      }).finally(() => {
        this.loading = false
      })
      sessionStorage.setItem('统计表-售票记录-查询条件', JSON.stringify(this.form)) // 下次记住
    },
    reduceCheckNum (list) {
      if (!list) return 0
      return list.reduce((prev, item) => {
        return prev + item.checkNum
      }, 0)
    },
    async getOrderDetail (order) {
      const res = await getSingleOrder(order.id)
      this.currentOrder = res?.data || order
    },
    async refundOrder (order) {
      await this.getOrderDetail(order)
      this.refundOrderDialogVisible = true
      this.refundOrderInfo.orderId = order.id
    },
    async secondPrint (order) {
      await this.getOrderDetail(order)
      this.secondPrintDialogVisible = true
      this.secondPrintInfo.orderId = order.id
    },
    submitRefundOrder () {
      if (!this.multipleSelection?.length) {
        return this.$message.error('请选择门票')
      }

      this.refundOrderInfo.ticketCancelRequestList = this.multipleSelection.map(v => {
        return {
          ticketId: v.id,
          cancelPrice: v.price
        }
      })

      this.$confirm('确定要退单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelOrder(this.refundOrderInfo).then(res => {
          if (res.code === '999999') {
            this.$message.warning(res.msg || '操作失败')
            return
          }
          this.$message.success('操作成功')
          this.refundOrderDialogVisible = false
          this.getOrderList()
        })
      })
    },
    submitSecondPrint () {
      if (!this.multipleSelection?.length) {
        return this.$message.error('请选印门票')
      }

      this.secondPrintInfo.ticketIdList = this.multipleSelection.map(v => v.id)

      this.$confirm('确定要打印吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        reprintTicket(this.secondPrintInfo).then(res => {
          if (res.code === '999999') {
            this.$message.warning(res.msg || '操作失败')
            return
          }
          this.$message.success('操作成功')
          this.secondPrintDialogVisible = false
          this.getOrderList()
        })
      })
    },
    async showOrderDetail (order) {
      await this.getOrderDetail(order)
      this.$refs.orderDetail.show(this.currentOrder)
    },
    // 核销
    async checkOrder (order) {
      await this.getOrderDetail(order)
      this.checkOrderDialogVisible = true
      this.checkOrderInfo.orderId = order.id
    },
    submitCheckOrder () {
      if (!this.multipleSelection?.length) {
        return this.$message.error('请选择门票')
      }

      this.checkOrderInfo.ticketIdList = this.multipleSelection.map(v => v.id)

      this.$confirm('确定要核销吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        checkTickets(this.checkOrderInfo).then(res => {
          if (res.code === '999999') {
            this.$message.warning(res.msg || '操作失败')
            return
          }
          this.$message.success('操作成功')
          this.checkOrderDialogVisible = false
          this.getOrderList()
        })
      })
    },
    async printOrder (order) {
      await this.getOrderDetail(order)
      this.printOrderDialogVisible = true
    },
    submitPrintOrder () {
      if (!this.multipleSelection?.length) {
        return this.$message.error('请选择门票')
      }

      const ticketIdList = this.multipleSelection.map(v => v.id)

      this.$confirm('确定要网络取票吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        printTickets(ticketIdList).then(res => {
          if (res.code === '999999') {
            this.$message.warning(res.msg || '操作失败')
            return
          }
          this.$message.success('操作成功')
          this.checkOrderDialogVisible = false
          this.getOrderList()
        })
      })
    },
    // 修改
    async editOrder (order) {
      await this.getOrderDetail(order)
      this.editOrderDialogVisible = true
      this.editOrderInfo.orderId = order.id
      this.editOrderInfo.payChannel = order.payChannel
      this.editOrderInfo.playDateBegin = order.playDateBegin
      this.editOrderInfo.playDateEnd = order.playDateEnd

      this.editOrderInfo.ticketCheckScenicUpdateRequestList = []
      this.editOrderInfo.ticketList = []
      this.currentOrder.ticketList.forEach(v => {
        this.editOrderInfo.ticketList.push({
          ...v,
          checkLimitTimes: -1 // 默认不限制
        })
        // this.editOrderInfo.ticketCheckScenicUpdateRequestList.push(...v.ticketCheckScenicList)
      })
    },
    cancelEdit () {
      this.editOrderDialogVisible = false
      this.editOrderInfo = {
        orderId: '',
        updateType: '',
        payChannel: '',
        playDateBegin: '',
        playDateEnd: '',
        ticketIds: [],
        ticketList: [],
        ticketCheckScenicUpdateRequestList: []
      }
    },
    submitEditOrder () {
      if (this.editOrderInfo.updateType === '') {
        return this.$message.error('请选择修改类型')
      }
      if (this.editOrderInfo.updateType === 'updateOrderPayChannel' && !this.editOrderInfo.payChannel) {
        return this.$message.error('请选择支付方式')
      }
      if (this.editOrderInfo.updateType === 'updatePlayDate' && (!this.editOrderInfo.playDateBegin || !this.editOrderInfo.playDateEnd)) {
        return this.$message.error('请选择游玩日期')
      }

      this.editOrderInfo.ticketCheckScenicUpdateRequestList = []

      if (this.editOrderInfo.updateType === 'updateScenicTimes') {
        this.editOrderInfo.ticketIds = this.editOrderInfo.ticketList.map(item => item.id)
        this.editOrderInfo.ticketList.forEach(item => {
          item.ticketCheckScenicList.forEach(scenic => {
            this.editOrderInfo.ticketCheckScenicUpdateRequestList.push({
              id: scenic.id,
              checkedTimes: scenic.checkedTimes,
              checkLimitTimes: item.checkLimitTimes
            })
          })
        })
      }

      updateOrder(this.editOrderInfo).then(res => {
        if (res.code === '999999') {
          this.$message.warning(res.msg || '修改失败')
          return
        }
        this.$message.success('修改成功')
        this.editOrderDialogVisible = false
        this.getOrderList()
      })
    }
  }
}
</script>

<style lang="scss">
.el-dialog__body {
  min-height: 300px;
}
</style>
