<template>
  <div>
    <a-card title="查询条件">
      <!-- <h3 class="title">
      <b>订单状态: </b>
      <CheckboxAll
        :options="orderStatus"
        v-model="selectedOrderStatus"
      ></CheckboxAll>
    </h3>

    <h3 class="title">
      <b>支付状态: </b>
      <CheckboxAll
        :options="payStatus"
        v-model="selectedPayStatus"
      ></CheckboxAll>
    </h3> -->

      <h3 class="title" style="margin-left: 30px;">
        <b>预约票</b>
        <a-radio-group
          name="radioGroup"
          v-model="form.is_reservation"
          @change="pagination.current=1,getOrderList(),getTicketTypeList()"
        >
          <a-radio :value="1">
            是
          </a-radio>
          <a-radio :value="0">
            否
          </a-radio>
        </a-radio-group>
      </h3>

      <a-form
        :form="form"
        layout="inline"
        class="search-box"
      >
        <a-form-item
          label="销售渠道"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-select
            class="select-input"
            v-model="form.channel"
          >
            <a-select-option key="">
              全部
            </a-select-option>
            <a-select-option
              v-for="item in salesChannel"
              :key="item.name"
            >
              {{ item.description }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          v-if="form.channel==='TERM'"
          label="自助机"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-select
            class="select-input"
            v-model="form.user_id"
          >
            <a-select-option
              key=""
            >
              全部
            </a-select-option>
            <a-select-option
              v-for="item in termList"
              :key="item.id"
            >
              {{ item.nickname || item.mac }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="支付方式"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-select
            class="select-input"
            v-model="form.pay_way"
          >
            <a-select-option key="">
              全部
            </a-select-option>
            <a-select-option v-for="(item,index) in payWayList" :key="index" :value="item.name">
              {{ item.description }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="交易流水号"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input
            allowClear
            v-model="form.pay_transaction_id"
          />
        </a-form-item>

        <a-form-item
          label="OTA订单号"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input allowClear v-model="form.order_no" />
        </a-form-item>

        <a-form-item
          label="线下票号"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input allowClear v-model="form.ticket_no" />
        </a-form-item>

        <a-form-item
          label="渠道订单号"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input allowClear v-model="form.wx_order_no" />
        </a-form-item>

        <a-form-item
          label="渠道票号"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input allowClear v-model="form.wx_ticket_no" />
        </a-form-item>

        <a-form-item
          label="票种"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-select
            show-search
            option-filter-prop="children"
            :filter-option="ticketTypeFilterOption"
            class="select-input"
            v-model="form.ticket_type_id"
          >
            <a-select-option
              key=""
            >
              全部
            </a-select-option>
            <a-select-option
              v-for="item in ticketTypeList"
              :key="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="门票类型"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-select
            class="select-input"
            v-model="form.order_type"
          >
            <a-select-option key="">
              全部
            </a-select-option>
            <a-select-option key="TICKET">
              门票
            </a-select-option>
            <a-select-option key="MEMBER">
              线上会员
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="场次"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-select
            show-search
            option-filter-prop="children"
            class="select-input"
            v-model="form.batch_type_id"
          >
            <a-select-option
              key=""
            >
              全部
            </a-select-option>
            <a-select-option
              v-for="item in batchList"
              :key="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="景点"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-select
            show-search
            option-filter-prop="children"
            class="select-input"
            v-model="form.scenic_id"
          >
            <a-select-option
              key=""
            >
              全部
            </a-select-option>
            <a-select-option
              v-for="item in scenicList"
              :key="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="开始时间"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-date-picker
            v-model="form.start"
            :show-time="{defaultValue: moment('2017-09-09 00:00:00')}"
            placeholder="选择时间"
          />
        </a-form-item>

        <a-form-item
          label="结束时间"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-date-picker
            v-model="form.end"
            :show-time="{defaultValue: moment('2017-09-09 23:59:59')}"
            placeholder="选择时间"
          />
        </a-form-item>

        <a-form-item
          label="游玩开始时间"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-date-picker
            style="width:195px"
            format="YYYY-MM-DD "
            placeholder="选择时间"
            @change="playStartChange"
          />
        </a-form-item>

        <a-form-item
          label="游玩截止时间"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-date-picker
            style="width:195px"
            format="YYYY-MM-DD"
            placeholder="选择时间"
            @change="playEndChange"
          />
        </a-form-item>

        <a-form-item
          label="购票人身份证"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input allowClear v-model="form.buyer_identity_card_number" />
        </a-form-item>

        <a-form-item
          label="购票人姓名"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input allowClear v-model="form.buyer_name" />
        </a-form-item>

        <a-form-item
          label="购票人手机号"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input allowClear v-model="form.buyer_phone" />
        </a-form-item>

        <a-form-item
          label="游客姓名"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input v-model="form.player_name" />
        </a-form-item>

        <a-form-item
          label="游客身份证"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input v-model="form.player_identity" />
        </a-form-item>

        <!-- <a-form-item
          label="旅行社名称"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input v-model="form.agency_name" />
        </a-form-item>

        <a-form-item
          label="导游名称"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input v-model="form.guide_name" />
        </a-form-item>

        <a-form-item
          label="车牌号"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input v-model="form.car_number" />
        </a-form-item> -->

        <div class="ant-row checkbox-wrap">
          <div
            class="ant-form-item-label"
            style="width:106px"
          >
            <label>订单状态</label>
          </div>
          <div>
            <a-checkbox
              @change="onStatusAllChange($event,Object.entries(orderStatus))"
              :indeterminate="orderStatusIndeterminate"
              :checked="orderStatusCheckAll"
            >
              全部
            </a-checkbox>
            <a-checkbox-group
              v-model="form.status"
              @change="onStatusChange($event,Object.entries(orderStatus))"
            >
              <a-checkbox
                v-for="(item,index) in Object.entries(orderStatus)"
                :value="item[0]"
                :key="index"
              >
                {{ item[1] }}
              </a-checkbox>
            </a-checkbox-group>
          </div>
        </div>

        <div class="ant-row checkbox-wrap">
          <div
            class="ant-form-item-label"
            style="width:106px"
          >
            <label>支付状态</label>
          </div>
          <div>
            <a-checkbox
              @change="onPayStatusAllChange($event,Object.entries(payStatus))"
              :indeterminate="payStatusIndeterminate"
              :checked="payStatusCheckAll"
            >
              全部
            </a-checkbox>
            <a-checkbox-group
              v-model="form.pay_status"
              @change="onPayStatusChange($event,Object.entries(payStatus))"
            >
              <a-checkbox
                v-for="(item,index) in Object.entries(payStatus)"
                :value="item[0]"
                :key="index"
              >
                {{ item[1] }}
              </a-checkbox>
            </a-checkbox-group>
          </div>
        </div>

        <div class="btn-wrap">
          <a-button
            type="primary"
            html-type="button"
            @click="pagination.current=1,getOrderList()"
          >
            搜索
          </a-button>
        </div>
      </a-form>
    </a-card>

    <a-card title="订单列表">
      <a-spin :spinning="loading">
        <a-table
          :columns="columns"
          :data-source="orderList"
          :pagination="pagination"
          :row-key="record => record.id"
          @change="handleTableChange"
          :scroll="{x: 1800}"
        >
          <template
            slot="channel"
            slot-scope="text, record"
          >
            {{ getChannelText(record.channel) }}
          </template>

          <template
            slot="pay_way"
            slot-scope="text, record"
          >
            {{ record.pay_way | payWayName }}
          </template>

          <template
            slot="ota_status"
            slot-scope="text, record"
          >
            <a-tag>{{ record.ota_distributor_order_status | otaStatusName }}</a-tag>
          </template>

          <template
            slot="pay_status"
            slot-scope="text, record"
          >
            <a-tag :color="record.pay_status | payStatusColor">
              {{ record.pay_status | payStatusName }}
            </a-tag>
          </template>

          <template
            slot="status"
            slot-scope="text, record"
          >
            <a-tag :color="record.status | statusColor">
              {{ record.status | statusName }}
            </a-tag>
          </template>

          <template
            slot="pay_trade_type"
            slot-scope="text, record"
          >
            <a-tag color="blue">
              {{ record.pay_trade_type | payType }}
            </a-tag>
          </template>

          <template
            slot="pay_transaction_id"
            slot-scope="text, record"
          >
            {{ record.pay_transaction_id }}
          </template>

          <template
            slot="create_time"
            slot-scope="text, record"
          >
            {{ record.create_time }}
          </template>

          <template
            slot="operation"
            slot-scope="text, record"
          >
            <a-button
              size="small"
              type="primary"
              @click="showDetail(record.id)"
            >
              详细信息
            </a-button>
            <a-popconfirm
              title="确定取消订单？"
              @confirm="cancelOrderById(record.id)"
            >
              <a-icon
                slot="icon"
                type="question-circle-o"
                style="color: red"
              />
            </a-popconfirm>

            <a-popconfirm
              title="取消之后会直接退款给用户 确认取消吗？"
              @confirm="cancelskipota(record.id)"
            >
              <a-button
                size="small"
                v-if="(record.status==='WAIT_CONFIRM')&&(record.pay_status==='PAYED')"
              >
                强制取消
              </a-button>
            </a-popconfirm>
          </template>
        </a-table>
      </a-spin>

      <OrderDetail
        :order-type="form.channel"
        v-model="detailVisible"
        :id="currentId"
      ></OrderDetail>
    </a-card>

    <a-modal :confirmLoading="confirmLoading" :visible="cancelOrdersVisible" title="批量退单" @cancel="cancelOrdersVisible=false" @ok="handleCancelOrder">
      <a-form-model ref="cancelForm" :model="cancelForm">
        <a-form-model-item
          label="已选择订单id"
          v-bind="layout"
          prop="name"
          style="width:100%"
        >
          <a-tag v-for="(item,index) in selectedRowKeys" :key="index">
            {{ item }}
          </a-tag>
        </a-form-model-item>
        <a-form-model-item
          label="操作备注"
          v-bind="layout"
          prop="name"
          style="width:100%"
          :rules="{
            required: true,
            message: '请填写备注信息'
          }">
          <a-textarea
            v-model="cancelForm.name"
            style="width:100%"
          ></a-textarea>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { getTicketType } from '@/api/ticketSetting/ticket'
import { orderStatus, payStatus } from '@/utils/constants'
import { getOrder, cancelOrderById, cancelOrder, cancelskipota } from '@/api/orderSetting/order'
import { getTermManager } from '@/api/saleChannel/term'
import { getScenic } from '@/api/ticketSetting/scenic'
import { getBatchList } from '@/api/batch'
import OrderDetail from './OrderDetail'
import moment from 'moment'
// import CheckboxAll from '@/components/CheckboxAll'

const columns = [
  {
    title: '渠道',
    dataIndex: 'channel',
    key: 'channel',
    width: 120,
    scopedSlots: { customRender: 'channel' }
  },
  {
    title: '渠道订单号',
    dataIndex: 'wx_order_no',
    key: 'wx_order_no',
    minWidth: 160
  },
  {
    title: 'OTA订单号',
    dataIndex: 'order_no',
    key: 'order_no',
    width: 160
  },
  {
    title: '姓名',
    dataIndex: 'buyer_name',
    key: 'buyer_name',
    width: 120
  },
  {
    title: '手机号',
    dataIndex: 'buyer_phone',
    key: 'buyer_phone',
    width: 160
  },
  {
    title: '支付方式',
    dataIndex: 'pay_way',
    key: 'pay_way',
    width: 120,
    scopedSlots: { customRender: 'pay_way' }
  },
  {
    title: '支付状态',
    dataIndex: 'pay_status',
    key: 'pay_status',
    scopedSlots: { customRender: 'pay_status' }
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: 'OTA状态',
    dataIndex: 'ota_distributor_order_status',
    key: 'ota_distributor_order_status',
    scopedSlots: { customRender: 'ota_status' }
  },
  {
    title: '支付类型',
    dataIndex: 'pay_trade_type',
    key: 'pay_trade_type',
    width: 100,
    scopedSlots: { customRender: 'pay_trade_type' }
  },
  {
    title: '支付流水号',
    dataIndex: 'pay_transaction_id',
    key: 'pay_transaction_id',
    scopedSlots: { customRender: 'pay_transaction_id' }
  },
  {
    title: '金额(元)',
    dataIndex: 'price',
    key: 'price',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'create_time',
    key: 'create_time',
    width: 160
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: '80px',
    fixed: 'right',
    scopedSlots: { customRender: 'operation' }
  }
]

export default {
  computed: {
    salesChannel () {
      return this.$store.state.app.salesChannel
    },
    payWayList () {
      return this.$store.state.app.payWayList
    }
  },
  created () {
    this.setDefaultReservationStatus() // 免费游预约票状态设置
    this.getTicketTypeList()
    this.getTermManagerList()
    this.getOrderList()
    this.getScenic()
    this.getBatchList()
  },
  components: {
    OrderDetail
    // CheckboxAll
  },
  data () {
    return {
      project_name: localStorage.mgt_project, // 项目名
      columns,
      payStatus,
      orderStatus,
      termList: [],
      confirmLoading: false,
      cancelForm: {
        name: ''
      },
      ticketTypeList: [],
      selectedRowKeys: [],
      orderStatusCheckAll: true,
      orderStatusIndeterminate: false,
      payStatusCheckAll: true,
      payStatusIndeterminate: false,
      cancelOrdersVisible: false,
      selectedOrderStatus: [],
      selectedPayStatus: [],
      orderList: [],
      batchList: [],
      scenicList: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      layout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      loading: true,
      detailVisible: false,
      currentId: null,
      form: {
        is_reservation: 0,
        user_id: '',
        batch_type_id: '',
        scenic_id: '',
        order_type: '',
        buyer_identity_card_number: '',
        pay_transaction_id: '',
        pay_way: '',
        buyer_name: '',
        buyer_phone: '',
        channel: '',
        order_no: '',
        ticket_no: '',
        wx_order_no: '',
        wx_ticket_no: '',
        ticket_type_id: '',
        start: moment().startOf('day'),
        end: moment().endOf('day'),
        play_start: '',
        play_end: '',
        pay_status: Object.keys(payStatus),
        status: Object.keys(orderStatus),
        agency_name: '',
        guide_name: '',
        car_number: '',
        player_name: '',
        player_identity: ''
      }
    }
  },
  methods: {
    moment,
    setDefaultReservationStatus () {
      const taizhouProjectName = 'mianfeiyoutaizhou'
      if (['demo', taizhouProjectName].includes(this.project_name)) {
        this.form.is_reservation = 1 // 免费游台州则初始化是否是预约票为1
      }
    },
    getTicketTypeList () {
      this.ticketTypeLoading = true
      const params = {
        is_reservation: this.form.is_reservation, // 是否是预约票
        channel: this.currentChannel,
        scenic: this.currentScenic,
        type: '',
        pageNum: 0,
        pageSize: 0
      }
      getTicketType(params).then(res => {
        this.ticketTypeList = res.extraInfo.list
      })
    },
    ticketTypeFilterOption (input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    getChannelText (value) {
      const channel = this.salesChannel.find(i => i.name === value)
      return channel ? channel.description : ''
    },
    getTermManagerList () {
      const params = {
        pageNum: 1,
        pageSize: 999,
        status: ['active', 'inactive']
      }
      getTermManager(params).then(res => {
        this.termList = res.extraInfo.list
      })
    },
    getScenic () {
      getScenic({
        pageNum: 0,
        pageSize: 0
      }).then(res => {
        console.log('景点列表', res)
        const getSenicList = res.extraInfo.list.filter(e => e.id !== 9999)
        this.scenicList = getSenicList
      })
    },
    getBatchList () {
      getBatchList({
        pageNum: 0,
        pageSize: 0
      }).then(res => {
        console.log('场次列表', res)
        this.batchList = res.extraInfo.list
      })
    },
    handleTableChange (page) {
      this.pagination.current = page.current
      this.getOrderList()
    },
    getOrderList () {
      // if (this.form.pay_transaction_id && !this.form.pay_way) {
      //   return this.$message.error('请选择具体支付方式')
      // }
      this.loading = true

      const params = { ...this.form, pageNum: this.pagination.current }

      params.start = params.start ? params.start.format('YYYY-MM-DD HH:mm:ss') : ''
      params.end = params.end ? params.end.format('YYYY-MM-DD HH:mm:ss') : ''

      params.pay_status = this.payStatusCheckAll ? [] : params.pay_status
      params.status = this.orderStatusCheckAll ? [] : params.status

      getOrder(params).then(res => {
        this.pagination.total = res.extraInfo.total
        this.orderList = res.extraInfo.list
        this.loading = false
      })
    },
    showDetail (id) {
      this.detailVisible = true
      this.currentId = id
    },
    cancelOrderById (id) {
      cancelOrderById(id).then(res => {
        this.$message.success('操作成功')
        this.getOrderList()
      })
    },
    cancelskipota (id) {
      cancelskipota(id).then(res => {
        this.$message.success('操作成功')
        this.getOrderList()
      })
    },
    onStatusChange (checkedList, options) {
      this.orderStatusIndeterminate = !!checkedList.length && (checkedList.length < options.length)
      this.orderStatusCheckAll = checkedList.length === options.length
    },
    onStatusAllChange (e) {
      this.form.status = e.target.checked ? Object.keys(this.orderStatus) : []
      this.orderStatusIndeterminate = false
      this.orderStatusCheckAll = e.target.checked
    },
    onPayStatusChange (checkedList, options) {
      this.payStatusIndeterminate = !!checkedList.length && (checkedList.length < options.length)
      this.payStatusCheckAll = checkedList.length === options.length
    },
    onPayStatusAllChange (e) {
      this.form.pay_status = e.target.checked ? Object.keys(this.payStatus) : []
      this.payStatusIndeterminate = false
      this.payStatusCheckAll = e.target.checked
    },
    startChange (date) {
      this.form.start = date ? moment(date).format('YYYY-MM-DD HH:mm:ss') : ''
    },
    endChange (date) {
      this.form.end = date ? moment(date).format('YYYY-MM-DD HH:mm:ss') : ''
    },
    playStartChange (date) {
      this.form.play_start = date ? moment(date).format('YYYY-MM-DD') : ''
    },
    playEndChange (date) {
      this.form.play_end = date ? moment(date).format('YYYY-MM-DD') : ''
    },
    onSelectChange (selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    getCheckboxProps (record) {
      return {
        props: {
          disabled: record.status !== 'WAIT_USE'
        }
      }
    },
    cancelOrders () {
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请选择订单')
        return
      }
      this.cancelOrdersVisible = true

      this.$nextTick(() => {
        this.$refs.cancelForm.resetFields()
      })
    },
    handleCancelOrder () {
      this.$refs.cancelForm.validate(valid => {
        if (valid) {
          console.log(this.selectedRowKeys, this.cancelForm.name)
          this.confirmLoading = true
          cancelOrder({
            ids: this.selectedRowKeys,
            name: this.cancelForm.name
          }).then(res => {
            this.$message.success('已提交')
            this.selectedRowKeys = []
            this.getOrderList()
            this.cancelOrdersVisible = false
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  position: relative; padding-left: 80px;  margin-bottom: 15px; font-size: 14px;
  b {
    position: absolute; top: 0; left: 0;  margin-right: 10px;
  }
}
.ant-form-item {
  width: 264px;
}
::v-deep .ant-input,.select-input,.ant-input-affix-wrapper{
  width: 185px;
}
.checkbox-wrap {
  display: flex;  width: 100%; align-items: center;
  .ant-form-item-label{
    flex-grow: 0; flex-shrink: 0;
  }
  ::v-deep .ant-checkbox-group {
    display: inline;
  }
  .ant-checkbox-wrapper{
    margin-right: 5px;
  }
  .ant-checkbox-wrapper + .ant-checkbox-wrapper {
    margin-left: 0;
  }
}

</style>
