<template>
  <div class="subPage flex-h">
    <div class="img">
      <img v-if="templateList.length" :src="templateList[templateActiveIndex].ModelLargeImgUrl" width="100%" alt="">
    </div>
    <div class="flex-item">
      <h1>基本信息</h1>
      <form class="mainForm">
          <div>
            <ul>
              <li class="flex-h">
                <span>案场：<em>*</em></span>
                <div class="flex-item">
                  <div style="width:50%">
                    <el-select :disabled="editOff || isread" v-model="CaseId" placeholder="请选择案场">
                      <el-option
                        v-for="item in cases"
                        :key="item.CaseId"
                        :label="item.CaseName"
                        :value="item.CaseId">
                      </el-option>
                    </el-select>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>活动名称：<em>*</em></span>
                <div class="flex-item">
                  <div style="width:50%">
                    <el-input
                      :disabled="isread"
                      placeholder="请输入活动名称"
                      v-model="postData.FlashBuyName"
                      clearable>
                    </el-input>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>活动主图：<em>*</em></span>
                <div class="flex-item">
                  <div>
                    <el-upload
                      class="avatar-uploader"
                      action='string'
                      :before-upload="toolClass.beforeUpload"
                      :http-request="toolClass.upload"
                      :show-file-list="false"
                      :on-success="handleMainImgSuccess">
                      <img v-if="postData.ActivityMainImg" :src="postData.ActivityMainImg" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>活动名额：<em>*</em></span>
                <div class="flex-item">
                  <div style="width:50%">
                    <el-input
                      :disabled="editOff || isread"
                      placeholder="请输入活动名额"
                      v-model="postData.FlashBuyMaxAttendant"
                      clearable>
                    </el-input>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>活动模板：<em>*</em></span>
                <div class="flex-item">
                  <div>
                    <div class="templateItem" v-for="(item,index) in templateList" :key="index">
                      <a :class="{'active': templateActiveIndex === index}" @click="cutTemplate(index)">
                        <img :src="item.ModelImgUrl" style="width:100%;height:100%;object-fit: contain;">
                      </a>
                    </div>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>活动时间：<em>*</em></span>
                <div class="flex-item">
                  <div>
                    <el-date-picker
                      :disabled="editOff || isread"
                      value-format="yyyy-MM-ddTHH:mm:ss+08:00"
                      v-model="postData.StartDate"
                      type="datetime"
                      placeholder="选择开始日期">
                    </el-date-picker>
                    <span>至</span>
                    <el-date-picker
                      :disabled="editOff || isread"
                      value-format="yyyy-MM-ddTHH:mm:ss+08:00"
                      v-model="postData.EndDate"
                      type="datetime"
                      placeholder="选择截止日期">
                    </el-date-picker>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>活动说明：<em>*</em></span>
                <div class="flex-item">
                  <div>
                    <quill-editor
                      :disabled="isread"
                      v-model="postData.FlashBuyInfo"
                      ref="myQuillEditor"
                      :options="editorOption">
                    </quill-editor>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>分享标题：<em>*</em></span>
                <div class="flex-item">
                  <div style="width:50%">
                    <el-input
                      :disabled="isread"
                      placeholder="请输入分享标题"
                      v-model="postData.ActivityTitle"
                      clearable>
                    </el-input>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>分享图片：<em>*</em></span>
                <div class="flex-item">
                  <div>
                    <el-upload
                      class="avatar-uploader"
                      action='string'
                      :before-upload="toolClass.beforeUpload"
                      :http-request="toolClass.upload"
                      :show-file-list="false"
                      :on-success="handleShareImgSuccess">
                      <img v-if="postData.ShareImg" :src="postData.ShareImg" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>分享文案：<em>*</em></span>
                <div class="flex-item">
                  <div style="width:50%">
                    <el-input
                      :disabled="isread"
                      placeholder="请输入分享文案"
                      v-model="postData.ShareContent"
                      clearable>
                    </el-input>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>参与类型：<em>*</em></span>
                <div class="flex-item">
                  <div>
                    <el-radio :disabled="editOff || isread" v-model="postData.AttendantType" label="no">不限</el-radio>
                    <el-radio :disabled="editOff || isread" v-model="postData.AttendantType" label="newuser">新用户</el-radio>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>核销时间：<em>*</em></span>
                <div class="flex-item">
                  <div class="flex-h" style="width: 100%;align-item: center;">
                    <el-radio :disabled="editOff || isread" v-model="postData.ValidateType" label="days" style="margin-right: 5px;"><em style="color: transparent;display:none;">1</em></el-radio>
                    <span>领取后</span>
                    <div style="width: 100px;display: inline-block;">
                      <el-input
                        :disabled="editOff || isread"
                        placeholder=""
                        v-model="postData.ValidateDays"
                        clearable>
                      </el-input>
                    </div>
                    <span>天内有效</span>
                  </div>
                  <div class="flex-h" style="width: 100%;align-item: center;margin-top: 10px;">
                    <el-radio :disabled="editOff || isread" v-model="postData.ValidateType" label="date" style="margin-right: 5px;"><em style="color: transparent;display:none;">2</em></el-radio>
                    <span>有效期</span>
                    <div style="display: inline-block;">
                      <el-date-picker
                        :disabled="editOff || isread"
                        value-format="yyyy-MM-ddT00:00:00+08:00"
                        v-model="postData.ValidateStart"
                        type="date"
                        placeholder="选择开始日期">
                      </el-date-picker>
                      <span>至</span>
                      <el-date-picker
                        :disabled="editOff || isread"
                        value-format="yyyy-MM-ddT23:59:59+08:00"
                        v-model="postData.ValidateEnd"
                        type="date"
                        placeholder="选择截止日期">
                      </el-date-picker>
                    </div>
                  </div>
                </div>
              </li>
              <li>
                <el-button
                  :disabled="isread"
                  size="mini"
                  type="primary"
                  @click="submitFlashbuy">保存</el-button>
                <el-button
                  size="mini"
                  type="danger" @click="reback">取消</el-button>
              </li>
            </ul>
          </div>
        </form>
    </div>
  </div>
</template>
<script>
import { quillEditor } from 'vue-quill-editor'
import uploadImage from 'quill-plugin-image'
import { mapState, createNamespacedHelpers } from 'vuex'
const { mapActions: mapActivityFlashbuyActions } = createNamespacedHelpers('activityFlashbuy')
export default {
  data () {
    return {
      isread: false,
      editOff: false,
      templateActiveIndex: 0, // 当前选择模板索引值
      templateList: [], // 模板列表
      postData: {
        CaseId: '', // 案场id
        FlashBuyName: '', // 活动名称
        FlashBuyMaxAttendant: '', // 活动名额
        ModelId: '', // 模板id
        StartDate: '', // 活动开始日期
        EndDate: '', // 活动截止日期
        FlashBuyInfo: '', // 活动说明
        AttendantType: 'no', // 参与类型
        ValidateDays: '', // 领取后有效天数
        ValidateStart: '', // 有效期开始时间
        ValidateEnd: '', // 有效期截止时间
        ValidateType: 'days', // 核销类型
        FlashBuyStatus: 'inactive', // 活动状态

        ActivityMainImg: '',
        ShareImg: '',
        ActivityTitle: '',
        ShareContent: '',
      },
      editorOption: {
      },
    }
  },
  components: {
    quillEditor,
  },
  computed: {
    ...mapState({
      cases: x => x.app.cases.list,
      defaultCaseId: x => x.app.cases.default
    }),
    CaseId: {
      get () {
        return this.postData.CaseId || this.defaultCaseId
      },
      set (val) {
        this.postData.CaseId = val
      }
    }
  },
  mounted () {
    uploadImage(this.$refs.myQuillEditor.quill, file => {
      return this.toolClass.upload({ file }).then(data => {
        const url = data.result.url
        return { src: url, alt: '' }
      })
    })
  },
  created () {
    if (this.$route.query.isread) {
      this.isread = true
    }
    if (this.$route.query.id) {
      this.editOff = true
    }
    this.getFlashbuyTemplateList().then((res) => {
      // console.log(JSON.stringify(res))
      res = res || []
      for (var n = 0; n < res.length; n++) {
        res[n].currentImg = ''
      }
      this.templateList = res
      if (this.$route.query.id) {
        this.getFlashbuyById(this.$route.query.id).then((resr) => {
          // console.log(JSON.stringify(resr))
          this.postData = resr
          for (var n = 0; n < this.templateList.length; n++) {
            if (this.templateList[n].ModelId === this.postData.ModelId) {
              this.templateActiveIndex = n
            }
          }
          if (this.postData.ValidateType === 'date') {
            this.postData.ValidateDays = ''
          } else {
            this.postData.ValidateStart = ''
            this.postData.ValidateEnd = ''
          }
        })
      }
    })
  },
  methods: {
    ...mapActivityFlashbuyActions([
      'getFlashbuyTemplateList',
      'addFlashbuy',
      'getFlashbuyById',
      'editFlashbuy',
    ]),
    submitFlashbuy () { // 提交抢购数据
      if (this.postData.CaseId === '' && this.defaultCaseId !== '') {
        this.postData.CaseId = this.defaultCaseId
      }
      if (!this.checkData()) {
        return false
      }
      this.postData.FlashBuyMaxAttendant = this.postData.FlashBuyMaxAttendant - 0
      this.postData.ModelId = this.templateList[this.templateActiveIndex].ModelId
      if (this.$route.query.id) {
        this.editFlashbuy(this.postData).then((res) => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.$router.push({ name: 'snapUpList' })
        })
      } else {
        this.addFlashbuy(this.postData).then((res) => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.$router.push({ name: 'snapUpList' })
        })
      }
    },
    checkData () { // 校验数据格式
      // console.log(this.postData.FlashBuyName)
      if (this.postData.CaseId === '') {
        this.$message({
          type: 'error',
          message: '请选择案场'
        })
        return false
      }
      if (this.postData.FlashBuyName === '') {
        this.$message({
          type: 'error',
          message: '活动名称不能为空'
        })
        return false
      }
      if (this.postData.ActivityMainImg === '') {
        this.$message({
          type: 'error',
          message: '请先上传活动主图'
        })
        return false
      }
      if (this.postData.FlashBuyMaxAttendant === '' || this.postData.FlashBuyMaxAttendant - 0 <= 0 || (this.postData.FlashBuyMaxAttendant - 0) % 1 !== 0) {
        this.$message({
          type: 'error',
          message: '活动名额须为大于0正整数'
        })
        return false
      }
      if (this.postData.StartDate === '') {
        this.$message({
          type: 'error',
          message: '活动开始时间不能为空'
        })
        return false
      }
      if (this.postData.EndDate === '') {
        this.$message({
          type: 'error',
          message: '活动截止时间不能为空'
        })
        return false
      }
      if (new Date(this.postData.StartDate).getTime() > new Date(this.postData.EndDate).getTime()) {
        this.$message({
          type: 'error',
          message: '活动开始时间不能大于截止时间'
        })
        return false
      }
      if (this.postData.FlashBuyInfo === '') {
        this.$message({
          type: 'error',
          message: '活动说明不能为空'
        })
        return false
      }
      if (this.postData.ActivityTitle === '') {
        this.$message({
          type: 'error',
          message: '分享标题不能为空'
        })
        return false
      }
      if (this.postData.ShareImg === '') {
        this.$message({
          type: 'error',
          message: '请先上传分享图片'
        })
        return false
      }
      if (this.postData.ShareContent === '') {
        this.$message({
          type: 'error',
          message: '分享文案不能为空'
        })
        return false
      }
      if (this.postData.ValidateType === 'days') {
        if (this.postData.ValidateDays - 0 <= 0 || (this.postData.ValidateDays - 0) % 1 !== 0) {
          this.$message({
            type: 'error',
            message: '领取后有效天数须为大于0正整数'
          })
          return false
        }
        this.postData.ValidateDays = this.postData.ValidateDays - 0
        delete this.postData.ValidateStart
        delete this.postData.ValidateEnd
      } else {
        if (this.postData.ValidateStart === '') {
          this.$message({
            type: 'error',
            message: '有效期开始时间不能为空'
          })
          return false
        }
        if (this.postData.ValidateEnd === '') {
          this.$message({
            type: 'error',
            message: '有效期截止时间不能为空'
          })
          return false
        }
        if (new Date(this.postData.ValidateStart).getTime() > new Date(this.postData.ValidateEnd).getTime()) {
          this.$message({
            type: 'error',
            message: '有效期开始时间不能大于截止时间'
          })
          return false
        }
        delete this.postData.ValidateDays
      }
      return true
    },
    cutTemplate (index) { // 切换模板
      if (!this.editOff && !this.isread) {
        this.templateActiveIndex = index
        this.postData.ModelId = this.templateList[index].ModelId
      }
    },
    reback () {
      this.$router.push({ name: 'snapUpList' })
    },
    handleMainImgSuccess (res, file) {
      this.postData.ActivityMainImg = res.result.url
    },
    handleShareImgSuccess (res, file) {
      this.postData.ShareImg = res.result.url
    },
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
@import "page.scss";
h1 {
  line-height: 40px;
  font-size: 16px;
}
.mainForm {
  width: 100%;
  li {
    margin-bottom: 20px;
    div.flex-h {
      align-items: center;
      & > * {
        margin-right: 20px;
      }
      > div {
        white-space: nowrap;
        > * {
          display: inline-block;
          margin-right: 5px;
        }
      }
    }
    > span {
      line-height: 40px;
      min-width: 100px;
      margin-right: 10px;
      em {
        color: red;
      }
    }
  }
  .el-table.el-table--fit.el-table--enable-row-hover {
    border: 1px solid #eee;
    border-bottom: none;
  }
  .templateItem {
    width: 120px;
    display: inline-block;
    margin: 0 20px 20px 0;
    position: relative;
    overflow: hidden;
    text-align: center;
    vertical-align: top;
    & > a {
      width: 100%;
      height: 120px;
      display: inline-block;
      position: relative;
      overflow: hidden;
      border: 1px dashed #ccc;
      box-sizing: border-box;
      &.active {
        border-color: #409eff;
      }
    }
  }
}
</style>
