<template>
  <div class="app-container calendar-list-container" v-loading.body="showLoadingBody">
    <div class="filter-container" ref="filter-container">
      <el-form ref="queryForm" :inline="inline" :model="listQuery" label-width="60px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="标题">
              <el-input v-model.number="listQuery.title" placeholder="请输入标题"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
              <el-select class="filter-item" v-model="listQuery.type" placeholder="请选择推送方式" @change="handleTypeChange">
                <el-option :key="null" label="全部" :value="null"></el-option>
                <el-option :key="1" label="手动推送" :value="1"></el-option>
                <el-option :key="2" label="系统自动推送" :value="2"></el-option>
              </el-select>
          </el-col>
          <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" type="primary" style="float: right;" @click="handleCreate">+ 添加通知</el-button>
        </el-row>
      </el-form>
    </div>
    <el-table :key='tableKey' :data="list" border fit highlight-current-row
              style="width: 100%">
      <el-table-column
        type="index"
        align="center" label="序号" width="98">
      </el-table-column>
      <el-table-column width="200" align="center" label="标题">
        <template scope="scope">
          <span>{{scope.row.title}}</span>
        </template>
      </el-table-column>
      <el-table-column  align="center" label="描述">
        <template scope="scope">
          <span>{{scope.row.alerts}}</span>
        </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="推送方式">
       <template scope="scope">
          <span v-if="scope.row.type==1">手动推送</span>
          <span v-if="scope.row.type==2">系统自动推送</span>
        </template>
      </el-table-column>
      <el-table-column width="250" align="center" label="创建时间">
        <template scope="scope">
          <span>{{scope.row.crtTimeStr}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="150" label="操作" fixed="right">
        <template scope="scope">
          <el-button size="small" class="el-button el-button--text el-button--small" @click="handleDown(scope.row)" v-show="scope.row.type==1">立即推送</el-button>
          <el-button size="small" class="el-button el-button--text el-button--small" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button class="el-button el-button--text el-button--small" size="small" @click="deleteHandler(scope.row)" style="color:red;">删除</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,40,50]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>
    <!-- banner modal弹窗 -->
    <el-dialog :title="modalTitle" :visible.sync="bannerDialogVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="90px">
        <el-form-item label="推送方式" >
          <el-radio-group v-model="form.type" size="medium">
            <el-radio-button label="1">手工推送</el-radio-button>
            <el-radio-button label="2">系统自动推送</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标题" prop="name">
          <el-input v-model="form.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="name">
        <el-input v-model="form.alert" placeholder="请输入描述"></el-input>
        </el-form-item>
        <el-form-item label="样式" >
          <el-radio-group v-model="form.style" size="medium" @change="handleRadio">
            <el-radio-button label="1">标准样式</el-radio-button>
            <el-radio-button label="3" >大图</el-radio-button>
            <el-radio-button label="2">自定义样式</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" prop="picture" v-if="showPic"  :style="{display:'block'}">
          <el-upload
            class="avatar-uploader"
            :action="BASE_API+'/api/universal/file/app/unauth/admin/upload'"
            :show-file-list="false"
            :headers="getHeaderWithToken"
            :on-success="handleAvatarSuccess">
            <img v-if="$utils.isString(form.bigPicPath) && !$utils.isEmpty(form.bigPicPath)" :src="form.bigPicPath" style="width:200px;max-height:200px;">
            <i v-else class="el-icon-plus avatar-uploader-icon" style="lineHeight:100px;width:100px;height: 100px;vertical-align: middle;"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelHandel">取 消</el-button>
        <el-button v-if="modalTitle=='创建'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import 'static/css/uploadImg.css';// 引入图片上传组件对话框

  import {
    formatDate
  } from 'utils/dateFormattor';

  import {
    toEast8Date,
    deepCopyDate,
    newEast8Date,
    convertDate2Str,
    timestamp2Date,
    getYMD_hm
  } from 'utils/dateUtils';

  import {
    getPushList,
    getObj,
    addObj,
    editObj,
    delObj,
    pushStype
  } from 'src/api/appManagement/pushManagement';

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

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

  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: 'pushManagement',
    components: {
      ElCol,
      ElRow,
      Element1
    },
    data() {
      return {
        showPic:false,
        tableKey:0,
        modalTitle: "创建",
        BASE_API: process.env.BASE_API,
        bannerDialogVisible: false,//添加、编辑弹框
        showLoadingBody: false,
        form: {
          type: "",
          title:'',
          alert:'',
          style:'',
          bigPicPath:'',
        },
        listQuery: {
          page: 1,
          limit: 10,
          title: '',//标题
          type:undefined
        },
        pushQuery: {
          id: 0,
          userIds: '',
        },
        rules: {
          title: {
              type: 'string',
              required: true,
              message: '请输入标题',
              trigger: 'blur'
          },
          alert: {
            type: 'string',
            required: true,
            message: '请输入描述',
          },
        },
        pickerOptionsStart: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
        pickerOptionsEnd: {
            disabledDate: time => {
                const beginDateVal = new Date(this.form.starTimeStr).getTime()
                if (beginDateVal) {
                    return time.getTime() < beginDateVal - 8.64e7
                }
            }
        },
        list: null,
        total: null,
        listLoading: true,
        inline: true,
      }
    },
    created() {
      this.getList();
    },
    computed: {
      ...mapGetters([
        'elements',
        'belong2Type'
      ]),
      getHeaderWithToken() {
        return {Authorization: getToken()};
      },
    },
    methods: {
      handleFilter() {
        this.listQuery.page = 1;
        this.$refs.queryForm.validate(valid => {
          if (valid) {
            this.getList();
          } else {
            return false;
          }
        });
      },
      handleRadio(item) {
        if(item == 3) {
          this.showPic = true;
        } else {
          this.showPic = false;
        }
      },
      handleTypeChange(item) {
        this.listQuery.type = item;
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      /**
       * 添加
       * */
      handleCreate() {
        this.cleanForm();
        this.modalTitle = '创建';
        this.bannerDialogVisible = true;
      },
      /**
       * 操作-编辑
       * */
      handleUpdate(row) {
        this.modalTitle = '编辑';
        this.cleanForm();
        getObj(row.id).then(response => {
          var item = response.data;
          item.up_name = item.timeType==0?'不限':item.timeType==1?'自定义':'';
          if(item.startTime>0&&item.timeType==1){
            item.starTimeStr = getYMD_hm(item.startTime);
          }else{
            item.starTimeStr = '';
          }
          if(item.endTime>0&&item.timeType==1){
            item.endTimeStr = getYMD_hm(item.endTime);
          }else{
            item.endTimeStr = '';
          }
          this.form = item;
          this.bannerDialogVisible = true;
        })

      },
      /**
       * 弹框-取消
       * */
      cancelHandel(){
        this.cleanForm();
        this.bannerDialogVisible = false;
      },
     /**
      * 清空表单
      * */
      cleanForm() {
        this.form = {
          type: "",
          title:'',
          alert:'',
          style:'',
          bigPicPath:'',
        }
      },
      /**
       * 获取banner列表数据
       * */
      getList() {
        this.listLoading = true;
        getPushList(this.listQuery).then(response => {
          let totalCountRs = undefined;
          let listRs = undefined;
          if (!this.$utils.isEmpty(response.data.data) && this.$utils.isInteger(response.data.totalCount)) {
            listRs = response.data.data;
            response.data.data.map(function(item){
              item.crtTimeStr = timestamp2Date(item.crtTime);
              item.alerts = item.alert;
              item.visible2 = false;
            });
            totalCountRs = response.data.totalCount;
          }
          this.listLoading = false;
          this.list = listRs;
          this.total = totalCountRs;
        });
      },
      /**
       * 创建
       * */
      create(formName) {
        let that = this;
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            addObj(this.form).then(response => {
                if (response.status === 200) {
                  this.bannerDialogVisible = false;
                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  });
                  this.getList();
                } else {
                  this.$notify({
                    title: '失败',
                    message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                    type: 'error',
                    duration: 2000
                  });
                }
              });
          } else {
            return false;
          }
        });
      },
      /**
       * 编辑-更新
       * */
      update(formName) {
        let that = this;
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            editObj(this.form).then(response => {
              if (response.status === 200) {
                this.bannerDialogVisible = false;
                this.$notify({
                  title: '成功',
                  message: '编辑成功',
                  type: 'success',
                  duration: 2000
                });
                this.getList();
              } else {
                this.$notify({
                  title: '失败',
                  message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                  type: 'error',
                  duration: 2000
                });
              }
            });
          } else {
            return false;
          }
        });
      },
      /**
       * 上传图片
       * @param file
       * @returns {boolean}
       */
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/gif';
        const isLt2M = file.size / 1024 / 1024 < 10;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/GIF 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 10MB!');
        }
        this.showLoadingBody = true;
        return isJPG && isLt2M;
      },
      handleAvatarSuccess(res, file) {
        this.form.bigPicPath = res.data;
        this.showLoadingBody = false;
      },
    /**
    * 操作-删除
    * */
    deleteHandler(row) {
      this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delObj(row.id).then(response => {
            if (response.status === 200) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              });
              this.getList();
            } else {
              this.$notify({
                title: '删除失败',
                message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                type: 'error',
                duration: 2000
              });
            }
          });
        })

      },
      /**
       * 操作-推送
       * */
      handleDown(row) {
        this.$confirm('确定推送吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           this.pushQuery.id=row.id
           pushStype(this.pushQuery).then(response => {
            if (response.status === 200) {
              this.$notify({
                title: '成功',
                message: '推送成功',
                type: 'success',
                duration: 2000
              });
              this.getList();
            } else {
              this.$notify({
                title: '推送失败',
                message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                type: 'error',
                duration: 2000
              });
            }
          });
        })

      },
    }
  }
</script>
