<template>
  <div class="app-container calendar-list-container" v-loading.body="showLoadingBody">
    <div>
      <div class="filter-container" ref="filter-container">
        <el-form :inline="inline" ref="queryForm" :model="listQuery" label-width="100px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="发布时间" prop="startTime">
                <el-date-picker
                  v-model="listQuery.startTime"
                  type="date"
                  :editable="false"
                  format="yyyy-MM-dd"
                  prop="startTime"
                  placeholder="请选择开始时间">
                </el-date-picker>~
                <el-date-picker
                  v-model="listQuery.endTime"
                  type="date"
                  :editable="false"
                  format="yyyy-MM-dd"
                  prop="endTime"
                  placeholder="请选择结束时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="来源">
                <el-select class="filter-item" v-model="listQuery.source" placeholder="请选择来源">
                  <el-option :key="undefined" label="全部" :value="undefined"></el-option>
                  <el-option key="1" label="后台创建" value="1"></el-option>
                  <el-option key="2" label="app用户" value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="点赞数 >">
                <el-input v-model.number="listQuery.praise" type="number" min="0" placeholder="请输入点赞数"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="评论数 >">
                <el-input v-model.number="listQuery.comment" type="number" min="0" placeholder="请输入评论数"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="用户名">
                <el-input v-model.number="listQuery.username" placeholder="请输入用户名"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
        <el-button class="filter-item" type="primary" v-waves @click="reloadPage">重置</el-button>
        <!-- <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate"
                   type="primary" icon="edit">添加
        </el-button> -->
      </div>
      <el-table :key='tableKey' :data="list" border fit highlight-current-row
                style="width: 100%">
        <el-table-column
          type="index"
          align="center" label="序号" width="65">
        </el-table-column>
        <el-table-column align="center" label="msgId">
          <template slot-scope="scope">
            <span>{{scope.row.msgId}}</span>
          </template>
        </el-table-column>
        <!--<el-table-column align="center" label="标题">-->
          <!--<template slot-scope="scope">-->
            <!--<span>{{scope.row.body?scope.row.body.title:''}}</span>-->
          <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column align="center" label="描述">
          <template slot-scope="scope">
            <span>{{scope.row.body?scope.row.body.text:''}}</span>
          </template>
        </el-table-column>
        <el-table-column  align="center" width="100" label="视频">
          <template slot-scope="scope">
            <el-button v-if="scope.row.body.videos" size="small" @click="handleVideo(scope.row.body.videos)" class="el-button el-button--text el-button--small" >点击查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column width="100" align="center" label="点赞数">
          <template slot-scope="scope">
            <span>{{scope.row.count?scope.row.count.praise:0}}</span>
          </template>
        </el-table-column>
        <el-table-column width="100" align="center" label="评论数">
          <template slot-scope="scope">
            <span>{{scope.row.count?scope.row.count.comment:0}}</span>
          </template>
        </el-table-column>
        <el-table-column width="200" align="center" label="发布时间">
          <template slot-scope="scope">
            <span>{{scope.row.body.timeStr}}</span>
          </template>
        </el-table-column>
        <el-table-column width="100" align="center" label="来源">
          <template slot-scope="scope">
            <span>{{scope.row.source == 1? '后台创建':'app用户'}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button size="small"  class="el-button el-button--text el-button--small" @click="handleUpdate(scope.row)">编辑
            </el-button>
            <el-button size="small" class="el-button el-button--text el-button--small" style="color: green;" v-if="scope.row.visible==2" @click="upStatus(scope.row)">设置为公开
            </el-button>
            <el-button size="small" class="el-button el-button--text el-button--small" style="color: red" v-if="scope.row.visible==1" @click="upStatus(scope.row)">设置为保密
            </el-button>
            <el-button  class="el-button el-button--text el-button--small" style="color:red;" size="small" v-if="scope.row.source == 1" @click="deleteHandler(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-show="!listLoading" class="pagination-container">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                       layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
    </div>
    <!-- 编辑 -->
    <el-dialog title="编辑" :visible.sync="oneTypeDialogVisible">
      <el-form label-width="90px">
        <el-row>
          <el-col :span="16">
            <el-row>
              <el-col :span="16">
                <el-form-item label="标题">
                  <el-input v-model="formE.title" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="16">
                <el-form-item label="描述">
                  <el-input v-model="formE.desc" type="textarea" :rows="4" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="视频" :style="{display:'block'}">
                  <video height="300" width="80%" v-for="(iitem, iindex) in formE.videos" :key="iindex" :src="iitem.oUrl" controls="controls" class="text item"></video>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间" prop="name">
              <el-input v-model="formE.crtTime" disabled></el-input>
            </el-form-item>
            <el-form-item label="userId" prop="name">
              <el-input v-model="formE.userId" disabled></el-input>
            </el-form-item>
            <el-form-item label="点赞数" prop="name">
              <el-input v-model="formE.praise" disabled></el-input>
            </el-form-item>
            <el-form-item label="评论数" prop="name">
              <el-input v-model="formE.comment" disabled></el-input>
            </el-form-item>
            <el-form-item label="分享次数" prop="name">
              <el-input v-model="formE.share" disabled></el-input>
            </el-form-item>
            <el-form-item label="创建位置" prop="name">
              <el-input v-model="formE.address" disabled></el-input>
            </el-form-item>
            <el-form-item label="对外可见">
              <el-select class="filter-item" v-model="formE.visible" placeholder="请选择来源">
                <el-option key="1" label="是" value="1"></el-option>
                <el-option key="2" label="否" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="来源">
              <el-select class="filter-item" v-model="formE.source" placeholder="请选择来源">
                <el-option key="1" label="后台创建" value="1"></el-option>
                <el-option key="2" label="app用户" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelHandel">取 消</el-button>
        <el-button type="primary" @click="updateMsgs">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 创建 -->
    <el-dialog title="创建" :visible.sync="createDialogVisible">
      <el-form label-width="90px">
        <el-row>
          <el-col :span="16">
            <el-row>
              <el-col :span="16">
                <el-form-item label="标题">
                  <el-input v-model="formC.title"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="16">
                <el-form-item label="描述">
                  <el-input v-model="formC.desc" type="textarea" :rows="4"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="视频" :style="{display:'block'}">
                  <el-upload class="avatar-uploader el-upload--text" :headers="getHeaderWithToken" :action="BASE_API+'/api/universal/file/app/unauth/uploadVideo'"
                             :show-file-list="false" :on-success="handleVideoSuccess" :before-upload="beforeUploadVideo" :on-progress="uploadVideoProcess">
                    <video v-if="videoForm.Video !='' && videoFlag == false" :src="videoForm.Video" class="avatar" controls="controls">您的浏览器不支持视频播放</video>
                    <i v-else-if="videoForm.Video =='' && videoFlag == false" class="el-icon-plus avatar-uploader-icon"></i>
                    <el-progress v-if="videoFlag == true" type="circle" :percentage="videoUploadPercent" style="margin-top:30px;"></el-progress>
                  </el-upload>
                  <p class="text">请保证视频格式正确，且不超过10M</p>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-form-item label="点赞数" prop="name">
              <el-input v-model="formC.praise"></el-input>
            </el-form-item>
            <el-form-item label="评论数" prop="name">
              <el-input v-model="formC.comment"></el-input>
            </el-form-item>
            <el-form-item label="分享次数" prop="name">
              <el-input v-model="formC.share"></el-input>
            </el-form-item>
            <el-form-item label="创建位置" prop="name">
              <el-input v-model="formC.addressStr" readonly placeholder="请拾取地址" :on-icon-click="selectDestination"
                        icon="edit"></el-input>
            </el-form-item>
            <el-form-item label="对外可见">
              <el-select class="filter-item" v-model="formC.visible" placeholder="请选择来源">
                <el-option key="1" label="是" value="1"></el-option>
                <el-option key="2" label="否" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="来源">
              <el-select class="filter-item" v-model="formC.source" placeholder="请选择来源">
                <el-option key="1" label="后台创建" value="1"></el-option>
                <el-option key="2" label="app用户" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelCreateHandel">取 消</el-button>
        <el-button type="primary" @click="createMsgs">确 定</el-button>
      </div>
    </el-dialog>

    <!--查看图片-->
    <el-dialog title="查看视频" :visible.sync="videoDialogVisible">
      <div style="display: flex;align-items: center;justify-content: center;" v-if="videosList.length>0">
        <video height="500" :src="videosList[0].oUrl" controls="controls" class="text item"></video>
      </div>
    </el-dialog>
    <!--拾取创建位置-->
    <address-modal v-if="showAddressVisible" :obj="addressObj"  v-on:addressEvent="addressEvent"></address-modal>
  </div>
</template>
<style>
  textarea {
    display: none;
  }
  .el-upload-list {
    display: flex;
    flex-wrap: wrap;
  }
  .el-upload-list li {
    margin-left: 10px;
  }
  .el-upload-list--picture .el-upload-list__item{
    width: 100px;
  }
</style>
<script>
  import 'static/css/uploadImg.css';// 引入图片上传组件对话框
  import addressModal from './modal/addressModal'
  import {
    getSonRegionByCodes,
    getRegionByCodes,
  } from 'api/base_info/region/';
  import {
    formatDate
  } from 'utils/dateFormattor';
  import {
    toEast8Date,
    deepCopyDate,
    newEast8Date,
    convertDate2Str,
    timestamp2Date
  } from 'utils/dateUtils';

  import rsCode from '../../utils/rsCode';

  import {mapGetters} from 'vuex';
  import {
    getToken
  } from 'utils/auth';
  import {
    objDeepCopy
  } from 'utils/index';

  import {
    page,
    updateMsg,
    delMsg
  } from 'api/discoveryModule';

  import Element1 from "../admin/menu/components/element";
  import ElRow from "element-ui/packages/row/src/row";
  import ElCol from "element-ui/packages/col/src/col";

  export default {
    name: 'tourManage',
    components: {
      ElCol,
      ElRow,
      Element1,
      addressModal
    },
    data() {
      return {
        modalTitle: "创建",
        BASE_API: process.env.BASE_API,
        oneTypeDialogVisible: false,//编辑弹框
        showLoadingBody: false,
        createDialogVisible: false,//创建弹框
        videoDialogVisible: false,//查看视频
        videosList: [],//查看视频列表
        videoFlag: false,
        form: {
          tagNames:"",//标签
          name: undefined,//旅游名称
          saleCount: undefined,//销量
          stock: undefined,//总数量
        },
        showAddressVisible: false,//拾取创建地址
        addressObj: {},//创建位置实体
        formE:{
          msgId: undefined,//消息id
          title: undefined,//标题
          desc:undefined,//描述
          crtTime: undefined,//创建时间
          userId: undefined,
          share: undefined,//分享次数
          praise:undefined,//点赞数
          comment: undefined,//评论数
          address: undefined,//创建位置
          visible: undefined,//1、公开 2、保密
          source: undefined,//来源： 1、'后台创建' 2、'app用户'
        },
        formC: {
          title: undefined,//标题
          desc:undefined,//描述
          share: undefined,//分享次数
          praise:undefined,//点赞数
          comment: undefined,//评论数
          address: undefined,//创建位置
          addressStr:'',
          visible: '1',//1、公开 2、保密
          source: "1",//来源： 1、'后台创建' 2、'app用户'
          listVideoUrl:'',//视频
        },
        fileList2: [],//图片
        list: null,
        total: null,
        videoForm: {},//上传视频
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          startTime: undefined,//开始时间
          endTime: undefined,//结束时间
          source: undefined,//来源
          praise:undefined,//点赞数
          comment: undefined,//评论数
          username: undefined,//用户名
          type: 4,// 消息类型 1=文字消息、2=图文消息（拍拍）、3=语音消息、4=视频消息、 5=文件消息 、 6=SDK分享消息
        },
        inline: true,
        textMap: {
          update: '编辑',
          create: '创建'
        },
        tableKey: 0,
        videoUploadPercent: 0,
      }
    },
    created() {
      this.getList();
    },
    computed: {
      ...mapGetters([
        'elements',
        'belong2Type'
      ]),
      getHeaderWithToken() {
        return {Authorization: getToken()};
      }
    },
    methods: {
      /**
       * 关闭关键标签配置
       * */
      cancelHandel() {
        this.oneTypeDialogVisible = false;
      },
      /**
       * 关闭创建弹框
       * */
      cancelCreateHandel(){
        this.createDialogVisible = false;
      },
      beforeUploadVideo(file) {
        const isLt10M = file.size / 1024 / 1024  < 10;
        if (['video/mp4', 'video/ogg', 'video/flv','video/avi','video/wmv','video/rmvb'].indexOf(file.type) == -1) {
          this.$message.error('请上传正确的视频格式');
          return false;
        }
        if (!isLt10M) {
          this.$message.error('上传视频大小不能超过10MB哦!');
          return false;
        }
      },
      uploadVideoProcess(event, file, fileList){
        this.videoFlag = true;debugger
        this.videoUploadPercent = file.percentage.toFixed(0)*1;
      },
      handleVideoSuccess(res, file) {
        this.videoFlag = false;
        this.videoUploadPercent = 0;
        if(res.status == 200){
          this.videoForm.Video = res.data;
        }else{
          this.$message.error('视频上传失败，请重新上传！');
        }
      },
      /**
       * 创建拍拍消息
       * */
      createMsgs(){
        this.createDialogVisible = false;
//        let params = {
//          id: this.formE.msgId,
//          visible: this.formE.visible,//1、公开 2、保密
//          source: this.formE.source,//来源： 1、'后台创建' 2、'app用户'
//        };
        console.log(this.formC);
        console.log(this.addressObj);
//        updateMsg(params).then(response => {
//          if (response.status === 200) {
//            this.$notify({
//              title: '成功',
//              message: '成功',
//              type: 'success',
//              duration: 2000
//            });
//            this.oneTypeDialogVisible = false;
//            this.getList();
//          } else {
//            this.$notify({
//              title: '失败',
//              message: '操作失败！',
//              type: 'error',
//              duration: 2000
//            });
//          }
//        });
      },

      /**
       * 保存编辑
       * */
      updateMsgs(){
        let params = {
          id: this.formE.msgId,
          visible: this.formE.visible,//1、公开 2、保密
          source: this.formE.source,//来源： 1、'后台创建' 2、'app用户'
        };
        console.log(params);
        updateMsg(params).then(response => {
          if (response.status === 200) {
            this.$notify({
              title: '成功',
              message: '成功',
              type: 'success',
              duration: 2000
            });
            this.oneTypeDialogVisible = false;
            this.getList();
          } else {
            this.$notify({
              title: '失败',
              message: '操作失败！',
              type: 'error',
              duration: 2000
            });
          }
        });
      },
      /**
       * 添加
       * */
      handleCreate() {
        this.modalTitle = '创建';
        this.formC = {
          title: undefined,//标题
          desc:undefined,//描述
          share: undefined,//分享次数
          praise:undefined,//点赞数
          comment: undefined,//评论数
          address: undefined,//创建位置
          listVideoUrl:'',//视频
          visible: '1',//1、公开 2、保密
          source: "1",//来源： 1、'后台创建' 2、'app用户'
        };
        this.createDialogVisible = true;
      },
      /**
       * 查看视频
       * */
      handleVideo(videosList){
        this.videosList = videosList;
        this.videoDialogVisible = true;
      },
      /**
       * 公开、秘密  参数 visible 1：公开，2：私密
       */
      upStatus(row){
        let params = {
          id: row.msgId,
          visible: row.visible==1?2:1
        };
        updateMsg(params).then(response => {
          if (response.status === 200) {
            this.$notify({
              title: '成功',
              message: '成功',
              type: 'success',
              duration: 2000
            });
            this.getList();
          } else {
            this.$notify({
              title: '失败',
              message: '操作失败！',
              type: 'error',
              duration: 2000
            });
          }
        });
      },
      /**
       * 删除
       * */
      deleteHandler(row) {
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delMsg({id:row.msgId}).then(response => {
            if (response.status === 200) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              });
              this.bannerDialogVisible = false;
              this.getList();
            } else {
              this.$notify({
                title: '删除失败',
                message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                type: 'error',
                duration: 2000
              });
            }
          });
        })
      },
      /**
       * 关闭地址弹框
       * */
      addressEvent(obj) {
        this.showAddressVisible = false;
        if (obj) {
          this.addressObj = obj;
          let provinceObj = getRegionByCodes([obj.province]);
          let cityObj = getRegionByCodes([obj.city]);
          this.addressObj.provinceName = provinceObj[0].name;
          this.addressObj.cityName = cityObj[0].name;
          this.formC.addressStr = this.addressObj.provinceName + this.addressObj.cityName + this.addressObj.address;
          console.log(this.addressObj);
        }
      },
      /**
       * 编辑创建地址
       * */
      selectDestination() {
        let that = this;
        this.addressObj.eventName = 'addressEvent';
        this.addressObj.keyword = this.addressObj.address?this.addressObj.address:this.addressObj.addressStr?this.addressObj.addressStr:'';
        this.showAddressVisible = true;
      },
      /**
       * 编辑
       * */
      handleUpdate(row) {
        this.modalTitle = '编辑';
        console.log(row);
        this.formE = {
          msgId: row.msgId,//消息id
          title: row.body.title?row.body.title:'',//标题
          videos: row.body.videos?row.body.videos:[],//视频
          desc:row.body.text,//描述
          crtTime: timestamp2Date(row.body.time),//创建时间
          userId: row.userId,
          share: row.count.share,//分享次数
          praise: row.count.praise,//点赞数
          comment: row.count.comment,//评论数
          address: row.body.address,//创建位置
          visible: row.visible+'',//1、公开 2、保密
          source: row.source+''
        };
        this.oneTypeDialogVisible = true;
      },
      /**
       * 详情modal传递回来的数据
       * */
      oneDialogEvent(e){
        this.oneTypeDialogVisible = false;
        if(e){
          //编辑成功-重新加载列表
          this.getList();
        }
      },
      /**
       * 获取拍拍列表
       * */
      getList() {
        this.listLoading = true;
        let params = objDeepCopy(this.listQuery);
        params.comment  = this.listQuery.comment? this.listQuery.comment:undefined;
        params.praise = this.listQuery.praise?this.listQuery.praise:undefined;

        if(this.listQuery.startTime  && (typeof this.listQuery.startTime == "object")){
          params.startTime = this.listQuery.startTime.getTime();
        }
        if(this.listQuery.endTime  && (typeof this.listQuery.endTime == "object")){
          params.endTime = this.listQuery.endTime.getTime();
        }
        page(params).then(response => {
          let totalCountRs = undefined;
          let listRs = undefined;
          if (!this.$utils.isEmpty(response.data.list) && this.$utils.isInteger(response.data.total)) {
            response.data.list.map(function(item){
              item.body.timeStr = timestamp2Date(item.body.time);
            });
            listRs = response.data.list;
            totalCountRs = response.data.total;
          }
          this.listLoading = false;
          this.list = listRs;
          this.total = totalCountRs;
        })
      },
      /**
       * 搜索
       * */
      handleFilter() {
        this.listQuery.page = 1;
        this.$refs.queryForm.validate(valid => {
          if (valid) {
            this.getList();
          } else {
            return false;
          }
        });
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      /**
       * 重置
       * */
      reloadPage() {
        this.listQuery = {
          page: 1,
          limit: 20,
          startTime: undefined,//开始时间
          endTime: undefined,//结束时间
          source: undefined,//来源
          startTime: undefined,//创建时间
          praise:undefined,//点赞数
          comment: undefined,//评论数
          username: undefined,//用户名
          type: 4,//消息类型
        };
        this.getList()
      },
    }
  }
</script>
