<template>
  <div class="mainBox">
    <!--搜索功能 start------------------------------------------------------------>
    <div class="layerBox_search">
      <div class="layerBoxLine">
        <el-row>
          <el-col :span="8">
            <div class="searchBox">
              <div class="searchTitle">资讯题目：</div>
              <el-input placeholder="请输入资讯题目" autocomplete="off" v-model="getApiData.title" />
            </div>
          </el-col>
          <el-col :span="8">
            <div class="searchBox">
              <div class="searchTitle">栏目名称：</div>
              <el-input placeholder="请输入栏目名称" autocomplete="off" v-model="getApiData.category_name" />
            </div>
          </el-col>
          <el-col :span="8">
            <div class="searchBox">
              <div class="searchTitle">作者：</div>
              <el-input placeholder="请输入作者姓名" autocomplete="off" v-model="getApiData.author" />
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="layerBoxLineTwo">
        <el-row>
          <el-col :span="8">
            <div class="searchBox">
              <div class="searchTitle">引用外链：</div>
              <el-select v-model="getApiData.islink" placeholder="请选择..">
                <el-option label="否" value="0"></el-option>
                <el-option label="是" value="1"></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="searchBox">
              <div class="searchTitle">资讯状态：</div>
              <el-select v-model="getApiData.status" placeholder="请选择..">
                <el-option label="待审核" value="0"></el-option>
                <el-option label="已拒绝" value="2"></el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <div class="layerBoxNoBg">
      <div>
        <!-- <el-button type="primary" @click="goCreat">发布资讯</el-button> -->
      </div>
      <div>
        <el-button @click="clearSearchList">重置</el-button>
        <el-button type="primary" @click="getData('search')">搜索</el-button>
      </div>
    </div>
    <!--搜索功能 end------------------------------------------------------------>

    <!--表格内容 start------------------------------------------------------------>
    <div class="layerBox">
      <tableTitle :name="tableDivTitle" />
      <el-row>
        <template>
          <el-table :data="tableData" style="width: 100%">
            <el-table-column fixed prop="id" label="编号" width="50"></el-table-column>
            <el-table-column prop="title" label="资讯题目" width=""></el-table-column>
            <el-table-column prop="category_name" label="栏目名称" width=""></el-table-column>
            <el-table-column prop="alias" label="展示名称" width="100"></el-table-column>
            <el-table-column prop="islink" label="是否引用外链" width=""></el-table-column>
            <el-table-column prop="linkurl" label="是否为原创" width="">
              <template slot-scope="scope">
                <span v-if="scope.row.is_original == 1">
                  是
                </span>
                <span v-if="scope.row.is_original == 0">
                  否
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="author" label="作者" width=""></el-table-column>
            <!-- <el-table-column prop="created_at" label="创建时间" width=""></el-table-column> -->
            <el-table-column prop="updated_at" label="修改时间" width=""></el-table-column>
            <el-table-column prop="status" label="审核状态" width="100">
              <template slot-scope="scope">
                <!-- <span v-if="scope.row.status==404">404</span>
                <el-switch
                  v-else
                  v-model="scope.row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="upRow(scope.row.id,scope.row.status)"
                ></el-switch> -->
                <span v-if="scope.row.status == 0">待审核</span>
                <span v-if="scope.row.status == 1">已审核</span>
                <span v-if="scope.row.status == 2">已拒绝</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="360" header-align="center"
              v-if="creatNews_user_type == 10000">
              <template slot-scope="scope">
                <div class="listBtnBox">
                  <div class="listMainBtn" @click="getUpRow(scope.row.id, tableData)"><i class="el-icon-check"></i>审核
                  </div>
                  <div class="listDeleteBtn" @click="deleteRow(scope.row.id, tableData)"><i
                      class="el-icon-delete"></i>删除</div>
                  <div class="listEditBtn" @click="goEdit(scope.row.id, tableData)"><i
                      class="el-icon-edit-outline"></i>编辑</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="360" header-align="center"
              v-if="creatNews_user_type != 10000">
              <template slot-scope="scope">
                <div class="listBtnBox">
                  <!-- <div class="listLinkBtn" @click="selectRow(scope.row.cat_arr_id, scope.row)"><i class="el-icon-full-screen"></i>站点选择</div>
                  <div class="listMainBtn" @click="getUpRow(scope.row.id, tableData)" v-if="scope.row.status==0"><i class="el-icon-check"></i>审核</div>
                  <div class="listUpBtn" @click="returnRow(scope.row.id, tableData)" v-else><i class="el-icon-refresh-right"></i>撤回</div> -->
                  <div class="listDeleteBtn" @click="deleteRow(scope.row.id, tableData)"><i
                      class="el-icon-delete"></i>删除</div>
                  <div class="listEditBtn" @click="goEdit(scope.row.id, tableData)"><i
                      class="el-icon-edit-outline"></i>编辑</div>
                </div>
              </template>
            </el-table-column>

          </el-table>
        </template>
      </el-row>
    </div>
    <!--分页 start------------------------------------------------------------>
    <div class="alignBox">
      <el-row>
        <el-col :span="24">
          <el-pagination @size-change="handleSizeChange" :current-page="getApiData.page"
            @current-change="handleCurrentChange" :page-size="10" layout="total, prev, pager, next, jumper"
            :total="allCount"></el-pagination>
        </el-col>
      </el-row>
    </div>
    <!--分页 end------------------------------------------------------------>
    <!--表格内容 end------------------------------------------------------------>

    <!--弹出框1：外部表单弹出框 start------------------------------------------------------------>
    <el-dialog title="请输入驳回理由" :visible.sync="examineWindow" :close-on-click-modal="false">
      <el-form :model="form" ref="form" :rules="formRules" label-position="left">
        <div class="formDiv">
          <el-form-item label="驳回原因：" :label-width="formLabelWidth" prop="reason" class="custom-align-right">
            <el-input type="textarea" v-model="form.reason" class="custom-textarea" placeholder="请输入驳回原因"
              :rows="3"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div>
          <el-button type="info" @click="examineWindow = false">取消</el-button>
          <el-button type="primary" @click="examineToServe">确定</el-button>
        </div>
      </div>
    </el-dialog>
    <!--弹出框1：外部表单弹出框 end------------------------------------------------------------>

    <!--弹出框2：选择要发布的网站 start------------------------------------------------------------>
    <el-dialog title="请选择不要发布的网站" :visible.sync="selectStatusWindow" :close-on-click-modal="false">
      <el-form label-position="left">
        <div class="formDiv">
          <el-table v-loading="loading" ref="multipleTable" :data="webSiteData" tooltip-effect="dark"
            style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="website_id" label="网站id"></el-table-column>
            <el-table-column prop="website_name" label="网站名称"></el-table-column>
          </el-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div>
          <el-button type="info" @click="selectStatusWindow = false">取消</el-button>
          <el-button type="primary" @click="selectWebSiteToServe">确定</el-button>
        </div>
      </div>
    </el-dialog>
    <!--弹出框2：选择要发布的网站 end------------------------------------------------------------>

  </div>
</template>

<script>
//表格标题
import tableTitle from './components/tableTitle';
//引入公用样式
import '@/styles/global.less';
//获得用户身份
import { getUseType } from '@/utils/auth'

export default {
  components: {
    tableTitle,//表格标题
  },
  data() {
    //0.全局操作 start ------------------------------------------------------------>
    let self = this;
    //表单验证
    const validateEmpty = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    //0.全局操作 end ------------------------------------------------------------>
    return {
      //1.列表和分页相关 start ------------------------------------------------------------>
      tableDivTitle: "资讯列表",
      creatNews_user_type: 0,//用户类型
      tableData: [],//内容
      webSiteData: [],//可选网站列表
      editId: 0,//要修改的网站id
      editStatus: 0,//要修改的网站状态
      selectStatusWindow: false,//反选窗口
      examineWindow: false,//审核窗口
      formLabelWidth: "120px",//表单label宽度
      getApiData: {
        title: "",//标题
        category_name: "",//导航池id
        author: "",//作者
        islink: "",//是否使用外链
        status: "",//资讯状态
        status1: "[0,2]", //默认传递 - 如果不为空，表示获取所有未审核与已拒绝的
        page: 1,//当前是第几页
        pageSize: 10,//一共多少条
      },
      //提交驳回
      form: {
        reason: ""
      },
      //选择要发布的网站
      webSiteForm: {
        ignore_ids: []
      },
      ids: [],//待选网站列表
      loading: false,//loading
      formRules: {
        //导航池名称不能为空
        reason: [{ required: true, trigger: 'blur', validator: validateEmpty }],
      },
      allCount: 0,//总条数
      //分页相关 end ------------------------------------------------------------>
    }
  },
  methods: {
    //1.列表和分页相关 start ------------------------------------------------------------>
    //1.1 开始请求列表信息方法
    getData(type) {
      if (type == "search") {
        this.getApiData.page = 1;
      }
      this.$store.dispatch('news/getArticleList', this.getApiData).then(res => {
        //格式化：islink=0为不使用外面 islink=1为使用外链
        //status=1为显示 status=2为不显示
        let data = [];
        for (let item of res.data.rows) {
          // if(item.status==0){item.status="隐藏"}
          // if(item.status==1){item.status="显示"}
          // if(item.status==404){item.status="已删除"}
          if (item.islink == 0) { item.islink = "否" }
          if (item.islink == 1) { item.islink = "是" }
          data.push(item)
        }
        this.tableData = res.data.rows; //给与内容
        this.allCount = res.data.count; //给与总条数
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '网络错误，请重试！'
        });
      })
    },
    //1.2 删除内容
    deleteRow(id) {
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("当前删除：" + id)
        this.$store.dispatch('news/delArticle', { id: id }).then(res => {
          this.getData();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      })
    },
    //1.3 撤回审核
    returnRow(id) {
      this.$confirm('确定要撤回吗?', '提示', {
        confirmButtonText: '撤回',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //撤回，把文章状态修改为0，重新进行审核
        this.upRow(id, 0)
      })
    },
    //1.4 审核温江
    getUpRow(id) {
      //设置待审核的id
      this.editId = id;
      console.log(id)
      this.$confirm('将此文章通过审核吗?', '提示', {
        confirmButtonText: '通过',
        cancelButtonText: '拒绝',
        type: 'warning'
      }).then(() => {
        this.upRow(id, 1)
      }).catch(() => {
        //输入驳回理由
        console.log("驳回")
        this.examineWindow = true;
      })
    },
    //1.5 修改文章状态
    upRow(id, status) {
      let data = {
        id: id,
        status: status
      }
      this.$store.dispatch('news/upArticleStatus', data).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '操作成功！'
          });
          this.getData();
        }
      })
    },
    //提交驳回内容
    examineToServe(id) {
      this.$refs.form.validate(valid => {
        if (valid) {
          let data = {
            id: this.editId,
            status: 2,//驳回status
            reason: this.form.reason
          }
          this.$store.dispatch('news/upArticleStatus', data).then(res => {
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '操作成功！'
              });
              this.getData();
              this.form.reason = "";//清空上一次的输入
              this.examineWindow = false;
            }
          })
        } else {
          this.$message.error("驳回理由不能为空！")
        }
      })
    },
    //1.6 打开反选窗口
    selectRow(cid, row) {
      console.log(row)
      this.selectStatusWindow = true;
      //给与编辑的id
      this.editId = row.id;
      //给与编辑的状态
      this.editStatus = row.status;
      //把cid转换成数组，然后取出最后一位
      let cidArr = cid.replace(/[\[\]]/g, '').split(',');
      // 获取数组的最后一个元素
      let cidLast = cidArr[cidArr.length - 1];
      this.getWebsiteNavPoolSite(cidLast, row)
    },
    //1.7 列表内容分页
    //直接跳转
    handleSizeChange(val) {
      this.getApiData.page = val;
      this.getData();
    },
    //1.8 点击分页
    handleCurrentChange(val) {
      this.getApiData.page = val;
      this.getData();
    },
    //1.9 重置按钮
    clearSearchList() {
      this.tableData = [];
      this.getApiData.title = "";
      this.getApiData.category_name = "";
      this.getApiData.author = "";
      this.getApiData.islink = "";
      this.getApiData.status = "";
      this.getApiData.page = 1;
      this.getApiData.pageSize = 10;
      this.getData();
    },
    //1.10 获取可选网站列表
    getWebsiteNavPoolSite(cid, row) {
      this.loading = true;
      let ignoreIds = JSON.parse(row.ignore_ids);
      this.webSiteData = [];
      this.$store.dispatch('news/getWebsiteNavPoolSite', { category_id: cid }).then(res => {
        // for(let item of res.data){
        //   if(item.website_name!=null){
        //     this.webSiteData.push(item)
        //   }
        // }
        this.webSiteData = res.data;
        //延迟一会返显，否则可能显示不了
        if (res.data.length > 0 && ignoreIds != null) {
          setTimeout(() => {
            for (let index in this.webSiteData) {
              if (ignoreIds.includes(this.webSiteData[index].website_id)) {
                console.log(1234656)
                console.log(index)
                //调用回显方法
                this.toggleSelection([this.webSiteData[index]])
              }
            }
            this.loading = false;
          }, 500)
        } else {
          this.loading = false;
        }
      })
    },
    //1.11 提交选择的网站列表
    selectWebSiteToServe(id) {
      let ids = [];
      for (let item of this.ids) {
        ids.push(item.website_id)
      }
      //把数组转换为字符串
      //let idsStr = ids.join(',');
      //把数组转换为字符串
      let idsStr = JSON.stringify(ids);

      if (idsStr.length == 0) {
        this.$message.error("至少需要选择一个网站！")
        return;
      } else {
        let data = {
          id: this.editId,
          ignore_ids: idsStr,
          status: this.editStatus
        }
        this.$store.dispatch('news/upArticleStatus', data).then(res => {
          console.log(res)
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '资讯绑定网站成功！'
            });
            this.selectStatusWindow = false;
            this.getData();
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }
    },
    //把选择的网站保存到待选择的网站列表
    handleSelectionChange(val) {
      console.log(val)
      this.ids = val;
    },
    //回显 选中的方法 
    toggleSelection(rows) {
      console.log(rows)
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //列表和分页相关 end ------------------------------------------------------------>

    //2.添加新闻 start ------------------------------------------------------------>
    //跳转到资讯发布页面
    goCreat() {
      this.$router.push({
        path: '/creatNews',
      });
    },
    goEdit(id) {
      let data = {
        id: id,
        to: "examine"
      }
      this.$router.push({
        path: '/creatNews',
        query: data
      });
    }
    //添加新闻 end ------------------------------------------------------------>
  },
  mounted() {
    this.creatNews_user_type = getUseType()
    //1.获得初始数据
    this.getData();
  }
}
</script>

<style scoped lang="less"></style>
