<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="tabs">
                    <a :class="[tabsIndex===0?'active':'']" @click="handleChangeTabs(0)">已校对 {{checkNumber[1]?checkNumber[1]:''}}</a>
                    <a :class="[tabsIndex===1?'active':'']" @click="handleChangeTabs(1)">待校对 {{checkNumber[0]?checkNumber[0]:''}}</a>
                </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" v-if="tabsIndex===0">
                        <label>状态</label>
                        <el-select v-model="searchStatus" @change="getList(1)" 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(1)" 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(1)" 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>
                <template v-if="tabsIndex===0">
                    <el-table
                        class="search-table"
                        :data="tableData"
                        style="width: 100%"
                        @sort-change="handleSort"
                        :default-sort = dataSort
                        :max-height="tableHeight"
                        key='checked-table'>
                        <el-table-column
                            type="index"
                            label="#"
                            sortable
                            width="56"
                            :index="(pageNumber-1)*pageSize+1">
                        </el-table-column>
                        <el-table-column
                            prop="iss_name"
                            label="名称"
                            sortable="custom"
                            min-width="226">
                        </el-table-column>
                        <el-table-column
                            prop="iss_no"
                            label="期数"
                            width="84"
                            sortable="custom">
                        </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="custom">
                        </el-table-column>
                        <el-table-column
                            prop="create_time"
                            label="创建时间"
                            width="144" 
                            sortable="custom">
                            <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="custom">
                            <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="150">
                            <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="(val)=>handleSizeChange(val,'pageSize','pageNumber')"
                        @current-change="(val)=>handleCurrentChange(val,'pageNumber')"
                        :current-page="pageNumber"
                        :page-sizes="[10, 20, 30, 40]"
                        :page-size="pageSize"
                        layout="total, prev, pager, next, sizes, jumper"
                        :total="total_count">
                    </el-pagination>
                </template>
                <template v-else>
                    <el-table
                        class="search-table"
                        :data="tableData"
                        style="width: 100%"
                        @sort-change="handleSort"
                        :default-sort = dataSort
                        :max-height="tableHeight"
                        :key="'check-table'">
                        <el-table-column
                            type="index"
                            label="#"
                            sortable
                            width="56"
                            :index="(pageNumbers-1)*pageSizes+1">
                        </el-table-column>
                        <el-table-column
                            prop="iss_name"
                            label="名称"
                            sortable="custom"
                            min-width="226">
                        </el-table-column>
                        <el-table-column
                            prop="iss_no"
                            label="期数"
                            width="84"
                            sortable="custom">
                        </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="create_time"
                            label="导入日期"
                            width="144" 
                            sortable="custom">
                            <template slot-scope="scope">
                                {{scope.row.create_time?scope.row.create_time.substring(0,10):'-'}}
                            </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="custom">
                            <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="190">
                            <template slot-scope="scope">
                                <el-button
                                    @click.native.prevent="handleEdits(scope.row)"
                                    type="text"
                                    size="small"
                                    class="primary-btn">
                                    校对
                                </el-button>
                                <el-button
                                    @click.native.prevent="handleChecks(scope.row, scope.$index)"
                                    type="text"
                                    size="small"
                                    class="primary-btn">
                                    完成校对
                                </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="(val)=>handleSizeChange(val,'pageSizes','pageNumbers')"
                        @current-change="(val)=>handleCurrentChange(val,'pageNumbers')"
                        :current-page="pageNumbers"
                        :page-sizes="[10, 20, 30, 40]"
                        :page-size="pageSizes"
                        layout="total, prev, pager, next, sizes, jumper"
                        :total="total_count">
                    </el-pagination>
                </template>
            </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 { mapState } from 'vuex'; 
import { getLogin } from "@/api/ajax";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: { Header, NavMenu, Breadcrumb },
  props: {},
  data() {
    //这里存放数据
    return {
        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,
        pageSizes: window.localStorage.getItem('pageSizes')?Number(window.localStorage.getItem('pageSizes')):10, 
        pageNumbers: window.localStorage.getItem('pageNumbers')?Number(window.localStorage.getItem('pageNumbers')):1,
        tableHeight: "", // 表格高度
        total_count: 0,
        dataSort: {
            prop:'update_time',
            order: 'descending'
        },
        tabsIndex: window.localStorage.getItem('tabsIndex')?Number(window.localStorage.getItem('tabsIndex'))*1:0,
        check_flag: window.localStorage.getItem('tabsIndex')?Number(window.localStorage.getItem('tabsIndex'))*1===1?false:true:true,
        checkNumber: [0,0]
    }
  },
  //计算属性 类似于data概念
  computed: {
    ...mapState(['$studyTypeAll','$checkStatusList', '$checkStatusColorList']),
  },
  //监控data中数据变化
  watch: {},
  //方法集合
  methods: {
    handleSort(value){
        let dataSort = {
            prop: value.prop,
            order: value.order
        }
        this.dataSort = dataSort
        this.getList()
    },
    handleChangeTabs(value){
        this.tabsIndex = value
        if(value===1){
            this.check_flag = false
        }else{
            this.check_flag = true
        }
        // this.pageNumber = 1
        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)
        window.localStorage.setItem('tabsIndex',this.tabsIndex)
        window.localStorage.removeItem('newsForm')
        window.localStorage.removeItem('newsStep')
        this.$router.push({
            path: "/createNewspaper",
            query: {
                id: row?row.id:'',
                isCreate: !row?'true':'false'
            },
        });
    },
    // 校对报刊
    handleEdits(row){
        // 根据登录用户判断当前用户是不是超管 在table里加上disabled

        // 点击时记录页码和每页条数
        window.localStorage.setItem('pageSizes',this.pageSizes)
        window.localStorage.setItem('pageNumbers',this.pageNumbers)
        window.localStorage.setItem('tabsIndex',this.tabsIndex)
        window.localStorage.removeItem('newsForm')
        window.localStorage.removeItem('newsStep')
        this.$router.push({
            path: "/articleChecklist",
            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.getList()
      });
    },
    // 审核
    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.getList()
            });
        }).catch(() => {
            data.iss_status = 3;
            updataData.iss_status = 3;
            getLogin(Mname, data).then(res => {
                this.$message.success("操作成功");
                this.getList()
            });      
        });
    },
    // 审核
    handleChecks(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 = 0;
            updataData.iss_status = 0;
            getLogin(Mname, data).then(res => {
                this.$message.success("操作成功");
                this.getList()
            });
        }).catch(() => {
               
        });
    },
    // 删除
    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()
            });
        }).catch(() => {
               
        });
    },
    handleSizeChange(val,type,page) {
        this[type] = val
        this[page] = 1
        this.getList()
    },
    handleCurrentChange(val,type) {
        this[type] = val
        this.getList()
    },
    //计算table高度(动态设置table高度)
    getTableHeight() {
      let tableH = 420; //距离页面下方的高度
      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
                })
            }else{
                order_column_list = [{
                    name: 'update_time',
                    asc: false
                }]
            }
        }else{
            order_column_list = [{
                name: 'update_time',
                asc: false
            }]
        }
        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,
            check_flag: this.check_flag
        }
        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(){
        this.yearList = [
            {
                value: -1,
                label: '全部'
            }
        ]
        let yearList = []
        let MethodName = "/ShopServer/Client/ShopHomeQuery/GetIssueYearLabelList"
        getLogin(MethodName, {})
        .then((res) => {
            if(res.status===1){
                res.year_label_list.forEach(nowYear => {
                    let obj = {
                        value: nowYear,
                        label: nowYear
                    }
                    yearList.push(obj)
                })
                this.yearList = this.yearList.concat(yearList)
            }
        })
        .catch(() => {
            this.loading = false
        });
        
    },
    // 获取数目
    getNumberData(){
        getLogin('/PaperServer/Manager/IssueManager/FindNotCheckAndCheckedIssCount', {})
        .then((res) => {
            if(res.status===1){
               this.checkNumber = res.data 
            }
        })
        .catch(() => {
            
        });
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getNumberData()
    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类 */
.tabs{
    display: flex;
    padding: 16px 0 0 0;
    a{
        font-size: 14px;
        line-height: 22px;
        color: #4E5969;
        border-radius: 100px;
        padding: 5px 16px;
        margin-right: 12px;
        &:hover{
            background: #F2F3F5;
        }
        &.active{
            background: #F2F3F5;
            font-weight: 500;
            color: #165DFF;
        }
    }
}
</style>
<style lang="scss">
.organize-manage{
    .el-cascader{
        width: 160px;
        height: 32px;
        line-height: 32px;
        .el-input{
            width: 100%;
            height: 32px;
        }
    }
}
</style>
