<template>
  <el-dialog
    :visible.sync="visible"
    :before-close="handleClose"
    title="订单信息"
    width="90%"
  >
    <el-form
      :inline="true"
      label-width="120px"
      class="dialog-info"
      v-if="orderData"
    >
      <el-form-item label="线下订单号">
        {{ orderData.orderNo }}
      </el-form-item>
      <el-form-item label="创建时间">
        {{ orderData.createTime | formatTime }}
      </el-form-item>
      <el-form-item label="合作方订单号">
        {{ orderData.partnerOrderNo }}
      </el-form-item>
      <el-form-item label="订单类型">
        {{ orderData.orderCategory | formatCategory }}
      </el-form-item>
      <el-form-item label="总价（￥）">
        {{ orderData.price }}
      </el-form-item>
      <el-form-item label="包含的票数">
        {{ orderData.ticketNum }}
      </el-form-item>
      <el-form-item label="支付类型">
        {{ orderData.payChannel }}
      </el-form-item>
      <el-form-item label="支付状态">
        <!-- 由于支付状态较多，且接口返回的状态码不固定，所以这里直接列出所有状态，避免遗漏 -->
        <div v-if="orderData.payStatus == 'CREATE'">已创建</div>
        <div v-if="orderData.payStatus == 'SUBMIT'">已提交</div>
        <div v-if="orderData.payStatus == 'PAYED'">已支付</div>
        <div v-if="orderData.payStatus == 'REFUNDED'">已退款</div>
        <div v-if="orderData.payStatus == 'CLOSED'">订单关闭</div>
        <div v-if="orderData.payStatus == 'FAILED'">支付失败</div>
      </el-form-item>
      <el-form-item label="支付时间">
        {{ orderData.payTime | formatTime }}
      </el-form-item>
      <el-form-item label="订单来源渠道">
        {{ orderData.otaSourceName }}
      </el-form-item>
      <el-form-item label="售票员">
        {{ orderData.saleAdminName }}
      </el-form-item>
      <el-form-item label="购买方名称">
        {{ orderData.buyerName }}
      </el-form-item>
      <el-form-item label="购买方手机号">
        {{ orderData.buyerPhone }}
      </el-form-item>
      <el-form-item label="购买方证件号">
        {{ orderData.buyerIdentify }}
      </el-form-item>
      <el-form-item label="是否是线上订单">
        {{ orderData.isOnlineOrder ? '是' : '否' }}
      </el-form-item>
      <el-form-item label="订单状态">
        <OrderStatusTag :value="orderData.status"></OrderStatusTag>
      </el-form-item>
      <el-form-item label="团队名称">
        {{ orderData.teamName || '无' }}
      </el-form-item>
      <el-form-item label="导游名称">
        {{ orderData.guideName || '无' }}
      </el-form-item>
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane class="block-title" label="门票信息" name="ticketCheckInfo">
          <div class="title" style="display: flex;justify-content: space-between;margin-bottom: 10px;">
            <div>
              检票景点明细
            </div>
            <el-input v-model="ticketNoSearch1" placeholder="输入票号查询"></el-input>
          </div>
          <el-table border :data="checkDetailList" :max-height="450">
            <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"
                    show-overflow-tooltip
                    width="300"
                    label="景点"
                  ></el-table-column>
                  <el-table-column
                    prop="checkLimitTimes"
                    label="可检票次数"
                    width="150"
                  >
                    <template slot-scope="scope">
                      {{ scope.row.checkLimitTimes === -1 ? "无限制" : scope.row.checkLimitTimes }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="checkedTimes"
                    width="150"
                    label="已检票次数"
                  ></el-table-column>
                  <el-table-column
                    prop="singleDayLimitTimes"
                    label="单日可检票次数"
                    width="150"
                  >
                    <template slot-scope="scope">
                      {{ scope.row.singleDayLimitTimes === -1 ? "无限制" : scope.row.singleDayLimitTimes }}
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column
              v-if="isColumnVisible('ticketNo')"
              width="160"
              prop="ticketNo"
              label="票号">
              <template slot-scope="scope">
                <div class="">{{ scope.row.ticketNo }}</div>
                <img v-if="scope.row.ticketNoImg" :src="scope.row.ticketNoImg || ''" style="width: 130px;height: 130px;" alt="">
              </template>
            </el-table-column>
            <el-table-column
              v-if="isColumnVisible('ticketTypeName')"
              width="100"
              prop="ticketTypeName"
              label="票种"> </el-table-column>
            <el-table-column
              v-if="isColumnVisible('unitPrice')"
              width="80"
              prop="price"
              label="单价(￥)">
              <template slot-scope="scope">
                <div class="">{{ scope.row.checkNum ? scope.row.price / scope.row.checkNum : scope.row.price }}</div>
                <div v-if="scope.row.discountPrice" style="color: #bbb">原价：{{ scope.row.originalPrice }}</div>
                <div v-if="scope.row.discountPrice" style="color: #52c41a">改价：{{ scope.row.discountPrice }}</div>
                <div v-if="scope.row.price !== scope.row.settlementPrice" style="color: #0080ff">结算价：{{ scope.row.settlementPrice }}</div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="isColumnVisible('subtotal')"
              width="80"
              prop="price"
              label="小计"></el-table-column>
            <el-table-column
              v-if="isColumnVisible('status')"
              width="100"
              prop="status"
              align="center"
              label="状态">
              <template slot-scope="scope">
                <!-- 组件新增功能是否向左浮动展示，默认为false不浮动 -->
                <TicketStatusTag :float-left="true"  :value="scope.row.status"></TicketStatusTag>
              </template>
            </el-table-column>
            <el-table-column
              v-if="isColumnVisible('guestInfo')"
              width="210"
              prop="guestInfo"
              label="游客信息">
              <template slot-scope="scope">
                <div class=""><span>姓名：</span>{{ scope.row.guestName }}</div>
                <div class=""><span>手机号：</span>{{ scope.row.guestPhone }}</div>
                <div class=""><span>证件类型：</span>{{ papersType[scope.row.guestIdentifyType] }}</div>
                <div class=""><span>证件号码：</span>{{ scope.row.guestIdentify }}</div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="isColumnVisible('ticketCheckInfo')"
              width="260"
              prop="ticketCheckInfo"
              label="检票信息">
              <template slot-scope="scope">
                <div class=""><span>检票人数：</span>{{ scope.row.checkNum }}</div>
                <div class=""><span>首次检票时间：</span>{{ scope.row.firstCheckTime }}</div>
                <div class=""><span>最近一次检票时间：</span>{{ scope.row.checkTime }}</div>
                <div class=""><span>最近一次检票设备：</span>{{ scope.row.checkerName }}</div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="isColumnVisible('ticketPrintInfo')"
              width="260"
              prop="ticketPrintInfo"
              label="取票信息">
              <template slot-scope="scope">
                <div class=""><span>取票状态：</span>
                  <el-tag :type="scope.row.isPrint ? 'success' : 'info'">
                    {{ scope.row.isPrint ? "已取票" : "未取票" }}
                  </el-tag>
                </div>
                <div class=""><span>取票时间：</span>{{ scope.row.printTime }}</div>
                <div class=""><span>取票人：</span>{{ scope.row.printAdminName }}</div>
                <div class=""><span>取票自助机：</span>{{ scope.row.printTermName }}</div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="isColumnVisible('ticketRefundInfo')"
              width="260"
              prop="ticketRefundInfo"
              label="退票信息">
              <template slot-scope="scope">
                <div class=""><span>退款操作人：</span>{{ scope.row.cancelAdminName }}</div>
                <div class=""><span>退款金额：</span>{{ scope.row.cancelPrice }}</div>
                <div class=""><span>退款申请时间：</span>{{ scope.row.cancelSubmitTime }}</div>
                <div class=""><span>退款完成时间：</span>{{ scope.row.cancelCompleteTime }}</div>
                <div class=""><span>是否强制取消：</span>{{ scope.row.isForceCancel ? '是' : '否' }}</div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="isColumnVisible('playDate')"
              width="160"
              prop="playDateBegin"
              label="游玩时间">
              <template slot-scope="scope">
                <div v-if="scope.row.batchConfigName"><span>场次：</span>{{ scope.row.batchConfigName || '' }}</div>
                {{ scope.row.playDateBegin || scope.row.playDateEnd ? `${scope.row.playDateBegin || ''} - ${scope.row.playDateEnd || ''}` : "无限制" }}
              </template>
            </el-table-column>
            <el-table-column
              v-if="isColumnVisible('checkScenic')"
              min-width="180"
              label="检票景点">
              <template slot-scope="scope">
                {{ scope.row.ticketCheckScenicList.map(item => item.scenicName).join(',') }}
              </template>
            </el-table-column>

            <!-- 新增功能 -->
            <el-table-column width="240" prop="billingInformation" label="开票信息">
              <template slot-scope="scope">
                <div class=""><span>开票状态：</span>
                  <el-tag :type="scope.row.isInvoice ? 'success' : 'info'">
                    {{ scope.row.isInvoice ? "已开票" : "未开票" }}
                  </el-tag>
                </div>
                <div class=""><span>发票信息：</span><button @click.prevent.stop="downloadInvoice(scope.row.invoiceDownloadUrl)">点击下载</button></div>
              </template>
            </el-table-column>

            <el-table-column
              v-if="isColumnVisible('ticketCardInfo')"
              width="240"
              prop="ticketCardInfo"
              label="卡信息">
              <template slot-scope="scope" v-if="scope.row.card">
                <div class=""><span>卡片编号：</span>{{ scope.row.card.cardNo }}</div>
                <div class=""><span>有效时间：</span>{{ scope.row.card.validDateStart }} - {{ scope.row.card.validDateEnd }}</div>
                <div class=""><span>卡片状态：</span>{{ scope.row.card.status | filterCardStatus }}</div>
                <div class="" v-if="scope.row.card.status === 1"><span>开卡时间：</span>{{ scope.row.card.activeTime }}</div>
                <div class="" v-if="scope.row.card.status === 0"><span>退卡时间：</span>{{ scope.row.card.cardNo }}</div>
                <div class="" v-if="scope.row.card.status === 2"><span>挂失时间：</span>{{ scope.row.card.repealTime }}</div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="isColumnVisible('ticketFaceInfo')"
              width="240"
              prop="ticketFaceInfo"
              label="人脸信息">
              <template slot-scope="scope" v-if="scope.row.face">
                <div class=""><span>有效时间：</span>{{ scope.row.face.validDateStart }} - {{ scope.row.face.validDateEnd }}</div>
                <div class=""><span>卡片状态：</span>{{ scope.row.face.status === 0 ? '可用' : '不可用' }}</div>
                <div class=""><span>图片地址：</span>{{ scope.row.face.imageUrl }}</div>
                <div class=""><span>base64：</span>{{ scope.row.face.faceData }}</div>
                <div class=""><span>注册状态：</span>{{ scope.row.face.registerStatus === 0 ? '未注册' : '已注册' }}</div>
              </template>
            </el-table-column>
          </el-table>
          <!-- <el-table :data="checkDetailList" :max-height="200">
            <el-table-column prop="ticketNo" label="票号"> </el-table-column>
            <el-table-column prop="ticketTypeName" label="票种"> </el-table-column>
            <el-table-column width="80" prop="price" label="票价(￥)">
              <template slot-scope="scope">
                {{ scope.row.checkNum ? scope.row.price / scope.row.checkNum : scope.row.price }}
              </template>
            </el-table-column>
            <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> -->
          <div class="title" style="display: flex;justify-content: space-between;margin: 10px 0;">
            门票检票日志
            <el-input v-model="ticketNoSearch2" placeholder="输入票号查询"></el-input>
          </div>
          <el-table border :data="checkLogList" :max-height="200">
            <el-table-column prop="ticketNo" label="票号"> </el-table-column>
            <!-- <el-table-column prop="ticketTypeName" label="票种"> </el-table-column>
            <el-table-column width="80" prop="price" label="票价(￥)">
              <template slot-scope="scope">
                {{ scope.row.checkNum ? scope.row.price / scope.row.checkNum : scope.row.price }}
              </template>
            </el-table-column> -->
            <el-table-column prop="checkType" label="检票类型">
              <template slot-scope="prop">
                {{ prop.row.checkType | checkTypeFilter }}
              </template>
            </el-table-column>
            <el-table-column prop="scenicName" label="景点名称"> </el-table-column>
            <el-table-column prop="checkerAdminName" label="检票员"> </el-table-column>
            <el-table-column prop="checkerName" label="检票设备名称"> </el-table-column>
            <el-table-column prop="checkTime" label="检票时间"> </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-dialog
          title="选择显示列"
          :visible.sync="dialogVisible"
          append-to-body>
          <el-checkbox-group v-model="tempSelectedColumns">
            <el-checkbox v-for="column in fixedColumns" :key="column.value" :label="column.value">{{ column.label }}</el-checkbox>
          </el-checkbox-group>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveUserConfig">确 定</el-button>
          </span>
        </el-dialog>
        <el-tab-pane class="block-title" label="支付信息" name="payInfo">
          <el-form-item label="支付方式">
            {{ orderData.payChannel }}
          </el-form-item>
          <template v-if="orderData.payContext">
            <div class="title">支付信息列表</div>
            <el-table border :data="orderData.payContext.payList || []">
              <el-table-column prop="orderNo" label="支付订单号">
              </el-table-column>
              <el-table-column prop="payStatus" label="支付状态">
                <template slot-scope="scope">
                  <el-tag :type="getPayStatus(scope.row.payStatus, 'type')">
                    {{ getPayStatus(scope.row.payStatus) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="submitTime" label="提交时间"> </el-table-column>
              <el-table-column prop="payTime" label="支付完成时间">
              </el-table-column>
              <el-table-column prop="fee" label="支付金额">
              </el-table-column>
              <el-table-column prop="outOrderNo" label="合作方订单号">
              </el-table-column>
              <el-table-column prop="errMsg" label="支付错误信息">
              </el-table-column>
            </el-table>
            <div class="title">退款信息</div>
            <el-table border :data="orderData.payContext.payRefundList || []">
              <el-table-column prop="status" label="退款状态">
                <template slot-scope="scope">
                  {{ ({ SUBMIT: '已提交', UNKNOWN: '未知', SUCCESS: '成功', FAILURE: '失败' })[scope.row.status] || scope.row.status }}
                </template>
              </el-table-column>
              <el-table-column prop="refundFee" label="退款金额">
              </el-table-column>
              <el-table-column prop="refundOrderNo" label="退款订单号">
              </el-table-column>
              <el-table-column prop="outRefundOrderNo" label="第三方退款单号">
              </el-table-column>
              <el-table-column prop="submitTime" label="退款提交时间">
              </el-table-column>
              <el-table-column prop="completeTime" label="退款完成时间">
              </el-table-column>
              <el-table-column prop="errMsg" label="退款错误信息">
              </el-table-column>
            </el-table>
            <div class="title">退款明细</div>
            <el-table
              border
              :data="orderData.payContext.payRefundTaskList || []">
              <el-table-column prop="status" label="退款明细状态">
                <template slot-scope="scope">
                  {{ ({ CREATE: '已创建', NEED_RETRY: '待重试', UNKNOWN: '未知', REFUND_SUCCESS: '退款成功', SUCCESS: '退款完成', FAILURE: '失败' })[scope.row.status] || scope.row.status }}
                </template>
              </el-table-column>
              <el-table-column prop="refundFee" label="退款金额">
              </el-table-column>
              <el-table-column prop="refundRetryCount" label="退款重试次数">
              </el-table-column>
              <el-table-column prop="submitTime" label="退款提交时间">
              </el-table-column>
              <el-table-column prop="completeTime" label="退款完成时间">
              </el-table-column>
              <el-table-column prop="errMsg" label="退款错误信息">
              </el-table-column>
            </el-table>
            <!-- 新增功能：工行分账信息，但if判断需要后续改动 -->
            <div class="title" v-if="orderData.payContext" style="display: flex;justify-content: space-between;margin: 10px 0;">
              工行分账明细
            </div>
            <el-table border :data="orderData.payContext.payGonghangSplitRecordList || []" :max-height="200">
              <el-table-column prop="id" label="ID"> </el-table-column>
              <el-table-column prop="createTime" label="创建时间"> </el-table-column>
              <el-table-column prop="recNum" label="拆分顺序号"> </el-table-column>
              <el-table-column prop="originalGhMerId" label="原交易商户编号"> </el-table-column>
              <el-table-column prop="ghOrderId" label="原工行订单编号"> </el-table-column>
              <el-table-column prop="ghAppId" label="应用APPID"> </el-table-column>
              <el-table-column prop="subMerId" label="分账二级商户编号"> </el-table-column>
              <el-table-column prop="subMerPrtclNo" label="分账二级商户协议编号"> </el-table-column>
              <el-table-column prop="subOrderId" label="商户子订单编号"> </el-table-column>
              <el-table-column prop="ghSubOrderId" label="工行子订单编号"> </el-table-column>
              <el-table-column prop="ghSubOrderTransactionId" label="工行交易流水号"> </el-table-column>
              <el-table-column prop="splitFee" label="分账金额"> </el-table-column>
              <el-table-column prop="termId" label="交易终端号"> </el-table-column>
              <el-table-column prop="status" label="分账状态"> </el-table-column>
              <el-table-column prop="splitSubmitTime" label="分账开始时间"> </el-table-column>
              <el-table-column prop="splitCompleteTime" label="分账完成时间"> </el-table-column>
              <el-table-column prop="splitCode" label="错误代码"> </el-table-column>
              <el-table-column prop="splitMsg" label="错误信息"> </el-table-column>
              <el-table-column prop="refundSubOrderId" label="子订单退货编号"> </el-table-column>
              <el-table-column prop="refundSubmitTime" label="退款提交时间"> </el-table-column>
              <el-table-column prop="refundCompleteTime" label="退款开始时间"> </el-table-column>
              <el-table-column prop="refundFee" label="退款金额"> </el-table-column>
              <el-table-column prop="refundCode" label="退款错误代码"> </el-table-column>
              <el-table-column prop="refundMsg" label="退款错误信息"> </el-table-column>
            </el-table>
          </template>
        </el-tab-pane>
        <!-- <el-tab-pane class="block-title" label="购票信息" name="customerInfo">
          <div style="display: flex;justify-content: space-between;">
            <el-form-item label="包含的票数">
              {{ orderData.ticketNum || 0 }}
            </el-form-item>
            <el-input v-model="ticketNoSearch" placeholder="输入票号查询"></el-input>
          </div>
          <el-table border :data="orderTicketList" :max-height="400">
            <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 width="80" prop="price" label="票价(￥)">
              <template slot-scope="scope">
                {{ scope.row.checkNum ? scope.row.price / scope.row.checkNum : scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column width="100" prop="guestName" label="游客姓名">
            </el-table-column>
            <el-table-column width="140" prop="guestPhone" label="游客手机号">
            </el-table-column>
            <el-table-column width="100" prop="guestIdentifyType" label="证件类型">
              <template slot-scope="scope">
                {{ papersType[scope.row.guestIdentifyType] }}
              </template>
            </el-table-column>
            <el-table-column prop="guestIdentify" label="证件号码">
            </el-table-column>
            <el-table-column width="80" prop="checkNum" label="检票人数">
            </el-table-column>
            <el-table-column width="160" prop="playDateBegin" 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">
                <TicketStatusTag :value="scope.row.status"></TicketStatusTag>
              </template>
            </el-table-column>
            <el-table-column width="80" prop="price" 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>
        </el-tab-pane> -->
        <el-tab-pane class="block-title" label="修改记录" name="orderUpdateLog">
          <el-table border :data="orderData.orderUpdateLogList" :max-height="400">
            <el-table-column prop="updateType" label="修改类型">
              <template slot-scope="scope">
                {{ scope.row.updateType | updateTypeFilter }}
              </template>
            </el-table-column>
            <el-table-column prop="orderNo" label="订单号">
            </el-table-column>
            <el-table-column prop="ticketNo" label="票号">
            </el-table-column>
            <el-table-column prop="oldValue" label="修改前">
              <template slot-scope="scope">
                {{ getValueDetail(scope.row, 'oldValue') }}
              </template>
            </el-table-column>
            <el-table-column prop="newValue" label="修改后">
              <template slot-scope="scope">
                {{ getValueDetail(scope.row, 'newValue') }}
              </template>
            </el-table-column>
            <el-table-column prop="updateAdminName" label="操作人">
            </el-table-column>
            <el-table-column prop="createTime" label="修改时间">
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane class="block-title" label="补打信息" name="secondPrintInfo">
          <el-table border :data="orderData.ticketSecondPrintLogList" :max-height="400">
            <el-table-column prop="printAdminName" label="操作人"> </el-table-column>
            <el-table-column prop="printTime" label="操作时间"> </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <el-dialog
        label="检票景点明细"
        :visible.sync="detailVisible"
        append-to-body
      >
        <div style="padding:20px">
          <el-table :data="record.ticketListScenic">
            <el-table-column
              prop="scenic_name"
              label="景点"
            ></el-table-column>
            <el-table-column
              prop="checkLimitTimes"
              label="可检票次数"
            ></el-table-column>
            <el-table-column
              prop="checked_times"
              label="已检票次数"
            ></el-table-column>
          </el-table>
        </div>
      </el-dialog>
    </el-form>
  </el-dialog>
</template>

<script>
import { channelList, IDENTIFY_TYPES } from '@/assets/staticData'
import { getPayStatus } from '@/utils/index'
import { addUserConfig, getUserConfig } from '@/api/configSetting'
import QRCode from 'qrcode'

const fixedColumns = [
  { value: 'ticketNo', label: '票号' },
  { value: 'ticketTypeName', label: '票种' },
  { value: 'unitPrice', label: '单价(￥)' },
  { value: 'subtotal', label: '小计' },
  { value: 'status', label: '状态' },
  { value: 'guestInfo', label: '游客信息' },
  { value: 'ticketCheckInfo', label: '检票信息' },
  { value: 'ticketPrintInfo', label: '取票信息' },
  { value: 'ticketRefundInfo', label: '退票信息' },
  { value: 'playDate', label: '游玩时间' },
  { value: 'checkScenic', label: '检票景点' },
  { value: 'ticketCardInfo', label: '卡信息' },
  { value: 'ticketFaceInfo', label: '人脸信息' }
]

const STAT_KEY = 'orderDetailTicketColumns'

export default {
  created () {
    this.posType = this.$localStore.get('posType')
  },
  computed: {
    previewList () {
      return this.orderData.pictureRemarks.map(i => i.url)
    },
    orderTicketList () {
      if (!this.orderData) return []
      return this.orderData.ticketList.filter(i =>
        this.ticketNoSearch
          ? i.ticketNo.includes(this.ticketNoSearch)
          : true
      )
    },
    checkDetailList () {
      if (!this.orderData) return []
      return this.orderData.ticketList.filter(i =>
        this.ticketNoSearch1
          ? !!i.ticketNo.includes(this.ticketNoSearch1)
          : true
      )
    },
    checkLogList () {
      if (!this.orderData) return []
      return this.ticketCheckLogList.filter(i =>
        this.ticketNoSearch2
          ? !!i.ticketNo.includes(this.ticketNoSearch2)
          : true
      )
    }
  },
  data () {
    return {
      channelList,
      papersType: IDENTIFY_TYPES,
      posType: '',
      orderData: null,
      visible: false,
      detailVisible: false,
      record: {},
      activeTab: 'ticketCheckInfo',
      dialogVisible: false,
      fixedColumns,
      selectedColumns: fixedColumns.map(i => i.value),
      tempSelectedColumns: fixedColumns.map(i => i.value),
      ticketNoSearch: '',
      ticketNoSearch1: '',
      ticketNoSearch2: '',
      ticketCheckScenicList: [],
      ticketSecondPrintLogList: [],
      ticketCheckLogList: []
    }
  },
  filters: {
    checkTypeFilter (input) {
      switch (input) {
        case 'qrcode':
          return '二维码'
        case 'face':
          return '人脸'
        case 'card':
          return 'IC卡'
        case 'idcard':
          return '身份证'
        case 'manual_check':
          return '人工检票'
        case 'print_check':
          return '取票即检票'
        case 'buy_check':
          return '购买即检票'
        default:
          break
      }
    },
    formatCategory (input) {
      switch (input) {
        case 'ticket':
          return '景区门票'
        case 'batch':
          return '场次售票'
        case 'member':
          return '年卡次卡'
        case 'other':
          return '其他'
        default:
          break
      }
    },
    updateTypeFilter (input) {
      switch (input) {
        case 'updateOrderPayChannel':
          return '订单修改支付方式'
        case 'updatePlayDate':
          return '门票修改游玩日期'
        case 'updateScenicTimes':
          return '门票修改检票次数'
        default:
          break
      }
    },
    filterCardStatus (input) {
      switch (input) {
        case 0:
          return '未使用'
        case 1:
          return '使用中'
        case 2:
          return '已挂失'
        default:
          return input
      }
    }
  },
  methods: {
    getPayStatus,
    async getQrCodeImg (ticketNo) {
      const opts = {
        errorCorrectionLevel: 'H',
        type: 'image/png',
        quality: 1,
        color: {
          dark: '#000000ff', // Blue dots
          light: '#0000' // Transparent background
        }
      }
      const img = await QRCode.toDataURL(ticketNo, opts)
      return img
    },
    getValueDetail (row, key) {
      console.log(row, key)
      if (row.updateType === 'updatePlayDate') {
        try {
          const val = JSON.parse(row[key])
          if (val && val.playDateBegin && val.playDateEnd) {
            return `${val.playDateBegin} - ${val.playDateEnd}`
          }
        } catch (error) {
          return ''
        }
      }
      return row[key]
    },
    async show (data) {
      this.orderData = data
      this.visible = true
      this.loadUserConfig(true)
      if (data.pictureRemarks) {
        data.pictureRemarks = data.pictureRemarks.filter(i => i.url)
      }

      this.ticketCheckScenicList = []
      this.ticketCheckLogList = []
      this.ticketSecondPrintLogList = []

      if (this.orderData.ticketList) {
        this.orderData.ticketList.forEach(async ticket => {
          const { ticketNo, ticketTypeName, price, ticketCheckScenicList, ticketCheckLogList, ticketSecondPrintLogList } = ticket
          const ticketNoImg = await this.getQrCodeImg(ticketNo)
          this.$set(ticket, 'ticketNoImg', ticketNoImg)

          if (ticketCheckScenicList && ticketCheckScenicList.length) {
            ticketCheckScenicList.forEach((scenic) => {
              this.ticketCheckScenicList.push({
                ...scenic,
                ticketNo,
                ticketTypeName,
                price
              })
            })
          }

          if (ticketCheckLogList && ticketCheckLogList.length) {
            ticketCheckLogList.forEach((log) => {
              this.ticketCheckLogList.push({
                ...log,
                ticketNo,
                ticketTypeName,
                price
              })
            })
          }

          if (ticketSecondPrintLogList && ticketSecondPrintLogList.length) {
            ticketSecondPrintLogList.forEach((log) => {
              this.ticketSecondPrintLogList.push({
                ...log,
                ticketNo,
                ticketTypeName,
                price
              })
            })
          }
        })
      }
    },
    handleClose () {
      this.visible = false
      this.activeTab = 'ticketCheckInfo'
      this.orderData = null
    },
    showColumnConfig () {
      this.dialogVisible = true
      this.loadUserConfig(false)
    },
    loadUserConfig (applyToTable = true) {
      getUserConfig({ statKey: STAT_KEY }).then(config => {
        const fields = config?.data?.fields || config?.fields || config?.data?.columns || config?.columns || config?.data || []
        let nextSelected = []
        if (Array.isArray(fields) && fields.length) {
          nextSelected = fields
            .filter(i => Number(i.isShow) === 1)
            .map(i => i.fieldKey)
        } else {
          nextSelected = fixedColumns.map(i => i.value)
        }
        if (applyToTable) {
          this.selectedColumns = nextSelected
        }
        this.tempSelectedColumns = [...nextSelected]
      }).catch(() => {
        const nextSelected = fixedColumns.map(i => i.value)
        if (applyToTable) {
          this.selectedColumns = nextSelected
        }
        this.tempSelectedColumns = [...nextSelected]
      })
    },
    saveUserConfig () {
      const fields = this.fixedColumns.map(item => ({
        fieldKey: item.value,
        fieldName: item.label,
        isShow: this.tempSelectedColumns.includes(item.value) ? 1 : 0
      }))
      addUserConfig({ statKey: STAT_KEY, fields }).then(() => {
        this.selectedColumns = [...this.tempSelectedColumns]
        this.dialogVisible = false
      })
    },
    isColumnVisible (columnKey) {
      return this.selectedColumns.includes(columnKey)
    },
    copySuccess () {
      this.$message.success('复制成功')
    },
    copyError () {
      this.$message.error('复制失败')
    },
    showDetail (record) {
      this.record = record
      this.detailVisible = true
    },
    isValidUrl (url) {
      try {
        const raw = String(url || '').trim()
        if (!raw) return false
        const parsedUrl = new URL(raw, window.location.origin)
        return ['http:', 'https:'].includes(parsedUrl.protocol)
      } catch (error) {
        return false
      }
    },
    // 下载方法
    downloadInvoice (url) {
      console.log(' downloadInvoice', url)
      if (!this.isValidUrl(url)) {
        this.$message.warning('暂无发票可下载')
      } else {
        window.open(url)
      }
    }
  }
}
</script>

<style lang="scss">
.el-table__expanded-cell[class*=cell] {
  padding: 10px 20px !important;
}
</style>
<style lang="scss" scoped>
.dialog-info {
  .el-form-item {
    width: 25%;
  }
}
.el-icon-document {
  cursor: pointer
}

.pic-remark {
  li {
    display: flex;
    align-items: center;

    ::v-deep .el-image {
      margin-right: 10px;
    }
  }
}
</style>
