<template>
    <div class="ajm-panel">
        <div class="page-content">
            <div class="ajm-search-form">
                <el-form ref="searchForm" :model="searchForm" :inline="true">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item class="operate-buttons">
                                <el-button type="primary" icon="el-icon-ajm-add" @click="addSystem">{{$t('message.add')}}</el-button>
                                <el-button icon="el-icon-delete" @click="batchDeleteSystems">{{$t('message.delete')}}</el-button>
                            </el-form-item>
                        </el-col>
                        <el-col :span="18" class="ajm-search-items">
                            <el-form-item>
                                <el-input id="enterSearch" class="search-item" v-model="searchForm.sysNameLike" :placeholder="$t('message.Base.confirmSysName')">
                                </el-input>
                            </el-form-item>
                            <el-form-item class="ajm-search-btns">
                                <el-button icon="el-icon-ajm-search" @click="search"></el-button>
                                <el-button icon="el-icon-ajm-refresh" @click="refreshSearch"></el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <div class="ajm-table-list">
                <el-table :data="pageResult.list" tooltip-effect="light" style="width: 100%" @selection-change="selectChange" v-loading="listLoading">
                    <el-table-column prop="systemId" type="selection" width="55" />
                    <el-table-column type="index" :label="$t('message.Table.index')" width="70"/>
                    <el-table-column prop="systemIcon" :label="$t('message.Manager.sysIcon')" width="70">
                        <template slot-scope="scope">
                            <img style="max-width: 40px;background: #dcdfe6" v-if="scope.row.systemIcon" :src="getImgUrl(scope.row.systemIcon)" class="avatar">
                        </template>
                    </el-table-column>
                    <el-table-column prop="systemName" :label="$t('message.Manager.sysName')" :show-overflow-tooltip="true"/>
                    <el-table-column prop="systemCode" :label="$t('message.Manager.sysCode')" :show-overflow-tooltip="true"/>
                    <el-table-column prop="isDefault.name" :label="$t('message.Manager.isDefault')" width="70"/>
                    <el-table-column prop="orderNo" :label="$t('message.Manager.orderNo')" width="70" sortable/>
                    <el-table-column prop="systemUrl" :label="$t('message.Manager.sysUrl')" :show-overflow-tooltip="true"/>
                    <el-table-column prop="remark" :label="$t('message.Manager.sysDescribe')" :show-overflow-tooltip="true"/>
                    <el-table-column prop="createdTime" :label="$t('message.Table.createdTime')" sortable width="180"/>
                    <el-table-column :label="$t('message.Table.operate')" width="90" fixed="right">
                        <template slot-scope="scope">
                            <el-tooltip :content="$t('message.edit')" placement="top">
                                <el-button size="small" type="text" @click="editSystem(scope.$index, scope.row)">
                                    <i class="el-icon-ajm-edit"></i>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip :content="$t('message.delete')" placement="top">
                                <el-button size="small" type="text" @click="deleteSystem(scope.$index, scope.row)" :disabled="scope.row.isDefault.value == 1">
                                    <i class="el-icon-ajm-delete"></i>
                                </el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="ajm-pagination-bar">
                    <el-pagination background
                        @current-change="changePage"
                        @size-change="changePageSize"
                        :current-page="pageResult.pageNum"
                        :page-sizes="[10, 20, 50, 100]"
                        :page-size="pageResult.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pageResult.total">
                    </el-pagination>
                </div>
            </div>

            <el-dialog :title="dialogTitle" width="30%" custom-class="ajm-dialog-middle" :visible.sync="systemFormVisible" top="0" :modal-append-to-body="false" :close-on-click-modal="false">
                <el-form class="ajm-form" :model="editForm" :rules="editFormRules" label-width="80px" ref="editForm">
                    <el-input v-model="editForm.systemId" style="display:none"/>
                    <el-form-item :label="$t('message.Manager.sysName')" prop="systemName">
                        <el-input v-model="editForm.systemName"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('message.Manager.sysCode')" prop="systemCode">
                        <el-input v-model="editForm.systemCode"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('message.Manager.sysType')" prop="systemCategoryId">
                        <el-select :placeholder="$t('message.Manager.conSysType')" v-model="editForm.systemCategoryId">
                            <el-option v-for="item in systemTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('message.Manager.sysIcon')">
                        <!--<el-input auto-complete="off" v-model="editForm.systemIcon"></el-input>-->
                        <el-upload
                            class="avatar-uploader"
                            :action="uploadFileUrl"
                            :show-file-list="false"
                            :on-success="uploadSystemIconSuccess"
                            :headers="headers">
                            <img v-if="systemIconUrl" :src="systemIconUrl" style="width: 48px;height: 48px;">
                            <i class="el-icon-plus avatar-uploader-icon" v-else></i>
                            <div class="del" v-if="systemIconUrl">
                                <i @click="removeSystemIcon" class="el-icon-ajm-delete"></i>
                            </div>
                        </el-upload>
                    </el-form-item>
                    <el-form-item :label="$t('message.Manager.sysUrl')">
                        <el-input v-model="editForm.systemUrl"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('message.Manager.orderNo')" prop="orderNo">
                        <el-input auto-complete="off" v-model="editForm.orderNo" type="number"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('message.Manager.sysDescribe')">
                        <el-input type="textarea" :rows="4" style="max-width: 260px" :maxlength="200" v-model="editForm.remark"></el-input>
                    </el-form-item>
                </el-form>

                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" size="small" @click="saveOrUpdateSystem('editForm')">{{$t('message.save')}}</el-button>
                    <el-button size="small" @click="systemFormVisible = false">{{$t('message.cancel')}}</el-button>
                </div>
            </el-dialog>
        </div>
    </div>

</template>

<style lang="less" scoped>
    .avatar-uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        width: 48px;
        height: 48px;
        img{
            width:48px;
            height:48px;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 48px;
            height: 48px;
            line-height: 48px;
        }
        .del{
            position: absolute;
            left: 0;
            top: 0;
            cursor: default;
            text-align: center;
            color: #fff;
            opacity: 0;
            font-size: 20px;
            background-color: rgba(0,0,0,.5);
            transition: opacity .3s;
            width: 48px;
            height: 48px;
        }
        .del:hover{
            opacity:1;
        }
    }
</style>


<script>

    // 导入vue
    import Vue from 'vue'
    // 系统服务
    import systemService from '../services/systemService';
    import AjmConfig from 'ajm-framework/core/utils/ajm-config'
    export default {
        data () {
            return {
                //系统类型
                systemTypeList:[],
                //服务器地址
                serverUrl: AjmConfig.getApiUrl(),
                //上传图片地址
                uploadFileUrl: AjmConfig.getApiUrl() + AjmConfig.get("BASE_CONTEXT_PATH") + "/api/file/uploadFile",
                //查看图片地址
                viewFileUrl: AjmConfig.get("BASE_CONTEXT_PATH") + '/api/file/viewFile/',
                dialogVisible: false,
                //弹窗标题
                dialogTitle:'',
                headers: {
                    Authorization: "Bearer " + this.$store.getters.tokenInfo.access_token,
                },
                systemIconUrl: '',//系统logo图片
                browserLogoUrl:'',//浏览器logo图片
                loginBgUrl:'',//登录页背景图
                checkList: [],
                // 列表加载
                listLoading: false,
                systemFormVisible: false,
                //分页结果集
                pageResult: {
                    pageNum: 1,
                    pageSize: 10,
                    total: 0,
                    list: []
                },
                // 查询表单
                searchForm: {
                    // 系统名
                    sysNameLike: '',
                    //系统编码
                    sysCodeLike: ''
                },
                // 选择系统集合
                selectedSystems: [],
                // 选择系统ID集合
                selectedSystemIds: [],
                // 系统
                editForm: {
                    systemId: '',
                    systemName: '',
                    systemCode: '',
                    systemIcon: '',
                    orderNo:'',
                    systemUrl: '',
                    remark: '',
                    systemCategoryId:'',
                    status:''
                },
                // 系统规则
                /*editFormRules: {
                    // 系统名称
                    systemName: [
                        {required: true, message: '请输入系统名称', trigger: 'blur'},
                        {min: 1, max: 20, message: '字符长度不超过20', trigger: 'blur'},
                        {validator: checkSystemName, trigger: 'blur'}
                    ],
                    systemCode: [
                        {required: true, message: '请输入系统编码', trigger: 'blur'},
                        {min: 3, max: 20, message: '系统编码为3~20个字符', trigger: 'blur'},
                        {validator: checkSystemCode, trigger: 'blur'}
                    ]
                },*/
            }
        },
        computed:{
            editFormRules() {
                var checkSystemName = (rule, value, callback) => {
                    var systemId = this.editForm.systemId;
                    systemService.checkSystemName(systemId, value).then(resp => {
                        var result = resp;
                        if (!result) {
                            callback();
                        } else {
                            return callback(new Error(this.$t('message.Manager.hasSysName')));
                        }
                    });
                };
                var checkSystemCode = (rule, value, callback) => {
                    var systemId = this.editForm.systemId;
                    systemService.checkSystemCode(systemId, value).then(resp => {
                        var result = resp;
                        if (!result) {
                            callback();
                        } else {
                            return callback(new Error(this.$t('message.Manager.hasSysCode')));
                        }
                    });
                };
                return{
                    // 系统名称
                    systemName: [
                        {required: true, message: this.$t('message.Manager.conSysName'), trigger: 'blur'},
                        {min: 1, max: 20, message: this.$t('message.Manager.sysNameClue'), trigger: 'blur'},
                        {validator: checkSystemName, trigger: 'blur'}
                    ],
                    systemCode: [
                        {required: true, message: this.$t('message.Manager.conSysCode'), trigger: 'blur'},
                        {min: 3, max: 20, message: this.$t('message.Manager.sysCodeClue'), trigger: 'blur'},
                        {validator: checkSystemCode, trigger: 'blur'}
                    ]
                }
            },
        },
        methods: {
            //上传系统logo成功
            uploadSystemIconSuccess(data){
                this.editForm.systemIcon = data.fileKey;
                this.systemIconUrl = this.getImgUrl(this.editForm.systemIcon);
            },
            //删除系统logo
            removeSystemIcon(){
                this.editForm.systemIcon = '';
                this.systemIconUrl = ''
            },
            getImgUrl(filekey){
                return this.serverUrl + this.viewFileUrl + filekey + '?access_token=' + this.$store.getters.tokenInfo.access_token;
            },
            //查询系统分页列表
            findSystemListByPage(){
                //查询系统列表
                /*this.listLoading = true;*/
                var params = {
                    page: this.pageResult.pageNum,
                    rows: this.pageResult.pageSize,
                };
                var sysNameLike = this.searchForm.sysNameLike;
                if(sysNameLike) {
                    params.sysNameLike = sysNameLike;
                }
                var sysCodeLike = this.searchForm.sysCodeLike;
                if(sysCodeLike) {
                    params.sysCodeLike = sysCodeLike;
                }
                // 查询系统分页列表
                systemService.findSystemListByPage(params).then((resp) => {
                    this.pageResult = resp.data || resp;
                    this.listLoading = false;
                })
            },
            // 系统集合改变
            selectChange(val){
                this.selectedSystemIds = [];
                this.selectedSystems = val;
                var num = 0;
                var $this = this;
                this.selectedSystems.forEach(function(item) {
                    $this.selectedSystemIds[num] = item.systemId;
                    num++;
                });
            },
            //切换页面
            changePage(page) {
                this.pageResult.pageNum = page;
                this.findSystemListByPage();
            },
            //根据页码切换页面
            changePageSize(pageSize) {
                this.pageResult.pageSize = pageSize;
                this.findSystemListByPage();
            },
            //刷新页面
            refreshSearch(){
                this.searchForm.sysNameLike = '';
                this.pageResult.pageNum = 1
                this.pageResult.pageSize = 10
                // 执行查询
                this.findSystemListByPage();
            },
            // 查询
            search () {
                this.findSystemListByPage();
            },
            //获取系统类别
            findBusinessSystemTypeList(){
                systemService.findBusinessSystemTypeList().then((resp) => {
                    let systemTypeList = resp;
                    this.systemTypeList = [];
                    systemTypeList.forEach(item => {
                        this.systemTypeList.push({
                            id: parseInt(item.value),
                            name: item.name,
                        })
                    })
                })
            },
            //重置表单
            resetForm(formName) {
                if (this.$refs[formName] !== undefined) {
                    this.$refs[formName].resetFields();
                }
            },
            // 添加系统
            addSystem(){
                this.resetForm("editForm");
                this.dialogTitle = this.$t('message.Manager.addSys');
                this.editForm = {};
                this.systemIconUrl = '';
                this.systemFormVisible = true;
                this.findBusinessSystemTypeList();
            },
            //执行添加系统
            saveOrUpdateSystem(formName){
                // 执行表单验证
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        //执行添加
                        systemService.saveOrUpdate(this.editForm).then((resp) => {
                            this.$message({
                                message: this.$t('message.saveSuccess'),
                                type: "success"
                            });
                            this.systemFormVisible = false;
                            this.findSystemListByPage();
                        }).catch(error => {
                            this.$message({
                                type: "error",
                                message: error
                            });
                        });
                    }
                });
            },
            // 编辑系统
            editSystem(index, row) {
                this.resetForm("editForm");
                this.dialogTitle = this.$t('message.edit')
                let systemId = row.systemId;
                this.editForm.systemId = systemId;
                this.editForm.systemName = row.systemName;
                this.editForm.systemCode = row.systemCode;
                this.editForm.systemIcon = row.systemIcon;
                this.editForm.browserLogo = row.browserLogo;
                this.editForm.loginBg = row.loginBg;
                this.editForm.systemUrl = row.systemUrl;
                this.editForm.orderNo = row.orderNo;
                this.editForm.remark = row.remark;
                this.editForm.systemCategoryId = row.systemCategoryId;
                this.editForm.status = row.status;
                if (row.systemIcon != null && row.systemIcon != '') {
                    this.systemIconUrl = this.getImgUrl(row.systemIcon);
                }else{
                    this.systemIconUrl = ''
                }
                if (row.loginBg != null && row.loginBg != '') {
                    this.loginBgUrl = this.getImgUrl(row.loginBg);
                }else{
                    this.loginBgUrl = ''
                }
                if (row.browserLogo != null && row.browserLogo != '') {
                    this.browserLogoUrl = this.getImgUrl(row.browserLogo);
                }else{
                    this.browserLogoUrl = ''
                }
                this.systemFormVisible = true;
                this.findBusinessSystemTypeList();
            },

            // 删除系统
            deleteSystem(index, row) {
                this.$confirm(this.$t('message.confirmRequest') +"[" + row.systemName + "]？", this.$t('message.delClue'), {
                    cancelButtonClass:"message-cancel-button",
                    confirmButtonText: this.$t('message.confirm'),
                    cancelButtonText: this.$t('message.cancel'),
                    type: 'warning'
                }).then(() => {
                    systemService.deleteSystemBySystemId(row.systemId).then((resp) => {
                        var num = resp.data || resp;
                        this.$message({
                            type: 'success',
                            message: this.$t('message.delSuccess')
                        });
                        this.findSystemListByPage();
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: this.$t('message.cancelDelete')
                    });
                });
            },
            //批量删除系统
            batchDeleteSystems() {
                if (this.selectedSystemIds.length > 0) {
                    this.$confirm(this.$t('message.confirmBatch'), this.$t('message.confirmDel'), {
                        cancelButtonClass:"message-cancel-button",
                        confirmButtonText: this.$t('message.confirm'),
                        cancelButtonText: this.$t('message.cancel'),
                        type: "warning"
                    }).then(() => {
                        systemService.batchDeleteSystems(this.selectedSystemIds)
                            .then(res => {
                                this.tips(res);
                                this.findSystemListByPage();
                            });
                    })
                        .catch(() => {});
                } else {
                    this.$message({
                        message: this.$t('message.Base.choosePara'),
                        type: "warning",
                        duration: 1000
                    });
                }
            },
            //提示信息
            tips(res) {
                var resp = res;
                var type = "success";
                var message = this.$t('message.delSuccess');
                if (resp.status == 500 || resp.data == 0) {
                    type = "error";
                    message = this.$t('message.delFailed');
                }
                this.$message({
                    message: message,
                    type: type,
                    duration: 1500
                });
            },
            //重置查询表单
            resetSearchForm(formName) {
                this.searchForm.sysNameLike = '';
                // 执行查询
                this.findSystemListByPage();
            },

        },
        //初始化
        mounted() {
            //加载
            this.findSystemListByPage();
            let self = this;
            document.getElementById("enterSearch").addEventListener("keydown", function (event) {
                if (event.keyCode === 13) {
                    self.search(event);
                }
            }, false);
        }
    }
</script>
