<template>
  <div>
    <xy-dialog ref="dialog" :width="74" type="form" :is-show.sync="isShow"
      :title="this.type === 'add' ? '新增会所产品' : '编辑会所产品'" :form="form" :rules="rules" @submit="submit">
      <template v-slot:name>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>产品名称：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.name" placeholder="请输入会所名称" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>

      <template v-slot:confinementServicesId>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>所属月子会所：

          </div>
          <div class="xy-table-item-content">
            <el-select clearable v-model="form.confinementServicesId" style="width: 300px;" placeholder="请选择所属月子会所">
              <Scroll :on-reach-bottom="loadMoreClub">
                <el-option v-for="item in clubs" :value="item.id" :key="item.id" :label="item.name">
                </el-option>
              </Scroll>
            </el-select>
          </div>
        </div>
      </template>

      <template v-slot:roomType>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>房间类型：
          </div>
          <div class="xy-table-item-content">
            <el-select clearable v-model="form.roomType" style="width: 300px;" placeholder="请选择房间类型">
              <el-option v-for="item in roomTypes" :value="item.id" :key="item.id" :label="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>

      <template v-slot:state>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            是否启用：
          </div>
          <div class="xy-table-item-content">
            <el-switch v-model="form.state" type="primary"></el-switch>
          </div>
        </div>
      </template>

      <template v-slot:recommend>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            是否推荐主页：
          </div>
          <div class="xy-table-item-content">
            <el-switch v-model="form.recommend" type="primary"></el-switch>
          </div>
        </div>
      </template>

      <template v-slot:sortNumber>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            排序：
          </div>
          <div class="xy-table-item-content">
            <el-input-number :precision="0" :controls="false" v-model="form.sortNumber" placeholder="请输入排序" clearable
              style="width: 300px;"></el-input-number>
          </div>
        </div>
      </template>


      <template v-slot:video>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            探店视频：
          </div>
          <div class="xy-table-item-content">
            <div v-if="form.video" style="position: relative;">
              <video :src="form.video" class="avatar" />
              <Button shape="circle" icon="md-close" type="error" size="small" class="img__delete"
                @click="form.video = ''"></Button>
            </div>
            <el-upload v-else :limit="1" accept="video/*" class="avatar-uploader" list-type="picture-card"
              :action="action" :show-file-list="true" :on-error="uploadFailVideo" :on-success="uploadSuccessVideo"
              :before-upload="uploadBeforeVideo">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </div>
      </template>

      <template v-slot:featuredLabel>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            特色标签：
          </div>
          <div class="xy-table-item-content">
            <div class="xy-table-item-content-label">
              <template v-for="(item,index) in form.featuredLabel">
                <el-tag type="primary" closable @close="labelClose(index)"
                  style="margin-right: 6px;margin-bottom: 4px;">{{item}}</el-tag>
              </template>
              <div style="margin-top: 15px;">
                <el-input clearable placeholder="请填写并添加特色标签" style="width: 300px" ref="labelInput" v-model="labelText">
                  <el-button type="primary" slot="append" icon="el-icon-plus" @click="appendLabel"></el-button>
                </el-input>
              </div>
            </div>
          </div>
        </div>
      </template>

      <template v-slot:roomOrientation>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            房间朝向：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.roomOrientation" placeholder="请输入房间朝向" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>

      <template v-slot:roomFacility>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            房间设备：
          </div>
          <div class="xy-table-item-content">
            <el-select multiple clearable v-model="form.roomFacility" placeholder="请选择房间设备" style="width: 300px;">
              <el-option v-for="item in equips" :value="item.id" :key="item.id" :label="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>

      <template v-slot:roomArea>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            房间面积：
          </div>
          <div class="xy-table-item-content xy-table-item-area">
            <el-input-number :precision="2" :controls="false" v-model="form.roomArea" placeholder="请输入房间面积" clearable
              style="width: 300px;"></el-input-number>
          </div>
        </div>
      </template>

      <template v-slot:price>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            价格：
          </div>
          <div class="xy-table-item-content xy-table-item-price">
            <el-input-number :precision="2" :controls="false" v-model="form.price" placeholder="请输入价格" clearable
              style="width: 300px;"></el-input-number>
          </div>
        </div>
      </template>

      <template v-slot:coverPicture>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>封面图：
          </div>
          <div class="xy-table-item-content xy-table-item-content-cover">
            <div v-if="form.coverPicture" style="position: relative;">
              <img :src="form.coverPicture" class="avatar">
              <Button shape="circle" icon="md-close" type="error" size="small" class="img__delete"
                @click="form.coverPicture = ''"></Button>
            </div>
            <el-upload v-else accept="picture" :limit="1" class="avatar-uploader" list-type="picture-card"
              :action="action" :show-file-list="true" :on-error="uploadFailPic" :on-success="uploadSuccessPic"
              :before-upload="uploadBeforePic">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </div>
      </template>

      <template v-slot:timeLimit>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            限时：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker clearable style="width: 440px;" v-model="form.timeLimit" type="datetimerange"
              range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" align="right"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </div>
        </div>
      </template>

      <template v-slot:content>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>内容：
          </div>
          <div class="xy-table-item-content" style="width: 680px;">
			<xyTinymce v-if="isShow" :height="200" v-model="form.content"></xyTinymce>
			  
            <!-- <tinymce ref="tinymce" :height="200" v-model="form.content" id='tinymce'></tinymce> -->
          </div>
        </div>
      </template>
    </xy-dialog>
  </div>
</template>

<script>
  import {
    store,
    show,
    save
  } from "@/api/clubProduct"
  import {
    index as clubIndex
  } from '@/api/confinementClub'
  import {
    getparameter
  } from "@/api/system/dictionary"
  import {
    Message
  } from 'element-ui'
import xyTinymce from "@/components/XyTinymce/index.vue";
    import {replaceAll} from "@/utils/index"
  // import tinymce from '@/components/Tinymce'
  export default {
    components: {
      // tinymce
	  xyTinymce
    },
    data() {
      return {
        id: '',
        isShow: false,
        type: '',
        action: `${process.env.VUE_APP_BASE_API}api/admin/upload-file`,
        clubSelect: {
          pageSize: 10,
          page: 1
        },
        clubs: [],
        roomTypes: [],
        equips: [],
        labelText: '',

        form: {
          name: '',
          confinementServicesId: '', //所属月子会所
          roomType: '',
          state: true,
          recommend: false,
          sortNumber: 0,
          featuredLabel: [],
          roomOrientation: '', //房间朝向
          roomFacility: '', //房间设施
          roomArea: 0,
          price: 0,
          coverPicture: '',
          timeLimit: '',
          content: '',
          video: ""
        },
        rules: {
          name: [{
            required: true,
            message: '请填写产品名称'
          }],
          confinementServicesId: [{
            required: true,
            message: '请选择所属月子会所'
          }],
          roomType: [{
            required: true,
            message: '请选择房间类型'
          }],
          coverPicture: [{
            required: true,
            message: '请上传封面图'
          }],
          content: [{
            required: true,
            message: '请填写内容'
          }]
        }
      }
    },
    methods: {


      //上传
      uploadFailVideo(err) {
        console.log(err)
      },
      uploadSuccessVideo(response) {
        console.log(response)
        this.form.video = response.url
      },
      uploadBeforeVideo(file) {
        if ((file.size / 1000) > 10240) {
          Message({
            type: 'warning',
            message: '上传视频大小超过10M！'
          })
          return false
        }
      },
      //上传
      uploadFailPic(err) {
        console.log(err)
      },
      uploadSuccessPic(response) {
        console.log(response)
        this.form.coverPicture = response.url
      },
      uploadBeforePic(file) {
        if ((file.size / 1000) > 2048) {
          Message({
            type: 'warning',
            message: '上传图片大小超过2M！'
          })
          return false
        }
      },

      //特色标签添加
      appendLabel() {
        if (!this.$refs['labelInput'].getInput().value) return
        this.form.featuredLabel.push(this.$refs['labelInput'].getInput().value)
        this.labelText = ''
      },
      //特色标签删除
      labelClose(index) {
        this.form.featuredLabel.splice(index, 1)
      },

      async getRoomTypes() {
        const res = await getparameter({
          number: 'confinementRoomType'
        })
        this.roomTypes = res.detail
      },

      async getClubs() {
        const res = await clubIndex({
          page: this.clubSelect.page,
          page_size: this.clubSelect.pageSize
        }, false)
        if (res?.rows?.length === 0) {
          this.$Message.info({
            content: '没有更多会所了',
            duration: 1
          })
          this.clubSelect.page--
        }
        this.clubs.push(...res.rows)
      },

      async getEquips() {
        const res = await getparameter({
          number: 'confinementEquip'
        })
        this.equips = res.detail
      },

      async getDetail() {
        const res = await show({
          id: this.id
        })
        console.log(res)
        this.form = {
          name: res?.name,
          confinementServicesId: res?.confinement_services_id, //所属月子会所
          roomType: res?.room_type,
          state: !!res?.state,
          recommend: !!res?.recommend,
          sortNumber: res?.sort_number,
          featuredLabel: res?.featured_label?.split(',') || [], //特色标签
          roomOrientation: res?.room_orientation, //房间朝向
          roomFacility: res?.room_facility?.split(',').map(item => Number(item)) || [], //房间设施
          roomArea: res?.room_area,
          price: res?.price,
          coverPicture: res?.cover_picture,
          timeLimit: res?.time_limit?.split(','),
          content: res?.content,
          video: res?.video
        }
        // this.$refs['tinymce'].setContent(this.form.content)
      },

      loadMoreClub() {
        this.clubSelect.page++
        this.getClubs()
      },

      submit() {
        let _form = {
          name: this.form.name,
          room_type: this.form.roomType,
          confinement_services_id: this.form.confinementServicesId,
          state: this.form.state ? 1 : 0,
          sort_number: this.form.sortNumber,
          featured_label: this.form.featuredLabel?.toString(),
          // content: this.form.content,
          recommend: this.form.recommend ? 1 : 0,
          room_orientation: this.form.roomOrientation,
          cover_picture: this.form.coverPicture,
          room_facility: this.form.roomFacility?.toString(),
          price: this.form.price,
          room_area: this.form.roomArea,
          time_limit: this.form.timeLimit?.toString(),
          video: this.form.video,
		  content: replaceAll(this.form.content,'../storage/files',`${process.env.VUE_APP_BASE_API}storage/files`)
		  
        }
        if (this.type === 'add') {
          store(_form).then(res => {
            Message({
              type: 'success',
              message: '新增月子产品成功'
            })
            this.isShow = false
            this.$emit('refresh')
          })

        } else if (this.type === 'editor') {
          save({
            id: this.id,
            ..._form
          }).then(res => {
            Message({
              type: 'success',
              message: '编辑月子产品成功'
            })
            this.isShow = false
            this.$emit('refresh')
          })
        }
      }
    },
    watch: {
      isShow(newVal) {
        if (newVal) {
          this.getClubs()
          this.getEquips()
          this.getRoomTypes()

          if (this.type === 'editor') {
            this.getDetail()
          }
        } else {
          this.id = ''
          this.type = ''
          this.clubs = []
          this.clubSelect.page = 1
          // this.$refs['tinymce'].setContent(" ")
          this.$refs['dialog'].reset()
        }
      }
    }

  }
</script>

<style scoped lang="scss">
  ::v-deep .ivu-select-dropdown {}

  ::v-deep .ivu-scroll-container {
    height: 140px !important;

    &::after {
      content: '加载更多..';
      text-align: center;
      font-size: 10px;
      zoom: 0.8;
      color: rgb(160, 160, 160);
      background: #fff;

      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
    }
  }

  .xy-table-item {
    &-label {
      width: 160px;
    }

    &-content {
      &-label {
        width: 300px;
        display: flex;
        flex-wrap: wrap;
        flex: 0;
      }
    }

    &-content-cover {
      position: relative;

      &::after {
        font-size: 10px;
        white-space: nowrap;
        word-break: keep-all;
        content: '建议尺寸 800*450';
        zoom: 0.84;

        position: absolute;
        bottom: -34px;
        right: 4px;
      }
    }

    &-area {
      position: relative;

      &::after {
        z-index: 1;
        position: absolute;
        right: 0;
        top: 0;
        content: '（平方米）'
      }

      ::v-deep .el-input__clear {
        position: relative;
        right: 30px;
        z-index: 2;
      }
    }
  }

  ::v-deep .el-input__inner {
    text-align: left;
  }
</style>
<style>
  .avatar-uploader .el-upload {
    width: 110px;
    height: 110px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #BF617C;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 110px;
    height: 110px;
    line-height: 110px;
    text-align: center;
  }

  .avatar {
    width: 110px;
    display: block;
    border-radius: 6px;
  }

  .img__delete {
    transform: scale(0.7, 0.7);

    position: absolute;
    top: 1px;
    left: 4%;
  }
</style>
