<template>
    <div>
        <div style="margin: 10px 0">
            <el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="name"></el-input>
            <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
            <el-button type="warning" @click="reset">重置</el-button>
        </div>
        <div style="margin: 10px 0">
            <el-button type="primary" @click="handleAdd" v-if="user.role === 'tenderee'|| user.role === 'admin'">发布招标项目<i class="el-icon-circle-plus-outline"></i></el-button>
            <el-popconfirm
                    class="ml-5"
                    confirm-button-text='确定'
                    cancel-button-text='我再想想'
                    icon="el-icon-info"
                    icon-color="red"
                    title="您确定批量删除这些数据吗？"
                    @confirm="delBatch"
            >
                <el-button type="danger" slot="reference" v-if="user.role === 'admin'">批量删除 <i class="el-icon-remove-outline"></i></el-button>
            </el-popconfirm>

        </div>
        <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"
                  @selection-change="handleSelectionChange" >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="name" label="招标项目名"></el-table-column>
            <el-table-column prop="content" label="招标内容" width="100" >
                <template slot-scope="scope">
                    <el-button @click="view(scope.row.content)" type="primary" style="width: 100%">查看内容</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="user" label="发布人"></el-table-column>
            <el-table-column prop="content" label="评论"  width="110" >
                <template slot-scope="scope">
                    <el-button @click="viewComment(scope.row.id)">查看评论</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="time" label="开始时间" :formatter="formatData"></el-table-column>
            <el-table-column prop="overtime" label="结束时间" :formatter="formatData"></el-table-column>
            <el-table-column prop="state" label="审核状态"></el-table-column>
            <el-table-column label="审核" v-if="user.role === 'admin'" width="203">
                <template v-slot="scope">
                    <el-button type="success" @click="changeState(scope.row, '审核通过')" :disabled="scope.row.state !== '待审核'">审核通过</el-button>
                    <el-button type="danger" @click="changeState(scope.row, '审核不通过')" :disabled="scope.row.state !== '待审核'">审核不通过</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="feedback" label="反馈信息" width="130px" >
                <template slot-scope="scope">
                    <el-button @click="view1(scope.row.feedback)" type="primary" style="width: 100px">查看反馈信息</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
                <template slot-scope="scope" >
                    <el-button type="success" @click="handleEdit(scope.row)" v-if="(user.role === 'tenderee'&&scope.row.user === user.nickname&& scope.row.state==='审核不通过' )||user.role === 'admin' ">编辑<i class="el-icon-edit"></i></el-button>

                    <el-button type="success" @click="handleEdit2(scope.row)" v-if="scope.row.state==='审核不通过' &&user.role === 'admin' ">反馈信息<i class="el-icon-edit"></i></el-button>
                    <el-upload
                               :action="'http://' + serverIp +':9090/file/upload'"
                               :show-file-list="false"
                               :headers="importHeaders"
                               :on-success="handleFileUploadSuccess"
                               style="display: inline-block">
                    <el-button type="primary" class="ml-5" v-if="(user.role === 'tenderee' && scope.row.state==='审核通过'&&scope.row.user === user.nickname )">上传招标文件<i class="el-icon-top"></i></el-button>
                </el-upload>
                    <el-popconfirm
                            class="ml-5"
                            confirm-button-text='确定'
                            cancel-button-text='我再想想'
                            icon="el-icon-info"
                            icon-color="red"
                            title="您确定删除吗？"
                            @confirm="del(scope.row.id)"
                    >
                        <el-button type="danger" slot="reference" v-if="user.role === 'admin'||(user.role === 'tenderee'&&scope.row.state==='审核不通过')">删除 <i class="el-icon-remove-outline"></i></el-button>

                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <div style="padding: 10px 0">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[2, 5, 10, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <el-dialog title="招标信息" :visible.sync="dialogFormVisible" width="60%" >
            <el-form label-width="80px" size="small">
                <el-form-item label="招标标题">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="招标内容">
                    <mavon-editor ref="md" v-model="form.content" :ishljs="true" @imgAdd="imgAdd"/>
                </el-form-item>
                <span class="demonstration">招标开始时间：</span>
                <el-date-picker
                        v-model="form.time"
                        type="datetime"
                        :picker-options="expireTimeOPtion"
                        placeholder="请选择开始时间"
                ></el-date-picker>
                <span class="demonstration">招标结束时间：</span>
                <el-date-picker
                         v-model="form.overtime"
                         type="datetime"
                         :picker-options="expireTimeOPtion"
                         placeholder="请选择截止时间"
                >
                </el-date-picker>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="招标信息" :visible.sync="dialogFormVisible1" width="60%" >
            <el-form label-width="80px" size="small">
                <el-form-item label="招标标题">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="招标内容">
                    <mavon-editor ref="md" v-model="form.content" :ishljs="true" @imgAdd="imgAdd"/>
                </el-form-item>
                <span class="demonstration">招标开始时间：</span>
                <el-date-picker
                        v-model="form.time"
                        type="datetime"
                        :picker-options="expireTimeOPtion"
                        placeholder="请选择开始时间"
                ></el-date-picker>
                <span class="demonstration">招标结束时间：</span>
                <el-date-picker
                        v-model="form.overtime"
                        type="datetime"
                        :picker-options="expireTimeOPtion"
                        placeholder="请选择截止时间"
                >
                </el-date-picker>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible1 = false">取 消</el-button>
                <el-button type="primary" @click="save2">确 定</el-button>
            </div>
        </el-dialog>

      <!--  <el-dialog title="投标信息" :visible.sync="dialogFormVisibles" width="40%" >
            <el-form label-width="80px" size="small">
                <el-form-item label="招标标题" >
                    <el-input v-model="form.name" autocomplete="off" disabled style="width: 250px"></el-input>
                </el-form-item>
                <el-form-item label="招标人">
                    <el-input v-model="form.user" autocomplete="off"disabled style="width: 250px"></el-input>
                </el-form-item>
                <el-form-item label="投标人">
                    <el-input v-model="user.nickname" autocomplete="off"disabled style="width: 250px"></el-input>
                </el-form-item>
                <span class="demonstration" >开始时间</span>
                <el-date-picker disabled
                                v-model="form.time"
                                type="datetime"
                                :picker-options="expireTimeOPtion"
                                placeholder="请选择截止时间"
                ></el-date-picker>
                <span class="demonstration" >结束时间</span>
                <el-date-picker disabled
                        v-model="form.overtime"
                        type="datetime"
                        :picker-options="expireTimeOPtion"
                        placeholder="请选择截止时间"
                >
                </el-date-picker>
                <el-form-item style="color: red;text-align: center">温馨提醒：信息提交后请及时上传投标文件!</el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisibles = false">取 消</el-button>
                <el-button type="primary" @click="save1">确 定</el-button>
            </div>
        </el-dialog>-->

        <el-dialog title="反馈信息表" :visible.sync="dialogFormVisible2" width="38%">
            <el-form label-width="80px" size="small">
                <el-form-item label="原因:" size="100px">
                    <el-input type="textarea" v-model="form.feedback" autocomplete="off" style="width: 400px;height: 100px"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible2 = false">取 消</el-button>
                <el-button type="primary" @click="save3">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="招标信息" :visible.sync="viewDialogVis" width="60%" >
            <el-card>
                <div>
                    <mavon-editor
                            class="md"
                            :value="content"
                            :subfield="false"
                            :defaultOpen="'preview'"
                            :toolbarsFlag="false"
                            :editable="false"
                            :scrollStyle="true"
                            :ishljs="true"
                    />
                </div>
            </el-card>
        </el-dialog>

        <el-dialog title="反馈信息" :visible.sync="viewDialogVis1" width="30%" >
            <el-card>
                <div>
                    <mavon-editor
                            class="md"
                            :value="feedback"
                            :subfield="false"
                            :defaultOpen="'preview'"
                            :toolbarsFlag="false"
                            :editable="false"
                            :scrollStyle="true"
                            :ishljs="true"
                    />
                </div>
            </el-card>
        </el-dialog>

        <el-dialog title="评论信息" :visible.sync="viewCommentDialog" width="60%" >
            <el-card>
                <div >
                    <div style="margin: 10px 0">
                        <div style="border-bottom: 1px solid orangered; padding: 10px 0; font-size: 20px">评论</div>
                        <div style="padding: 10px 0">
                            <el-input size="small" type="textarea" v-model="commentForm.content"></el-input>
                        </div>
                        <div class="pd-10" style="text-align: right">
                            <el-button type="primary" size="small" @click="saveComment">评论</el-button>
                        </div>
                    </div>
                </div>
                <div>
                    <div v-for="item in comments" :key="item.id" style="border-bottom: 1px solid #ccc; padding: 10px 0; ">
                        <div style="display: flex">
                            <div style="width: 100px; text-align: center">
                                <el-image :src="item.avatarUrl" style="width: 50px; height: 50px; border-radius: 50%"></el-image>
                            </div> <!--  头像-->
                            <div style="flex: 1; font-size: 14px; padding: 5px 0; line-height: 25px">
                                <b>{{ item.nickname }}：</b>
                                <span>{{ item.content }}</span>

                                <div style="display: flex; line-height: 20px; margin-top: 5px">
                                    <div style="width: 200px;">
                                        <i class="el-icon-time"></i><span style="margin-left: 5px">{{ item.time }}</span>
                                    </div>
                                    <div style="text-align: right; flex: 1">
                                        <el-button style="margin-left: 5px" type="text" @click="handleReply(item.id)">回复</el-button>
                                        <el-button type="text" style="color: red" @click="delComment(item.id)" v-if="user.id === item.userId">删除</el-button>
                                    </div>
                                </div>
                            </div>   <!--  内容-->
                        </div>

                        <div v-if="item.children.length"  style="padding-left: 200px;">
                            <div v-for="subItem in item.children" :key="subItem.id"  style="background-color: #f0f0f0; padding: 5px 20px">
                                <!--          回复列表-->
                                <div style="font-size: 14px; padding: 5px 0; line-height: 25px">
                                    <div>
                                        <b style="color: #3a8ee6" v-if="subItem.pnickname">@{{ subItem.pnickname }}</b>
                                    </div>
                                    <div style="padding-left: 5px">
                                        <b>{{ subItem.nickname }}：</b>
                                        <span>{{ subItem.content }}</span>
                                    </div>

                                    <div style="display: flex; line-height: 20px; margin-top: 5px; padding-left: 5px">
                                        <div style="width: 200px;">
                                            <i class="el-icon-time"></i><span style="margin-left: 5px">{{ subItem.time }}</span>
                                        </div>
                                        <div style="text-align: right; flex: 1">
                                            <el-button style="margin-left: 5px" type="text" @click="handleReply(subItem.id)">回复</el-button>
                                            <el-button type="text" style="color: red" @click="delComment(subItem.id)" v-if="user.id === subItem.userId">删除</el-button>
                                        </div>
                                    </div>
                                </div>   <!--  内容-->
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>
        </el-dialog>

        <el-dialog title="回复" :visible.sync="dialogReply" width="50%" >
            <el-form label-width="80px" size="small">
                <el-form-item label="回复内容">
                    <el-input type="textarea" v-model="commentForm.contentReply" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogReply = false" size="small">取 消</el-button>
                <el-button type="primary" @click="saveComment"  size="small">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {serverIp} from "../../public/config";
    import axios from "axios";
    var moment = require('moment');
    moment().format();
    export default {
        name: "Article",
        data() {
            return {
                id:null,
                comments:[],
                commentForm:{},
                form: {},
                tableData: [],
                name: '',
                multipleSelection: [],
                pageNum: 1,
                pageSize: 10,
                total: 0,
                viewCommentDialog:false,
                dialogReply:false,
                dialogFormVisible1:false,
                dialogFormVisible: false,
                dialogFormVisibles:false,
                viewDialogVis1:false,
                dialogFormVisible2:false,
                teachers: [],
                user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
                content: '',
                feedback: '',
                viewDialogVis: false,
                serverIp: serverIp,
                importHeaders: {token:  JSON.parse(localStorage.getItem('user')).token},
                expireTimeOPtion: {
                    disabledDate(time) {
                        return time.getTime() < Date.now() //如果没有后面的-8.64e7就是不可以选择今天的
                    },
                },
                defaultValue:'',
            }
        },
        created() {
            this.load()
        },
        methods: {
           formatData1(row, column, cellValue, index){
                //最终返回 s 就可以了
               var s =	new Date(cellValue).toLocaleString();
               return s;

            },
            formatData(row, column, cellValue, index){
                //最终返回 s 就可以了
                var s =	new Date(cellValue).toLocaleString();
                return s;

            },
            changeState(row, state) {
                this.form = JSON.parse(JSON.stringify(row))
                this.form.state = state;
                this.save3();
            },
            view(content) {
                this.content = content
                this.viewDialogVis = true
            },
            view1(feedback) {
                this.feedback = feedback
                this.viewDialogVis1 = true
            },
            // 绑定@imgAdd event
            imgAdd(pos, $file) {
                let $vm = this.$refs.md
                // 第一步.将图片上传到服务器.
                const formData = new FormData();
                formData.append('file', $file);
                axios({
                    url: 'http://' + serverIp +':9090/file/upload',

                    method: 'post',
                    data: formData,
                    headers: {'Content-Type': 'multipart/form-data',token:  JSON.parse(localStorage.getItem('user')).token},
                }).then((res) => {
                    // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
                    $vm.$img2Url(pos, res.data);
                })
            },
            load() {
                this.request.get("/article/page", {
                    params: {
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        name: this.name,

                    }

                }).then(res => {
                    this.tableData = res.data.records
                    this.total = res.data.total

                })

            },
            changeEnable(row) {
                this.request.post("/article/update", row).then(res => {
                    if (res.code === '200') {
                        this.$message.success("操作成功")
                    }
                })
            },
            handleAdd() {
                this.dialogFormVisible = true
                this.form = {}

            },
            handleEdit(row) {
                this.form = JSON.parse(JSON.stringify(row))
                this.dialogFormVisible1 = true
            },
            handleEdit2(row) {
                this.form = JSON.parse(JSON.stringify(row))
                this.dialogFormVisible2 = true
            },

            handleEdit1(row) {
                const t1 = moment(row.overtime).format('x')
                const t2 = moment(row.time).format('x')
                const t3 = moment(new Date).format('x')
                console.log(t1,t2,t3)
                if (t3<t2){
                    this.$message.error("开始时间未到，请稍后再试")
                }
                else if(t3>t1){
                    this.$message.error("投标结束时间已结束")
                    this.dialogFormVisibles = false
                }else{
                    this.form = JSON.parse(JSON.stringify(row))
                    this.dialogFormVisibles = true
                }
            },
            handleFileUploadSuccess(res) {
                console.log(res)
                this.$message.success("上传成功")
                this.load()
            },
            del(id) {
                this.request.delete("/article/" + id).then(res => {
                    if (res.code === '200') {
                        this.$message.success("删除成功")
                        this.load()
                    } else {
                        this.$message.error("删除失败")
                    }
                })
            },
            handleSelectionChange(val) {
                console.log(val)
                this.multipleSelection = val
            },
            delBatch() {
                let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
                this.request.post("/article/del/batch", ids).then(res => {
                    if (res.code === '200') {
                        this.$message.success("批量删除成功")
                        this.load()
                    } else {
                        this.$message.error("批量删除失败")
                    }
                })
            },
            save() {
                this.request.post("/article/save1", this.form).then(res => {
                    if (res.code === '200') {
                        this.$message.success("保存成功")
                        this.dialogFormVisible = false
                        this.load()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            },
            save1() {
                this.request.post("/manage", this.form).then(res => {
                    if (res.code === '200') {
                        this.$message.success("投标成功，请及时上传投标文件!")
                        this.dialogFormVisibles = false
                        this.load()
                    } else {
                        this.$message.error("投标失败")
                    }
                })
            },
            save2() {
                this.request.put("/article", this.form).then(res => {
                    if (res.code === '200') {
                        this.$message.success("保存成功!")
                        this.dialogFormVisible1 = false
                        this.load()
                    } else {
                        this.$message.error("保存失败")
                    }
                })
            },
            save3() {
                this.request.put("/article/update", this.form).then(res => {
                    if (res.code === '200') {
                        this.$message.success("修改成功!")
                        this.dialogFormVisible1 = false
                        this.dialogFormVisible2 = false
                        this.load()
                    } else {
                        this.$message.error("保存失败")
                    }
                })
            },

            reset() {
                this.name = ""
                this.load()
            },
            handleSizeChange(pageSize) {
                console.log(pageSize)
                this.pageSize = pageSize
                this.load()
            },
            handleCurrentChange(pageNum) {
                console.log(pageNum)
                this.pageNum = pageNum
                this.load()
            },
            download(url) {
                window.open(url)
            },
            // 评论
            //查看评论
            viewComment(id){
                //加载评论
                this.id = id
                this.request.get("/comment/tree/" + id).then(res => {
                    console.log(res)
                    this.comments = res.data
                })
                this.viewCommentDialog = true
            },
            //保存评论
            saveComment() {
                this.commentForm.articleId = this.id
                if (this.commentForm.contentReply) {
                    this.commentForm.content = this.commentForm.contentReply
                }
                this.request.post("/comment", this.commentForm).then(res => {
                    if (res.code === '200') {
                        this.$message.success("评论成功")
                        this.commentForm = {}  // 初始化评论对象内容
                        //加载评论
                        this.dialogReply = false
                        this.request.get("/comment/tree/" + this.id).then(res => {
                            // console.log(res)
                            this.comments = res.data
                        })
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            },
            //删除评论
            delComment(id) {
                this.request.delete("/comment/" + id).then(res => {
                    if (res.code === '200') {
                        this.$message.success("删除成功")
                        this.request.get("/comment/tree/" + this.id).then(res => {
                            // console.log(res)
                            this.comments = res.data
                        })
                    } else {
                        this.$message.error("删除失败")
                    }
                })
            },
            //回复评论
            handleReply(pid){
                this.commentForm = { pid: pid }
                this.dialogReply = true
            },
        }
    }
</script>

<style scoped>

</style>