<template>
    <div style="width: 100%; height: 100%; padding: 0px 20px; box-sizing: border-box">
        <div style="overflow: hidden;">
            <!-- <el-select v-model="currentJournal.journal_id" @change="selectJournal" placeholder="Please select journal" style="width: 500px">
                <el-option v-for="item in jourList" :key="item.journal_id" :label="item.title" :value="item.journal_id">
                    <span style="float: left">{{ item.title }}</span>

                   
                    <span

                        style="
                            float: right;
                            height: 20px;
                            line-height: 20px;
                            border-radius: 4px;
                            color: #8492a6;
                            font-size: 12px;
                            padding: 0 5px;
                            margin-top: calc((34px - 20px) / 2);
                            color: #fff;
                            background: #006699;
                            border: 1px solid #006699;
                            display: inline-block;
                        "
                        v-if="item.cycle == 0"
                        > {{ $t('articleListEditor.Continuouspublication') }}</span
                    >
                </el-option>
            </el-select> -->

            <el-button type="primary" icon="el-icon-plus" @click="openEditJournal" style="float: right;"> {{ $t('articleListEditor.add') }}</el-button>
          
        </div>

        <!-- <el-button type="primary" @click="horizontal = !horizontal">切换tree方向</el-button> -->

        <div style="padding: 20px 0; box-sizing: border-box">
            <el-table
                height="84vh"
                :data="JournalList"
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                empty-text="New messages (0)"
                
            >
                <!-- <el-table-column type="expand" width="30">
                    <template slot-scope="scope">
                     
                    </template>
                </el-table-column> -->
                <!-- <el-table-column label="No." align="center" width="50">
                    <template slot-scope="scop">
                        {{ scop.$index + 1 }}
                    </template>
                    
                </el-table-column> -->
                <el-table-column prop="title" label="title">
                    <template slot-scope="scope">
                        <p>
                            <span style="font-size: 16px !important; font-weight: 700 !important; color: rgb(51, 51, 51)">
                                {{
                                    scope.row.stage_year +
                                    ' Vol.' +
                                    scope.row.stage_vol +
                                    ' issue.' +
                                    scope.row.stage_no +
                                    scope.row.stage_pagename +
                                    scope.row.stage_page
                                }}
                            </span>
                        </p>
                    </template>
                </el-table-column>
                <el-table-column prop="stage_icon" :label="$t('articleListEditor.coverImage')" width="200">
                    <template slot-scope="scope">
                        <div style="width: 80px; height: auto; padding: 4px; box-sizing: border-box">
                            <img
                                style="width: 100%; height: 100%"
                                :src="scope.row.stage_icon ? `https://www.tmrjournals.com/public/${scope.row.stage_icon}` : ''"
                                alt=""
                            />
                        </div>
                    </template>
                </el-table-column>
               

                <el-table-column label=" " width="100" align="center">
                    <template slot-scope="scope">

                        <el-button size="mini" @click="handleDelete(scope.row)" type="danger" plain icon="el-icon-delete">
							{{ $t('articleListEditor.delete') }}</el-button>
                       </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog :title="$t('GroupClassification.add')" :visible.sync="editDialogVisible1" width="600px"  :append-to-body="true" :before-close="handleEditClose">
            <el-form ref="detail_form" :model="detailForm" :rules="rules" label-width="165px" >
                <el-form-item label="Journal :">
                    <p style="display: flex; align-items: center; justify-content: space-between">
                        <span>{{ journal.title }}</span>
                        <span
                            style="
                                border-radius: 2px;
                                padding: 0 4px;
                                line-height: 24px;
                                height: 24px;
                                box-sizing: border-box;
                                border: 1px solid rgb(0, 102, 153) !important;
                                color: rgb(0, 102, 153);
                                font-size: 12px;
                            "
                        >
                            {{ getCycle(journal.cycle) }}
                        </span>
                    </p>
                </el-form-item>
                <el-form-item label="Cover Image :" prop="image">
                    <el-upload
                        class="avatar-uploader"
                        ref="upIconIMg"
                        :action="baseUrl + 'journalmaster/journal/up_file'"
                        :show-file-list="false"
                        name="journalicon"
                        :on-success="handleAvatarSuccess2"
                        :on-error="handleAvatarError2"
                        :before-upload="beforeAvatarUpload2"
                    >
                        <img
                            v-if="detailForm.stage_icon"
                            :src="detailForm.stage_icon ? `https://www.tmrjournals.com/public/${detailForm.stage_icon}` : ''"
                            class="avatar"
                            accept=".png,.jpg"
                        />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>

                <el-form-item label="Year :" prop="stage_year">
                    <!-- <el-date-picker
      v-model="detailForm.stage_year"
      type="year"
     > </el-date-picker>-->
     <el-input v-model="detailForm.stage_year" clearable></el-input>
                 
                </el-form-item>
                <el-form-item label="Vol :" prop="stage_vol">
                    <el-input v-model="detailForm.stage_vol" clearable></el-input>
                </el-form-item>
                <el-form-item label="No :" prop="stage_no">
                    <el-input v-model="detailForm.stage_no" clearable></el-input>
                </el-form-item>
                <el-form-item label="Page :" prop="stage_page">
                    <el-input v-model="detailForm.stage_page" placeholder='15–20' clearable></el-input>
                </el-form-item>
                <el-form-item label="Issue Date :" prop="issue_date">
                 
    
                    <el-input v-model="detailForm.issue_date" placeholder='01 May 2025' clearable></el-input>
                </el-form-item>
              
               
               
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleEditClose()">{{ $t('GroupClassification.cancel') }}</el-button>
                <el-button type="primary" @click="handleEdit()">{{ $t('GroupClassification.submit') }}</el-button>
            </span>
        </el-dialog>
      

      
    </div>
</template>

<script>
import OrgTree from '@/components/org-tree';
// import commonclass from './class.vue';
// import commonAgreement from './agreement.vue';
// import commonJournalInstallment from './JournalInstallment.vue';
import bus from '@/components/common/bus';
export default {
    name: 'app',
    props: ['urlList', 'source', 'journal'],
    components: {
        OrgTree
        // commonclass,
        // commonAgreement,
        // commonJournalInstallment
    },
    directives: {
        focus: {
            inserted: function (el) {
                el.querySelector('input').focus();
            }
        }
    },
    data() {
        return {
            baseUrl: this.Common.baseUrl,
            activeNames: [],
            jourList: [],
            detailForm: {},

            currentJournalStage: {},

            expands: [],
            edit_id: localStorage.getItem('U_id'),
            AssociatedJournalList: [],
            JournalList: [],
            drawer: false,
            drawerAgreement: false,
            bd: true,
            ruleForm: {
                major_title: '',
                nickname: ''
            },
            rules: {
					stage_year: [{
						required: true,
						message: 'Please enter year',
						trigger: 'blur'
					}],
					stage_vol: [{
						required: true,
						message: 'Please enter vol',
						trigger: 'blur'
					}],
					stage_no: [{
						required: true,
						message: 'Please enter no',
						trigger: 'blur'
					}],
					stage_page: [{
						required: true,
						message: 'Please enter page',
						trigger: 'blur'
					}],
					issue_date: [{
						required: true,
						message: 'Please select date',
						trigger: 'blur'
					}],
					
					
				},

            editDialogVisible1: false,
            dialogVisible: false,
            dialogVisible2: false,
            isShowF: false,
            data: {
                id: 'abc0',
                label: this.$t('sidebar.GroupClassification'),
                leave: 1, // tree层级
                children: []
            },
            horizontal: true,
            collapsable: true,
            isEdit: 0,
            currentTreeData: {},
            currentJournal: {},
            lastId: 11,
            labelClassName: 'bg-white'
        };
    },
    watch: {
        dialogVisible: {
            handler(newV, oldV) {
                if (newV == false) {
                    this.ruleForm = {};
                }
            }
        }
    },
    async created() {
        this.init();
    },
    async activated() {
        this.init();
    },
    methods: {
        async getJourList() {
            this.$api
                .post(this.urlList.getJournalList, {
                    // username: this.query.username
                })
                .then(async (res) => {
                    this.jourList = res;
                    // this.currentJournal = this.jourList[0];
                    await this.getDate();
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        async selectJournal(v) {
            console.log('e at line 155:', v);
            this.tableData = [];
            this.currentJournal = this.jourList.find((e) => e.journal_id == v);

            await this.getDate();
        },
        async init() {
            
            await this.getJourList();
        },
        beforeAvatarUpload2(file) {
            const isLt2M = file.size / 1024 / 1024 < 1;
            if (!isLt2M) {
                this.$message.error('Picture size cannot exceed 1M!');
            }
            return isLt2M;
        },
        handleAvatarError2(res, file) {
            // this.$message.error(res);
        },
        //上传图片
        handleAvatarSuccess2(res, file) {
            if (res.code == 0) {
                this.detailForm.stage_icon = res.upurl;
            }
        },
        handleDelete(row) {
            this.$confirm(this.$t('articleListEditor.deleteInfo'), this.$t('citeList.tip'), {
                type: 'warning'
            })
                .then(() => {
                    this.$api
                        .post('api/Journal/delJournalStage', { journal_stage_id: row.journal_stage_id })
                        .then((res) => {
                            if (res.code == 0) {
                                this.$message.success(res.msg);
                                this.init();
                            } else {
                                this.$message.error(res.msg);
                            }
                        })
                        .catch((err) => {
                            this.$message.error(err);
                        });
                })
                .catch(() => {});
        },
        handleEdit() {
            this.$refs.detail_form.validate((valid) => {
                if (valid) {
                    this.$api
                        .post('api/Journal/creatJournalStage', this.detailForm)
                        .then((res) => {
                            if (res.code == 0) {
                                this.$message.success('Success!');
                                this.editDialogVisible1 = false;
                                this.getDate();
                            } else {
                                this.$message.error(res.msg);
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                } else {
                    this.$message.error('error submit!!');
                    return false;
                }
            });
        },
        selectType(val) {
            console.log('val at line 193:', val);
        },
        getCycle(val) {
            var text = '';
            switch (val) {
                case 0:
                    text = this.$t('articleListEditor.journalType0');
                    break;
                case 1:
                    text = this.$t('articleListEditor.journalType1');
                    break;
                case 3:
                    text = this.$t('articleListEditor.journalType3');
                    break;
            }

            return text;
        },
        expndChange(row, expandedRows) {
            if (expandedRows.length) {
                this.expands = [];
                if (row) {
                    this.expands.push(row.journal_id); // 每次push进去的是每行的ID
                }
            } else {
                this.expands = []; // 默认不展开
            }
        },
        getRowKeys(row) {
            return row.journal_id;
        },
        changeBind(b) {
            var BindInfo = b.selected == 0 ? this.$t('GroupClassification.BindInfo') : this.$t('GroupClassification.UnBindInfo');
            this.$confirm(`${this.$t('GroupClassification.JournalBindInfo')} ${b.title}${BindInfo}`, '提示', {
                confirmButtonText: this.$t('GroupClassification.submit'),
                dangerouslyUseHTMLString: true,
                cancelButtonText: this.$t('GroupClassification.cancel'),
                type: 'warning'
            })
                .then(() => {
                    var url = '';
                    if (b.selected == 1) {
                        url = this.urlList.unbind;
                    } else if (b.selected == 0) {
                        url = this.urlList.bind;
                    }
                    url;
                    console.log('url at line 278:', url);
                    this.$api
                        .post(url, {
                            journal_issn: b.issn,
                            major_id: this.currentTreeData.major_id
                        })
                        .then(async (res) => {
                            if (res.code == 0) {
                                this.$message({
                                    type: 'success',
                                    message: res.msg
                                });
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: res.msg
                                });
                            }
                        });

                    this.$nextTick(async () => {
                        setTimeout(async () => {
                            await this.getAssociatedJournalList();
                        }, 200);
                    });
                })
                .catch(() => {
                    // this.$message({
                    //     type: 'info',
                    //     message: this.$t('GroupClassification.cancel')
                    // });
                });
        },
        handleClose() {
            this.drawer = false;
            this.currentJournalStage = {};
        },
        handleCloseJournalInstallment() {
            this.drawerJournalInstallment = false;
            this.currentJournalStage = {};
        },
        handleEditClose() {
            this.editDialogVisible1 = false;
            this.currentJournalStage = {};
            this.detailForm = {};
        },
        handleAgreementClose() {
            this.drawerAgreement = false;
            this.currentJournalStage = {};
        },
        getAssociatedJournalList() {
            this.$api
                .post(this.urlList.AssociatedJournalList, {
                    major_id: this.currentTreeData.major_id
                })
                .then(async (res) => {
                    if (res.code == 0) {
                        this.AssociatedJournalList = res.data.list;
                        console.log('this.AssociatedJournalList at line 234:', this.AssociatedJournalList);
                    } else {
                        this.$message.error(res.msg);
                    }
                })
                .catch((err) => {
                    this.$message.error(err);
                });
        },

        openEditJournal() {
            var that = this;
            // this.currentJournalStage = data;
            this.detailForm = {
                issn: this.currentJournal.issn,
                // stage_icon: '11.jpg',

                // stage_icon: data.stage_icon,
                // stage_vol: data.stage_vol,
                // stage_year: data.stage_year,
                // stage_no: data.stage_no,
                // stage_page: data.stage_page,
                // issue_date: data.issue_date,
                // stage_icon: data.stage_icon
            };
            this.editDialogVisible1 = true;
            // this.$nextTick(() => {
            //     that.$refs.commonClassRef.init();
            // });
        },
        openJournalAgreement(data) {
            var that = this;
            this.currentJournal = data;
            this.drawerAgreement = true;
            this.$nextTick(() => {
                that.$refs.commonAgreementRef.init();
            });
        },
        renameKeys(obj, oldKey, newKey) {
            if (obj[oldKey]) {
                obj[newKey] = obj[oldKey];
                delete obj[oldKey];
            }
            for (let k in obj) {
                if (typeof obj[k] === 'object') {
                    this.renameKeys(obj[k], oldKey, newKey);
                }
            }
        },
        // 获取数据
        async getDate() {
            const loading = this.$loading({
                lock: true,
                text: 'Loading...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            this.$api
                .post('api/Web/getStages', {
                    journal_id: this.journal.journal_id
                })
                .then(async (res) => {
                    if (res.code == 0) {
                        this.JournalList = res.data.stages;
                        loading.close();
                    } else {
                        this.$message.error(res.msg);
                        loading.close();
                    }

                    this.$forceUpdate();
                })
                .catch((err) => {
                    this.$message.error(err);
                    loading.close();
                });
        },

        // 增加千分位
        numFormatter(num) {
            let res = num;
            if (num && num !== null) {
                res = num.toString().replace(/\d+/, (n) => {
                    return n.replace(/(\d)(?=(\d{3})+$)/g, ($1) => {
                        return $1 + ',';
                    });
                });
            }
            return res;
        },
        cccc(a, b) {
            // console.log(a);
            // console.log(b);
        },
        mouseWheelDia() {
            // bugfix 鼠标移入弹层，滚动鼠标不能缩放bug
            this.isShowF = false;
        },
        Mouseover() {
            // 鼠标移入缩放icon
            this.bd = false;
        },
        Mouseout() {
            // 鼠标移出缩放icon
            this.bd = true;
        },
        clearDialog() {
            // 关闭添加/编辑/删除弹层
            this.dialogVisible = false;
            this.dialogVisible2 = false;
            this.ruleForm.major_title = '';
        },
        addOrEdit(val) {
            // 点击添加/编辑
            // 新增val：0，编辑val：1
            this.dialogVisible = true;
            this.isEdit = val;
            // eslint-disable-next-line eqeqeq
            if (val == 1) {
                // 编辑回显
                this.ruleForm = {
                    major_title: this.currentTreeData.label,
                    major_sort: this.currentTreeData.major_sort,
                    major_id: this.currentTreeData.major_id,
                    nickname: this.currentTreeData.nickname
                };
            } else {
                this.ruleForm.pid = this.currentTreeData.major_id;
            }
        },
        async confirm() {
            // 添加/编辑的确定
            this.$refs.ruleForm.validate(async (valid) => {
                if (valid) {
                    if (this.isEdit == 1) {
                        // 编辑
                        // this.ruleForm.major_title =
                        // data.id = this.treeData.id;
                        // this.currentTreeData.label = data.label;

                        this.$api
                            .post(this.urlList.edit, {
                                major_title: this.ruleForm.major_title,
                                major_id: this.ruleForm.major_id,
                                major_sort: this.ruleForm.major_sort,
                                nickname: this.ruleForm.nickname
                            })
                            .then(async (res) => {
                                if (res.code == 0) {
                                    this.$message({
                                        type: 'success',
                                        message: res.msg
                                    });
                                    this.clearDialog();
                                } else {
                                    this.$message({
                                        type: 'error',
                                        message: res.msg
                                    });
                                }
                            });

                        // 前端编辑数据

                        // loading.close();
                    } else {
                        this.$api
                            .post(this.urlList.add, {
                                major_title: this.ruleForm.major_title,
                                pid: this.ruleForm.pid,
                                major_sort: this.ruleForm.major_sort,
                                nickname: this.ruleForm.nickname
                            })
                            .then(async (res) => {
                                if (res.code == 0) {
                                    this.$message({
                                        type: 'success',
                                        message: res.msg
                                    });
                                    this.clearDialog();
                                } else {
                                    this.$message({
                                        type: 'error',
                                        message: res.msg
                                    });
                                }
                            });
                        // 添加
                        // 前端添加数据,需要自己生成子级id,可以传数据的时候把最后一级id传过来,进行累加
                        // data.id = this.lastId++;
                        // // data.level = this.currentTreeData.level + 1;
                        // data.label = this.ruleForm.major_title;
                        // data.expand = true;
                        // const render = (formData) => {
                        //     formData.some((item) => {
                        //         if (item.id === this.currentTreeData.id) {
                        //             if (item.children) {
                        //                 item.children.push(data);
                        //             } else {
                        //                 this.$set(item, 'children', [data]);
                        //             }
                        //         } else if (item.children) {
                        //             render(item.children);
                        //         }
                        //     });
                        // };
                        // const arr = [this.data];
                        // render(arr);
                        // this.data = arr[0];

                        // loading.close();
                    }
                    this.$nextTick(async () => {
                        setTimeout(async () => {
                            await this.getDate();
                        }, 200);
                    });
                } else {
                    // loading.close();
                }
            });
        },
        del() {
            this.dialogVisible2 = true;
        },
        async confimdelete() {
            // 是否确定删除当前节点
            // 前端删除 遍历原数据,删除匹配id数据
            this.$api
                .post(this.urlList.delete, {
                    major_id: this.currentTreeData.major_id
                })
                .then(async (res) => {
                    if (res.code == 0) {
                        this.$message({
                            type: 'success',
                            message: res.msg
                        });
                        this.clearDialog();
                    } else {
                        this.$message({
                            type: 'error',
                            message: res.msg
                        });
                    }

                    this.$nextTick(async () => {
                        setTimeout(async () => {
                            await this.getDate();
                        }, 200);
                    });
                });
            // const deleteData = (data) => {
            //     data.some((item, i) => {
            //         if (item.id === this.currentTreeData.id) {
            //             data.splice(i, 1);
            //         } else if (item.children) {
            //             deleteData(item.children);
            //         }
            //     });
            // };
            // const arr = [this.data];
            // deleteData(arr);
            // this.data = arr[0] ? arr[0] : {};
            // this.dialogVisible2 = false;
            // this.$message({
            //     type: 'success',
            //     message: '节点删除成功！'
            // });
        },
        onMouseover(e, data) {
            var collapse = localStorage.getItem('collapse');
            var width = Number(e.clientX - (!collapse || collapse == 'false' ? 260 : 40));

            // 鼠标移入树节点
            this.currentTreeData = data; // 鼠标移入，该节点的所有数据

            this.isShowF = true;
            var floating = document.getElementsByClassName('floating')[0];
            if (floating) {
                floating.style.left = width + 'px';
                floating.style.top = e.clientY - 80 + 'px';
            }
        },
        onMouseout(e, data) {
            // 鼠标移出树节点
            this.isShowF = false;
        },
        renderContent(h, data) {
            return data.label;
        },
        onExpand(e, data) {
            // 节点展开收缩
            // eslint-disable-next-line eqeqeq
            if (data.leave == 1 && data.expand == true) {
                // bugfix
                var dom = document.getElementById('ddd');
                (dom.style.top = '50%'), (dom.style.left = '8%');
            }
            if ('expand' in data) {
                data.expand = !data.expand;
                if (!data.expand && data.children) {
                    this.collapse(data.children);
                }
            } else {
                this.$set(data, 'expand', true);
            }
        },
        collapse(list) {
            list.forEach((child) => {
                if (child.expand) {
                    child.expand = false;
                }

                child.children && this.collapse(child.children);
            });
        },
        toggleExpand(data, val) {
            // 节点默认全部展开
            var _this = this;
            // console.log(data);
            if (Array.isArray(data)) {
                data.forEach(function (item) {
                    _this.$set(item, 'expand', val);
                    if (item.children) {
                        _this.toggleExpand(item.children, val);
                    }
                });
            } else {
                this.$set(data, 'expand', val);
                if (data.children) {
                    _this.toggleExpand(data.children, val);
                }
            }
        }
    }
};
</script>
<style lang="less" scoped>
.floating {
    background: rgba(0, 0, 0, 0.7);
    box-shadow: rgba(0, 0, 0, 0.2);
    width: auto;
    // height: 45px;
    line-height: 24px;
    // display: flex;
    // justify-content: space-around;
    position: absolute;
    color: #fff;
    border-radius: 5px;
    box-sizing: border-box;
    left: 0;
    top: 0;
    transition: all 0.3s;
    z-index: 999;
    font-size: 12px;
    padding: 6px;
    span {
        cursor: pointer;
    }
}
</style>
<style lang="less">
.addOrEditDia,
.delDia {
    padding: 14px 18px 10px 18px;
    border-radius: 4px !important;
    .el-dialog__header {
        display: flex;
        justify-content: space-between;
        padding: 20px 0 !important;
    }
    .el-dialog__body {
        padding: 0;
        padding-top: 20px;
        // margin-top: 37px;
    }
    .el-dialog__footer {
        padding: 27px 0 9px 0 !important;
    }
    .el-dialog__headerbtn {
        position: static !important;
    }
}
.bg-white {
    background-color: white;
}
.bg-orange {
    background-color: orange;
}
.bg-gold {
    background-color: gold;
}
.bg-gray {
    background-color: gray;
}
.bg-lightpink {
    background-color: lightpink;
}
.bg-chocolate {
    background-color: chocolate;
}
.bg-tomato {
    background-color: tomato;
}
.outBox {
    height: calc(100% - 100px) !important;
    margin-top: 10px;
    width: calc(100% - 40px) !important;
    overflow: auto !important;
}
.tableExpand1 {
    margin-top: 5px;
    padding: 2px 0;
    // padding-left: 40px;
    box-sizing: border-box;
    .title {
        display: inline-block;
        // width: 140px;
        margin-right: 10px;
        font-weight: 700 !important;
        color: #333333de;
    }
    .item {
        // margin-bottom: 4px;
    }
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 120px;
    height: 120px;
}

.avatar-uploader_small {
    height: 120px;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
}

.avatar-uploader_small .el-upload {
    width: 80px;
    height: 80px;
}

.avatar-uploader_small .avatar-uploader-icon {
    line-height: 80px;
    margin-left: -30px;
}

.avatar {
    width: 120px;
    height: 120px;
    display: block;
}
</style>
