<!--  -->
<template>
  <div v-loading.fullscreen.lock="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)">
    <main-top :crumb="crumbData"></main-top>
    <div class="table-interface">
      <div class="top-body">
        <div class="top-title">方案信息:</div>
        <div class="form-con">
          <el-form ref="displayform" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="方案名称：" style="width:318px;" prop="name">
              <el-input v-model="form.name" maxlength="20" show-word-limit placeholder="请输入方案名称"></el-input>
            </el-form-item>

            <el-form-item label="展示说明：">
              <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入文物介绍"
                maxlength="200"
                show-word-limit
                v-model="form.description">
              </el-input>
            </el-form-item>

            <el-form-item></el-form-item>
          </el-form>
        </div>
        <div class="top-title">展示信息:</div>
        <div class="form-con">
          <el-form ref="form" :model="form" label-width="100px">
            <el-form-item label="展示类别：" style="width:318px;">
              <el-select v-model="form.typeId" placeholder="请选择文物类别">
                <el-option v-for="(item,i) in exhibitionlist" :key="i" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>

             <el-form-item label="展示封面：" class="vrequired">
               <!-- <Cropper
                  :width="900"
                  :height="200"
                  :fixed-number="[4.5,1]"
                  :uploadUrl = "'/exhibition/upload'"
                  :img="form.webUrl"
                  @subUploadSucceed="getShopImages"
              /> -->

               <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :headers="{
                  token,
                }"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :on-success="upload_avatar_success"
                >
                <img v-if="form.webUrl" :src="form.webUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>

              <!-- <span style="color:#999">建议图片尺寸为316*200</span> -->
            </el-form-item>

            <el-form-item label="展示文物：" class="vrequired">
              <el-table :data="tableData" v-if="tableData.length>0" style="width: 100%">
                <el-table-column
                  v-for="(item, idx) in data"
                  :key="idx"
                  :prop="item.prop"
                  :label="item.label"
                >
                  <template slot-scope="scope">
                    <span>{{scope.row[item.prop]}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <span class="o-span" @click="del(scope.row)">删除</span>
                  </template>
                </el-table-column>
              </el-table>
              <div @click="getInformation" class="avatar-uploader">
                <i class="el-icon-plus avatar-uploader-icon"></i>
                <span class="wwtxt">文物库</span>
              </div>
            </el-form-item>
            <el-form-item label="是否启用：">
              <el-radio-group v-model="form.state">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <el-button type="primary" @click="onSubmit">发布</el-button>
        <el-button @click="$router.back()">取消</el-button>
      </div>
      <div @click="showSelect=false" class="select-hover" v-if="showSelect">
        <div @click.stop class="select-con">
          <div class="info-left">
            <span>按文物类别查看：</span>
            <el-select style="width:100px;" v-model="typeId" placeholder="请选择">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="(item,i) in tlist" :key="i" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <span style="margin-left:20px;">按文物年代查看：</span>
            <el-select style="width:100px;" v-model="timeId" placeholder="请选择">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="(item,i) in timelist" :key="i" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-input style="width:220px;margin:0 20px;" v-model="inputKey" placeholder="请输入文物名称搜索"></el-input>
            <el-button type="primary" @click="getInformation">查找</el-button>
            <!-- <el-button @click="inputKey=''">重置</el-button> -->
            <el-button @click="reset">重置</el-button>
          </div>
          <ul>
            <li :class="{'active':isSelect(item,i)}" @click="pushIn(item)" v-for="(item,i) in collectList" :key="i">
              <div class="mask">
                <!-- <div>{{1}}</div> -->
              </div>
              <div class="li-img">
                <img :src="item.pic" alt />
                <div><span>浏览量: {{Math.round(Math.random()*100000)}}</span> 点赞数: {{Math.round(Math.random()*1000)}}</div>
              </div>
              <div>{{item.timeName}} {{item.typeName}}</div>
              <p>{{item.name}}</p>
            </li>
          </ul>
          <div class="save-btn">
            <el-button type="primary" @click="showSelect=false">确定</el-button>
            <el-button @click="()=>{showSelect=false}">取消</el-button>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

import MainTop from '@/components/main-top'
import SearchBar from '@/components/search-bar'
import Cropper from '@/components/cropper'

import { VueEditor } from 'vue2-editor'

let urlType = {
  0: '/exhibition/addExhibition',
  1: '/exhibition/updateExhibition'
}

let urlType1 = {
  0: '/exhibition/insertExhibitionCollection',
  1: '/exhibition/updateExhibitionCollection'
}

let data = [
  {
    prop: 'idx',
    label: '序号'
  },
  {
    prop: 'name',
    label: '文物名称'
  },
  {
    prop: 'typeName',
    label: '文物类别'
  },
  {
    prop: 'timeName',
    label: '文物年代'
  }
]
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    MainTop,
    VueEditor,
    SearchBar,
    Cropper
  },
  data () {
    let crumbData = [
      {
        name: '展示管理',
        id: 0
      },
      {
        name: this.$route.params.type ? '编辑方案' : '新增方案',
        id: 1
      }
    ]
    return {
      crumbData,
      data,
      plist: [],
      tlist: [],
      exhibitionlist: [],
      showSelect: false,
      content: '<h1>Some initial content</h1>',
      form: {
        name: '',
        typeId: 3,
        equipmentId: 1,
        state: 0,
        description: '',
        webUrl: ''
      },
      rules: {
        name: [{ required: true, message: '请输入方案名称', trigger: 'blur' }]
      },
      tableData: [],
      collectList: [],
      timelist: [],
      typeId: '',
      timeId: '',
      inputKey: '',
      type: this.$route.params.type,
      id: this.$route.params.id,
      loading: false,
      token: window.localStorage.getItem('token'),
      uploadUrl: `${this.$serverName}/exhibition/upload`
    }
  },
  watch: {
    inputKey () {
      this.refresh()
    },
    tableData (newVal) {
      newVal.forEach((item, i) => {
        item.idx = i + 1
      })
    }
  },
  methods: {
    // 点击重置
    reset () {
      this.inputKey = this.timeId = this.typeId = ''
      this.getInformation()
    },
    beforeUpload () {
      this.loading = true
    },
    upload_avatar_success (data) {
      this.loading = false
      this.form.webUrl = data.data
    },
    // getShopImages (img) {
    //   this.form.webUrl = img
    // },

    refresh () {
      this.loading = true
      this.getInformation()
      this.loading = false
    },
    async getPositionList () {
      let result = await this.$http({
        method: 'post',
        url: '/position/list'
      })

      this.plist = result.data
    },
    async getcollectList () {
      let result = await this.$http({
        method: 'post',
        data: {
          state: 0
        },
        url: '/collection/typeList'
      })
      this.tlist = result.data

      this.form.typeId = this.tlist[0].id
      let result1 = await this.$http({
        method: 'post',
        url: '/collection/timeList'
      })
      this.timelist = result1.data

      let result2 = await this.$http({
        method: 'post',
        url: '/exhibition/typeList'
      })
      this.exhibitionlist = result2.data
    },
    async getexhibitionList (exhibitionId) {
      let result = await this.$http({
        method: 'post',
        data: {
          exhibitionId: Number(exhibitionId)
        },
        url: '/exhibition/findCollectionByExhibition'
      })

      this.tableData = result.data
      console.log('tableData', result.data)

      this.tableData.forEach((item, i) => {
        item.idx = i + 1
      })
    },
    isSelect (item, idx) {
      if (this.tableData.length > 0) {
        for (let i = 0; i < this.tableData.length; i++) {
          let sub = this.tableData[i]
          if (sub.id === item.id) {
            return true
          }
        }
      }
      return false
    },
    onSubmit () {
      this.$refs['displayform'].validate(async (valid) => {
        if (valid) {
          if (this.tableData.length <= 0) {
            return this.$alert('展示文物不能为空')
          }

          let { name, id, typeId, equipmentId, state, description, webUrl } = this.form
          let data = { name, typeId, equipmentId, state, description, webUrl }

          if (!webUrl) {
            return this.$alert('展示封面不能为空')
          }
          if (this.type) {
            data['id'] = id
          }
          this.$http.post(urlType[this.type], data).then(res => {
            if (res.code === 0) {
              console.log(res)
              let exhibitionId = res.data.id

              let collectionId = []

              this.tableData.forEach(sub => {
                collectionId.push(sub.id)
              })
              let params = {
                exhibitionId,
                collectionId: collectionId.join(',')
              }
              this.$http.post(urlType1[this.type], params).then(res => {
                if (res.code === 0) {
                  this.$alert('操作成功', '提示', {
                    confirmButtonText: '确定',
                    callback: action => {
                      this.$router.back()
                    }
                  })
                } else {
                  this.$notify.error({
                    title: '错误',
                    message: res.message
                  })
                }
              })
            } else {
              this.$notify.error({
                title: '错误',
                message: res.message
              })
            }
          })
        }
      })
    },

    pushIn (item) {
      for (let i = 0; i < this.tableData.length; i++) {
        let sub = this.tableData[i]
        if (sub.id === item.id) {
          return this.tableData.splice(i, 1)
        }
      }
      this.tableData.push(item)
    },
    del (item) {
      let arr = []
      this.tableData.forEach(sub => {
        if (sub.id !== item.id) {
          arr.push(sub)
        }
      })

      this.tableData = arr
    },
    async getInformation () {
      this.showSelect = true
      let params = {
        name: this.inputKey,
        typeId: this.typeId,
        timeId: this.timeId,
        pageNum: 1,
        pageSize: 180
      }

      let result = await this.$http({
        method: 'post',
        data: params,
        url: '/collection/list'
      })

      if (result.code !== 0) {
        return
      }
      this.collectList = result.data.list
    },
    async getDetail () {
      let result = await this.$http({
        method: 'post',
        headers: {
          token: window.localStorage.getItem('token')
        },
        url: `/exhibition/getExhibitionById`,
        data: {
          id: Number(this.id)
        }
      })

      this.form = result.data
      this.tableData = result.data.collectionList
    }
  },

  mounted () {
    this.getcollectList()
    this.getPositionList()
    if (this.id && this.id !== 'none') {
      this.getDetail()
      // this.getexhibitionList(this.id)
    }
  }
}
</script>

<style scoped>
/* 引入公共css类 */
@import url(./style);
</style>

<style>
.ql-picker-label {
  line-height: 1;
  overflow: hidden;
}

.avatar-uploader{
  border: 1px dashed #ccc;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  margin-top: 10px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px!important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.vrequired .el-form-item__label::before{
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
}
</style>
