<template>
    <div>
        <el-button type="primary" size="small" @click="addArticleList">创建文章</el-button>
        <el-popover
                placement="bottom"
                class="addBtn"
                trigger="click">
            <div class="add-text">
                <!--<Dialog></Dialog>-->
                <span @click="ISMobile">移动</span>
                <span @click="articleBatchRelese(1)">发布</span>
                <span @click="articleBatchRelese(0)">停止发布</span>
            </div>
            <el-button class="btn-primary" size="small" slot="reference">批处理</el-button>
        </el-popover>
        <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="30%">
            <el-tree
                    :data="ArticleData"
                    :props="defaultProps"
                    @node-click="targetNode"
                    highlight-current>
            </el-tree>
            <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="articleMobile">确 定</el-button>
                    </span>
        </el-dialog>
        <el-form :model="articleListFrom"  label-width="100px" class="demo-ruleForm">
            <el-row style="margin-top: 20px">
                <el-col :span="4" style="width: 160px;">
                    <el-form-item label="置顶" prop="top" label-width="40px">
                        <el-select v-model="articleListFrom.top" placeholder="全部" style="width: 120px;">
                            <el-option label="全部" value=-1></el-option>
                            <el-option label="置顶" value=1></el-option>
                            <el-option label="未置顶" value=0></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="10"  style="width: 450px;">
                    <el-form-item label="发布状态" prop="release">
                        <el-select v-model="articleListFrom.release" placeholder="全部" style="width: 120px;">
                            <el-option label="全部" value=-1></el-option>
                            <el-option label="发布" value=1></el-option>
                            <el-option label="未发布" value=0></el-option>
                        </el-select>
                        <el-input v-model="articleListFrom.keywords" placeholder="请输入关键字" style="width: 40%"></el-input>
                    </el-form-item>

                </el-col>
                <el-col :span="10" style="position: relative;z-index: 210; width: 150px;">
                    <el-button type="primary" size="small" plain v-if="!isSenior" @click="isSenior = true">高级</el-button>
                    <el-button type="primary" size="small" plain v-if="isSenior" @click="packUp">收起</el-button>
                    <el-button type="primary" size="small" @click="submit">查询</el-button>
                </el-col>
            </el-row>
            <el-row v-if="isSenior">
                <el-col :span="8" style="width: 450px;">
                    <el-form-item label="创建时间" label-width="68px">
                        <div class="block">
                            <el-date-picker
                                    v-model="articleListFrom.create_start"
                                    type="daterange"
                                    align="right"
                                    unlink-panels
                                    value-format="yyyy-MM-dd"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    :picker-options="pickerOptions2">
                            </el-date-picker>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12"  style="width: 450px;">
                    <el-form-item label="发布时间">
                        <div class="block">
                            <el-date-picker
                                    v-model="articleListFrom.release_start"
                                    type="daterange"
                                    align="right"
                                    unlink-panels
                                    value-format="yyyy-MM-dd"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    :picker-options="pickerOptions2">
                            </el-date-picker>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <el-table
                :data="tableData"
                border
                @selection-change="selectionChange"
                style="width: 100%">
            <el-table-column
                    label="全选"
                    type="selection"
                    width="50">
            </el-table-column>
            <el-table-column
                    fixed
                    prop="id"
                    label="文章ID"
                    width="200">
            </el-table-column>
            <el-table-column
                    prop="top"
                    label="置顶"
                    width="120">
            </el-table-column>
            <el-table-column
                    prop="title"
                    label="文章标题"
                    width="200">
            </el-table-column>
            <el-table-column
                    prop="category"
                    label="所属分类"
                    width="200">
            </el-table-column>
            <el-table-column
                    prop="operator"
                    label="最近操作人"
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="createTime"
                    label="创建时间"
                    :formatter="dateFormat1" 
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="releaseTime"
                    label="发布时间"
                    :formatter="dateFormat" 
                    width="180">
            </el-table-column>
            <el-table-column
                    fixed="right"
                    label="操作"
                    width="245">
                <template slot-scope="scope">
                    <el-button @click="articleDetail(scope.row)" size="small">编辑</el-button>
                    <el-button type="primary" class="btn-primary" size="small" v-if="!scope.row.releaseTime" @click="articleRelese(scope.row, 1)">发布</el-button>
                    <el-button type="danger" size="small" v-if="scope.row.releaseTime" @click="articleRelese(scope.row, 0)">停止发布</el-button>
                    <el-popover
                            placement="bottom"
                            class="addBtn"
                            trigger="click">
                        <div class="add-text" style="min-width:107px">
                            <span @click.stop="openDialog(scope.row)">预览</span>
                            <span @click="articleCopy(scope.row)">复制</span>
                            <span @click="articleDelete(scope.row)">删除</span>
                        </div>
                        <el-button size="small" slot="reference">更多</el-button>
                    </el-popover>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
          background
          v-if="tableData.length !== 0"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :page-size="20"
          :total="total">
        </el-pagination>
        <!--预览-->
        <previewDialog :previewData="dialogData"></previewDialog>
        
    </div>
</template>

<script>
import { mapGetters } from 'vuex';
import axios from '../../../common/axios';
import { timeQuick, categoryFn, getParents } from '../../../common/common';
import moment from 'moment';
import previewDialog from './Preview.vue'; 

export default {
    name: "article-list",
    data() {
        return {
            isSenior: false,
            defaultProps: {
                children: 'children',
                label: 'abstract'
            },
            dialogVisible: false,
            articleListFrom: {
                type: 1,
                parent_id: this.$route.query.parent_id,
                top: '',
                release: '',
                keywords: '',
                create_start: '',
                release_start: '',
                create_start_time: '',
                create_end_time: '',
                release_start_time: '',
                release_end_time: '',
                page_num: ''
            },
            tableData: [],
            pickerOptions2: timeQuick,
            batchId: [],
            batchParentId: '',
            targetId: '',
            watchId: this.$route.query.id,
            dialogData: {
                dialogFormVisible: false,
            },
            total: 0
        };
    },
    methods: {
        findLastChildrens(arr) {
            var result = [];

            for (var i in arr) {
                var obj = arr[i];
                if (!obj.children) {
                    continue;
                }
                var findResult = this.findLastChildrens(obj.children);
                if (findResult.length === 0) {
                    result.push(obj.children);
                } 
                else {
                    result = result.concat(findResult);
                }
            }
            return result;
        },
        handleCurrentChange(currentPage) {
            this.submit(currentPage);
        },
        openDialog(row) {
            this.dialogData = Object.assign(this.dialogData, row);
            if (this.dialogData.releaseTime && typeof row.releaseTime !== 'string') {
                this.dialogData.release_time = moment(this.dialogData.releaseTime * 1000).format("YYYY-MM-DD HH:mm:ss"); 
                this.dialogData.releases = '发布';
            }
            else {
                this.dialogData.release_time = '';
                this.dialogData.releases = '未发布';
            }
            this.dialogData.tops = row.top;

            if (this.dialogData.topEndTime && typeof row.topEndTime !== 'string') {
                this.dialogData.top_end_time =  moment(this.dialogData.topEndTime * 1000).format("YYYY-MM-DD HH:mm:ss"); 
            }
            else {
                this.dialogData.top_end_time = '';
            }
            if (this.dialogData.createTime && typeof row.createTime !== 'string') {
                this.dialogData.create_time = moment(this.dialogData.createTime * 1000).format("YYYY-MM-DD HH:mm:ss");  
            }
            this.dialogData.parent_title = categoryFn(this.$route.query.breadcrumb, this.dialogData.parent_title);
            this.dialogData.dialogFormVisible = true;
        },
        articleMobile() {
            axios({
                method: 'post',
                url: '//api-ces-test.oasgames.com/api/item/move',
                params: {
                    id: this.batchId,
                    target_id: this.targetId
                }
            }).then((response) => {
                this.tableData.map((key, i) => {
                    this.batchId.map((item, j) => {
                        if (this.tableData[i].id === this.batchId[j]) {
                            this.tableData.splice(i, 1);
                        }
                    });
                });
                this.dialogVisible = false;
            });
        },
        targetNode(node) {
            this.targetId = node.id;
        },
        ISMobile() {
            if (this.batchId.length !== 0) {
                this.dialogVisible = true;
            }
            else {
                this.$message({
                    type: 'warning',
                    message: '请您选择要移动文章!'
                });
            }
        },
        selectionChange(selectData) {
            this.batchId = [];
            selectData.map((key, index) => {
                this.batchId.push(key.id);
                this.batchParentId = key.parent_id;
            });
        },
        submit(currentPage) {
            this.articleListFrom.create_start_time = '';
            this.articleListFrom.create_start_time = '';
            this.articleListFrom.release_end_time = '';
            this.articleListFrom.release_start_time = '';
            if (this.articleListFrom.create_start) {
                this.articleListFrom.create_end_time = this.articleListFrom.create_start[1];
                this.articleListFrom.create_start_time = this.articleListFrom.create_start[0];
            }
            else {
                this.articleListFrom.create_end_time = '';
                this.articleListFrom.create_start_time = '';
            }
            if (this.articleListFrom.release_start) {
                this.articleListFrom.release_end_time = this.articleListFrom.release_start[1];
                this.articleListFrom.release_start_time = this.articleListFrom.release_start[0];
            }
            else {
                this.articleListFrom.release_end_time = '';
                this.articleListFrom.release_start_time = '';
            }
          
            for (let i in this.articleListFrom) {
                if (!this.articleListFrom[i]) {
                    delete this.articleListFrom[i];
                }
            }
            if (typeof currentPage === 'number') {
                this.articleListFrom.page_num = currentPage;     
            }

            this.articleListFrom.parent_id = this.$route.query.id;
            axios({
                method: 'post',
                url: '//api-ces-test.oasgames.com/api/item/list',
                params: this.articleListFrom
            }).then((response) => {
                this.tableData = [];
                if (response.data.data.length) {
                    this.tableData = response.data.data;
                    this.tableData.map((key, index) => {
                        key.top = key.top ? '置顶' : '未置顶';
                    });
                    this.total = parseInt(response.data.total);
                }

            });
        },
        addArticleList() {
            this.$router.push({
                path: '/article/add',
                query: this.$route.query
            });
        },
        articleDetail(row) {
            this.$router.push({
                path: '/article/edit',
                query: {
                    id: row.id,
                    parent_id: row.parentId,
                    breadcrumb: this.$route.query.breadcrumb
                }
            });
        },
        articleCopy(row) {
            this.$router.push({
                name: 'articleAdd',
                query: {
                    id: row.id,
                    parent_id: row.parentId,
                    breadcrumb: this.$route.query.breadcrumb,
                    copy: 'yes'
                }
            });
        },
        articleDelete(row) {
            this.$confirm('您确定删除该文章吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios({
                    method: 'post',
                    url: '//api-ces-test.oasgames.com/api/item/delete',
                    params: {
                        id: row.id,
                        parent_id: row.parent_id,
                        category: 0
                    }
                }).then((response) => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.tableData.map((key, i) => {
                        if (this.tableData[i].id === row.id) {
                            this.tableData.splice(i, 1);
                        }
                    });
                }).catch((error) => {
                    console.log(error);
                });

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        articleRelese(row, status) {
            axios({
                method: 'post',
                url: '//api-ces-test.oasgames.com/api/item/status',
                params: {
                    id: [row.id],
                    parent_id: row.parent_id,
                    status: status
                }
            }).then((response) => {
                if (status === 0) {
                    row.releaseTime = 0;
                }
                else {
                    row.releaseTime = response.data.result;
                }
            });
        },
        articleBatchRelese(status) {
            axios({
                method: 'post',
                url: '//api-ces-test.oasgames.com/api/item/status',
                params: {
                    id: this.batchId,
                    parent_id: this.batchParentId,
                    status: status
                }
            }).then((response) => {
                if (response.data.result) {
                    this.tableData.map((key, i) => {
                        this.batchId.map((item, j) => {
                            if (this.tableData[i].id === this.batchId[j] && status === 1) {
                                this.tableData[i].releaseTime = response.data.result;
                            }
                            if (this.tableData[i].id === this.batchId[j] && status === 0) {
                                this.tableData[i].releaseTime = 0;
                            }
                        });
                    });
                }
            });
        },
        dateFormat(row, column) {
            if (row.releaseTime) {
                return moment(row.releaseTime * 1000).format("YYYY-MM-DD HH:mm"); 
            }
            else {
                return '未发布';
            }
        },
        dateFormat1(row, column) {
            if (row.createTime) {
                return moment(row.createTime * 1000).format("YYYY-MM-DD HH:mm");  
            }
        },
        packUp() {
            this.isSenior = false;
            this.articleListFrom.create_start = '';
            this.articleListFrom.release_start = '';
        }
    },
    computed: {
        ...mapGetters('article', {
            articleTypeDetail: 'articleTypeDetail',
            ArticleData: 'isArticleData',
        })
    },
    watch: {
        $route (to, from) {   
            if (to.query.id !== from.query.id) {
                this.submit();
            }
        },
    },
    mounted() {
        this.submit();
    },
    components: {
        previewDialog
    },
    updated() {
        this.$nextTick(function () {
            this.tableData.map((key, index) => {
                let getParent = getParents(this.ArticleData, key.parentId).reverse();
                let abstract = '';
                getParent.map((item, j) => {
                    abstract += '/' + item.abstract;
                    this.tableData[index].category = abstract;
                });
                
            });
        });
    }
};
</script>

<style scoped>
    .el-popover{
        max-width:136px;
    }
</style>
