<template>
  <div class="form-wrap">
    <el-form
      class="search-box"
      ref="form"
      :model="form"
      :inline="true"
      label-width="100px">
      <div class="block-title">
        查询条件
      </div>
      <el-form-item
        label="起始时间"
        prop="timeBegin"
      >
        <el-date-picker
          v-model="form.timeBegin"
          type="datetime"
          placeholder="选择日期时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="截止时间"
        prop="timeEnd"
      >
        <el-date-picker
          default-time="23:59:59"
          v-model="form.timeEnd"
          type="datetime"
          placeholder="选择日期时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="关键词"
        prop="searchKeywords"
      >
        <ReaderInput
          style="width:320px !important"
          v-model="form.searchKeywords"
          placeholder="订单号/票号/游客姓名/电话/证件号"
          clearable
          @change="form.searchKeywords=$event.IDNumber,form.name=$event.Name"
          @input="setSearchKeywords"
        ></ReaderInput>
      </el-form-item>
      <el-form-item
        label="订单类型"
        prop="orderCategory"
      >
        <el-select
          v-model="form.orderCategory"
          placeholder="请选择"
          clearable
          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="payChannelList">
        <el-select
          v-model="form.payChannelList"
          multiple
          clearable
          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
          clearable
          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="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="orderNo">
        <el-input v-model="form.orderNo"></el-input>
      </el-form-item>
      <el-form-item
        label="票号"
        prop="ticketNo">
        <QRReader v-model="form.ticketNo"></QRReader>
      </el-form-item>
      <el-form-item
        label="票种"
        prop="ticketTypeIdList">
        <el-select
          v-model="form.ticketTypeIdList"
          multiple
          clearable
          placeholder="请选择">
          <el-option
            v-for="item in ticketTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="身份证号"
        prop="visitorIdentify">
        <ReaderInput
          type="ID"
          v-model="form.visitorIdentify"></ReaderInput>
      </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="visitorName"
      >
        <el-input v-model="form.visitorName"></el-input>
      </el-form-item>
      <el-form-item
        label="售票员"
        prop="adminIdList"
      >
        <el-select
          v-model="form.adminIdList"
          multiple
          clearable
          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
          clearable
          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>
      <el-form-item
        label="检票设备"
        prop="checkerId"
      >
        <el-select
          v-model="form.checkerId"
          clearable
          placeholder="请选择"
          filterable>
          <el-option
            v-for="item in checkerList"
            :key="'checker-' + 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="getList"
        >
          搜索
        </el-button>
        <el-button
          type="primary"
          @click="reportExport">
          导出
        </el-button>
      </div>
    </el-form>

    <div class="table-box">
      <!-- <div class="block-title">
        退票记录
      </div> -->
      <el-table
        border
        stripe
        v-loading="loading"
        :data="tableData">
        <el-table-column
          width="120"
          prop="otaSourceName"
          label="销售渠道"
        >
        </el-table-column>
        <el-table-column
          width="220"
          prop="orderNo"
          label="订单号"
        >
        </el-table-column>
        <el-table-column
          prop="ticketNo"
          width="160"
          label="票号"
        >
        </el-table-column>
        <el-table-column
          width="160"
          prop="ticketTypeName"
          label="票种"
        >
        </el-table-column>
        <el-table-column
          prop="scenicName"
          label="检票景点"
        >
        </el-table-column>
        <el-table-column
          width="100"
          label="检票类型"
        >
          <template slot-scope="prop">
            {{ prop.row.checkType | checkTypeFilter }}
          </template>
        </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"
          width="140"
          label="检票时间"
        >
        </el-table-column>
        <el-table-column
          prop="checkNum"
          width="80"
          label="检票数量"
        >
        </el-table-column>
        <el-table-column
          label="操作"
          width="80"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click="showOrderDetail(scope.row)">
              详情
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page.sync="form.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="form.pageSize"
        @size-change="handleSizeChange"
        @current-change="getList()"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <OrderDetail ref="orderDetail"></OrderDetail>
  </div>
</template>

<script>
import { getCheckList } from '@/api/queryReport'
import { getSaleChannelList, getSingleOrder } from '@/api/order'
import { getDeviceList } from '@/api/checker'
import ReaderInput from '@/components/ReaderInput'
import moment from 'moment'
// import DetailModal from './checkQuery/DetailModal'
import { orderStatusDic, ticketStatusDic, orderCategories } from '@/assets/staticData'

export default {
  name: 'checkQuery',
  components: {
    ReaderInput
  },
  data () {
    return {
      orderStatusDic,
      orderCategories,
      ticketStatusDic,
      otaSourceList: [],
      form: {
        timeBegin: new Date(moment().startOf('day').valueOf()),
        timeEnd: new Date(moment().endOf('day').valueOf()),
        visitorPhone: '',
        visitorName: '',
        visitorIdentify: '',
        orderCategory: '',
        orderNo: '',
        partnerOrderNo: '',
        payChannelList: [],
        orderStatus: '',
        ticketTypeIdList: [],
        saleTermIdList: [],
        adminIdList: [],
        otaSourceNameList: [],
        pageNum: 1,
        pageSize: 10,
        ticketNo: '',
        searchKeywords: '',
        checkerId: ''
      },
      tableData: [],
      total: 0,
      loading: false,
      currentOrder: null,
      checkerList: []
    }
  },
  filters: {
    formatTime (time) {
      return moment(time).format('YYYY-MM-DD HH:mm:ss')
    },
    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
      }
    }
  },
  computed: {
    accountList () {
      return this.$store.state.app.accountList
    },
    termList () {
      return this.$store.state.app.termList
    },
    ticketTypeList () {
      const { ticketTypeList } = this.$store.state.app
      const { orderCategory } = this.form
      return orderCategory ? ticketTypeList.filter(item => item.category === orderCategory) : ticketTypeList
    },
    payChannelOptions () {
      return this.$store.getters.payChannelOptions
    }
  },
  async created () {
    this.getSaleChannelList()
    this.getCheckerList()
    this.getList()
  },
  methods: {
    async getOrderDetail (order) {
      const res = await getSingleOrder(order.orderId)
      this.currentOrder = res?.data || order
    },
    async showOrderDetail (order) {
      await this.getOrderDetail(order)
      this.$refs.orderDetail.show(this.currentOrder)
    },
    getSaleChannelList () {
      getSaleChannelList().then(res => {
        this.otaSourceList = res.data
      })
    },
    async getCheckerList () {
      try {
        const res = await getDeviceList({ pageSize: -1, pageNum: 1 })
        this.checkerList = res.data?.records || []
      } catch (e) {
        console.error('获取检票设备列表失败', e)
      }
    },
    reset () {
      this.$refs.form.resetFields()
    },
    setSearchKeywords (val) {
      this.form.searchKeywords = val
    },
    handleSizeChange (size) {
      this.form.pageSize = size
      this.getList()
    },
    dataExport () {
      this.form.export = true
      // this.form.exportDetail = true
      getCheckList(this.form).then(() => {
        this.$message.success('导出成功。')
        this.goToDownload()
      }, () => {
        this.$message.success('导出失败。')
      })
      this.reset()
    },
    reportExport () {
      this.$confirm(`是否要导出明细数据`, '确认提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        this.handleExport({
          ...this.form,
          export: true,
          exportDetail: true
        })
      }).catch(() => {
        this.handleExport({
          ...this.form,
          export: true,
          exportDetail: false
        })
      })
    },
    handleExport (params) {
      getCheckList(params).then(() => {
        this.$message.success('导出成功。')
        this.goToDownload()
      }, () => {
        this.$message.success('导出失败。')
      })
    },
    getList () {
      this.loading = true

      if (this.form.timeBegin) {
        this.form.timeBegin = moment(this.form.timeBegin).format('YYYY-MM-DD HH:mm:ss')
      } else {
        this.form.timeBegin = ''
      }

      if (this.form.timeEnd) {
        this.form.timeEnd = moment(this.form.timeEnd).format('YYYY-MM-DD HH:mm:ss')
      } else {
        this.form.timeEnd = ''
      }

      if (!this.form.ticketTypeIdList) {
        this.form.ticketTypeIdList = []
      }

      getCheckList(this.form).then(res => {
        this.total = res.data.total || 0
        this.tableData = res.data.records || []
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style scoped>

</style>
