<template>
    <section>
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true">
                <el-form-item :label="user.timeType.customDegreeName + $t('guan-li')">
                    <el-input :placeholder="$t('qing-shu-ru-guan-jian-ming-cheng')" v-model.trim="searchNameVal" clearable class="input-with-select"
                        style="margin-left: 50px" @keyup.enter.native="searchName()">
                        <el-button slot="append" @click="searchName()">{{ $t('sou-suo') }}</el-button>
                    </el-input>
                </el-form-item>

                <!-- <el-link type="primary" :underline="false" @click="intoCenterRatio" class="tanjia">批量导入{{user.timeType.customDegreeName}}</el-link>
                <el-link icon="el-icon-circle-plus-outline" type="primary" :underline="false" class="tanjia" @click="addNewSubProject()">添加{{user.timeType.customDegreeName}}</el-link>
                <el-link type="primary" :underline="false" @click="batchDelete" class="tanjia">批量删除{{user.timeType.customDegreeName}}</el-link> -->
                <el-link type="primary" :underline="false" @click="batchDelete" class="tanjia">{{ $t('Batchdelete')
                }}</el-link>
                <el-link type="primary" :underline="false" @click="outoCenterRatio" class="tanjia">{{ $t('Exportdata')
                }}</el-link>
                <el-link type="primary" :underline="false" @click="intoCenterRatio" class="tanjia">{{ $t('bulkimport')
                }}</el-link>
                <el-link icon="el-icon-circle-plus-outline" type="primary" :underline="false" class="tanjia"
                    @click="addNewSubProject()">{{ $t('add') }}</el-link>

            </el-form>
        </el-col>
        <el-table :data="subProjectList" highlight-current-row v-loading="listLoading" :height="heightDoms"
            style="width: 100%;" @selection-change="selectionChange">
            <el-table-column type="selection"></el-table-column>
            <el-table-column prop="id" width="200" :label="$t('headerTop.serialNumber')" align="center">
                <template slot-scope="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column prop="name" :label="$t('names')" width="160" show-overflow-tooltip></el-table-column>
            <el-table-column prop="projectNum" :label="$t('numberofrelatedprojects')" width="160">
                <template slot-scope="scope">{{ scope.row.projectNum + $t('ge') }}</template>
            </el-table-column>
            <el-table-column prop="projects" :label="$t('relatedprojects')" min-width="180"
                show-overflow-tooltip></el-table-column>
            <el-table-column prop="rmark" :label="$t('bei-zhu')" min-width="180" show-overflow-tooltip></el-table-column>
            <el-table-column :label="$t('operation')" width="170">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" @click="addNewSubProject(scope.row)">{{ $t('bian-ji')
                    }}</el-button>
                    <el-button size="small" type="danger" @click="deleteSubPro(scope.row)">{{ $t('btn.delete')
                    }}</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog :title="$t('addedormodifiedthemaintenancedata')" v-if="addSubProject" :visible.sync="addSubProject"
            :close-on-click-modal="false" customClass="customWidth" width="600px">
            <el-form ref="form2" :model="addfm" :rules="ruless" label-width="100px">
                <el-form-item :label="$t('names')" prop="name">
                    <el-input v-model="addfm.name" :placeholder="$t('peaseenterthe')" clearable></el-input>
                </el-form-item>
                <el-form-item :label="$t('bei-zhu')">
                    <el-input type="textarea" :rows="4" :placeholder="$t('peaseenterthe')" v-model="addfm.rmark" clearable
                        maxlength="150" show-word-limit> </el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addSubProject = false">{{ $t('btn.cancel') }}</el-button>
                <el-button type="primary" @click="submitInsertSubProject" :loading="addLoading">{{ $t('btn.submit')
                }}</el-button>
            </div>
        </el-dialog>
        <!-- 导入结果说明 -->
        <el-dialog :title="$t('importtheresults')" v-if="showImportResult" :visible.sync="showImportResult"
            customClass="customWidth" width="500px">
            <div>
                <span>{{ importResultMsg }}</span>

            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="showImportResult = false">{{ $t('btn.determine') }}</el-button>
            </span>
        </el-dialog>
        <!-- <span>{{ $t('importTemplate') }}</span> -->
        <el-dialog :title="$t('dao-ru') + user.timeType.customDegreeName + $t('shu-ju')" v-if="intoCenterDialog"
            :visible.sync="intoCenterDialog" customClass="customWidth" width="500px">
            <p>1. {{ $t('other.download') }}
                <el-link type="primary" style="margin-left:5px;" :underline="false" href="./upload/研究中心导入模板.xlsx"
                    :download="user.timeType.customDegreeName + $t('importTemplate') + '.xlsx'">{{
                        user.timeType.customDegreeName
                        + $t('importTemplate') }}.xlsx</el-link>
            </p>
            <!-- <p>2. 填写excel模板,请确保模板中的项目和人员已添加到系统中。</p> -->
            <p style="display: flex;justify-content: center;padding:1em 0">
                <el-upload ref="upload" action="#" :limit="1" :http-request="batchImportData" :show-file-list="false">
                    <el-button type="primary" :underline="false" :loading="importingData">{{ $t('other.startImporting')
                    }}</el-button>
                </el-upload>
            </p>
        </el-dialog>
    </section>
</template>
<script>
export default {
    data() {
        return {
            user: JSON.parse(sessionStorage.getItem("user")),
            listLoading: false,
            addfm: {
                name: '',
                rmark: ''
            },
            addSubProject: false,
            ruless: {
                name: [{ required: true, message: this.$t('pleaseentername'), trigger: "blur" }],
            },
            heightDoms: document.documentElement.clientHeight - 140,
            intoCenterDialog: false,
            importingData: false,
            importResultMsg: null,
            showImportResult: false,
            selectionArr: [],
            subProjectList: [],//子项目列表
            subProjectListArr: [], // 备用列表
            searchNameVal: '',
            options: [],
            value: ''
        };
    },
    methods: {
        aabbcc() {
            console.log(12345)
        },  
        searchName() {
            var val = this.searchNameVal
            let arr = []
            if (val) {
                arr = this.subProjectListArr.filter((num) => {
                    if (num.name.indexOf(val) != '-1') {
                        return num
                    }
                })
                this.subProjectList = arr
            } else {
                this.subProjectList = this.subProjectListArr
            }

        },
        // 批量删除
        selectionChange(selection) {
            this.selectionArr = selection
            console.log(this.selectionArr);
        },
        batchDelete() {
            if (this.selectionArr.length == 0) {
                this.$message(this.$t('pleaseselectheonesyouwanttodelete') + this.user.timeType.customDegreeName + this.$t('shu-ju'))
                return
            } else {
                let nametext = ''
                for (let i in this.selectionArr) {
                    nametext += this.selectionArr[i].name + '、'
                }
                nametext = nametext.substring(0, nametext.length - 1)
                this.$confirm(this.$t('makesuretodeleteinbatches') + this.user.timeType.customDegreeName + this.$t('shu-ju') + '：' + nametext + '\u3000' + $t('ma'), this.$t('btn.delete'), {
                    confirmButtonText: this.$t('btn.determine'),
                    cancelButtonText: this.$t('btn.cancel'),
                    type: 'warning'
                }).then(() => {
                    let batchIds = ''
                    for (let m in this.selectionArr) {
                        batchIds += this.selectionArr[m].id + ','
                    }
                    batchIds = batchIds.substring(0, batchIds.length - 1)
                    this.http.post('/report-extra-degree/batchDelete', {
                        batchIds
                    }, res => {
                        if (res.code == 'ok') {
                            this.$message({
                                message: this.$t('message.successfullyDeleted'),
                                type: 'success'
                            })
                            this.getSub()
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            })
                        }
                    }, err => {
                        this.$message({
                            message: err,
                            type: 'error'
                        })
                    })
                })
            }
        },


        intoCenterRatio() {
            this.intoCenterDialog = true;
        },
        outoCenterRatio() {
            this.http.post('/report-extra-degree/exportData', {},
                res => {
                    if (res.code == 'ok') {
                        let filePath = res.data;
                        let fileName = filePath.split('/upload/')[1]
                        const a = document.createElement('a'); // 创建a标签
                        a.setAttribute('download', fileName);// download属性
                        a.setAttribute('href', filePath);// href链接
                        a.click(); //自执行点击事件
                        a.remove();
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                }, err => {
                    this.$message({
                        message: err,
                        type: 'error'
                    })
                })
        },
        batchImportData(item) {
            //首先判断文件类型
            let str = item.file.name.split(".");
            let format = str[str.length - 1];
            if (format != "xls" && format != "xlsx") {
                this.$message({
                    message: this.$t('other.PleaseselecttheXLSorXLSXfile'),
                    type: "error"
                });
            } else {
                this.importingData = true;
                let formData = new FormData();
                formData.append("file", item.file);
                this.http.uploadFile('/report-extra-degree/importData', formData,
                    res => {
                        this.$refs.upload.clearFiles();
                        this.importingData = false;
                        this.showImportResult = true;
                        if (res.code == "ok") {
                            //换成弹出框，以免有人等了半天回来啥也没看到
                            this.importResultMsg = this.$t('importedupdatedsuccessfully') + res.data + this.$t('customersdata') + "。" + (res.msg ? res.msg : "");
                            this.getSub();
                        } else {
                            this.importResultMsg = this.$t('export.Importfailure') + "：" + res.msg;
                        }
                    },
                    error => {
                        this.$refs.upload.clearFiles();
                        this.importingData = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                    });
            }
        },
        getSub() {
            this.listLoading = true;
            this.http.post('/report-extra-degree/getAll ', { withProjects: 1 },
                res => {
                    this.listLoading = false;
                    if (res.code == "ok") {
                        console.log(res, '看看')
                        this.subProjectList = res.data
                        this.subProjectListArr = res.data
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                }
            );
        },
        addNewSubProject(subProject) {
            // console.log(1234)
            // if (subProject == null) {
            //     this.addForm = {projectId: this.currentProject.id, level:1}
            // } 
            // else {
            //     this.addForm = subProject;
            // }
            if (subProject) {
                this.addfm.name = subProject.name
                this.addfm.id = subProject.id
                this.addfm.rmark = subProject.rmark
            } else {
                this.addfm = { name: '', rmark: '' }
            }
            this.addSubProject = true;
        },
        deleteSubPro(subProject) {
            this.$confirm(this.$t('makesuretodeletethisone') + subProject.name + this.$t('shu-ju'), this.$t('btn.delete'), {
                confirmButtonText: this.$t('btn.determine'),
                cancelButtonText: this.$t('btn.cancel'),
                type: "warning"
            })
                .then(() => {
                    this.listLoading = true;
                    this.http.post('/report-extra-degree/delete', {
                        id: subProject.id
                    },
                        res => {
                            this.listLoading = false;
                            if (res.code == "ok") {
                                this.$message({
                                    message: this.$t('message.successfullyDeleted'),
                                    type: "success"
                                });
                                this.getSub();
                            } else {

                                this.$message({
                                    message: res.msg,
                                    type: "error"
                                });

                            }
                        },
                        error => {
                            this.listLoading = false;
                            this.$message({
                                message: error,
                                type: "error"
                            });
                        }
                    );
                })
                .catch(() => { });
        },
        submitInsertSubProject() {
            this.$refs.form2.validate(valid => {
                if (valid) {
                    var slp = this.addfm
                    this.http.post('/report-extra-degree/addOrMod', slp,
                        res => {
                            this.listLoading = false;
                            if (res.code == "ok") {
                                this.$message({
                                    message: this.$t('other.successful'),
                                    type: "success"
                                });
                                this.addfm = { name: '', rmark: '' }
                                this.addSubProject = false
                                this.getSub()
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: "error"
                                });
                            }
                        },
                        error => {
                            this.listLoading = false;
                            this.$message({
                                message: error,
                                type: "error"
                            });
                        }
                    );
                }
            })
        },
    },
    created() {
        this.getSub()
    },
    mounted() {

    }
};
</script>

<style lang="scss" scoped>
@import "../../assets/scss/handle";

.themeFontColor {
    @include font_color("color");
}
.addNode {
    cursor: pointer;
}

.addNode:hover {
    @include font_color("color");
}

.panel {
    padding: 30px 15px;
    box-shadow: 0 2px 4px rgba(3, 3, 3, 0.12), 0 0 6px rgba(0, 0, 0, .04);

}

.sample {
    margin-top: 30px;
    color: #999;
}

.tip {
    margin-left: 10px;
    color: gray;

}

.tanjia {
    float: right;
    box-sizing: border-box;
    margin: 10px 28px;
}
</style>
<style>
.el-tooltip__popper {
    max-width: 600px;
}
</style>