<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <!-- <el-form-item label="来源" prop="datasourceName">
        <el-select v-model="queryParams.datasourceName" placeholder="来源" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="时间" prop="docSrcTime">
        
        <el-date-picker
          v-model="dateRange"
          style="width: 340px"
          value-format="yyyy-MM-dd"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
       
      </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="['business:studyhelper:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdateChk"
          v-hasPermi="['business:studyhelper:edit']"
        >修改</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="['business:studyhelper:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:config:export']"
        >导出</el-button>
      </el-col> -->
      
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" align="center" prop="title" width="180">
        <template slot-scope="scope">
         <!-- <i class="el-icon el-icon-sort-up" v-if="scope.row.isTop==1"></i> -->
         {{scope.row.title}}
        </template>
      </el-table-column>
      <el-table-column label="数据来源" align="center" prop="datasourceName" width="100" >
        <template slot-scope="scope">
         <div v-if="scope.row.datasourceCode=='-1'">管理员手动录入</div>
         <div v-if="scope.row.datasourceCode=='1'">理论前沿</div>
         <div v-if="scope.row.datasourceCode=='2'">学习园地</div>
         <div v-if="scope.row.datasourceCode=='3'">学习强国</div>
        </template>
      </el-table-column>
      <el-table-column label="内容" align="center" prop="content"  >
        <template slot-scope="scope">
          <el-popover placement="top-start" title="" width="800" trigger="hover" popper-class="workorder-problem-desc" v-if="deleteTag(scope.row.content).length>20">
            <div>{{ deleteTag(scope.row.content).substr(0,500)+ '...' }}</div>
            <span slot="reference">
              {{ deleteTag(scope.row.content).length > 20 ? deleteTag(scope.row.content).substr(0,20) + '...':deleteTag(scope.row.content) }}
            </span>
          </el-popover>
          <span v-else>{{deleteTag(scope.row.content)}}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="来源地址" align="center" prop="url" width="100" />
      <el-table-column label="所属网络" align="center" prop="urlType" width="100" >
        <template slot-scope="scope">
         <div v-if="scope.row.datasourceCode=='0'">GAW </div>
         <div v-if="scope.row.datasourceCode=='1'">互联网</div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="排序" align="center" prop="orderNum" :show-overflow-tooltip="true" /> -->
      <el-table-column label="文章时间" align="center" prop="docSrcTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.docSrcTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="浏览量" align="center" prop="pageViewNum" width="80" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleLook(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:studyhelper:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:studyhelper:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateViewNum(scope.row)"
            v-hasPermi="['business:studyhelper:editview']"
          >浏览量</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :fullscreen="true">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <!-- <el-form-item label="来源" prop="datasourceName">
         
          <el-input v-model="form.datasourceName" placeholder="请输入来源" />
        </el-form-item> -->
        <el-form-item label="文章时间" prop="docSrcTime">
          <el-date-picker
          type="datetime"
            v-model="form.docSrcTime"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择文章时间"
          ></el-date-picker>
        
        </el-form-item>
        <el-form-item label="地址" prop="url">
          <el-input v-model="form.url" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="所属网络" prop="urlType">
          
          <el-select v-model="form.urlType" placeholder="请选择所属网络">
            <el-option
              v-for="item in urlTypes"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
           
        <el-form-item label="内容" prop="content">
          
          <editor v-model="form.content" :min-height="292"/>
        </el-form-item>
        <!-- <el-form-item label="排序" >
          
           <el-input-number v-model="form.orderNum" controls-position="right" :min="1" :max="10000"></el-input-number>
        </el-form-item>
        <el-form-item label="是否置顶" >
     
           <el-radio v-model="form.isTop" label="1">置顶</el-radio>
          <el-radio v-model="form.isTop" label="0">不置顶</el-radio>
        </el-form-item> -->
      </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>

    <el-dialog title="修改浏览量" :visible.sync="openViewNum" width="800px" append-to-body >
      <el-form ref="formViewNum" :model="formViewNum" :rules="rulesViewNum" label-width="80px">
        <el-form-item label="浏览量" prop="pageViewNum">
          <el-input v-model="formViewNum.pageViewNum" placeholder="请输入浏览量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormViewNum">确 定</el-button>
        <el-button @click="cancelViewNum">取 消</el-button>
      </div>
    </el-dialog>

    <el-drawer
      title="查看"
      :visible.sync="drawer"
      :before-close="beforeCloseFun"
      direction="rtl" size='50%'>
      <div style="margin:20px;">
        <div><h2>{{form.title}}</h2></div>
        <div style="color:#666;margin-top: 20px;font-size:12px;">来源地址：{{form.url}}</div>
        <div style="margin-top: 20px;" v-html="form.content"></div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { list, getConfig, del, add, update, refreshCache, updateViewNum, addViewNum, listByDictType, findDocInfoById } from "@/api/business/studyhelper";

export default {
  name: "Config",
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openViewNum:false, 
      drawer: false, 
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        title: undefined,
        datasourceName: undefined
      },
      // 表单参数
      form: {
        // isTop: '0', 
        // orderNum: '0',
        docId: null,
        url: '',
        content: ''
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        // url: [
        //   { required: true, message: "来源地址不能为空", trigger: "blur" }
        // ],
        docSrcTime: [
          { required: true, message: "时间不能为空", trigger: "blur" }
        ]
        ,
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ]
      },
      formViewNum:{
        pageViewNum: null,
        docId: null
      },
      rulesViewNum
      :{
        pageViewNum: [
          { required: true, message: "浏览量不能为空", trigger: "blur" }
        ]
      },
      urlTypes:[]
    };
  },
  created() {
    let that = this;
    this.getList();
    this.getDicts('study_url_type',function(datas){
      that.urlTypes = datas;
    });
    // this.form = {
    //     title: '测试',
    //     url: 'www.baidu.com',
    //     content: '<p><b>aaaaa</b></p>'
    //   }
  },
  methods: {
    beforeCloseFun(done){
      done();
      this.getList();
    },
    deleteTag(content)
    {
        var regx = /<[^>]*>|<\/[^>]*>/gm;
        var result = content.replace(regx,"");
        return result;

    },
    getDicts(study_datasource_type, callback){
      listByDictType(study_datasource_type).then(response => {
          callback(response.data);
        }
        );
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      list(this.queryParams).then(response => {
          this.configList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        }
        );
      
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        docId: undefined,
        title: undefined,
        
        url: undefined,
        content: undefined,
        // isTop: '0', 
        // orderNum: '0'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文章";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.docId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdateChk() {
      this.reset();
      const id = this.ids[0];
      var arr = this.configList.filter(item => id == item.docId)
      // getConfig(configId).then(response => {
      this.form = arr[0];
      this.open = true;
      this.title = "修改文章";
      // });
    },
    handleUpdate(row) {
      this.reset();
      const configId = row.docId
      // getDetail(configId).then(response => {
        // this.form = response.data;
        this.form  = JSON.parse(JSON.stringify(row));;
        this.open = true;
        this.title = "修改文章";
      // });
    },
    handleUpdateViewNum(row){
      this.openViewNum = true;
      this.formViewNum.docId = row.docId;
      this.formViewNum.pageViewNum = row.pageViewNum;
    },
    handleLook(row){
      let that = this;
      this.drawer = true;
      // this.form =row;

      findDocInfoById({
        docId: row.docId
      }).then(res=>{
        console.log('增加文章阅读量:', res)
        that.form = res.data;
      })
    },
    submitFormViewNum(){
      // alert(this.formViewNum.docId )
      this.$refs["formViewNum"].validate(valid => {
        if (valid) {
          if (this.formViewNum.docId != undefined) {
            updateViewNum(this.formViewNum).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openViewNum = false;
              this.getList();
            });
      
            
          }
        }
      });
    },
    cancelViewNum(){
      this.openViewNum = false;
      this.formViewNum.docId = null;
      this.formViewNum.pageViewNum = null;
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.docId != undefined) {
            update(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            add(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // const configIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除该条记录？').then(function() {
          return del({
            docId: row.docId
          });
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
      });
    }
  }
};
</script>
