<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--公告数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入标题"
              clearable
              style="width: 200px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="渠道" prop="channel" label-width="80px">
        <el-select v-model="queryParams.channel" placeholder="渠道" clearable>
          <el-option
            v-for="item in channel"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否显示" prop="isShow" label-width="80px">
        <el-select v-model="queryParams.isShow" placeholder="是否显示" clearable>
          <el-option
            v-for="item in isShow"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
         </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['img:notice:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['img:notice:remove']"
            >删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="编号" align="center" key="id" prop="id" v-if="columns[0].visible" />
          <el-table-column label="标题" align="center" key="title" prop="title" v-if="columns[1].visible" :show-overflow-tooltip="true" width="150"/>
          <el-table-column label="内容" align="center" key="content" prop="content" v-if="columns[2].visible" :show-overflow-tooltip="true" width="200"/>
          <el-table-column label="渠道" align="center" key="channel" prop="channel" v-if="columns[3].visible">
            <template slot-scope="scope">
              {{scope.row.channel == '0' ? "通用" : scope.row.channel == '1' ? "抖音": scope.row.channel == '2' ? "快手": scope.row.channel == '3' ? "微信": ''}}
            </template>
          </el-table-column>
          <el-table-column label="图片" align="center" key="img" prop="img" v-if="columns[4].visible" width="120">
            <template slot-scope="scope">
              <el-image :src="scope.row.img" :preview-src-list="bigImgList" @click="getBigImg(scope.row)" style="width: 160px; height: 60px"/>
            </template>
          </el-table-column>
          <el-table-column label="序号" align="center" key="sort" prop="sort" v-if="columns[5].visible"/>
          <el-table-column label="是否显示" align="center" key="isShow" v-if="columns[6].visible">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isShow"
                active-value="1"
                inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[7].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" align="center" prop="updateTime" v-if="columns[8].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['img:notice:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['img:notice:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" maxlength="30" />
            </el-form-item>
          </el-col>
           <el-col :span="12">
            <el-form-item label="渠道" prop="channel" label-width="80px">
        <el-select v-model="form.channel" placeholder="渠道" clearable>
          <el-option
            v-for="item in channel"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="内容" prop="content">
              <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="form.content" />
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item label="notice上传" prop="noticeImg">
                <el-upload
                  ref="upload"
                  :action="upload.url"
                  :limit="1"
                  accept=".jpg, .jpeg, .png"
                  :headers="upload.headers"
                  :disabled="upload.isUploading"
                  :on-progress="handleFileUploadProgress"
                  :on-success="handleFileSuccess"
                  :file-list="fileList"
                  :auto-upload="true"
                  list-type="picture"
                  drag>
                 
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                  <span>仅允许上传jpg,jpeg,png格式图片。</span>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNotice, addNotice, editNotice, delNotice, getNoticeDetails, changeStatus } from "@/api/img/notice";
import { getToken } from "@/utils/auth";

export default {
  name: "notice",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // notice列表数据
      noticeList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      //上传图片文件列表
      fileList:[],
      //大图列表
      bigImgList:[],
      //来源渠道
      channel: [
        { value:'0',label:'通用'},
        { value:'1',label:'抖音'},
        { value:'2',label:'快手'},
        { value:'3',label:'微信'},
      ],
      //是否显示
      isShow: [
          { value: '0', label: `否`},
          { value: '1', label: `是`}
        ],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 图片上传参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/uploadnotice" //http://localhost:7010/file/upload
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        channel: undefined,
        isShow: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `编号`, visible: true },
        { key: 1, label: `标题`, visible: true },
        { key: 2, label: `内容`, visible: true },
        { key: 3, label: `渠道`, visible: true },
        { key: 4, label: `图片`, visible: true },
        { key: 5, label: `序号`, visible: true },
        { key: 6, label: `是否显示`, visible: true },
        { key: 7, label: `创建时间`, visible: true },
        { key: 8, label: `更新时间`, visible: true }
      ],
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '标题长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" },
        ],
        channel: [
          { required: true, message: "渠道不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询公告列表 */
    getList() {
      this.loading = true;
      listNotice(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.noticeList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.isShow === "1" ? "启用" : "停用";
      this.$modal.confirm('确认要' + text + 'id为' + row.id + '的公告吗？').then(function() {
        let data = {
          id: row.id,
          status: row.isShow
        }
        return changeStatus(data);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.isShow = row.isShow === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        noticeName: undefined,
        noticeUrl: undefined,
        noticeImg: undefined,
        source: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 查看大图 */
    getBigImg(row){
      this.bigImgList.push(row.img)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加公告";
      this.fileList = []
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getNoticeDetails(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改公告";
        this.fileList = []
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            editNotice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNotice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + id + '"的公告吗？').then(function() {
        return delNotice(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.form.noticeImg = response.data
      this.fileList.url = response.data
      this.fileList.name = '图片上传结果'
      this.upload.open = false;
      this.upload.isUploading = false;
      //this.$refs.upload.clearFiles();
      //this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      //this.getList();
    }
  }
};
</script>