<template>
  <a-modal
    :visible="value"
    width="70%"
    destroyOnClose
    title="编辑景点"
    ok-text="确定并发布"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="loading">
      <a-form
        :form="form"
        v-if="formData"
      >
        <div class="block-title">
          基本信息
        </div>
        <a-form-item
          label="景点名称"
          v-bind="formItemLayout"
        >
          <a-input
            v-decorator="[
              'name',
              {
                initialValue:formData.name,
                rules: [{ required: true, message: '请输入景点名称' }]
              }
            ]"
          ></a-input>
        </a-form-item>

        <a-form-item
          label="景点地址"
          v-bind="formItemLayout"
        >
          <a-input
            v-decorator="[
              'address',
              {
                initialValue:formData.address,
                rules: [{ required: true, message: '请输入景点名称' }]
              }
            ]"
          ></a-input>
        </a-form-item>

        <a-form-item
          label="广告位"
          v-bind="formItemLayout"
        >
          <a-select
            v-decorator="[
              'adv_position_id',
              {
                initialValue:formData.adv_position&&formData.adv_position.id || 0
              }
            ]">
            <a-select-option :value="0">
              无
            </a-select-option>
            <a-select-option v-for="(item,index) in adPostionList" :key="index" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="景点副标题"
          v-bind="formItemLayout"
        >
          <a-input
            v-decorator="[
              'subtitle',
              {
                initialValue:formData.subtitle
              }
            ]"
          ></a-input>
        </a-form-item>

        <a-form-item
          label="景点设施"
          v-bind="formItemLayout"
        >
          <a-select
            mode="multiple"
            style="width: 100%"
            :token-separators="[',']"
            v-decorator="[
              'tags',
              {
                initialValue:formData.tags.map(i=>i.id)
              }
            ]"
          >
            <a-select-option
              v-for="i in tags"
              :key="i.id"
            >
              {{ i.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="景点开放时间"
          v-bind="formItemLayout"
        >
          <a-input
            v-decorator="[
              'opening_time',
              {
                initialValue:formData.opening_time
              }
            ]"
          ></a-input>
        </a-form-item>

        <a-form-item
          label="公告"
          v-bind="formItemLayout"
        >
          <a-input
            v-decorator="[
              'announcement',
              {
                initialValue:formData.announcement
              }
            ]"
          ></a-input>
        </a-form-item>

        <a-form-item
          label="门票可售时间"
          v-bind="formItemLayout"
          :validate-status="workTimesItem.validateStatus"
          :help="workTimesItem.help"
        >
          <a-button @click="addWorkTimesVisible = true">
            <a-icon type="plus" /> 新增可售时间
          </a-button>
          <div
            class="workTimesItem"
            v-for="(item,index) in worktimes"
            :key="index"
          >
            <a-tag color="#0099a0">
              {{ item.type | workTimesType }}
            </a-tag>

            <a-form-item
              label="日期范围"
              v-bind="formItemLayout"
              v-if="item.type==='SPECIAL_DAY'"
            >
              {{ item.start }} 至 {{ item.end }}
            </a-form-item>
            <a-form-item
              label="日期"
              v-bind="formItemLayout"
              v-if="item.type==='SPECIAL_WEEKDAY'"
            >
              {{ item.day | weekDays }}
            </a-form-item>
            <a-form-item
              label="日期"
              v-bind="formItemLayout"
              v-if="item.type==='SPECIAL_MONTHDAY'"
            >
              {{ item.day | monthDays }}
            </a-form-item>
            <a-form-item
              label="法定日类型"
              v-bind="formItemLayout"
              v-if="item.type==='LEGAL_HOLIDAY'"
            >
              {{ item.legal_type | legalType }}
            </a-form-item>
            <a-form-item
              label="时间范围"
              v-bind="formItemLayout"
            >
              <ul>
                <li
                  v-for="(k,i) in item.periods"
                  :key="i"
                >
                  {{ k.start }} 至 {{ k.end }}
                </li>
              </ul>
            </a-form-item>
            <a-form-item
              label="是否允许"
              v-bind="formItemLayout"
            >
              {{ item.permit?'是':'否' }}
            </a-form-item>
            <a-form-item
              label="优先级"
              v-bind="formItemLayout"
            >
              {{ item.priority }}
            </a-form-item>
            <a-form-item
              label="禁止开放提示语"
              v-bind="formItemLayout"
            >
              {{ item.no_permit_prompt }}
            </a-form-item>
            <div class="btns-wrap">
              <a-button
                type="primary"
                size="small"
                @click="eidtWorkTime(item,index)"
              >
                编辑
              </a-button>
              <a-button
                type="danger"
                size="small"
                @click="deleteWorkTime(index)"
              >
                删除
              </a-button>
            </div>
          </div>
        </a-form-item>
        <a-form-item
          label="是否开放预约"
          v-bind="formItemLayout"
        >
          <a-switch
            checked-children="是"
            un-checked-children="否"
            v-decorator="[
              'support_reservation',
              {
                valuePropName: 'checked',
                initialValue:formData.support_reservation
              }
            ]"
          />
        </a-form-item>
        <a-form-item
          label="景点轮播图"
          v-bind="formItemLayout"
        >
          <a-upload
            list-type="picture-card"
            :before-upload="beforeImageUpload"
            @preview="handleImagePreview"
            @change="handleImageChange"
            :customRequest="()=>{}"
            :file-list="imageList"
            v-decorator="[
              'pictures',
              {
                initialValue:imageList
              }
            ]"
          >
            <div v-if="imageList.length < 6">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>

          <a-modal
            :visible="previewImageVisible"
            :footer="null"
            @cancel="handleImageCancel"
          >
            <img
              alt="example"
              style="width: 100%"
              :src="previewImage"
            >
          </a-modal>

          <div class="clearfix"></div>
          <a-alert
            banner
            type="warning"
            message="图片格式支持 JPG/PNG，大小不超过1MB，最多可上传6张图片。推荐分辨率640*360（px）"
          ></a-alert>
        </a-form-item>

        <a-form-item
          label="视频介绍"
          v-bind="formItemLayout"
        >
          <a-upload
            :action="uploadUrl"
            :file-list="videoList"
            :before-upload="beforeVideoUpload"
            @change="handleVideoChange"
            v-decorator="[
              'videos',
              {
                initialValue:videoList
              }
            ]"
          >
            <a-button v-if="videoList.length < 1">
              <a-icon type="upload" /> 点击上传
            </a-button>
          </a-upload>

          <video
            :src="videoList.length>0 && (videoList[0].url || videoList[0].response.link)"
            v-if="videoList.length>0 && (videoList[0].url || (videoList[0].response && videoList[0].response.link))"
            style="width:400px;"
            controls
          ></video>

          <div class="clearfix"></div>
          <a-alert
            banner
            type="warning"
            message="可上传1个视频，格式支持：MP4 H.264，大小不超过100MB"
          ></a-alert>
        </a-form-item>

        <div class="block-title">
          图文介绍
        </div>

        <a-form-item
          label="标题"
          v-bind="formItemLayout"
        >
          <a-input
            v-decorator="[
              'introduction_title',
              {
                initialValue:formData.introduction_title,
                rules: [{ required: true, message: '请输入标题' }]
              }
            ]"
          ></a-input>
        </a-form-item>

        <a-form-item
          label="详情"
          v-bind="formItemLayout"
        >
          <a-input
            v-show="false"
            v-decorator="[
              'introduction_content',
              {
                initialValue:formData.introduction_content,
                rules: [{ required: true, message: '请输入详情内容' }]
              }
            ]"
          ></a-input>
          <Editor ref="editor" v-model="formData.introduction_content"></Editor>
        </a-form-item>
      </a-form>
    </a-spin>

    <!-- 开放时间弹窗 -->
    <AddWorkTimesModal
      v-model="addWorkTimesVisible"
      @change="addWorkTime"
    ></AddWorkTimesModal>

    <!-- 开放时间弹窗 -->
    <EditWorkTimesModal
      v-model="editWorkTimesVisible"
      :work-time="currentWorkTime"
      @change="updateWorkTime"
    ></EditWorkTimesModal>

    <ImageCropper
      ref="cropper"
      :info="fileInfo"
      @success="handleCropper"
    ></ImageCropper>
  </a-modal>
</template>

<script>
import { getScenicById, updateScenic } from '@/api/ticketSetting/scenic'
import { groupBy } from 'lodash'
import scenicMixin from './scenicMixin.js'
import Editor from '@/components/Editor/index.vue'
import { mapState } from 'vuex'

export default {
  mixins: [scenicMixin],
  components: {
    Editor
  },
  computed: {
    ...mapState({
      adPostionList: state => state.app.adPostionList
    })
  },
  data () {
    return {
      formData: null,
      loading: false
    }
  },
  props: {
    id: {
      type: Number,
      default: 0
    }
  },
  methods: {
    handleOk (e) {
      e.preventDefault()
      // 验证工作区间
      if (!this.validateWorkTimes()) return

      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          values.pictures = this.imageList.map(item => {
            return {
              size: item.size,
              url: item.url
            }
          })

          values.videos = this.videoList.map(item => {
            if (item.response) {
              return {
                size: item.size,
                url: item.response.link
              }
            } else {
              return {
                size: item.size,
                url: item.url
              }
            }
          })

          values.tags = values.tags || []

          values.worktimes = this.formatWorksTimes(this.worktimes)

          updateScenic(this.id, values).then(res => {
            this.$message.success('修改成功')
            this.form.resetFields()
            this.$emit('input', false)
            this.$emit('update')
          })
        }
      })
    },
    getFileList (obj) {
      if (obj && obj.fileList) {
        return obj.fileList.map(item => {
          const info = item.response
          if (info) {
            return {
              size: info.size - 0,
              url: info.link
            }
          } else {
            return {
              size: item.size,
              url: item.url
            }
          }
        })
      }

      if (Array.isArray(obj)) {
        return obj.map(item => {
          return {
            size: item.size,
            url: item.url
          }
        })
      }

      return []
    },
    // 将日期字段合并成数组
    getWorkTimes (serverWorkTimes) {
      const result = []
      const worktimes = JSON.parse(JSON.stringify(serverWorkTimes))

      const groupWorkTimes = groupBy(worktimes, item => {
        const i = Object.assign({}, item)
        i.day !== undefined && delete i.day
        return JSON.stringify(i)
      })

      for (const key in groupWorkTimes) {
        const days = []
        groupWorkTimes[key].forEach(i => {
          if (i.day !== undefined) {
            days.push(i.day)
          }
        })
        const groupTimes = groupWorkTimes[key][0].day !== undefined ? Object.assign(groupWorkTimes[key][0], { day: days }) : groupWorkTimes[key][0]
        result.push(groupTimes)
      }
      return result
    }
  },
  watch: {
    value (val) {
      this.loading = true
      val && getScenicById(this.id).then(res => {
        this.formData = res.extraInfo
        this.loading = false
        this.imageList = this.formData.pictures.map((i, index) => {
          return {
            uid: index + '',
            name: '图' + index,
            url: i.url,
            thumbUrl: i.url,
            size: i.size,
            percent: 100
          }
        })
        this.videoList = this.formData.videos.map((i, index) => {
          return {
            uid: index + '',
            name: '视频' + index,
            url: i.url,
            thumbUrl: '',
            size: i.size,
            percent: 100
          }
        })
        this.worktimes = this.formData.worktimes
      })
    }
  }
}
</script>

<style>
</style>
