<template>
    <div class="app-container calendar-list-container">
  
      <!-- 查询和其他操作 -->
      <div class="filter-container">
        <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入标题" v-model="listQuery.title"></el-input>
        <el-select v-model="listQuery.type" clearable placeholder="请选择" style="top: -4px;width: 200px;">
          <el-option
                  :key="item.type"
                  v-for="item in newsTypeList"
                  :label="item.name"
                  :value="item.type"
                >
                </el-option>
        </el-select>
        <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 type="selection" width="55px"> </el-table-column>
        <el-table-column type="index" label="序号" header-align="center" align="center">
        </el-table-column>
  
        <el-table-column align="center" min-width="100px" label="标题" prop="title">
        </el-table-column>
  
        <el-table-column align="center" min-width="200px" label="简介" prop="subTitle">
        </el-table-column>
  
        <el-table-column align="center" min-width="80px" label="发布日期" prop="pubDate">
        </el-table-column>
        <el-table-column align="center" min-width="80px" label="客户类型">
          <template slot-scope="props">
            <span v-if="props.row.type == 'highTechnology'">高科技</span>
            <span v-if="props.row.type == 'fastExtinction'">快销</span>
            <span v-if="props.row.type == 'manufacturingIndustry'">制造业</span>
          </template>
        </el-table-column>
  
        <el-table-column align="center" label="操作" width="240px" 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="mini"  @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%"
      >
        <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width: 700px; margin-left:50px;'>
         <el-form-item  label="标题" prop="title">
              <el-input v-model="dataForm.title"></el-input>
            </el-form-item>
  
            <el-form-item
              label="简介"
              prop="subTitle"
            >
              <el-input v-model="dataForm.subTitle"></el-input>
            </el-form-item>
            <el-form-item label="发布日期" prop="pubDate">
                <el-date-picker
                  v-model="dataForm.pubDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  style="width: 350px"
                ></el-date-picker>
              </el-form-item>
              <el-form-item
              label="客户类型"
              prop="type"
            >
              <el-select
                v-model="dataForm.type"
                filterable
                placeholder="请选择"
                style="width: 350px"
              >
                <el-option
                  :key="item.type"
                  v-for="item in newTypeList"
                  :label="item.name"
                  :value="item.type"
                >
                </el-option>
              </el-select>
            </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
              style="width: 800px"
              label="封面图片"
              prop="image"
            >
              <el-tooltip content="建议图片宽高比260*200" placement="top-start">
                <el-upload
                  :action="fileImgUrl"
                  list-type="picture-card"
  
                  :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
              style="width: 800px"
              label="内容"
              prop="content"
            >
              <tinymce v-model="dataForm.content" ref="tinymce"></tinymce>
            </el-form-item>
  
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
          <el-button v-else type="primary" @click="updateData">确定</el-button>
        </div>
      </el-dialog>
  
    </div>
  </template>
  
  <style>
    .demo-table-expand {
      font-size: 0;
    }
    .demo-table-expand label {
      width: 200px;
      color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
      margin-right: 0;
      margin-bottom: 0;
    }
  </style>
  
  <script>
    import {getdgtIndustryNews, listNews, createNews, updateNews, deleteNews, deleteAllNews } from "@/api/newsCenter";
    import waves from "@/directive/waves"; // 水波纹指令
    import Tinymce from '@/components/Tinymce'
  
  export default {
    name: 'customerStories',
    components: { Tinymce },
    directives: { waves },
    data() {
      return {
        newsTypeList:[
            // {
            //     type:'highTechnology',
            //     name:'高科技'
            // },
            // {
            //     type:'fastExtinction',
            //     name:'快销'
            // },
            // {
            //     type:'manufacturingIndustry',
            //     name:'制造业'
            // },
            // {
            //     type:'dgtIndustryNews',
            //     name:'全部'
            // },
        ],
        newTypeList:[
        // {
        //     type:'highTechnology',
        //     name:'高科技'
        //   },
        //   {
        //     type:'fastExtinction',
        //     name:'快销'
        //   },
        //   {
        //     type:'manufacturingIndustry',
        //     name:'制造业'
        //   },
        ],
        list: undefined,
        delarr: [],
        multipleSelection: [],
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          type: 'dgtIndustryNews',
          title: '',
          // sort: '+id'
        },
        dataForm: {
          type: undefined,
          title: undefined,
          subTitle: undefined,
          pubDate: undefined,
          image: undefined,
          content: undefined,
          weight: undefined,
          images: [],
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: "编辑",
          create: "创建",
        },
        imageUrl: undefined,
        rules: {
          title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
          pubDate: [{ required: true, message: "请选择发布时间", trigger: "blur" }],
          type: [{ required: true, message: "请选择客户类型", trigger: "blur" }],
          // subTitle: [{ required: true, message: "简介不能为空", trigger: "blur" }],
          content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
        },
        fileImgUrl: this.upLoadUrl,
      }
    },
    created() {
      getdgtIndustryNews().then(response => {
          this.newsTypeList = response.data.data;
          this.newTypeList = response.data.data.filter(item => item.type != 'dgtIndustryNews');
          console.log(this.newTypeList);
        }).catch(() => {
          this.newsTypeList = []
          this.newTypeList = []
        });
        
        this.getList();
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
  
        if (
          this.contentType == "notice" ||
          this.contentType == "manual" ||
          this.contentType == "rules"
        ) {
          // this.dataForm.file = ''
          // this.dataForm.fileName = ''
          // this.dataForm.files = []
  
          let files = [];
          let names = [];
          for (let i in fileList) {
            let response = fileList[i].response;
            let name = fileList[i].name;
            let url = response.data.url;
            files.push(url);
            names.push(name);
          }
          this.dataForm.file = files.join(",");
          this.dataForm.fileName = names.join(",");
        } 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(",");
        }
      },
      uploadBannerImg(file) {
        const isJPGs = file.type === "image/jpeg";
        console.log(isJPGs);
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件！，共选择了 ${
            files.length + fileList.length
          } 个文件`
        );
      },
      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(",");
      },
      resetForm() {
        this.dataForm = {
          type: undefined,
          title: undefined,
          subTitle: undefined,
          pubDate: undefined,
          image: undefined,
          content: undefined,
          weight: undefined,
          images: [],
        };
      },
      handleCreate() {
        this.resetForm();
  
        this.dialogFormVisible = true;
        this.dialogStatus = "create";
  
        this.$nextTick(() => {
          this.$refs.tinymce.setContent("");
          this.$refs["dataForm"].clearValidate();
        });
      },
      createData() {
        this.$refs["dataForm"].validate((valid) => {
          if (valid) {
            if (!this.dataForm.image) {
                this.$alert("请上传封面图片", "提示", {
                  confirmButtonText: "确定",
                });
            }else{
              createNews(this.dataForm)
                  .then((response) => {
                    this.getList();
                    this.dialogFormVisible = false;
  
                    this.$notify({
                      title: "成功",
                      message: "创建成功",
                      type: "success",
                      duration: 2000,
                    });
                    this.reload();
                  })
                  .catch(() => {});
            } 
          }
        });
      },
      getList() {
        this.listLoading = true
        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()
      },
  
      handleUpdate(row) {
        this.dataForm = Object.assign({}, 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 } },
            });
          }
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs.tinymce.setContent(content);
          this.$refs['dataForm'].clearValidate()
        })
      },
  
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (!this.dataForm.image) {
              this.$alert("请上传封面图片", "提示", {
                confirmButtonText: "确定",
              });
            }else{
              updateNews(this.dataForm).then(() => {
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000
                })
                this.getList()
              })
            }
            
          }
        })
      },
  
      handleDelete(row) {
  
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteNews(row).then(response => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
        }).catch(() => {
  
        })
  
      },
      delAll() {
        this.$confirm("确认删除吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            debugger
            const length = this.multipleSelection.length;
  
            if (length > 0) {
              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(() => {});
            } else {
              this.$notify({
                title: "警告提示",
                message: "请选择要删除的信息！",
                type: "warning",
              });
            }
          })
          .catch(() => {});
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
    }
  }
  </script>
  <style>
    .ad-avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .ad-avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .ad-avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .ad-avatar {
      display: block;
    }
  </style>
  