<template>
  <el-dialog
    :visible.sync="visible"
    title="价格方案"
    width="980px"
    append-to-body
    @close="handleCancel"
  >
    <div
      class="wrap">
      <el-alert type="warning" :closable="false" title="当前价格优先级:特定日期 > 周期性规则 > 日常价格" />
      <!-- <div v-loading="loading">
        <div class="block-title">
          基础价格
        </div>
        <el-input
          placeholder="请输入内容"
          v-model="basicPrice"
          style="width: 160px">
        </el-input>
      </div> -->
      <div v-loading="weekLoading">
        <div class="block-title">
          周价格
        </div>
        <div
          class="weekWrap"
          style="margin-bottom:30px"
        >
          <div
            class="weekItem"
            v-for="(item,index) in weekDayPriceList"
            :key="index"
          >
            <label>{{ item.label }}</label>
            <el-input
              oninput="value=value.replace(/[^\d.]/g,'')"
              class="priceInput"
              v-model="item.value"
            />
            <el-switch
              style="margin-top: 10px"
              v-model="item.isSale"
              :inactive-value="0"
              :active-value="1"
              active-text="在售"
              inactive-text="禁售">
            </el-switch>
          </div>
        </div>
      </div>

      <div v-loading="loading">
        <div class="block-title">
          日期段价格（时间不可重叠）
          <el-button
            class="addBtn"
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
            size="small"
          >
            新增
          </el-button>
        </div>
        <div
          class="noData"
          v-if="priceList.length===0"
        >
          暂无
        </div>
        <ul class="price-list">
          <li
            v-for="(item,index) in priceList"
            :key="index"
          >
            <el-date-picker
              class="calendarPicker"
              type="daterange"
              v-model="item.dateRange"
              @change="handleChange($event,item)"
            />
            <el-input-number
              class="priceInput"
              :controls="false"
              v-model="item.price"
            />

            <el-switch
              style="margin-top: 10px"
              v-model="item.isSale"
              :inactive-value="0"
              :active-value="1"
              active-text="在售"
              inactive-text="禁售">
            </el-switch>

            <el-button
              type="danger"
              icon="el-icon-close"
              size="small"
              @click="handleDelete(index)"
            ></el-button>
          </li>
        </ul>
      </div>
      <div
        class="btn-wrap"
        slot="footer">
        <el-button
          size="small"
          @click="visible=false">
          取 消
        </el-button>
        <el-button
          size="small"
          type="primary"
          @click="handleOk">
          保 存
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import moment from 'moment'

import { getPricePlan, addTicketPricePlan } from '@/api/ticketPricePlan'

const week = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
const weekMap = {
  '周日': 1,
  '周一': 2,
  '周二': 3,
  '周三': 4,
  '周四': 5,
  '周五': 6,
  '周六': 7
}

const stragegiesMap = {
  PERIOD: '日期段价格',
  WEEKDAY: '周价格',
  BASIC: '日常价格'
}

export default {
  data () {
    return {
      week,
      stragegiesMap,
      ticketTypeId: '',
      loading: false,
      visible: false,
      weekLoading: false,
      confirmLoading: false,
      basicPrice: '',
      ticketPricePlanList: [],
      priceList: [],
      weekDayPriceList: [],
      ticketInfo: {}
    }
  },
  methods: {
    show (ticket) {
      this.ticketInfo = ticket
      this.weekDayPriceList = week.map((val, index) => {
        return {
          label: val,
          value: null,
          isSale: 1
        }
      })
      getPricePlan({
        ticketTypeId: ticket.id,
        pageSize: 10,
        pageNum: 0
      }).then(res => {
        if (res.code === '200') {
          const list = res.data || []

          list.filter(l => l.weekdays).forEach(l => {
            this.weekDayPriceList.forEach(w => {
              if (l.weekdays.includes(weekMap[w.label])) {
                w.value = l.price
              }
            })
          })

          this.priceList = list.filter(l => !l.weekdays).map(l => {
            const { startDate, endDate, specificDate, price, isSale } = l
            return {
              dateRange: [moment(specificDate || startDate), moment(specificDate || endDate)],
              price,
              isSale
            }
          }).reverse()
        }
      })
      this.visible = true
      this.ticketTypeId = ticket.id
    },
    handleCancel () {
      this.visible = false
    },
    handleChange (event, item) {
      this.$set(item, 'start', moment(event[0]).format('YYYY-MM-DD'))
      this.$set(item, 'end', moment(event[1]).format('YYYY-MM-DD'))
    },
    handleDelete (index) {
      this.$confirm('确定删除吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.priceList.splice(index, 1)
      }).catch(() => {})
    },
    handleAdd () {
      let lastPrice

      if (this.priceList.length > 0) {
        lastPrice = JSON.parse(JSON.stringify(this.priceList[this.priceList.length - 1]))
      } else {
        lastPrice = { start: new Date(), end: new Date(), price: '' }
      }

      lastPrice.dateRange = [moment(lastPrice.start), moment(lastPrice.end)]

      this.priceList.push({
        ...lastPrice,
        isEdit: true,
        isSale: 1
      })
    },
    handleOk () {
      this.confirmLoading = true
      const { id } = this.ticketInfo
      const planList = []
      const weekPriceList = []
      let priority = 0
      const wpList = this.weekDayPriceList.filter(wp => wp.value !== null && wp.value !== undefined)
      wpList.forEach(wp => {
        const hasPrice = weekPriceList.find(item => wp.value === item.price && wp.isSale === item.isSale)

        if (hasPrice) {
          hasPrice.weekdays += `,${weekMap[wp.label]}`
        } else {
          weekPriceList.push({
            ticketTypeId: id,
            isSale: wp.isSale,
            priority,
            price: wp.value,
            weekdays: weekMap[wp.label]
          })
        }
      })
      planList.push(...weekPriceList)

      this.priceList.forEach(item => {
        priority--
        const { start, end, price, isSale } = item
        const startDate = moment(start).format('YYYY-MM-DD')
        const endDate = moment(end).format('YYYY-MM-DD')

        if (startDate === endDate) {
          planList.push({
            ticketTypeId: id,
            isSale,
            priority,
            price,
            specificDate: startDate
          })
        } else {
          planList.push({
            ticketTypeId: id,
            isSale,
            priority,
            price,
            startDate,
            endDate
          })
        }
      })

      addTicketPricePlan(planList).then(res => {
        if (res.code === '200') {
          this.$message.success('设置成功')
          this.handleCancel()
        }
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrap{
  padding: 20px;
}
.btn-wrap{
  text-align: right; margin-top: 20px;
}
.price-list {
  font-variant: tabular-nums;
  li {
    margin-bottom: 15px;
    display: flex;
    justify-content: space-around;
  }
  .calendarTxt {
    display: inline-block; width: 332px; box-sizing: border-box; padding-right: 30px;margin-right: 20px;text-align: center;
    span {
      display: inline-block; width: 135px;
    }
  }
  .priceTxt {
    display: inline-block; width: 200px; box-sizing: border-box; padding-left: 10px;margin-right: 20px;
    span {
      margin-right: 5px;
    }
  }
  .calendarPicker {
    margin-right: 20px;
  }
  .priceInput {
    display: inline-block; width: 200px; margin-right: 20px;
  }
}

.weekWrap {
  display: flex; justify-content: space-between;
  .weekItem{
    label{
      display: block; text-align: center; margin-bottom: 5px; font-weight: bold;
    }
  }
  .weekItem + .weekItem {
    margin-left: 10px;
  }
  .priceTxt{
    width: 88px; padding: 0 11px; display: inline-block;
    i{
      font-style: normal;
    }
  }
}
.addBtn {
  float: right; margin-bottom: 5px;
}
.noData {padding: 10px;
  text-align: center; border: 1px dashed #ddd;
}

</style>
