<template>
  <el-dialog
    :visible.sync="visible"
    title="价格方案"
    width="780px"
    append-to-body
    @close="handleCancel"
  >
    <div
      class="wrap"
      v-loading="loading">
      <div>
        <div class="block-title">
          日期类型
        </div>
        <!-- <el-input
          placeholder="请输入内容"
          v-model="basic_price"
          style="width: 160px">
        </el-input> -->
        <el-select
          v-model="form.dateType">
          <el-option
            v-for="item in dateTypes"
            :key="item.value"
            :label="item.key"
            :value="item.value"></el-option>
        </el-select>
        <template v-if="form.dateType==='DATE_NOT_REQUIRED'">
          卖价：
          <el-input-number
            label="卖价"
            placeholder="卖价"
            class="priceInput"
            :precision="2"
            v-model="form.prices[0].salePrice"
          />
          结算价：
          <el-input-number
            placeholder="结算价"
            class="priceInput"
            :precision="2"
            v-model="form.prices[0].costPrice"
          />
        </template>
      </div>
      <div v-if="form.dateType==='DATE_REQUIRED'">
        <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="priceList">
          <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
              placeholder="卖价"
              class="priceInput"
              :controls="false"
              :precision="2"
              v-model="item.salePrice"
            />
            <el-input-number
              placeholder="结算价"
              class="priceInput"
              :controls="false"
              :precision="2"
              v-model="item.costPrice"
            />
            <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
          :loading="confirmLoading"
          size="small"
          type="primary"
          @click="handleOk">
          保 存
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import moment from 'moment'

import { getPricePlan, syncDatePriceModify } from '@/api/otaTicketSale'

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

export default {
  data () {
    return {
      dateTypes:
        [{ key: '指定日期', value: 'DATE_REQUIRED' },
          {key: '无需指定日期', value: 'DATE_NOT_REQUIRED'}
        ],
      stragegiesMap,
      pricecode: '',
      loading: false,
      visible: false,
      confirmLoading: false,
      basic_price: '',
      priceList: [],
      form: {
        dateType: 'DATE_NOT_REQUIRED',
        prices: [
          {
            costPrice: 0.00,
            salePrice: 0.00
          }
        ]
      }
    }
  },
  methods: {
    moment,
    show (id) {
      Object.assign(this.$data, this.$options.data())
      this.visible = true
      this.pricecode = id
      this.getPricePlan()
    },
    getPricePlan (e) {
      let params = { 'pricecode': this.pricecode }
      this.loading = true
      getPricePlan(params).then(res => {
        try {
          let basicPrice = res.find(v => v.type === 'basic')
          basicPrice && (this.basic_price = basicPrice.price_content)

          let priceList = res.find(v => v.type === 'period')
          priceList && (priceList = JSON.parse(priceList.price_content))
          priceList && priceList.forEach(item => {
            item.dateRange = [new Date(item.start), new Date(item.end)]
          })
          this.priceList = priceList || []
        } catch (e) {
          console.log(e)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    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
      })
    },
    setDate () {
      const dateList = []
      console.log('%c [ this.priceList ]-220', 'font-size:13px; background:pink; color:#bf2c9f;', this.priceList)

      this.priceList.forEach(item => {
        let startDate = item.start
        console.log('%c [ startDate ]-223', 'font-size:13px; background:pink; color:#bf2c9f;', startDate)
        let period = moment(item.end, 'YYYY-MM-DD').diff(item.start, 'days') + 1
        console.log('%c [ period ]-224', 'font-size:13px; background:pink; color:#bf2c9f;', period)
        for (let i = 0; i < period; i++) {
          dateList.push({
            date: moment(startDate, 'YYYY-MM-DD').add(i, 'days').format('YYYY-MM-DD'),
            costPrice: item.costPrice,
            salePrice: item.salePrice
          })
        }
      })
      this.form.prices = dateList
      console.log('%c [ dateList ]-233', 'font-size:13px; background:pink; color:#bf2c9f;', dateList)
    },
    handleOk () {
      this.confirmLoading = true
      if (this.form.dateType === 'DATE_REQUIRED') {
        this.setDate()
      }
      // if (this.form.dateType === 'DATE_NOT_REQUIRED') {
      //   this.form.prices[0].costPrice = this.form.prices[0].costPrice
      //   this.form.prices[0].salePrice = this.form.prices[0].salePrice
      // }
      // let params = {}
      // params = JSON.parse(JSON.stringify(this.form))
      this.form.supplierOptionId = this.pricecode + ''
      console.log('%c [ this.form ]-248', 'font-size:13px; background:pink; color:#bf2c9f;', this.form)
      syncDatePriceModify(this.form).then(res => {
        this.$message.success('设置成功')
        this.handleCancel()
      }).finally(() => {
        this.confirmLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrap{
  padding: 20px;
}
.btn-wrap{
  text-align: right; margin-top: 20px;
}
.priceList {
  font-variant: tabular-nums;
  li {
    margin-bottom: 15px;
  }
  .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: 100px; 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>
