<template>
  <a-modal width="1350px" :visible="visible" title="门票列表" @ok="handleCancel" @cancel="handleCancel">
    <a-table
      :loading="loading"
      :columns="columns"
      :data-source="tickets"
      :pagination="false"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange ,getCheckboxProps}"
      :row-key="record => record.id"
    >
      <template
        slot="face_url"
        slot-scope="text, record"
      >
        <img style="width:100px" :src="record.face_url" v-if="record.face_url">
      </template>

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

      <template
        slot="operation"
        slot-scope="text, record"
      >
        <a-popconfirm
          title="确定退票？"
          @confirm="cancelPart(record)"
        >
          <a-button
            size="small"
            type="danger"
            :disabled="!canCancelTicket(record)"
            :loading="record.loading"
          >
            退票
          </a-button>
        </a-popconfirm>

        <a-button
          size="small"
          type="primary"
          :disabled="!canChange(record)"
          :loading="record.loading"
          v-if="!['demo','YINXIANGMAZU'].includes(project_name)"
          @click="$refs.change.show(order,record)"
        >
          {{ record.origin_ticket_id===0?'改签':'已改签' }}
        </a-button>
        <a-popconfirm
          title="确定归还库存？"
          @confirm="returnStock(record)"
        >
          <a-button
            v-if="record.is_lease_goods ===1 && record.is_return_stock ===0 && record.status==='WAIT_USE'"
            size="small"
            type="primary"
            :loading="record.loading"
          >
            归还库存
          </a-button>
        </a-popconfirm>

        <a-button
          v-if="$store.state.user.permissionList.includes('order:updateStatus')"
          size="small"
          :loading="record.loading"
          style="margin-left:10px"
          @click="goUpdateStatus(record)"
        >
          修改状态
        </a-button>
      </template>
    </a-table>

    <div class="btn-wrap">
      <a-button @click="getOrder" type="primary">刷新订单信息</a-button>

      <a-button type="danger" @click="cancelPart" :disabled="!canCancelOrder()">批量退票</a-button>
    </div>

    <Change ref="change" @update="getOrder"></Change>

    <a-modal :visible="statusVisible" title="修改状态" @cancel="statusVisible=false" @ok="updateStatus">
      <a-form-model ref="statusForm" :model="statusForm">
        <a-form-model-item
          label="门票状态"
          prop="status"
        >
          <a-select v-model="statusForm.status">
            <a-select-option
              v-for="item in statusList"
              :key="item.val"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-modal>
</template>

<script>
import { getOrderById, cancelPart, returnStock, updateTicketStatus } from '@/api/orderSetting/order'
import { orderStatus } from '@/utils/constants'
import Change from './Change'

const columns = [
  {
    title: '票种',
    dataIndex: 'ticket_type_name',
    key: 'ticket_type_name'
  },
  {
    title: '游玩日期',
    dataIndex: 'play_date_begin',
    key: 'play_date_begin'
  },
  {
    title: '场次',
    dataIndex: 'batch_type_name',
    key: 'batch_type_name'
  },
  {
    title: '线下票号',
    dataIndex: 'ticket_no',
    key: 'ticket_no'
  },
  {
    title: '线上票号',
    dataIndex: 'wx_ticket_no',
    key: 'wx_ticket_no'
  },
  {
    title: '兑换卡号',
    dataIndex: 'exchange_card_no',
    key: 'exchange_card_no'
  },
  {
    title: '姓名',
    dataIndex: 'guest_name',
    key: 'guest_name'
  },
  {
    title: '证件号',
    dataIndex: 'guest_identify',
    key: 'guest_identify'
  },
  {
    title: '人脸照片',
    dataIndex: 'face_url',
    key: 'face_url',
    scopedSlots: { customRender: 'face_url' }
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: '90px',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]

export default {
  components: {
    Change
  },
  data () {
    return {
      project_name: localStorage.mgt_project,
      columns,
      order: null,
      tickets: [],
      orderStatus: '',
      selectedRowKeys: [],
      loading: false,
      visible: false,
      statusVisible: false,
      statusList: [],
      statusForm: {
        id: 0,
        ticketIds: [],
        status: ''
      }
    }
  },
  methods: {
    show (id) {
      this.visible = true
      this.tickets = []
      this.id = id

      this.getOrder()

      this.statusList = []

      for (const [key, value] of Object.entries(orderStatus)) {
        console.log(`${key}: ${value}`)
        this.statusList.push({ label: value, val: key })
      }
    },
    handleCancel () {
      this.visible = false
    },
    getOrder () {
      this.loading = true
      this.selectedRowKeys = []
      getOrderById(this.id).then(res => {
        this.order = res.extraInfo
        this.tickets = res.extraInfo.tickets.filter(i => i.status !== 'CHANGED')
      }).finally(() => {
        this.loading = false
      })
    },
    cancelPart (item) {
      // 退单张门票或多张
      const ticketIds = item.id ? [item.id] : this.selectedRowKeys

      if (!ticketIds.length) {
        this.$message.error('请选择门票')
        return
      }

      const params = {
        id: this.order.id,
        ticketIds
      }
      const _this = this
      this.$confirm({
        content: '确定退票吗？',
        onOk () {
          _this.$set(item, 'loading', true)

          cancelPart(params).then(res => {
            _this.getOrder()
            _this.$emit('update')
          }).finally(() => {
            _this.$set(item, 'loading', false)
          })
        }
      })
    },
    returnStock (item) {
      const ticketIds = item.id ? [item.id] : this.selectedRowKeys
      if (!ticketIds.length) {
        this.$message.error('请选择门票')
        return
      }
      const params = {
        id: this.order.id,
        ticketIds
      }
      const _this = this
      this.$confirm({
        content: '确定归还库存吗？',
        onOk () {
          _this.$set(item, 'loading', true)

          returnStock(params).then(res => {
            _this.getOrder()
          }).finally(() => {
            _this.$set(item, 'loading', false)
          })
        }
      })
    },
    goUpdateStatus (record) {
      this.statusForm.id = record.order_id
      this.statusForm.ticketIds = [record.id]
      this.statusForm.status = record.status
      this.statusVisible = true
    },
    async updateStatus () {
      await updateTicketStatus(this.statusForm)
      this.$message.success('修改成功')
      this.statusVisible = false
      this.getOrder()
    },
    onSelectChange (selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    canCancelTicket (record) {
      const cancelStatus = {
        COMPLETE: 1,
        PART_USE: 1,
        WAIT_USE: 1,
        USED: 1
      }

      return !!cancelStatus[record.status] && this.canCancelOrder()
    },
    canCancelOrder () {
      const cancelOrderStatus = {
        PART_USE: 1,
        WAIT_USE: 1,
        COMPLETE: 1
      }
      return this.order && !!cancelOrderStatus[this.order.status]
    },
    canChange (ticket) {
      const canChangeStatus = {
        WAIT_USE: 1,
        PART_USE: 1
      }
      return !!canChangeStatus[ticket.status] && ticket.origin_ticket_id === 0
    },
    getCheckboxProps (record) {
      return {
        props: {
          disabled: !this.canCancelTicket(record)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.btn-wrap{
  text-align: center; padding-top: 20px;
}
</style>
