<template>
  <div class="manage-root organize-manage">
    <Header />
    <div class="manage-root-contain">
        <nav-menu class="manage-root-contain-left" :activeMenuIndex="activeMenuIndex"></nav-menu>
        <div class="manage-root-contain-right personnel-manage-right">
            <breadcrumb :breadcrumbList="breadcrumbList" class="breadcrumb-box"></breadcrumb>
            <div class="personal-inner">
                <div class="common-title-box">
                    <h3>报纸管理</h3>
                    <div class="btn-box">
                        <el-button type="primary" size="small" @click="handleEdit">创建报纸</el-button>
                    </div>
                </div>
                <div class="search-box">
                    <div class="search-item">
                        <label>搜索</label>
                        <el-input
                            placeholder="输入搜索内容"
                            v-model="searchInput">
                            <i slot="suffix" class="el-input__icon el-icon-search" @click="getList(1)" style="cursor: pointer;"></i>
                        </el-input>
                    </div>
                    <div class="search-item">
                        <label>状态</label>
                        <el-select v-model="searchStatus" @change="getList" placeholder="请选择">
                            <el-option
                                v-for="item in $checkStatusList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="search-item">
                        <label>年份</label>
                        <el-select v-model="searchYear" @change="getList" placeholder="请选择">
                            <el-option
                                v-for="(itemy,indexy) in yearList"
                                :key="indexy" 
                                :label="itemy.label"
                                :value="itemy.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="search-item">
                        <label>学段</label>
                        <el-select v-model="searchStudy" @change="getList" placeholder="请选择">
                            <el-option
                                v-for="item in $studyTypeAll"
                                :key="item.study_phase"
                                :label="item.study_phase_name"
                                :value="item.study_phase">
                            </el-option>
                        </el-select>
                    </div>
                </div>
                <el-table
                    class="search-table"
                    :data="tableData"
                    style="width: 100%"
                    @sort-change="handleSort"
                    :default-sort = dataSort
                    :max-height="tableHeight">
                    <el-table-column
                        type="index"
                        label="#"
                        sortable
                        width="56">
                    </el-table-column>
                    <el-table-column
                        prop="iss_name"
                        label="名称"
                        sortable
                        min-width="226">
                    </el-table-column>
                    <el-table-column
                        prop="iss_no"
                        label="期数"
                        width="84"
                        sortable>
                    </el-table-column>
                    <el-table-column
                        prop="study_phase"
                        label="学段"
                        width="72">
                        <template slot-scope="scope">
                            {{formatterStudy(scope.row)}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="status"
                        label="状态"
                        width="104" >
                        <template slot-scope="scope">
                            <div class="status-box">
                                <span :style="{background:$checkStatusColorList[scope.row.iss_status].bg}"></span>
                                <b :style="{color:$checkStatusColorList[scope.row.iss_status].color}">{{$checkStatusColorList[scope.row.iss_status].text}}</b>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="creator_real_name"
                        label="创建人"
                        width="88"
                        sortable>
                    </el-table-column>
                    <el-table-column
                        prop="create_time"
                        label="创建时间"
                        width="144" 
                        sortable>
                        <template slot-scope="scope">
                            {{scope.row.create_time?scope.row.create_time.substring(0,16):'-'}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="updater_real_name"
                        label="最近编辑"
                        min-width="96">
                    </el-table-column>
                    <el-table-column
                        prop="update_time"
                        label="最近编辑时间"
                        width="144"
                        sortable>
                        <template slot-scope="scope">
                            {{scope.row.update_time?scope.row.update_time.substring(0,16):'-'}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="right"
                        label="操作"
                        width="220">
                        <template slot-scope="scope">
                            <el-button
                                @click.native.prevent="handleEdit(scope.row)"
                                type="text"
                                size="small"
                                class="primary-btn">
                                编辑
                            </el-button>
                            <el-button
                                @click.native.prevent="handleCheck(scope.row, scope.$index)"
                                type="text"
                                size="small"
                                class="primary-btn"
                                v-if="scope.row.iss_status===0||scope.row.iss_status===3">
                                审核
                            </el-button>
                            <el-button
                                @click.native.prevent="handleUp(scope.row, scope.$index)"
                                type="text"
                                size="small"
                                class="primary-btn"
                                v-if="scope.row.iss_status===1">
                                上架
                            </el-button>
                            <el-button
                                @click.native.prevent="handleUp(scope.row, scope.$index)"
                                type="text"
                                size="small"
                                class="red-btn"
                                v-else-if="scope.row.iss_status===2">
                                下架
                            </el-button>
                            <el-button
                                @click.native.prevent="handleDelete(scope.row, scope.$index)"
                                type="text"
                                size="small"
                                class="red-btn">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNumber"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="pageSize"
                    layout="total, prev, pager, next, sizes, jumper"
                    :total="total_count">
                </el-pagination>
            </div>
        </div>
    </div>
  </div>
</template>

<script>
//这里可以导入其它文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》from ‘《组件路径》';
import Header from "../../../components/Header.vue";
import NavMenu from "../../../components/NavMenu.vue"
import Breadcrumb from '../../../components/Breadcrumb.vue';
import {
  provinceAndCityData
} from "element-china-area-data";
import { getLogin } from "@/api/ajax";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: { Header, NavMenu, Breadcrumb },
  props: {},
  data() {
    //这里存放数据
    return {
        provinceAndCityData,
        activeMenuIndex: "newspaper_manage",
        breadcrumbList:[
            {
                icon:'file-list-line',
                url:'',
                text:''
            },
            {
                icon:'',
                url:'',
                notLink: true,
                text:'内容管理'
            },
            {
                icon:'',
                url:'',
                text:'报纸管理'
            }
        ],
        searchInput: '',
        searchStudy: -1,
        searchStatus: -1,
        searchYear: -1, 
        typeList:[
            {
                value:'',
                label:'全部'
            },
            {
                value:'0',
                label:'小学'
            },
            {
                value:'1',
                label:'初中'
            },
            {
                value:'2',
                label:'高中'
            },
            {
                value:'3',
                label:'大学'
            }
        ],
        studyList:[
            {
                value:'',
                label:'全部'
            },
            {
                value:'0',
                label:'初一'
            },
            {
                value:'1',
                label:'初二'
            },
            {
                value:'2',
                label:'初三'
            },
            {
                value:'3',
                label:'高一'
            }
        ],
        yearList:[
            {
                value: -1,
                label: '全部'
            }
        ],
        tableData:[],
        pageSize: window.localStorage.getItem('pageSize')?Number(window.localStorage.getItem('pageSize')):10, 
        pageNumber: window.localStorage.getItem('pageNumber')?Number(window.localStorage.getItem('pageNumber')):1,
        tableHeight: "", // 表格高度
        total_count: 0,
        dataSort: {}
    }
  },
  //计算属性 类似于data概念
  computed: {
    
  },
  //监控data中数据变化
  watch: {},
  //方法集合
  methods: {
    handleSort(value){
        let dataSort = {
            prop: value.prop,
            order: value.order
        }
        this.dataSort = dataSort
        this.getList()
    },
    // 处理学段
    formatterStudy(row){
        let studyCn = ''
        let list = this.$studyTypeAll
        if(row.study_phase){
            for(let i=0;i<list.length;i++){
                if(row.study_phase===list[i].study_phase){
                    studyCn = list[i].study_phase_name
                }
            }
        }else{
            studyCn = '未知'
        }
        return studyCn
    },
    // 创建机构或者编辑信息
    handleEdit(row){
        // 根据登录用户判断当前用户是不是超管 在table里加上disabled

        // 点击时记录页码和每页条数
        window.localStorage.setItem('pageSize',this.pageSize)
        window.localStorage.setItem('pageNumber',this.pageNumber)
        this.$router.push({
            path: "/createNewspaper",
            query: {
                id: row?row.id:''
            },
        });
    },
    // 停用 启用
    handleUp(row, index) {
      let Mname = "/PaperServer/Manager/IssueManager/EditIssueStatus";
      let updataData = JSON.parse(JSON.stringify(row));
      let data = {
        id: row.id
      };
      if (row.iss_status === 1) {
        // 下架状态
        data.iss_status = 2;
        updataData.iss_status = 2;
      } else if (row.iss_status === 2) {
        data.iss_status = 1;
        updataData.iss_status = 1;
      }
      getLogin(Mname, data).then(res => {
        this.$message.success("操作成功");
        this.$set(this.tableData, index, updataData);
      });
    },
    // 审核
    handleCheck(row, index){
        let Mname = "/PaperServer/Manager/IssueManager/EditIssueStatus";
        let updataData = JSON.parse(JSON.stringify(row));
        let data = {
            id: row.id
        };
        this.$confirm('审核', '提示', {
          confirmButtonText: '审核通过',
          cancelButtonText: '驳回',
          type: 'warning'
        }).then(() => {
            data.iss_status = 1;
            updataData.iss_status = 1;
            getLogin(Mname, data).then(res => {
                this.$message.success("操作成功");
                this.$set(this.tableData, index, updataData);
            });
        }).catch(() => {
            data.iss_status = 3;
            updataData.iss_status = 3;
            getLogin(Mname, data).then(res => {
                this.$message.success("操作成功");
                this.$set(this.tableData, index, updataData);
            });      
        });
    },
    // 删除
    handleDelete(row){
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           let Mname = "/PaperServer/Manager/IssueManager/DelIssueById";
            let data = {
                id: row.id,
            };
            getLogin(Mname, data).then(res => {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                this.getList(1)
            });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    handleSizeChange(val) {
        this.pageSize = val
        this.pageNumber = 1
        this.getList()
    },
    handleCurrentChange(val) {
        this.pageNumber = val
        this.getList()
    },
    //计算table高度(动态设置table高度)
    getTableHeight() {
      let tableH = 370; //距离页面下方的高度
      let tableHeightDetil = window.innerHeight - tableH;
      if (tableHeightDetil <= 300) {
        this.tableHeight = 300;
      } else {
        this.tableHeight = window.innerHeight - tableH;
      }
    },
    getList(val){
        if(val){
            this.pageNumber = val
        }
        let MethodName = "/PaperServer/Manager/IssueManager/PageQueryIssue"
        let order_column_list = []
        if(this.dataSort != {}){
            if(this.dataSort.order=='descending'){
                order_column_list.push({
                    name: this.dataSort.prop,
                    asc: false
                })
            }else if(this.dataSort.order=='ascending'){
                order_column_list.push({
                    name: this.dataSort.prop,
                    asc: true
                })
            }
        }
        let data = {
            key_word: this.searchInput.trim(),
            iss_status: this.searchStatus===-1?null:this.searchStatus,
            study_phase: this.searchStudy===-1?null:this.searchStudy,
            release_year: this.searchYear===-1?null:this.searchYear,
            page_capacity:this.pageSize,
            cur_page:this.pageNumber,
            order_bys: order_column_list
        }
        getLogin(MethodName, data)
        .then((res) => {
            if(res.status===1){
               this.tableData = res.data.list
               this.total_count = res.data.total_count
            }
        })
        .catch(() => {
            this.loading = false
        });
    },
    // 获取年份列表
    getYearList(){
        let nowYear = new Date().getFullYear()
        let yearList = []
        for(let i = 0; i < 20; i++){
            let obj = {
                value: nowYear - i,
                label: nowYear - i
            }
            yearList.push(obj)
        }
        this.yearList = this.yearList.concat(yearList)
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getYearList()
    this.getTableHeight();
    this.getList()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  //生命周期-创建之前
  beforeCreated() { },
  //生命周期-挂载之前
  beforeMount() { },
  //生命周期-更新之前
  beforUpdate() { },
  //生命周期-更新之后
  updated() { },
  //生命周期-销毁之前
  beforeDestory() { },
  //生命周期-销毁完成
  destoryed() { },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() { }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */

</style>
<style lang="scss">
.organize-manage{
    .el-cascader{
        width: 160px;
        height: 32px;
        line-height: 32px;
        .el-input{
            width: 100%;
            height: 32px;
        }
    }
}
</style>
