<template>
  <el-card>
    <div
      slot="header"
      class="card-title">
      <span>订单明细</span>
      <!-- 订单内显示所有景区 -->
      <div v-if="false">
        {{ currentTicket.ticketTypeScenic.map(item => item.scenic.name) }}
      </div>
      <el-link
        type="primary"
        @click="$emit('clear')">
        清空订单
      </el-link>
    </div>
    <div>
      <div class="payChannel-wrap">
        <label class="text">支付方式：</label>
        <el-radio-group
          fill="#379143"
          class="tags-btn"
          @change="$localStore.set('group_payment',$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 class="btn-wrap">
        <div>
          <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="remark"
              style="width:200px"></el-input>
          </span>
          <span class="item">图片备注：
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="showUploadImgDialog"
            >
              编辑查看
            </el-button>
          </span>
        </div>

        <el-button
          type="primary"
          class="warnBtn item"
          :disabled="value.length===0"
          @click="handleConfirm">
          确认出票
        </el-button>
      </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">折扣：<b>{{ discount }}</b> 折</span> -->
        <span class="item price">折后总价：<b>{{ finalPrice }}</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>
    </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.payDateBegin | formatDate }}
        </template>
      </el-table-column>
      <el-table-column
        prop="count"
        label="数量">
      </el-table-column>
      <el-table-column
        prop="price"
        label="单价">
      </el-table-column>
      <!-- <el-table-column
        prop="total"
        label="小计">
      </el-table-column> -->
      <el-table-column
        label="操作"
        width="140">
        <template slot-scope="scope">
          <el-button
            @click="handleDelete(scope.row)"
            type="text">
            删除
          </el-button>
          <el-button
            @click="showTouristList(scope.row)"
            type="text">
            门票列表
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <ConfirmZhaosu
      :discount="discount"
      :remark="remark"
      :tickets="tickets"
      :order-items="value"
      :form-data="formData"
      :order-price="orderPrice"
      :final-price="finalPrice"
      :total-count="totalCount"
      :pay-channel="payChannel"
      @complete="handleComplete"
      :current-ticket="currentTicket"
      ref="confirm"></ConfirmZhaosu>
    <!-- 图片备注 -->
    <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 ConfirmZhaosu from './ConfirmZhaosu'
import PrintSmallTicketCheckbox from '../common/PrintSmallTicketCheckbox'
import UploadImgList from '../common/uploadImgList'
import orderItemMixin from '../common/orderItemMixin'

export default {
  mixins: [mixin, orderItemMixin],
  props: {
    currentTicket: {
      type: Object,
      default: () => null
    },
    value: {
      type: Array,
      default: () => []
    }
  },
  components: {
    ConfirmZhaosu,
    PrintSmallTicketCheckbox,
    UploadImgList
  },
  computed: {
    // 弃用mixin里的，昭苏改到这里定制
    payChannelOptions () {
      const rawPayChannelOptions = this.$store.state.app.payChannelOptions.filter(i => i.indexOf('旅行社') < 0)
      // 若不开启昭苏天马的景点筛选支付方式，直接返回全部支付方式
      if (!this.enablePayChannelFilterInTianMa || !this.currentTicket?.ticketTypeScenic) {
        return rawPayChannelOptions
      }

      // 景点是严格匹配，支付关键词是只需要包含即可
      const scenicPaymentOptions = [
        { scenic: '天马文化园', paymentMustContain: '新疆农信B扫CII' },
        { scenic: '测试', paymentMustContain: '新疆农信B扫CII' }
        // { scenic: '天马', paymentMustContain: '支付' },
        // { scenic: '测试景区', paymentMustContain: '现金' },
        // { scenic: '上海景区', paymentMustContain: '支付' }
        // 添加其他景点和对应的支付方式
      ]

      // 通过当前票的景点进行筛选支付方式
      const scenicArr = this.currentTicket?.ticketTypeScenic.map(item => item.scenic.name)
      // 静态对象数组包含景点名称和对应的支付方式

      // 函数式实现根据景点名称返回对应的支付方式筛选关键字
      const getPaymentByScenic = (scenicName) => {
        const matchedOption = scenicPaymentOptions.find(option => option.scenic === scenicName)
        return matchedOption ? matchedOption.paymentMustContain : null
      }

      const keyArr = scenicArr.map(s => getPaymentByScenic(s)).filter(Boolean) // 去除为null的元素
      // 通过当前票的景点进行筛选支付方式
      const filterPayChannels = (rawPayChannelOptions, keyArr) => {
        return keyArr && keyArr.length
          ? rawPayChannelOptions.filter(option => keyArr.some(key => option.includes(key)))
          : rawPayChannelOptions
      }
      return filterPayChannels(rawPayChannelOptions, keyArr)
    },
    payBack () {
      if (this.actualMoney === undefined) {
        return -this.finalPrice
      } else {
        return (this.actualMoney - this.finalPrice).toFixed(2)
      }
    },
    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.original_price)
        return this.$NP.plus(init, price)
      }, 0)
    },
    finalPrice () {
      let price = this.tickets.reduce((init, item) => {
        return this.$NP.plus(init, item.discountPrice)
      }, 0)
      let original_finalPrice = this.$NP.round(price, 2)
      /* 由于加入了满减策略, 比如9元票满3减1的话, 可能出现count=3,price=9,而total=18的情况.这里作个判断,通过判断是否存在price为0的元素来判断是否满减 */
      let hasZeroPrice = this.value.some(element => element.tickets.some(ticket => ticket.price === 0)) // 是否存在price为0的元素
      if (hasZeroPrice) {
        console.log('存在price为0的元素,属于满减情况')
      } else {
        return original_finalPrice // 没有票价为0的情况,不是满减,正常返回
      }
      /* 吴江团体票等票的total系统之前没有设置，若按total可能会出问题。故下订单时，对'吴江团体票'等添加了之前没有的total属性 */
      let manJian_totalPrice = this.value.reduce((init, item) => {
        let t = item.total
        return this.$NP.plus(init, t)
      }, 0)
      console.log('满减时,订单所有票种总的票价(总价)为：' + manJian_totalPrice)
      return manJian_totalPrice
    },
    tickets () {
      return this.value.reduce((init, item) => {
        item.tickets.forEach(t => {
          t.discountPrice = this.$NP.times(item.price, this.$NP.divide(this.discount, 10))
        })
        return init.concat(item.tickets)
      }, [])
    }
  },
  data () {
    return {
      enablePayChannelFilterInTianMa: true,
      payChannel: '',
      remark: '',
      actualMoney: 0,
      formData: {},
      pictureRemarks: [{
        idKey: randomString(),
        url: '',
        remark: ''
      }],
      discount: 0,
      autoPrint: this.$localStore.get('autoPrint') || false,
      autoPrintSmallTicket: this.$localStore.get('autoPrintSmallTicket')
    }
  },
  methods: {
    // 更新图片备注列表
    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.remark = ''
      this.$localStore.get('defaultPayWay') && this.setPayWay()
      this.$parent.$parent.$refs.orderRecord.getOrderList()
    },
    setPayWay () {
      const payment = this.$localStore.get('defaultPayWay') || this.payChannelOptions[0]

      this.payChannel = this.payChannelOptions.indexOf(payment) < 0 ? this.payChannelOptions[0] : payment
    }
  },
  watch: {
    finalPrice (val) {
      this.actualMoney = val
    },
    payChannelOptions: {
      handler (val) {
        if (val.length) {
          this.setPayWay()
        }
      },
      immediate: true
    }
  },
  mounted () {
    this.payChannel = this.$localStore.get('defaultPayWay') || this.$localStore.get('group_payment') || 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>
