<!-- 初始：8.x分支中1.4.204版本的OrderInfo.vue -->
<template>
  <el-card>
    <div
      slot="header"
      class="card-title"
      style="display: flex">
      <div class="top-title">订单明细</div>
      <!-- <el-button
        type="text"
        @click="distinctOrder">
        优惠/说明
      </el-button> -->
    </div>
    <div>
      <div class="is-flex">
        <div class="amount-info">
          <span class="item">实付金额：
            <el-input-number
              :min="0"
              :precision="2"
              :controls="false"
              v-model.number="actualMoney"></el-input-number>
          </span>
          <span class="item">下单备注：
            <el-input
              clearable
              v-model="createOrderRemark"
              style="width:200px"></el-input>
          </span>
        </div>
        <div class="pay-channel-wrap">
          <label class="text">支付方式：</label>
          <el-radio-group
            fill="#379143"
            class="tags-btn"
            @change="$localStore.set('retailPayment',$event)"
            v-model="payChannel"
            border>
            <el-radio
              border
              v-for="val in payChannelOptions"
              :key="val"
              :value="val"
              :label="val"></el-radio>
          </el-radio-group>
        </div>
      </div>

      <div class="btn-wrap">
        <span class="item price">总数：<b>{{ totalCount }}</b> 张</span>
        <span class="item price">总价：<b>{{ orderPrice }}</b> 元</span>
        <span class="item price">{{ payBack>0?'找零':'还需支付' }}：<b>{{ Math.abs(payBack) }}</b> 元</span>
        <span class="item">
          <PrintSmallTicketCheckbox v-model="autoPrintSmallTicket"></PrintSmallTicketCheckbox>
          <el-checkbox
            v-model="autoPrint"
            style="margin:10px"
            @change="handleAutoPrintChange"
          >
            自动打印
          </el-checkbox>
        </span>
        <div class="opt-btns">
          <el-button
            @click="$emit('clear')">
            清空订单
          </el-button>
          <el-button
            type="primary"
            class="danger-btn item"
            :disabled="value.length === 0 || !payChannel"
            @click="handleConfirm">
            确认出票
          </el-button>
        </div>
      </div>
    </div>

    <el-table
      border
      :data="value">
      <el-table-column
        prop="ticketName"
        label="票种名称"
        width="180">
      </el-table-column>
      <el-table-column label="游玩日期">
        <template slot-scope="scope">
          {{ scope.row.playDateBegin }}
        </template>
      </el-table-column>
      <el-table-column
        prop="count"
        label="数量">
      </el-table-column>
      <el-table-column
        prop="price"
        label="单价">
        <template slot-scope="scope">
          <span v-if="scope.row.discountPrice">
            {{ scope.row.originalPrice + scope.row.discountPrice }} <s style="color: #f56c6c;">{{ scope.row.originalPrice }}</s>
          </span>
          <span v-else>
            {{ scope.row.price }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="total"
        label="小计">
        <template slot-scope="scope">
          <span v-if="scope.row.discountPrice">
            {{ scope.row.total + scope.row.discountPrice * scope.row.tickets.length }} <s style="color: #f56c6c;">{{ scope.row.total }}</s>
          </span>
          <span v-else>
            {{ scope.row.total }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="160">
        <template slot-scope="scope">
          <el-button
            @click="showTouristList(scope.row)"
            type="text">
            门票列表
          </el-button>
          <el-button
            @click="distinctTicket(scope.row)"
            type="text">
            改价
          </el-button>
          <el-button
            @click="handleDelete(scope.row)"
            type="text">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 设置改价说明的弹框 -->
    <el-dialog
      title="改价/说明"
      :visible.sync="showDiscountDialog"
      width="400px"
      @close="showDiscountDialog = false"
    >
      <el-form label-width="80px">
        <el-form-item label="票单价">
          <span>{{ discountInfo.ticketPrice }}</span>
        </el-form-item>
        <el-form-item label="改价金额">
          <el-input-number
            v-model.number="discountInfo.discountPrice"
            :precision="2"
            style="width: 200px"
          ></el-input-number>
          <el-tag type="warning" style="margin-top: 5px;">负数表示减价，正数表示加价</el-tag>
        </el-form-item>
        <el-form-item label="改价说明">
          <el-input
            type="textarea"
            v-model="discountInfo.discountDescription"
            :rows="3"
            placeholder="请输入说明"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showDiscountDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmDistinct">确定</el-button>
      </span>
    </el-dialog>

    <Confirm
      :create-order-remark="createOrderRemark"
      :tickets="tickets"
      :order-items="value"
      :form-data="formData"
      :order-price="orderPrice"
      :total-count="totalCount"
      :pay-channel="payChannel"
      :current-ticket="currentTicket"
      @complete="handleComplete"
      ref="confirm"></Confirm>
    <!-- 图片备注 -->
    <UploadImgList
      :picture-remarks="pictureRemarks"
      :update-remarks="updateRemarks"
      ref="uploadImgDialog">
    </UploadImgList>

    <!-- 游客列表 -->
    <TouristList
      :check-face="formData.checkWay === 4"
      :check-id="formData.checkWay === 3"
      :check-ticket-no="formData.checkWay === 5"
      :tourist-list="touristList"
      :update-tourist="updateTourist"
      ref="touristList"></TouristList>
  </el-card>
</template>

<script>
import mixin from './mixin'
import { randomString } from '@/utils'
import Confirm from './Confirm'
import PrintSmallTicketCheckbox from '../common/PrintSmallTicketCheckbox'
import UploadImgList from '../common/uploadImgList'
import orderItemMixin from '../common/orderItemMixin'

export default {
  mixins: [mixin, orderItemMixin],
  props: {
    value: {
      type: Array,
      default: () => []
    },
    currentTicket: {
      type: Object,
      default: () => null
    }
  },
  components: {
    Confirm,
    PrintSmallTicketCheckbox,
    UploadImgList
  },
  computed: {
    payBack () {
      if (this.actualMoney === undefined) {
        return -this.orderPrice
      } else {
        return this.$NP.minus(this.actualMoney, this.orderPrice)
      }
    },
    totalCount () {
      return this.value.reduce((init, item) => {
        return init + item.count
      }, 0)
    },
    orderPrice () {
      return this.value.reduce((init, item) => {
        let price = this.$NP.times(item.count, item.originalPrice)
        return this.$NP.plus(init, price, item.discountPrice ? item.discountPrice * item.tickets.length : 0)
      }, 0)
    },
    tickets () {
      return this.value.reduce((init, item) => {
        return init.concat(item.tickets)
      }, [])
    }
  },
  data () {
    return {
      payChannel: '',
      actualMoney: 0,
      createOrderRemark: '',
      formData: {},
      pictureRemarks: [{
        idKey: randomString(),
        url: '',
        remark: ''
      }],
      autoPrint: this.$localStore.get('autoPrint'),
      autoPrintSmallTicket: this.$localStore.get('autoPrintSmallTicket'),
      showDiscountDialog: false,
      currentItem: null,
      discountInfo: {
        ticketPrice: 0,
        discountPrice: 0,
        discountDescription: ''
      }
    }
  },
  methods: {
    distinctOrder () {
      if (this.tickets.length === 0) {
        this.$message.warning('请先添加订单项')
        return
      }
      this.showDiscountDialog = true
    },
    distinctTicket (item) {
      this.currentItem = item
      this.discountInfo.ticketPrice = item.currentTicket.price
      this.discountInfo.discountPrice = item.discountPrice || 0
      this.discountInfo.discountDescription = item.discountDescription || ''
      this.showDiscountDialog = true
    },
    confirmDistinct () {
      const { discountPrice, discountDescription } = this.discountInfo

      this.$set(this.currentItem, 'discountPrice', discountPrice)
      this.$set(this.currentItem, 'discountDescription', discountDescription)
      this.currentItem.tickets.forEach(ticket => {
        this.$set(ticket, 'discountPrice', discountPrice)
        this.$set(ticket, 'price', ticket.originalPrice + discountPrice)
        this.$set(ticket, 'discountDescription', discountDescription)
      })
      this.showDiscountDialog = false
    },
    // 更新图片备注列表
    updateRemarks (data) {
      this.pictureRemarks = data
    },
    // 显示图片备注弹窗
    showUploadImgDialog () {
      this.$refs.uploadImgDialog.show()
    },
    changePayChannel (n) {
      if (this.confirmVisible) return

      let i = this.payChannelOptions.findIndex(channel => channel === this.payChannel)
      let l = this.payChannelOptions.length
      let j = (i - n + l) % l
      this.payChannel = this.payChannelOptions[j]
    },
    PageUp () {
      this.changePayChannel(1)
    },
    PageDown () {
      this.changePayChannel(-1)
    },
    handleDelete (item) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        const idx = this.value.findIndex(i => i.keyId === item.keyId)
        this.value.splice(idx, 1)
      })
    },
    handleAutoPrintChange (val) {
      this.$localStore.set('autoPrint', val)
    },
    handleComplete () {
      this.$emit('clear')
      this.createOrderRemark = ''
      this.$localStore.get('defaultPayWay') && this.setPayWay()
      try {
        this.$parent.$parent.$refs.recentOrder && this.$parent.$parent.$refs.recentOrder.getOrderList()
      } catch (e) {
        console.warn('刷新最近订单失败', e)
      }
    },
    setPayWay () {
      const payment = this.$localStore.get('defaultPayWay') || this.payChannelOptions[0]

      this.payChannel = this.payChannelOptions.indexOf(payment) < 0 ? this.payChannelOptions[0] : payment
    }
  },
  watch: {
    orderPrice (val) {
      this.actualMoney = val
    },
    payChannelOptions: {
      handler (val) {
        if (val.length) {
          this.setPayWay()
        }
      },
      immediate: true
    }
  },
  mounted () {
    this.payChannel = this.$localStore.get('defaultPayWay') || this.$localStore.get('retailPayment') || this.payChannelOptions[0]
  }
}
</script>

<style lang="scss" scoped>
.item {
  margin-left: 20px;
}

.price-info {
  padding: 10px 0;
  text-align: right;
  background: #fff;
}

.btn-wrap {
  display: flex;
  width: 100%;
  margin-bottom: 10px;
  font-size: 14px;
  justify-content: space-between;
  align-items: center;

  .el-input {
    display: inline-block;
    width: 100px;
  }
}
</style>
