<template>
  <a-modal
    :visible="value"
    title="新增商品"
    @ok="handleOk"
    width="60%"
    destroyOnClose
    @cancel="handleCancel"
  >

    <a-form :form="form">
      <div class="block-title">
        景点和渠道
      </div>
      <a-form-item
        label="绑定景点"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-select
          mode="multiple"
          v-model="bindScenic"
        >
          <a-select-option
            v-for="scenic in scenicList"
            :key="scenic.id"
            :value="scenic.id"
          >
            {{ scenic.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="绑定渠道"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-select
          mode="multiple"
          v-model="bindChannel"
        >
          <a-select-option
            v-for="channel in salesChannel"
            :key="channel.id"
            :value="channel.id"
          >
            {{ channel.description }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <div class="block-title">
        基础信息
      </div>
      <a-form-item
        label="商品名称"
        v-bind="formItemLayout"
      >
        <a-input
          v-decorator="[
            'name',
            {
              rules: [{ required: true, message: '请输入' }]
            }
          ]"
        ></a-input>
      </a-form-item>
      <a-form-item
        label="原价"
        v-bind="formItemLayout"
      >
        <a-input-number
          :precision="2"
          :min="0"
          :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
          :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
          v-decorator="[
            'price_original',
            {
              initialValue:0
            }
          ]"
        />（仅供显示）
      </a-form-item>

      <a-form-item
        label="价格"
        v-bind="formItemLayout"
      >
        <a-input-number
          :precision="2"
          :min="0"
          :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
          :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
          v-decorator="[
            'price',
            {
              rules: [{ required: true, message: '请选择' }]
            }
          ]"
        />
      </a-form-item>
      <a-form-item
        label="商品分组"
        v-bind="formItemLayout"
      >
        <a-select
          style="width: 100%"
          v-decorator="[
            'goods_group_id',
            {
              rules: [{ required: true, message: '请选择' }]
            }
          ]"
        >
          <a-select-option
            v-for="(i,index) in goodsGroupList"
            :value="i.id"
            :key="index"
          >
            {{ i.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="是否是租赁商品"
        v-bind="formItemLayout"
      >
        <a-switch
          checked-children="是"
          un-checked-children="否"
          v-decorator="[
            'is_lease_goods',
            {
              valuePropName: 'checked',
              initialValue:false
            }
          ]"
        />
      </a-form-item>
      <div class="block-title">
        销售限制
      </div>

      <a-form-item
        label="售卖日期范围"
        v-bind="formItemLayout"
      >
        <a-range-picker
          v-decorator="[
            'sellDate',
            {
              initialValue:[moment(),moment().add('year',10)],
              rules: [{ required: true, message: '请选择销售日期' }]
            }
          ]"
        />
      </a-form-item>

      <a-form-item
        label="使用日期范围"
        v-bind="formItemLayout"
      >
        <a-range-picker
          v-decorator="[
            'useDate',
            {
              initialValue:[moment(),moment().add('year',10)],
              rules: [{ required: true, message: '请选择使用日期' }]
            }
          ]"
        />
      </a-form-item>

      <a-form-item
        label="可售开始时间"
        v-bind="formItemLayout"
      >
        <a-time-picker
          v-decorator="[
            `sale_time_start`,
            {
              initialValue:moment().startOf('day'),
              rules: [{ required: true, message: '请选择时间' }]
            }
          ]"
        />
      </a-form-item>

      <a-form-item
        label="可售截止时间"
        v-bind="formItemLayout"
      >
        <a-time-picker
          v-decorator="[
            `sale_time_end`,
            {
              initialValue:moment().endOf('day'),
              rules: [{ required: true, message: '请选择时间' }]
            }
          ]"
        />
      </a-form-item>
      <a-form-item
        label="最小起订数"
        v-bind="formItemLayout"
      >
        <a-input-number
          :min="0"
          v-decorator="[
            'book_min',
            {
              initialValue:1,
              rules: [{ required: true, message: '请输入' }]
            }
          ]"
        >
        </a-input-number>
      </a-form-item>

      <a-form-item
        label="最大限订数"
        v-bind="formItemLayout"
      >
        <a-input-number
          :min="0"
          v-decorator="[
            'book_max',
            {
              initialValue:100,
              rules: [{ required: true, message: '请输入' }]
            }
          ]"
        >
        </a-input-number>
      </a-form-item>

      <a-form-item
        label="可提前预定的天数"
        v-bind="formItemLayout"
      >
        <a-input-number
          :min="0"
          v-decorator="[
            'book_future_days',
            {
              initialValue:30,
              rules: [{ required: true, message: '请输入' }]
            }
          ]"
        >
        </a-input-number>
      </a-form-item>
      <a-form-item
        label="当日可订"
        v-bind="formItemLayout"
      >
        <a-switch
          checked-children="是"
          un-checked-children="否"
          v-decorator="[
            'is_book_today',
            {
              valuePropName: 'checked',
              initialValue:true
            }
          ]"
        />
      </a-form-item>
      <a-form-item
        v-if="form.getFieldValue('is_book_today')"
        label="当日可订截止时间"
        v-bind="formItemLayout"
      >
        <a-time-picker
          v-decorator="[
            `book_today_endtime`,
            {
              initialValue:moment().endOf('day'),
              rules: [{ required: true, message: '请选择结束时间' }]
            }
          ]"
        />
      </a-form-item>
      <div class="block-title">
        销售数量设置
      </div>
      <a-form-item
        label="是否限制销售数量"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-switch
          checked-children="是"
          un-checked-children="否"
          @change="formData.is_restricted_sales=$event"
          v-decorator="[
            'is_restricted_sales',
            {
              valuePropName: 'checked',
              initialValue:false
            }
          ]"
        />
      </a-form-item>

      <a-form-item
        v-if="formData.is_restricted_sales"
        label="每天可销售数量"
        v-bind="formItemLayout"
      >
        <a-input-number
          :min="0"
          v-decorator="[
            'sales_volume',
            {
              initialValue:0,
              rules: [{ required: true, message: '请输入' }]
            }
          ]"
        >
        </a-input-number> （不限制填 0）
      </a-form-item>

      <a-form-item
        v-if="formData.is_restricted_sales"
        label="总库存"
        v-bind="formItemLayout"
      >
        <a-input-number
          :min="0"
          v-decorator="[
            'total_sales_limit',
            {
              initialValue:0,
              rules: [{ required: true, message: '请输入' }]
            }
          ]"
        >
        </a-input-number> （不限制填 0）
      </a-form-item>
      <div class="block-title">
        退货设置
      </div>
      <a-form-item
        label="是否可退"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-switch
          checked-children="是"
          un-checked-children="否"
          v-decorator="[
            'is_refund',
            {
              valuePropName: 'checked',
              initialValue:true
            }
          ]"
        />
      </a-form-item>

      <template v-if="form.getFieldValue('is_refund')">
        <a-form-item
          label="提前可退天数"
          v-bind="formItemLayout"
        >
          <RefundAdvanceDay
            v-decorator="[
              'refund_advance_days',
              {
                initialValue:0,
                rules: [{ required: true, message: '请输入' }]
              }
            ]"></RefundAdvanceDay>
        </a-form-item>

        <a-form-item
          label="当日可退截止时间"
          v-bind="formItemLayout"
        >
          <RefundDayEndtime
            v-decorator="[
              `refund_today_endtime`,
              {
                initialValue:moment().endOf('day'),
                rules: [{ required: true, message: '请选择结束时间' }]
              }
            ]"
          />
        </a-form-item>
        <a-form-item
          label="退货策略"
          v-bind="formItemLayout"
        >
          <a-select
            @change="formData.refund_strategy.type=$event"
            v-decorator="[
              'refund_strategy.type',
              {
                initialValue: formData.refund_strategy.type,
                rules: [{ required: true, message: '请输入' }]
              }
            ]"
          >
            <a-select-option value="FIXED">
              固定价格
            </a-select-option>
            <a-select-option value="RATE">
              固定费率
            </a-select-option>
            <a-select-option value="TIME_RATE">
              阶梯费率
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="退货费率"
          v-if="formData.refund_strategy.type==='RATE'"
          v-bind="formItemLayout"
        >
          <a-input-number
            :precision="2"
            :min="0"
            :max="1"
            :step="0.01"
            v-decorator="[
              'refund_strategy.rate',
              {
                initialValue:formData.refund_strategy.rate,
                rules: [{ required: true, message: '请输入' }]
              }
            ]"
          />（0 表示全额退款）
        </a-form-item>

        <a-form-item
          label="退货价格"
          v-if="formData.refund_strategy.type==='FIXED'"
          v-bind="formItemLayout"
        >
          <a-input-number
            :precision="2"
            :min="0"
            :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
            v-decorator="[
              'refund_strategy.price',
              {
                initialValue:formData.refund_strategy.price,
                rules: [{ required: true, message: '请输入' }]
              }
            ]"
          />
        </a-form-item>
        <br>
        <a-form-item
          label="阶梯费率"
          v-if="formData.refund_strategy.type==='TIME_RATE'"
          v-bind="formItemLayout"
        >
          <a-button
            class="addBtn"
            type="primary"
            icon="plus"
            @click="handleAdd"
            size="small"
          >新增</a-button>
          <br>
          <ul class="priceList">
            <li
              v-for="(item,index) in timeRateList"
              :key="index"
            >

              <template>
                <div style="display:flex;margin-bottom:10px;width:400px">
                  <span style="white-space:nowrap">时间：</span>
                  <a-select v-model="item.timeEffect" slot="prepend" placeholder="请选择">
                    <a-select-option value="+">开场前</a-select-option>
                    <a-select-option value="-">开场后</a-select-option>
                  </a-select>
                  <a-input-number
                    style="width:100%"
                    v-model="item.timeNum"
                    controls-position="right"
                    :min="0"
                    :max="999"></a-input-number>
                  <a-select v-model="item.timeType" slot="prepend" placeholder="请选择">
                    <a-select-option value="minute">分钟</a-select-option>
                    <a-select-option value="hour">小时</a-select-option>
                    <a-select-option value="day">天</a-select-option>
                    <a-select-option value="week">周</a-select-option>
                    <a-select-option value="month">月</a-select-option>
                  </a-select>
                  <span style="white-space:nowrap" v-if="item.timeEffect">{{ item.timeEffect ==='-'?'之后':'以内' }}</span>
                  <span style="white-space:nowrap;margin-left:20px">费率：</span>
                  <a-input-number
                    style="width:100%;"
                    :precision="2"
                    :min="0"
                    :max="1"
                    :step="0.01"
                    v-model="item.rate"
                  />
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>删除</span>
                    </template>

                    <a-popconfirm
                      title="确定删除吗？"
                      @confirm="handleDelete(index)"
                      ok-text="是"
                      cancel-text="否"
                    >
                      <a-button
                        type="danger"
                        icon="close"
                        size="small"
                        style="width:100px"
                      ></a-button>
                    </a-popconfirm>
                  </a-tooltip>
                </div>
              </template>
            </li>
          </ul>
        </a-form-item>
      </template>
      <div class="block-title">
        商品详情介绍 <span style="font-size:13px;color:red"> （上传图片后，请将图片宽高设置为100%）</span>
      </div>
      <a-form-item
        label="购买须知"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-input
          v-show="false"
          v-decorator="[
            'purchase_notice'
          ]"
        ></a-input>

        <Editor ref="editor" v-model="purchase_content"></Editor>
      </a-form-item>
      <a-form-item
        label="使用须知"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-input
          v-show="false"
          v-decorator="[
            'description'
          ]"
        ></a-input>

        <Editor ref="editor" v-model="description_content"></Editor>
      </a-form-item>
      <a-form-item
        label="退改须知"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-input
          v-show="false"
          v-decorator="[
            'withdrawal_notice'
          ]"
        ></a-input>

        <Editor ref="editor" v-model="withdrawal_content"></Editor>
      </a-form-item>
      <a-form-item
        label="其他须知"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-input
          v-show="false"
          v-decorator="[
            'other_notice'
          ]"
        ></a-input>

        <Editor ref="editor" v-model="other_content"></Editor>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { addTicketType, setTicketScenic, setTicketChannel } from '@/api/ticketSetting/ticket'
import goodsMixin from './goodsMixin.js'
import Editor from '@/components/Editor/index.vue'
export default {
  mixins: [goodsMixin],
  data () {
    return {
      bindScenic: [],
      greyValue: undefined,
      greylistIdentities: [],
      limitIdentities: [],
      blacklistIdentities: [],
      bindChannel: [],
      purchase_content: '',
      description_content: '',
      withdrawal_content: '',
      other_content: '',
      timeRateList: [
        { timeEffect: '+',
          timeNum: '30',
          timeType: 'minute',
          rate: 0
        }
      ],
      formData: {
        is_restricted_sales: 0,
        is_order_limit: 0,
        refund_strategy: {
          type: 'RATE',
          pirce: 0,
          rate: 0,
          contents: []
        }

      }
    }
  },
  components: {
    Editor
  },
  props: {
    scenicList: {
      type: Array,
      default: () => []
    },
    salesChannel: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    goodsGroupList () {
      return this.$store.state.app.goodsGroupList
    }
  },
  methods: {
    // 添加阶梯费率弹窗
    handleAdd () {
      let lastTimeRate
      if (this.timeRateList.length > 0) {
        lastTimeRate = JSON.parse(JSON.stringify(this.timeRateList[this.timeRateList.length - 1]))
      } else {
        lastTimeRate = { seconds: '', rate: '' }
      }
      this.timeRateList.push({
        ...lastTimeRate
      })
    },
    handleDelete (index) {
      this.timeRateList.splice(index, 1)
    },
    handleScenicChange () {
      const params = {
        scenics: this.bindScenic.length > 0 ? this.bindScenic : null
      }
      setTicketScenic(this.id, params).then(res => {
        this.$message.success('绑定景点成功')
      })
    },
    handleChannelChange () {
      const params = {
        channels: this.bindChannel.length > 0 ? this.bindChannel : null
      }
      setTicketChannel(this.id, params).then(res => {
        this.$message.success('绑定渠道成功')
      })
    },
    handleOk (e) {
      e.preventDefault()
      this.form.validateFieldsAndScroll((err, values) => {
        console.log('values', values)
        if (!err) {
          if (values.book_max < values.book_min) {
            this.$message.error('最小起订数不能大于最大限订数')
            return
          }
          if (values.refund_strategy && values.refund_strategy.type === 'TIME_RATE') {
            values.refund_strategy.contents = this.timeRateList.map(item => {
              const seconds = item.timeEffect + item.timeNum * this.calculateTime(item.timeType)
              const rate = item.rate
              return {
                seconds,
                rate
              }
            })
          }
          const params = this.formatParams(values)
          params.pictures = values.pictures ? values.pictures.fileList.map(item => {
            const info = item.response
            return {
              size: info.size - 0,
              url: info.link
            }
          }) : []
          params.purchase_notice = this.purchase_content
          params.description = this.description_content
          params.withdrawal_notice = this.withdrawal_content
          params.other_notice = this.other_content
          addTicketType(params).then(res => {
            this.$message.success('添加成功')
            this.id = res.extraInfo
            this.handleScenicChange()
            this.handleChannelChange()
            this.handleCancel()
            setTimeout(() => {
              this.$emit('update')
            }, 500)
          })
        }
      })
    },
    calculateTime (e) {
      switch (e) {
        case 'minute':
          return 60
        case 'hour':
          return 60 * 60
        case 'day':
          return 60 * 60 * 24
        case 'week':
          return 60 * 60 * 24 * 7
        case 'month':
          return 60 * 60 * 24 * 30
        default:
          return 0
      }
    }
  }
}
</script>

<style scoped>
.ant-form-item{
  width: 50%; display: inline-block;
}
.ant-alert{
  margin-bottom: 20px;
}
</style>
