<template>

  <div class="app-container theme_main">
    <!-- 右上角btn -->
    <div class="home_publish_btn">
      <el-button round class="el_button_green" @click="addEditClassify(0)">新增</el-button>
      <el-button round type="primary" @click="addEditClassify(1)">编辑</el-button>
      <el-button round class="el_button_red" @click="uploadTheme()">上传</el-button>
    </div>
    <div style="position:relative">
      <!-- 主题库list -->
      <ThemeGalleryList
        ref="ThemeGalleryList"
        :is-multi-selected="isMultiSelected"
        :mulit-text="mulitText"
        :show-item-info="showItemInfo"
        :tab-item="tabItem"
        @changedMultiSelected="changedMultiSelected"
      />
      <div class="material_btn">
        <el-button round type="primary" @click="uploadHistoryVisible=true">上传历史</el-button>
        <el-button round @click="multiSelectBtn">{{ mulitText }}</el-button>
      </div>
    </div>

    <!-- 平台技术人员-新增/编辑分类 -->
    <div class="upload_layer">
      <el-dialog append-to-body :show-close="false" :visible.sync="addDialogVisible" :close-on-click-modal="false" :title="layerTitle" width="620px">
        <el-form ref="classifyForm" inline :model="classifyForm" size="small" label-width="80px">
          <el-form-item
            v-if="isAddEdit==0"
            label="类别名称"
            prop="class_name"
            :rules="[
              { required: true, message: '请输入类别名称', trigger: 'blur' }
            ]"
          >
            <el-input v-model="classifyForm.class_name" style="width: 360px;" />
          </el-form-item>
          <el-form-item
            v-else
            label="类别名称"
            prop="class_name"
            :rules="[
              { required: true, message: '请选择类别名称', trigger: 'change' }
            ]"
          >
            <el-select v-model="classifyForm.class_name" placeholder="请选择" value-key="class_name" style="width: 360px;" @change="selectName">
              <el-option v-for="item in tabItem" :key="item.id" :label="item.class_name" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="所属机构"
            prop="searchClassify"
          >
            <el-select v-model="searchClassify" multiple placeholder="请选择" style="width: 360px;" @change="changeSelect">
              <el-option
                v-for="item in organOptions"
                :key="item.value"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" round @click="submitForm('classifyForm')">保 存</el-button>
          <el-button round @click="resetForm('classifyForm')">关 闭</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 平台技术人员-上传 -->
    <el-dialog append-to-body :show-close="false" :visible.sync="uploadDialogVisible" :close-on-click-modal="false" :title="uploadTitle" class="upload_layer">
      <el-form ref="uploadForm" :model="uploadForm" size="small" label-width="80px">
        <el-form-item label="类别名称" prop="selectClassifyList">
          <el-checkbox-group v-model="selectClassifyList">
            <el-checkbox v-for="item in tabItem" :key="item.id" :label="item.id" :value="item.id">{{ item.class_name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="设备方向" prop="device_direction">
          <el-radio-group v-model="uploadForm.device_direction">
            <el-radio :label="1" value="1">横屏</el-radio>
            <el-radio :label="2" value="2">竖屏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="isUploadThemeType == 1" prop="material_name" label="文件名称">
          <el-input v-model="uploadForm.material_name" style="width:336px" />
        </el-form-item>
        <el-form-item class="upload_source" label="上传内容" prop="deposit_url">
          <div v-if="formatType != -1" class="source_cont">
            <img v-if="formatType==0" :src="uploadForm.deposit_url" alt="" width="150" />
            <video v-if="formatType==1" :src="uploadForm.deposit_url" controls width="200"></video>
            <audio v-if="formatType==2" :src="uploadForm.deposit_url" controls></audio>
            <!-- <p>文件名：{{ fileNames }}</p> -->
          </div>
          <Upload ref="uploadMaterial" :is-theme="isTheme" @saveMaterial="saveMaterial" @uploadSubmit="uploadSubmit" />
        </el-form-item>
        <el-form-item v-if="formatType != 0" label="添加封面" prop="img_path">
          <UploadCover ref="childUpload" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" round @click="uploadSubmit('uploadForm')">确 定</el-button>
        <el-button round @click="resetForm('uploadForm')">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 上传历史layer -->
    <div class="upload_layer">
      <el-dialog title="上传历史" :close-on-click-modal="false" :visible.sync="uploadHistoryVisible" width="1100px">
        <!-- 上传历史 - 搜索 -->
        <el-form ref="form" :model="queryForm" label-width="80px" class="query_history">
          <el-form-item label="文件名称">
            <el-input v-model="queryForm.name" style="width:200px" @keyup.enter.native="getThemeHistoryList(pager = 1)" @blur="getThemeHistoryList(pager = 1)" />
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker v-model="queryForm.date" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="getThemeHistoryList(pager = 1)" @blur="getThemeHistoryList(pager = 1)" />
          </el-form-item>
        </el-form>
        <!-- 上传历史 - table-list -->
        <el-table :data="uploadHistoryListData" :header-cell-style="{ color: '#333' }">
          <el-table-column align="center" prop="material_name" label="文件名称" />
          <el-table-column align="center" prop="cover" label="发布内容">
            <template slot-scope="scope">
              <div v-if="scope.row.img_path">
                <img width="48px" height="64px" size="medium" :src="scope.row.img_path" />
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="classes" label="类别名称" width="180">
            <template slot-scope="scope">
              <div class="tag_list">
                <el-tag v-for="tag in scope.row.classes.split(',')" :key="tag" type="primary">{{ tag }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="device_direction" label="设备方向">
            <template slot-scope="scope">
              {{ scope.row.device_direction==2 ? "竖屏" : "横屏" }}
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" prop="agency" label="所属机构" /> -->
          <el-table-column align="center" prop="create_time" label="上传时间" width="150">
            <template slot-scope="{row}">
              <div>{{ row.create_time | parseTime }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="create_by" label="发布人" />
          <el-table-column align="center" prop="handle" label="操作">
            <template slot-scope="scope">
              <el-button type="primary" round class="edit_btn" @click="editUploadTheme(scope.row)">编辑</el-button>
              <el-button type="primary" round :class="['start_btn', { stop_btn: scope.row.is_state == 1 }]" @click="isStopHandle(scope.row)">{{ scope.row.is_state == 1 ? "停用" : "恢复" }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination style="margin-top: 20px;" background :current-page="page" :total="total" :page-size="size" :pager-count="5" :page-sizes="[3, 5, 10]" layout="prev, pager, next, jumper,->,sizes,total" @current-change="getThemeHistoryList" @size-change="handleSizeChange" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { FetchAddOrEdit, FetchThemeHistoryList, FetchUpdateThemeState } from '@/api/theme/theme.js'
import { saveMaterial } from '@/api/material/material'
import ThemeGalleryList from '../components/ThemeGalleryList.vue'
import Upload from '../components/upload'
import UploadCover from '../components/upload_cover'
import { parseTime } from '@/utils/index.js'
export default {
  name: 'ThemeGallery',
  components: { ThemeGalleryList, UploadCover, Upload },
  filters: {
    parseTime(time, cFormat) {
      return parseTime(time, cFormat)
    }
  },
  data() {
    return {
      isTheme: true,
      orga_id: '133221333123111', // 机构ID
      addDialogVisible: false, // 新增编辑-分类弹框
      layerTitle: '新增',
      isAddEdit: 0, // 判断分类菜单是新增还是编辑
      classifyForm: { //  主题库分类菜单form
        class_name: '',
        is_all: false,
        id: '',
        orga_ids: []
      },
      tabItem: [], // 分类菜单data
      searchClassify: [], // 机构选择多选操作
      oldSearchClassify: [],
      organOptions: [ // 机构list-data
        {
          label: '全部',
          value: 'ALL_SELECT',
          id: 'ALL_SELECT'
        },
        {
          label: '武汉图书馆',
          value: '01',
          id: '133221333123111'
        }
      ],
      mulitText: '多选', // 主题库list - 多选操作
      isMultiSelected: false,
      showItemInfo: true, // 判断是否显示画册
      uploadDialogVisible: false, // 上传主题内容 - 弹框
      uploadHistoryVisible: false, // 上传主题历史 - 弹框
      uploadTitle: '上传', // 上传-弹框内
      isUploadThemeType: 0, // 判断上传-新增还是编辑
      uploadForm: { // 上传素材
        class_ids: [
          // 素材类id集合
        ],
        deposit_url: null, // 素材存放路径
        device_direction: null, // 横竖屏 1.横屏 2.竖屏,
        duration: null, // 时长s
        material_id: null,
        folder_id: null, // 文件夹id
        img_path: null, // 封面图片id
        material_name: null, // 素材名称
        material_type: null, // 素材类别
        file_size: null, // 文件大小
        orga_id: null, // 机构id
        store_type: null // 库类型 1.素材库 2.主题库
      },
      fileNames: '',
      formatType: -1,
      materialImgPath: null,
      materialDuration: null,
      selectClassifyList: [],
      queryForm: { // 历史list - 搜索
        name: '',
        date: []
      },
      uploadHistoryListData: [], // 上传历史list
      isEditTheme: false,
      page: 1,
      size: 10,
      total: 0
    }
  },
  watch: {
  },
  mounted() {
    // 上传历史list
    this.getThemeHistoryList()
  },
  methods: {
    // 机构选择 全选 / 多选
    changeSelect(val) {
      const allValues = []
      // 保留所有值
      for (const item of this.organOptions) {
        allValues.push(item.id)
      }
      // 用来储存上一次的值，可以进行对比
      const oldVal = this.oldSearchClassify.length === 1 ? this.oldSearchClassify[0] : []
      // 若是全部选择
      if (val.includes('ALL_SELECT')) this.searchClassify = allValues
      // 取消全部选中 上次有 当前没有 表示取消全选
      if (oldVal.includes('ALL_SELECT') && !val.includes('ALL_SELECT')) this.searchClassify = []
      // 点击非全部选中 需要排除全部选中 以及 当前点击的选项
      // 新老数据都有全部选中
      if (oldVal.includes('ALL_SELECT') && val.includes('ALL_SELECT')) {
        const index = val.indexOf('ALL_SELECT')
        val.splice(index, 1) // 排除全选选项
        this.searchClassify = val
      }
      // 全选未选 但是其他选项全部选上 则全选选上 上次和当前 都没有全选
      if (!oldVal.includes('ALL_SELECT') && !val.includes('ALL_SELECT')) {
        if (val.length === allValues.length - 1) this.searchClassify = ['ALL_SELECT'].concat(val)
      }
      // 储存当前最后的结果 作为下次的老数据
      this.oldSearchClassify[0] = this.searchClassify
    },
    // 编辑分类 - 类型名称选择
    selectName(vId) {
      this.classifyForm.id = vId.id
      this.classifyForm.class_name = vId.class_name
    },
    // 主题库分类菜单 - 新增 / 编辑
    addEditClassify(index) {
      this.addDialogVisible = true
      if (index == 1) {
        this.layerTitle = '编辑'
        this.isAddEdit = 1
        this.tabItem = this.$refs.ThemeGalleryList.tabItem
        this.activeIndex = this.$refs.ThemeGalleryList.activeIndex
        this.classifyForm.class_name = this.tabItem[this.activeIndex].class_name
        this.classifyForm.id = this.tabItem[this.activeIndex].id
        // if (this.classifyForm.is_all) {
        //   this.classifyForm.is_all_name == '全部'
        //   this.classifyForm.orga_ids = []
        // } else {
        //   this.classifyForm.is_all_name == '武汉图书馆'
        // }
      } else {
        this.layerTitle = '新增'
        this.isAddEdit = 0
        this.classifyForm.id = null
        this.classifyForm.class_name = ''
      }
    },
    // 新增/编辑 - 分类菜单 - 提交
    submitForm(formName) {
      this.classifyForm.is_all = !!this.searchClassify.includes('ALL_SELECT')
      this.classifyForm.orga_ids = this.searchClassify.includes('ALL_SELECT') ? [] : this.searchClassify
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.searchClassify.length == 0) {
            this.$message.error('请选择所属机构！')
            return false
          }
          FetchAddOrEdit(this.classifyForm).then(res => {
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: this.classifyForm.id ? '编辑成功' : '新增成功'
              })
              this.addDialogVisible = false
              this.searchClassify = []
              this.$refs.ThemeGalleryList.getThemeClassList()
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 表单 - 关闭btn
    resetForm(formName) {
      this.addDialogVisible = false
      this.uploadDialogVisible = false
      this.searchClassify = []
      // 上传表单重置
      this.selectClassifyList = []
      this.uploadForm.device_direction = 0
      this.uploadForm.deposit_url = null
      this.formatType = -1
      this.uploadForm.material_type = null
      this.uploadForm.img_path = null
      this.materialImgPath = null
      this.$nextTick(() => {
        this.$refs.uploadMaterial.filePercent = 0
        if (this.$refs.childUpload) {
          this.$refs.childUpload.imageUrl = null
        }
      })
      this.$refs[formName].resetFields()
    },
    // list - 多选btn
    multiSelectBtn() {
      this.isMultiSelected = !this.isMultiSelected
      if (this.isMultiSelected) {
        this.mulitText = '取消'
      } else {
        this.mulitText = '多选'
      }
    },
    // 新增 - 上传
    uploadTheme() {
      this.isEditTheme = false
      this.$nextTick(() => {
        this.tabItem = this.$refs.ThemeGalleryList.tabItem
      })
      this.uploadDialogVisible = true
      this.isUploadThemeType = 0
      this.uploadTitle = '新增'
      this.uploadForm.device_direction = 0
    },
    // 编辑 - 上传
    editUploadTheme(row) {
      this.isEditTheme = true
      this.uploadDialogVisible = true
      this.isUploadThemeType = 1
      this.uploadTitle = '编辑'
      this.$nextTick(() => {
        this.tabItem = this.$refs.ThemeGalleryList.tabItem
        const classifyListName = row.classes.split(',')
        if (classifyListName) {
          this.selectClassifyList = []
          this.tabItem.filter(item => {
            if (classifyListName.indexOf(item.class_name) != -1) {
              this.selectClassifyList.push(item.id)
            }
          })
        }
      })
      this.uploadForm.device_direction = row.device_direction
      this.uploadForm.material_name = row.material_name
      this.fileNames = row.material_name
      this.uploadForm.deposit_url = row.deposit_url

      this.formatType = row.material_type
      if (this.formatType != 0) {
        this.$nextTick(() => {
          if (this.$refs.childUpload) {
            this.$refs.childUpload.imageUrl = row.img_path
          }
        })
      } else {
        this.uploadForm.img_path = row.deposit_url
      }
      this.uploadForm.material_type = this.formatType
      this.uploadForm.duration = row.duration
      this.uploadForm.file_size = row.file_size
      this.uploadForm.material_id = row.material_id
    },
    // 素材上传完之后 - 获取相关info
    saveMaterial() {
      const formatType = this.$refs.uploadMaterial.formatType
      const uploadFileUrl = this.$refs.uploadMaterial.uploadFileUrl
      // 视频和音频的时长
      const duration = this.$refs.uploadMaterial.duration
      switch (formatType) {
        case 'image':
          this.formatType = 0
          this.materialImgPath = uploadFileUrl
          this.materialDuration = 0
          break
        case 'video':
          this.formatType = 1
          this.materialDuration = duration
          this.materialImgPath = null
          break
        case 'audio':
          this.formatType = 2
          this.materialDuration = duration
          this.materialImgPath = null
          break
      }
      this.uploadForm.deposit_url = uploadFileUrl
      this.fileNames = this.$refs.uploadMaterial.fileNames
      this.uploadForm.material_name = this.$refs.uploadMaterial.fileNames
      this.uploadForm.material_type = this.formatType
      this.uploadForm.file_size = this.$refs.uploadMaterial.fileSize
      this.uploadForm.img_path = this.materialImgPath
      this.uploadForm.duration = this.materialDuration
    },
    // 上传 - 提交btn
    uploadSubmit(formName) {
      if (this.isEditTheme) {
        this.$nextTick(() => {
          if (this.$refs.childUpload) {
            this.uploadForm.img_path = this.$refs.childUpload.imageUrl
          }
        })
      }
      this.uploadForm.class_ids = this.selectClassifyList
      // this.uploadForm.orga_id = this.orga_id
      this.uploadForm.store_type = 2
      this.$refs[formName].validate((valid) => {
        if (valid) {
          setTimeout(() => {
            saveMaterial(this.uploadForm).then(res => {
              if (res.code === 200) {
                this.$message({
                  message: '上传素材成功',
                  type: 'success'
                })
                this.uploadDialogVisible = false
                this.getThemeHistoryList()
                // 上传表单重置
                this.selectClassifyList = []
                this.uploadForm.device_direction = 0
                this.uploadForm.deposit_url = null
                this.formatType = -1
                this.uploadForm.material_type = null
                this.uploadForm.img_path = null
                this.materialImgPath = null
                this.$nextTick(() => {
                  this.$refs.uploadMaterial.filePercent = 0
                  if (this.$refs.childUpload) {
                    this.$refs.childUpload.imageUrl = null
                  }
                })
                this.$refs.uploadForm.resetFields()
              } else {
                this.$message.error(res.msg)
              }
            })
          }, 200)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 上传历史list - 主题库
    getThemeHistoryList(pager = 1) {
      this.page = pager
      let start_time = ''
      let end_time = ''
      if (this.queryForm.date) {
        start_time = this.queryForm.date[0]
        end_time = this.queryForm.date[1]
      } else {
        start_time = end_time = null
      }
      const params = {
        theme_name: this.queryForm.name,
        theme_class: null,
        device_direction: null,
        orga_id: null,
        start_time: start_time,
        end_time: end_time,
        folder_id: null,
        page: this.page,
        size: this.size
      }
      FetchThemeHistoryList(params).then(res => {
        if (res.code === 200) {
          this.uploadHistoryListData = res.data.content
          this.total = res.data.totalElements
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 每条显示数据改变时的事件
    handleSizeChange(size) {
      // 整理参数
      this.size = size
      this.getThemeHistoryList()
    },
    // 上传历史-停用/恢复
    isStopHandle(row) {
      row.is_state = row.is_state == 1 ? 2 : 1
      const params = {
        id: row.material_id,
        state: row.is_state
      }
      FetchUpdateThemeState(params).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg)
          this.getThemeHistoryList()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 有选择中的文件夹时，同时存在素材多选操作时，素材多选操作取消
    changedMultiSelected() {
      if (this.isMultiSelected) {
        this.isMultiSelected = false
        this.mulitText = '多选'
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.theme_main {
  position: relative;
  padding: 0;
  background: none;
  ::v-deep .el-tabs {
    height: 55px;
    padding: 0 24px;
    margin-bottom: 24px;
    line-height: 55px;
    background: #fff;
  }
  ::v-deep .el-tabs__nav-wrap::after {
    display: none;
  }
  ::v-deep .el-tabs__active-bar {
    display: none;
  }
  ::v-deep .theme_item_tab {
    margin-bottom: 0;
    .el-tabs__header {
      margin-bottom: 0;
      border-bottom: 1px solid #eee;
    }
  }
  ::v-deep .theme_img {
    align-content: flex-start;
    height: calc(100vh - 246px);
    padding: 18px 24px 0 24px;
    overflow-y: auto;
    background: #fff;
  }
  .material_btn {
    top: 93px;
  }
}
.upload_layer {
  .query_history {
    display: flex;
    margin-top: -16px;
  }
  ::v-deep .el-dialog__body {
    .el-form-item__label {
      height: 30px;
      line-height: 30px;
    }
    .el-input__inner {
      height: 30px;
      line-height: 30px;
    }
    .el-range-separator {
      line-height: 26px;
    }
    .el-checkbox__label {
      line-height: 30px;
    }
  }
}
.upload_source {
  ::v-deep .el-form-item__content{
    display: flex;
  }
  .source_cont{
    margin-right: 20px;
    p{
      font-size: 12px;
      padding: 0 10px;
      line-height: 32px;
    }
  }
  video{
    display: block;
  }
  audio{
    display: block;
  }
  img{
    display: block;
  }
}
::v-deep .components_upload{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
  text-align: center;
  width: 128px;
  height: 120px;
  font-size: 14px;
  border: 1px dashed #dcdde3;
  background: #f2f7ff;
  border-radius: 6px;
  .cont_upload_btn{
    display: block;
    width: 100px;
    height: 34px;
    font-size: 14px;
    left: 50%;
    top: 14px;
    margin-left: -50px;
  }
  #upFile{
    margin: 0 auto;
  }
  .start_upload{
    display: block;
    width: 100px;
    height: 34px;
    color: #fff;
    text-align: center;
    border: none;
    background: linear-gradient(to right, #fc8c6f, #fa544e);
    border-radius: 34px;
    margin: 10px auto;
  }
}
.tag_list{
  ::v-deep .el-tag{
    margin:  0 5px 5px 0;
  }
}
</style>
