<template>
  <div class="app-container calendar-list-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-if="contentType=='servicePacesetter'" clearable class="filter-item" style="width: 200px;" placeholder="请输入姓名" v-model="listQuery.title"></el-input>
      <el-input v-else clearable class="filter-item" style="width: 200px;" placeholder="请输入标题" v-model="listQuery.title"></el-input>
      <el-input  clearable class="filter-item" style="width: 200px;" placeholder="请输入创建者" v-model="listQuery.creator"></el-input>

      <el-date-picker  clearable class="filter-item"
                      v-model="listQuery.dateRange"
                      type="daterange"
                      unlink-panels
                      range-separator="至"
                      value-format="yyyy-MM-dd"
                      start-placeholder="创建开始日期"
                      end-placeholder="创建结束日期"
                       :picker-options="pickerOptions4">
      </el-date-picker>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" type="primary" @click="handleCreate" icon="el-icon-edit">添加</el-button>
      <el-button class="filter-item" type="warning" icon="el-icon-delete" @click="delAll">批量删除</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading="listLoading" @selection-change="handleSelectionChange" element-loading-text="正在查询中。。。" border fit
              highlight-current-row>

      <el-table-column  :key="Math.random()" type="expand" v-if="contentType == 'servicePacesetter'">
        <template slot-scope="props">
          <el-form v-if="contentType=='activity'" label-position="left" inline class="demo-table-expand">
          </el-form>
          <el-form v-else-if="contentType == 'servicePacesetter'" label-position="left" inline class="demo-table-expand">
            <el-form-item label="头像：">
              <img :src="props.row.image" style="width: 50px;height: 50px;border-radius: 50%"/>
            </el-form-item>
          </el-form>
          </template>

      </el-table-column>
      <el-table-column :key="Math.random()" type="selection" width="55px"> </el-table-column>
      <el-table-column :key="Math.random()" type="index" label="序号" header-align="center" align="center">
      </el-table-column>

      <el-table-column :key="Math.random()" v-if="contentType == 'servicePacesetter'" align="center" min-width="150px" label="姓名" prop="title">
      </el-table-column>


      <el-table-column :key="Math.random()" v-else align="center" min-width="150px" label="标题" prop="title">
      </el-table-column>

<!--      <el-table-column :key="Math.random()" v-if="contentType == 'servicePacesetter'" align="center" min-width="100px" label="描述" prop="content">-->
<!--      </el-table-column>-->

      <el-table-column :key="Math.random()" v-if="contentType != 'servicePacesetter'" align="center" min-width="100px" label="创建者" prop="creator">
      </el-table-column>


      <el-table-column :key="Math.random()" align="center" min-width="120px" label="创建时间" prop="createDate">
      </el-table-column>
      <el-table-column :key="Math.random()" align="center" min-width="80px" label="优先级" prop="weight"></el-table-column>

      <el-table-column :key="Math.random()" align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleUpdate(scope.row, false)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="70%">
      <template v-if="!dialogFlag">
        <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left"
                 label-width="110px" style='width: 600px; margin-left:50px;'>

          <el-form-item v-if="contentType == 'servicePacesetter'" label="姓名" prop="title">
            <el-input v-model="dataForm.title"></el-input>
          </el-form-item>
          <el-form-item v-else label="标题" prop="title">
            <el-input v-model="dataForm.title"></el-input>
          </el-form-item>

          <el-tooltip content="优先级越大，位置越靠前！" placement="top-start">
            <el-form-item  label="优先级" prop="weight">
              <el-input-number :precision="0" :step="1" v-model="dataForm.weight"></el-input-number>
            </el-form-item>
          </el-tooltip>

          <el-form-item v-if="contentType == 'servicePacesetter'" label="首页头像" prop="image">
            <el-upload
              class="avatar-uploader"
              :action="fileUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>


          <el-form-item v-if="contentType=='administrationInfo' || contentType=='centraActivities'" style="width: 800px;" label="列表图片" prop="image">
            <el-tooltip content="建议图片宽高比260*200" placement="top-start">
            <el-upload
              :action="fileUrl"
              list-type="picture-card"
              multiple
              :limit="5"
              :file-list="dataForm.images"
              :on-success="handleGallerySucess"
              :on-exceed="handleExceed"
              :before-upload="uploadBannerImg"
              :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
            </el-tooltip>
          </el-form-item>


          <el-form-item v-if="contentType=='notice'" label="上传附件">
            <el-upload
              class="avatar-uploader"
              :action="fileUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :file-list="dataForm.files"
              :on-success="handleAvatarSuccess"
              :on-exceed="handleExceed">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>

          </el-form-item>


          <template v-if="contentType == 'centraActivities'">
            <el-form-item label="活动地点" prop="activityAddress">
              <el-input v-model="dataForm.activityAddress"></el-input>
            </el-form-item>


            <el-form-item label="活动开始时间" prop="activityStartDate" label-width="10">
              <el-date-picker v-model="dataForm.activityStartDate" type="datetime" value-format="yyyy-MM-dd HH:mm"
                              placeholder="选择日期" :picker-options="pickerOptions2" style="width: 350px;"></el-date-picker>
            </el-form-item>

            <el-form-item label="活动结束时间" prop="activityEndDate" label-width="10">
              <el-date-picker v-model="dataForm.activityEndDate" type="datetime" value-format="yyyy-MM-dd HH:mm"
                              placeholder="选择日期" :picker-options="pickerOptions3" style="width: 350px;"></el-date-picker>
            </el-form-item>

          </template>


          <el-form-item style="width: 800px;"  label="内容" prop="content">
            <tinymce v-model="dataForm.content" ref="tinymce1"></tinymce>
          </el-form-item>

        </el-form>
      </template>
      <template v-else>
        <el-form status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        </el-form>
      </template>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <template v-if="!dialogFlag">
          <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
          <el-button v-else type="primary" @click="updateData">确定</el-button>
        </template>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {listNews, createNews, readNews, updateNews,updateNewsAuth, deleteNews, deleteAllNews,listActivityOrg} from
      '@/api/news'
  import {selectOrg, createOrg, updateOrg} from "@/api/organize"
  import waves from '@/directive/waves' // 水波纹指令
  import BackToTop from '@/components/BackToTop'
  import Tinymce from '@/components/Tinymce'
  import SidebarItem from "../layout/components/Sidebar/SidebarItem";

    export default {
      name: "index",
      components: {SidebarItem, BackToTop, Tinymce },
      directives: {
        waves
      },
      data() {
        let checkTitle=(rule, value, callback)=>{
          if (!value) {
            if(this.contentType=='servicePacesetter'){
              callback(new Error("名称不能为空！"));
            }else{
              callback(new Error("标题不能为空！"));
            }
          } else {
            if(this.contentType=='servicePacesetter'){
              if(value.length>5){
                callback(new Error("名字不能超过5个字！"));
              }
            }
            callback();
          }
        }
          return {
            contentType: undefined,
            title: '',
            listLoading: false,
            listQuery: {
              type: undefined,
              activityType: [],
              activityState: undefined,
              title: undefined,
              creator: undefined,
              page: 1,
              limit: 20,
              sort: '+id',
              dateRange: undefined,
              activityAuditState: -1
            },
            list: undefined,
            // userList:undefined,
            delarr:[],
            multipleSelection: [],
            total: 0,
            dialogFormVisible: false,
            UdialogFormVisible: false,
            dialogStatus: '',
            dialogFlag: false,
            textMap: {
              update: '编辑',
              create: '创建'/*,
              userList:'参加人员名单'*/
            },
            fileUrl: process.env.BASE_API + '/storage/create',
            dataForm: {
              id: undefined,
              type: undefined,
              title: undefined,
              content: undefined,
              image: '',
              images: [],
              file: undefined,
              fileName: undefined,
              files: [],
              creator: undefined,
              createDate: undefined,
              activityStartDate: undefined,
              activityEndDate: undefined,
              registStartDate: undefined,
              registEndDate: undefined,
              activity: undefined,
              activityAddress: undefined,
              activitys: [],
              organizeId: [],
              activityAuditState: undefined,
              activityForNews: undefined,
              universitarios: undefined,
              activityCost: 0.00,
              activityLimit:0,
              activityType:undefined
            },
            imageUrl: undefined,
            rules: {
              title: [{ required: true,validator:checkTitle, trigger: 'blur' }

              ],
              image:[{required: true, message: '图片不能为空', trigger: 'blur' }],
              images:[{required: true, message: '图片不能为空', trigger: 'blur' }],
              registStartDate:[{required: true, message: '时间不能为空', trigger: 'blur'}],
              registEndDate:[{required: true, message: '时间不能为空', trigger: 'blur'}],
              activityStartDate:[{required: true, message: '时间不能为空', trigger: 'blur'}],
              activityEndDate:[{required: true, message: '时间不能为空', trigger: 'blur'}],
              activitys:[{required: true, message: '标签不能为空', trigger: 'blur'}]
            },
            downloadLoading: false,
            // dynamicTags: [],
            inputVisible: false,
            inputValue: '',
            activityList: [],
            organizes: [],
            pickerOptions0: {
              disabledDate: (time) => {
                let beginDateVal = new Date(this.dataForm.registEndDate).getTime();
                if (beginDateVal) {
                  return (time.getTime() > beginDateVal) || (time.getTime() < Date.now() - 8.64e7);
                }else{
                  return time.getTime() < Date.now() - 8.64e7
                }
              }
            },
            pickerOptions1: {
              disabledDate: (time) => {
                let beginDateVal = new Date(this.dataForm.activityStartDate).getTime();
                if (beginDateVal) {
                  return (time.getTime() > beginDateVal) || (time.getTime() < Date.now() - 8.64e7);
                }else{
                  return time.getTime() < Date.now() - 8.64e7
                }
              }
            },
            pickerOptions2: {
              disabledDate: (time) => {
                let beginDateVal = new Date(this.dataForm.activityEndDate).getTime();
                if (beginDateVal) {
                  return (time.getTime() > beginDateVal) || (time.getTime() < Date.now() - 8.64e7);
                }else{
                  return time.getTime() < Date.now() - 8.64e7;
                }
              }
            },
            pickerOptions3: {
              disabledDate: (time) => {
                return time.getTime() < Date.now() - 8.64e7;
              }
            },
            pickerOptions4: {
              disabledDate: (time) => {
                return time.getTime() > Date.now();
              }
            },
            aTypeOptions:
              [{
                value: 'mail',
                label: '是'
              }, {
                value: '',
                  label: '否'
              }],
          }
      },

      created() {
        this.title = this.$route.meta.title
        this.textMap.create = "创建-" + this.title
        this.contentType = this.$route.name


        selectOrg({orgType: undefined, orgName: undefined, page: 1, limit: 1000}).then(response => {
          this.organizes = response.data.data.items
        }).catch(() => {
          this.organizes = []
        })

        this.getList()
      },

      methods: {
        resetForm() {
          this.dataForm = {
            id: undefined,
            type: undefined,
            title: undefined,
            content: undefined,
            image: undefined,
            images: [],
            file: undefined,
            fileName: undefined,
            files: [],
            createDate: undefined,
            activityStartDate: undefined,
            activityEndDate: undefined,
            activity: undefined,
            activityAddress: undefined,
            activitys: [],
            organizeId: [],
            activityAuditState: undefined,
            activityForNews: undefined,
            universitarios: undefined,
            activityCost: 0.00,
            activityLimit: 0,
            activityType:undefined
          }
        },

        resetList() {
          this.listQuery = {
            type: undefined,
            activityType: [],
            activityState: undefined,
            title: undefined,
            creator: undefined,
            page: 1,
            limit: 20,
            sort: '+id',
            dateRange: undefined,
            activityAuditState: -1
          }
          this.list = undefined
          // this.userList = undefined
          this.total = 0
        },
        getList() {
          this.listLoading = true
          this.listQuery.type = this.contentType
          listNews(this.listQuery).then(response => {

            this.list = response.data.data.items
            this.total = response.data.data.total
            this.listLoading = false
          }).catch(() => {

            this.list = []
            this.total = 0
            this.listLoading = false

          })
        },

        handleFilter() {
          this.listQuery.page = 1;
          this.getList();
        },

        handleSizeChange(val) {
          this.listQuery.limit = val
          this.getList()
        },

        handleCurrentChange(val) {
          this.listQuery.page = val
          this.getList()
        },

        handleCreate() {

          this.resetForm()
          this.imageUrl=undefined
          this.dialogFormVisible = true
          this.dialogStatus = 'create'
          this.dialogFlag = false

          this.$nextTick(() => {
            this.$refs.tinymce1.setContent('')
            this.$refs['dataForm'].clearValidate()
          })
        },

        createData() {
          this.$refs['dataForm'].validate((valid) => {
            if(valid) {
              if(this.dataForm.activityEndDate < this.dataForm.activityStartDate) {
                this.$alert('活动结束时间不得小于活动开始时间', '提示', {
                  confirmButtonText: '确定',
                });
              } else if (this.dataForm.activityStartDate < this.dataForm.registEndDate) {
                this.$alert('活动开始时间不得小于报名截止时间', '提示', {
                  confirmButtonText: '确定',
                });
              } else if (this.dataForm.registEndDate < this.dataForm.registStartDate) {
                this.$alert('报名截止时间不得小于报名开始时间', '提示', {
                  confirmButtonText: '确定',
                });
              } else {
                this.dataForm.type = this.contentType
                createNews(this.dataForm).then(response => {
                  //this.list.unshift(response.data.data)
                  this.getList()
                  this.dialogFormVisible = false

                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                }).catch(() => {

                })
              }
            }
          })
        },
        handleUpdate(row) {
          this.dataForm = Object.assign({organizeId: [], activitys: []}, row)
          let content = this.dataForm.content


          // 构建轮播图片列表
          if(this.dataForm.image) {
            let images = this.dataForm.image.split(',')
            this.dataForm.images = []
            for(let i in images) {
              let url = images[i]
              let name = 'image_' + i

              this.dataForm.images.push({name: name, url: url, response: {error: '0', data: {url: url}}})
            }
          }
          if(this.contentType == 'servicePacesetter') {
            this.imageUrl = this.dataForm.image
          }

          if(this.dataForm.file) {
            let fileUrl = this.dataForm.file
            // let fileName = fileUrl.substr(fileUrl.lastIndexOf('/') + 1, fileUrl.length)
            let fileName = this.dataForm.fileName
            this.dataForm.files = []
            this.dataForm.files.push({name: fileName, url: fileUrl, response: {error: '0', data: {url: fileUrl}}})
          }

          listActivityOrg({newsId : this.dataForm.id}).then(response => {
            let items = response.data.data.items
            this.dataForm.organizeId = items.map((item)=>{
              return item.organizeId
            })

          }).catch(() => {

          })

          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs.tinymce1.setContent(content)
            this.$refs['dataForm'].clearValidate()
          })
        },

        updateData() {
          this.$refs['dataForm'].validate((valid) => {
            if(valid) {
              if(this.dataForm.activityEndDate < this.dataForm.activityStartDate) {
                this.$alert('活动结束时间不得小于活动开始时间', '提示', {
                  confirmButtonText: '确定',
                });
              } else if (this.dataForm.activityStartDate < this.dataForm.registEndDate) {
                this.$alert('活动开始时间不得小于报名截止时间', '提示', {
                  confirmButtonText: '确定',
                });
              }else if (this.dataForm.registEndDate < this.dataForm.registStartDate) {
                this.$alert('报名截止时间不得小于报名开始时间', '提示', {
                  confirmButtonText: '确定',
                });
              } else {
                updateNews(this.dataForm).then(() => {
                  this.getList()
                  // for(const v of this.list) {
                  //   if(v.id === this.dataForm.id ) {
                  //     const index = this.list.indexOf(v)
                  //     this.list.splice(index, 1, this.dataForm)
                  //     break
                  //   }
                  // }

                  this.dialogFormVisible = false
                  this.$notify({
                    title: '成功',
                    messagae: '更新成功',
                    type: 'success',
                    duration: 2000
                  })
                }).catch(() => {

                })
              }
            }
          })
        },

        handleDelete(row) {

          this.$confirm('确认删除吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteNews(row).then(()=>{
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })

              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            }).catch(() => {

            })
          }).catch(() => {

          })

        },
        delAll(){
          this.$confirm('确认删除吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const length = this.multipleSelection.length;

            for (let i = 0; i < length; i++){
              this.delarr.push(this.multipleSelection[i].id)
            }
            const newsIds = this.delarr.join(",");
            deleteAllNews({newsId:newsIds}).then(()=>{
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            this.getList();
            }).catch(() => {

          })
        }).catch(() => {

          })
        },
        handleSelectionChange(val){
          this.multipleSelection = val;
        },


        handlePreview(file) {
          console.log(file);
        },

        beforeRemove(file, fileList) {
          return this.$confirm(`确定移除 ${ file.name }？`)
        },

        handleRemove(file, fileList) {
          console.log(file, fileList)

          if(this.contentType=='notice') {
            this.dataForm.file = ''
            this.dataForm.fileName = ''
            this.dataForm.files = []

          } else {
            let images = []
            for(let i in fileList) {
              let response = fileList[i].response
              let url = response.data.url
              images.push(url)
            }

            this.dataForm.image = images.join(',')
          }

        },

        handleExceed(files, fileList) {
          this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件！`)
        },

        uploadBannerImg(file) {
          const isJPGs = file.type === 'image/jpeg'
          console.log(isJPGs)
        },

        handleAvatarSuccess(res, file, fileList) {
          // this.imageUrl = URL.createObjectURL(file.raw)


          if(this.contentType == 'servicePacesetter') {
            this.imageUrl = res.data.url
            this.dataForm.image = res.data.url
          } else if(this.contentType=='notice') {
            this.dataForm.file = res.data.url
            this.dataForm.fileName = res.data.oldName
            this.dataForm.files = []
            this.dataForm.files.push(file)
          }
        },

        beforeAttacheUpload(file) {
          return true
        },

        beforeAvatarUpload(file) {
          const isJPG = file.type === 'image/jpeg'
          const isLt2M = file.size / 1024 / 1024 < 2

          if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!')
          }
          if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!')
          }
          return isJPG && isLt2M
        },

        handleGallerySucess(res, file, fileList) {

          this.dataForm.image = '' // 清空画廊图片数组

          let images = []
          for(let i in fileList) {
            let response = fileList[i].response
            if(response.errno && response.errno != '0') {
              this.$message.error('该图片上传失败,已被移除,请重新上传!')
              // 上传失败移除该 file 对象
              fileList.splice(i, 1)
            } else {

              let url = response.data.url
              images.push(url)
            }
          }

          this.dataForm.image = images.join(',')
        },


        showInput() {
          this.inputVisible = true
          this.$nextTick(() => {
            this.$refs.saveTagInput.$refs.input.focus();
          })
        },
      },

      watch: {
        '$route'(to, from) {
          this.title = this.$route.meta.title
          this.textMap.create = "创建-" + this.title
          this.contentType = this.$route.name

          this.resetForm()
          this.resetList()


          this.getList()
        }
      }
    }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    border-radius: 178px;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    margin-top: 2px;
    height: 28px;
    line-height: 23px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
