<template>
  <a-modal
    class="container"
    :visible="value"
    title="编辑导游"
    width="60%"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form
      :form="form"
      v-if="formData"
    >
      <!-- <div class="block-title">
        绑定景点和渠道
      </div>
      <a-form-item
        label="已绑定景点"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-select
          mode="multiple"
          v-model="bindScenic"
          show-search
          :filter-option="filterOption"
        >
          <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"
          show-search
          :filter-option="filterOption"
        >
          <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"
      >
        {{ formData.name }}
      </a-form-item>
      <a-form-item
        label="导游标签"
        v-bind="formItemLayout"
      >
        <a-input
          v-decorator="[
            'tag',
            {
              initialValue:formData.tag,
              rules: [{ required: true, message: '请输入' }]
            }
          ]"
        ></a-input>
      </a-form-item>
      <a-form-item
        label="场次库存"
        v-bind="formItemLayout"
      >
        <a-input-number
          v-decorator="[
            'book_limit',
            {
              initialValue:formData.book_limit,
              rules: [{ required: true, message: '请输入' }]
            }
          ]"
          :min="0"
          :precision="0"
        ></a-input-number>
      </a-form-item>
      <a-form-item
        label="绑定票种"
        v-bind="formItemLayout"
      >
        <a-select
          v-decorator="[
            'ticket_type_id',
            {
              initialValue:formData.ticket_type_id,
              rules: [{ required: true, message: '请输入' }]
            }
          ]"
        >
          <a-select-option v-for="{id,name} in ticketTypeList" :key="id" :value="id">
            {{ name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="导游图片"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-upload
          :action="uploadUrl"
          listType="picture-card"
          :before-upload="beforeImageUpload"
          @preview="handleImagePreview"
          @change="handleImageChange"
          :customRequest="()=>{}"
          :file-list="imageList"
        >
          <div v-if="imageList.length < 1">
            <a-icon type="plus" />
            <div class="ant-upload-text">
              点击上传
            </div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item
        label="导游星级"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-rate
          v-decorator="[
            'stars',
            {
              initialValue:formData.stars,
              rules: [{ required: true, message: '请输入' }]
            }
          ]"
        />
      </a-form-item>
      <a-form-item
        label="导游介绍"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-textarea
          v-decorator="[
            'description',
            {
              initialValue:formData.description,
              rules: [{ required: true, message: '请输入' }]
            }
          ]"
          :auto-size="{ minRows: 3, maxRows: 5 }"
        ></a-textarea>
      </a-form-item>
    </a-form>

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

    <ImageCropper
      :width="414"
      :height="216"
      ref="cropper"
      :info="fileInfo"
      @success="handleCropper"
    ></ImageCropper>

  </a-modal>
</template>

<script>
import { updateGuide } from '@/api/guide'
import guideMixin from './guideMixin.js'
import ImageCropper from '@/components/ImageCropper'

// function getBase64 (file) {
//   return new Promise((resolve, reject) => {
//     const reader = new FileReader()
//     reader.readAsDataURL(file)
//     reader.onload = () => resolve(reader.result)
//     reader.onerror = error => reject(error)
//   })
// }

export default {
  mixins: [guideMixin],
  components: {
    ImageCropper
  },
  props: {
    formData: {
      type: Object,
      default: () => null
    },
    scenicList: {
      type: Array,
      default: () => []
    },
    salesChannel: {
      type: Array,
      default: () => []
    },
    ticketTypeList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      fileInfo: null,
      imageList: [],
      previewImage: '',
      previewVisible: false
    }
  },
  methods: {
    handleOk (e) {
      e.preventDefault()
      if (!this.imageList[0].url) {
        return this.$message.error('请上传图片')
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          const image = this.imageList.map(item => {
            return {
              size: item.size,
              url: item.url
            }
          })
          updateGuide({ id: this.formData.id, image: JSON.stringify(image), ...values }).then(res => {
            this.$message.success('修改成功。')
          })

          this.form.resetFields()
          this.$emit('input', false)

          // 数据更新有延迟
          setTimeout(() => {
            this.$emit('update')
          }, 500)
        }
      })
    },
    handleImageChange (info) {
      const fileList = info.fileList

      if (info.file.status === 'uploading') {
        var reader = new FileReader() // 实例化文件读取对象
        reader.readAsDataURL(info.file.originFileObj) // 将文件读取为 DataURL,也就是base64编码
        reader.onload = (ev) => { // 文件读取成功完成时触发
          var dataURL = ev.target.result // 获得文件读取成功后的DataURL,也就是base64编码

          this.$refs.cropper.show({
            img: dataURL
          })
        }
        return
      }

      if (!info.file.status) {
        const index = fileList.findIndex(item => {
          return item.uid === info.file.uid
        })
        fileList.splice(index, 1)
      }
      this.imageList = fileList
    },
    handleCropper (i) {
      const index = this.imageList.length
      this.imageList = this.imageList.concat({
        uid: index + '',
        name: '图' + index,
        url: i.link,
        thumbUrl: i.link,
        size: i.size,
        percent: 100
      })
      console.log(this.imageList)
    },
    beforeImageUpload (file) {
      const isImage = file.type.indexOf('image') > -1
      if (!isImage) {
        this.$message.error('请选择图片格式的文件')
      }
      return isImage
    },
    async handleImagePreview (file) {
      // if (!file.url && !file.preview) {
      //   file.preview = await getBase64(file.originFileObj)
      // }
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    }
  },
  watch: {
    value (val) {
      console.log(this.formData)
      if (typeof this.formData.image === 'string') {
        const image = JSON.parse(this.formData.image)
        this.imageList = image.map((i, index) => {
          return {
            uid: index + '',
            name: '图' + index,
            url: i.url,
            thumbUrl: i.url,
            size: i.size,
            percent: 100,
            status: 'done'
          }
        })
      } else {
        this.imageList = []
      }
    }
  }
  // watch: {
  //   value (val) {
  //     if (val) {
  //       if (this.formData.image) {
  //         this.fileList = [
  //           {
  //             uid: 0,
  //             name: '图片',
  //             url: this.formData.image,
  //             thumbUrl: this.formData.image,
  //             size: 100,
  //             percent: 100,
  //             status: 'done'
  //           }
  //         ]
  //       } else {
  //         this.fileList = []
  //       }
  //     }
  //   }
  // }
}
</script>

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