<template>
    <div class="ajm-panel">
        <div class="ajm-search-form">
            <el-form ref="searchForm" :model="searchComForm" :inline="true">
                <el-row>
                    <el-col :span="8">
                        <el-form-item class="operate-buttons">
                            <el-button type="primary" icon="el-icon-ajm-add" @click="goAddCompany">{{$t('message.add')}}</el-button>
                            <!--<el-button icon="el-icon-ajm-delete" @click="goAddCompany" v-permission-code="''">删除</el-button>-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="16" class="ajm-search-items">
                        <el-form-item>
                            <el-input id="enterSearch" class="search-item" v-model="searchComForm.cnNameLike" :placeholder="$t('message.Manager.confirmCnName')">
                            </el-input>
                        </el-form-item>
                        <el-form-item class="ajm-search-btns">
                            <el-button icon="el-icon-ajm-search" @click="searchCompany"></el-button>
                            <el-button icon="el-icon-ajm-refresh" @click="refreshPage"></el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <div class="ajm-table">
            <el-table :data="pageResult.list" v-loading="listLoading" tooltip-effect="light" @sort-change="handleSortChange">
                <el-table-column prop="logId" :label="$t('message.Table.index')" type="index" sortable width="70">
                </el-table-column>
                <el-table-column prop="companyLogo" :label="$t('message.Manager.logo')" width="85">
                    <template slot-scope="scope">
                        <img :src="getImgUrl(scope.row.companyLogo)" v-if="scope.row.companyLogo" width="38px" height="38px">
                    </template>
                </el-table-column>
                <el-table-column prop="cnName" :label="$t('message.Manager.cnName')" :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column prop="enName" :label="$t('message.Manager.enName')" :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column prop="contactPerson" :label="$t('message.Manager.contactPerson')" :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column prop="contactPhone" :label="$t('message.Manager.contactPhone')" width="120px">
                </el-table-column>
                <el-table-column prop="contactAddress" :label="$t('message.Manager.contactAddress')" :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column prop="createdTime" :label="$t('message.Table.createdTime')" sortable="custom" width="180">
                </el-table-column>
                <el-table-column :label="$t('message.Table.operate')" width="120" fixed="right">
                    <template slot-scope="scope">
                        <el-tooltip :content="$t('message.edit')" placement="top">
                            <el-button size="small" type="text" @click="goEditCompany(scope.$index, scope.row)">
                                <i class="el-icon-ajm-edit"></i>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip :content="$t('message.Manager.serverConfig')" placement="top">
                            <el-button size="small" type="text" @click="EditSystem(scope.$index, scope.row)">
                                <i class="el-icon-ajm-record"></i>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip :content="$t('message.delete')" placement="top">
                            <el-button size="small" type="text" @click="deleteCompany(scope.$index, scope.row)">
                                <i class="el-icon-ajm-delete"></i>
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!--<div class="empty-block" v-if="isSearch == true && pageResult.list.length == 0 && isReload == true">
                &lt;!&ndash;<img src="../images/no_search.png" alt="">&ndash;&gt; 暂无搜索结果
            </div>
            <div class="empty-block" v-if="isSearch == false && pageResult.list.length == 0 && isReload == true">
                &lt;!&ndash;<img src="../images/no_data.png" alt="">&ndash;&gt; 暂无数据
            </div>-->
        </div>
        <div class="ajm-pagination-bar">
            <el-pagination background @current-change="changePage" @size-change="goChangePageSize" :current-page="pageResult.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="pageResult.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageResult.total" />
        </div>

        <el-dialog custom-class="ajm-dialog-middle" :title="dialogTitle" top="0" :visible.sync="companyFormVisible" :modal-append-to-body="false" :close-on-click-modal="false" width="35%">
            <!--步骤条-->
            <div v-if="!isEdit" style="display: flex;line-height: 36px;padding-top: 5px">
                <div :class="[active == 0 ? 'process' : 'first-success']">
                    <img class="icon-success" src="../images/icon_success.png" v-if="active != 0" />
                    <div class="el-step__icon is-text icon-step icon-process" v-else><div class="el-step__icon-inner">1</div></div>{{$t('message.Manager.companyInfo')}}
                </div>
                <div :class="{'first-wait':active == 0,'process':active == 1,'last-success':active == 2}">
                    <img class="icon-success" style="margin-left: 10px" src="../images/icon_success.png" v-if="active == 2" />
                    <div class="el-step__icon is-text icon-step" style="margin-left: 10px" :class="[active == 0 ? 'icon-wait' : 'icon-process']" v-else>
                        <div class="el-step__icon-inner">2</div>
                    </div>{{$t('message.Manager.cnManager')}}
                </div>
                <div :class="[active == 2 ? 'last-process' : 'last-wait']" style="">
                    <div class="el-step__icon is-text icon-step" :class="[active == 2 ? 'icon-process' : 'icon-wait']">
                        <div class="el-step__icon-inner">3</div>
                    </div>{{$t('message.Manager.serverConfig')}}
                </div>
            </div>

            <!--企业信息-->
            <el-form v-show="active == 0" class="ajm-form" :model="companyInfoForm" :rules="companyInfoRules" ref="companyInfoForm" :label-width="formLabelWidth">
                <el-form-item :label="$t('message.Manager.logo')">
                    <el-upload
                        class="avatar-uploader"
                        :action="uploadFileUrl"
                        :show-file-list="false"
                        :on-success="uploadImgSuccess"
                        :headers="headers"
                        :beforeUpload="beforeImgUpload" accept=".png">
                        <img v-if="companyIconUrl" :src="companyIconUrl">
                        <i class="el-icon-plus avatar-uploader-icon"></i>
                        <div class="del" v-if="companyIconUrl">
                            <i @click="removeCompanyIcon" class="el-icon-ajm-delete"></i>
                        </div>
                    </el-upload>
                    <div class="tip-text">{{$t('message.Manager.iconClue')}}</div>
                </el-form-item>
                <el-form-item :label="$t('message.Manager.cnName')" prop="cnName">
                    <el-input v-model="companyInfoForm.cnName" :maxlength="50" :placeholder="$t('message.Manager.confirmCnName')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.Manager.enName')" prop="enName">
                    <el-input v-model="companyInfoForm.enName" :maxlength="50" :placeholder="$t('message.Manager.confirmEnName')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.Manager.contactPerson')" prop="contactPerson">
                    <el-input v-model="companyInfoForm.contactPerson" :maxlength="50" :placeholder="$t('message.Manager.confirmPerson')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.Manager.contactPhone')" prop="contactPhone">
                    <el-input v-model="companyInfoForm.contactPhone" :maxlength="14" :placeholder="$t('message.Manager.confirmPhone')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.Manager.contactAddress')" prop="contactAddress">
                    <el-input v-model="companyInfoForm.contactAddress" :maxlength="200" :placeholder="$t('message.Manager.confirmAddress')"></el-input>
                </el-form-item>
            </el-form>
            <!--用户信息-->
            <el-form v-show="active == 1" class="ajm-form" :model="adminVO" ref="adminVO" :rules="adminVORules" label-width="80px">
                <el-form-item :label="$t('message.UserInfo.userName')" prop="userName">
                    <el-input auto-complete="off" v-model="adminVO.userName" :placeholder="$t('message.UserInfo.confirmUserName')" :maxlength="20"></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.UserInfo.realName')" prop="realName">
                    <el-input auto-complete="off" v-model="adminVO.realName" :placeholder="$t('message.UserInfo.confirmRealName')" :maxlength="50"></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.UserInfo.email')" prop="email">
                    <el-input auto-complete="off" v-model="adminVO.email" :placeholder="$t('message.UserInfo.confirmEmail')" :maxlength="50"></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.UserInfo.phone')" prop="mobilephone">
                    <el-input auto-complete="off" v-model="adminVO.mobilephone" :placeholder="$t('message.UserInfo.confirmPhone')" :maxlength="11"></el-input>
                </el-form-item>
            </el-form>
            <!--服务配置-->
            <el-form v-show="active == 2" class="ajm-form" :model="serviceForm" ref="serviceForm" label-width="80px">
                <el-row v-for="(items,index) in serviceForm.companySystemList" :key="items.index" v-if="serviceForm.companySystemList.length > 0" style="border-bottom: 1px solid #ccc;">
                    <el-form-item :label="$t('message.Manager.serverName')" required>
                        <el-input auto-complete="off" v-model="items.systemName" disabled></el-input>
                    </el-form-item>
                    <el-col :span="22">
                        <el-form-item :label="$t('message.Table.date')" required>
                            <el-date-picker v-model="items.validDates" type="daterange" range-separator=" - " format="yyyy-MM-dd" :editable="false"
                                            :clearable="false" :picker-options="pickerOptions1" :placeholder="$t('message.Table.dateRange')" align="left">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <span @click="deleteService(index)" v-if="items.isDefault && items.isDefault.value != 1" style="cursor: pointer">{{$t('message.delete')}}</span>
                    </el-col>
                </el-row>
                <el-dropdown trigger="click" @command="changeService" v-if="serviceList.length > 0" style="margin-top: 15px">
                    <el-button type="primary">
                        {{$t('message.Manager.addServer')}}<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item :command="index" v-for="(items,index) in serviceList" :key="items.systemId" :label="items.systemName" :value="items.systemId">{{items.systemName}}</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="!isEdit">
                <el-button type="primary" size="small" @click="last" v-if="active !=0">{{$t('message.last')}}</el-button>
                <el-button type="primary" size="small" v-if="active == 2" :loading="saveCompanyLoading" @click="addCompany()">{{$t('message.save')}}</el-button>
                <el-button type="primary" size="small" :loading="nextLoading" @click="next" v-else>{{$t('message.next')}}</el-button>
                <el-button size="small" @click="companyFormVisible = false">{{$t('message.cancel')}}</el-button>
            </div>
            <div slot="footer" class="dialog-footer" v-if="isEdit && active == 0">
                <el-button type="primary" size="small" :loading="saveCompanyLoading" @click="saveCompanyOrUpdate('companyInfoForm')">{{$t('message.save')}}</el-button>
                <el-button size="small" @click="companyFormVisible = false">{{$t('message.cancel')}}</el-button>
            </div>
            <div slot="footer" class="dialog-footer" v-if="isEdit && active == 2">
                <el-button type="primary" size="small" :loading="saveCompanyLoading" @click="saveOrUpdateSystem('companyInfoForm')">{{$t('message.save')}}</el-button>
                <el-button size="small" @click="companyFormVisible = false">{{$t('message.cancel')}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import companyService from "../services/companyService";
    //用户服务
    import userService from "../services/userService";
    // 系统服务
    import systemService from '../services/systemService';
    import dateformat from "dateformat";
    import AjmConfig from 'ajm-framework/core/utils/ajm-config'

    export default {
        data() {
            return {
                //是否查询
                isSearch: false,
                isReload: false,
                //查询表单
                searchComForm: {
                    cnNameLike: '',
                },
                //弹窗名称
                dialogTitle:'',
                //弹窗表单
                companyFormVisible: false,
                //加载公司列表数据动画
                listLoading: false,
                //保存公司表单信息动画
                saveCompanyLoading: false,
                //公司列表分页结果集
                pageResult: {
                    pageNum: 1,
                    pageSize: 10,
                    total: 0,
                    list: []
                },
                //是否修改服务配置
                isEditSystem:false,
                //当前步骤
                active:0,
                //下一步loading动画
                nextLoading:false,
                //是否修改企业
                isEdit:false,
                companyIconUrl: '',//企业logo图片
                //服务器地址
                serverUrl: AjmConfig.getApiUrl(),
                //上传图片地址   配置zuul 是为看了解决中文乱码 放在BASE_CONTEXT_PATH上下文之前，但是如果是走单机会造成API 404
                uploadFileUrl: AjmConfig.getApiUrl() + AjmConfig.get("BASE_CONTEXT_PATH") + "/api/file/uploadFile",
                //查看图片地址
                viewFileUrl: AjmConfig.get("BASE_CONTEXT_PATH") + "/api/file/viewFile/",
                headers: {
                    Authorization: "Bearer " + this.$store.getters.tokenInfo.access_token
                },
                //表单标题宽度
                formLabelWidth: "80px",
                //公司表单信息
                companyInfoForm: {
                    companyId: "",
                    cnName: "",
                    enName: "",
                    logoName: "",
                    companyLogo: "",
                    contactPhone: "",
                    contactAddress: "",
                    contactPerson: "",
                },
                /*//表单规则
                companyInfoRules: {
                    cnName: [
                        { required: true, validator: checkCompanyCnNameExist, trigger: "" }
                    ],
                    enName: [
                        { required: false, validator: checkCompanyEnNameExist, trigger: "" }
                    ],
                    contactPhone: [
                        { message: "请输入企业电话", trigger: "" },
                        { pattern: /^(0?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8})|(400|800)([0-9\\-]{7,10})|(([0-9]{4}|[0-9]{3})(-| )?)?([0-9]{7,8})((-| |转)*([0-9]{1,4}))?$/, message: '联系电话格式不正确' }
                    ],
                    contactAddress: [
                        { message: "请输入企业地址", trigger: "" },
                    ],
                    contactPerson: [
                        { message: "请输入企业联系人", trigger: "" },
                    ]
                },*/


                //用户新增表单
                adminVO: {
                    //用户id
                    userId: "",
                    // 用户名称
                    userName: "",
                    realName:"",
                    // 手机号
                    mobilephone: "",
                    //邮箱
                    email: "",
                },
                /*adminVORules: {
                    userName: [{required:true, validator: checkUserName, trigger: "blur" }],
                    realName:[{required:true,message:"请输入姓名", trigger: "blur"}],
                    mobilephone: [{ validator: checkMobilephone, trigger: "blur" }],
                    email: [{required:true, validator: checkEmail,  trigger: "blur" }],
                },*/

                //服务配置表单
                serviceForm :{
                    companySystemList:[],
                },
                serviceList:[],
                pickerOptions1: {
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7
                    }
                },
                sortType: 2
            };
        },
        computed:{
            //表单规则
            companyInfoRules() {
                var checkCompanyCnNameExist = (rule, value, callback) => {
                    if (!value) {
                        return callback(new Error(this.$t('message.Manager.confirmCnName')));
                    }
                    var reg = /^\S{1,50}$/;
                    if (reg.test(value)) {
                        let params = {
                            companyId: this.companyInfoForm.companyId,
                            cnName: value
                        }
                        companyService.checkCompanyCnNameExist(params).then(resp => {
                            var result = resp;
                            if (result) {
                                return new callback(new Error(this.$t('message.Manager.hasCnName')))
                            } else {
                                callback();
                            }
                        });
                    } else {
                        callback(new Error(this.$t('message.Manager.cnNameClue')));
                    }
                };
                var checkCompanyEnNameExist = (rule, value, callback) => {
                    if (!value) {
                        return callback();
                    }
                    // var reg = /^[a-zA-Z]{2,50}$/;
                    var reg = /^\S{1,50}$/;
                    if (reg.test(value)) {
                        let params = {
                            companyId: this.companyInfoForm.companyId,
                            enName: value
                        }
                        companyService.checkCompanyEnNameExist(params).then(resp => {
                            var result = resp;
                            if (result == true) {
                                return callback(new Error(this.$t('message.Manager.hasEnName')));
                            } else {
                                callback();
                            }
                        });
                    }
                    // else {
                    //     callback(new Error("企业简称仅允许1-50位字母"));
                    // }
                };
                return{
                    cnName: [
                        { required: true, validator: checkCompanyCnNameExist, trigger: "" }
                    ],
                    enName: [
                        { required: false, validator: checkCompanyEnNameExist, trigger: "" }
                    ],
                    contactPhone: [
                        { message: this.$t('message.Manager.confirmPhone'), trigger: "" },
                        { pattern: /^(0?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8})|(400|800)([0-9\\-]{7,10})|(([0-9]{4}|[0-9]{3})(-| )?)?([0-9]{7,8})((-| |转)*([0-9]{1,4}))?$/, message: '联系电话格式不正确' }
                    ],
                    contactAddress: [
                        { message: this.$t('message.Manager.confirmAddress'), trigger: "" },
                    ],
                    contactPerson: [
                        { message: this.$t('message.Manager.confirmPerson'), trigger: "" },
                    ]
                }

            },
            adminVORules() {
                var checkUserName = (rule, value, callback) => {
                    var userId = this.adminVO.userId;
                    if (userId) {
                        return callback();
                    }
                    if (!value) {
                        return callback(new Error(this.$t('message.UserInfo.confirmUserName')));
                    }
                    var reg = /^[a-zA-Z0-9]{4,20}$/;
                    if (reg.test(value)) {
                        userService.checkUserName(value).then(resp => {
                            var result = resp;
                            if (result) {
                                callback();
                            } else {
                                return callback(new Error(this.$t('message.UserInfo.hasUserName')));
                            }
                        });
                    } else {
                        callback(new Error(this.$t('message.UserInfo.userNameClue')));
                    }
                };
                var checkMobilephone = (rule, value, callback) => {
                    if (value === "") {
                        callback();
                    }
                    var reg = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[0-8])|(18[0-9]))\d{8}$/;
                    if (reg.test(value)) {
                        callback();
                    } else {
                        callback(new Error(this.$t('message.UserInfo.checkPhone')));
                    }
                };
                var checkEmail = (rule, value, callback) => {
                    if (!value) {
                        callback(new Error(this.$t('message.UserInfo.confirmEmail')));
                    } else if (! /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(value)) {
                        callback(new Error(this.$t('message.UserInfo.checkEmail')));
                    } else {
                        callback();
                    }
                };
                return{
                    userName: [{required:true, validator: checkUserName, trigger: "blur" }],
                    realName:[{required:true,message:this.$t('message.UserInfo.confirmRealName'), trigger: "blur"}],
                    mobilephone: [{ validator: checkMobilephone, trigger: "blur" }],
                    email: [{required:true, validator: checkEmail,  trigger: "blur" }],
                }
            },
        },
        methods: {
            //进入下一步骤
            next(){
                this.nextLoading = true;
                if (this.active == 0){
                    this.$refs['companyInfoForm'].validate(valid => {
                            if (valid) {
                                this.nextLoading = false
                                this.active = 1
                            }else {
                                this.nextLoading = false;
                                return false;
                            }
                    });
                }else if(this.active == 1){
                    this.$refs['adminVO'].validate(valid => {
                        if (valid) {
                            this.nextLoading = false
                            this.active = 2
                            this.findAllSystemList()
                        }else {
                            this.nextLoading = false;
                            return false;
                        }
                    });
                }
            },
            //返回上一步骤
            last(){
                this.active--
            },
            //删除企业logo
            removeCompanyIcon(){
                this.companyInfoForm.companyLogo = '';
                this.companyIconUrl = ''
            },
            //获取所有服务类型
            findAllSystemList(){
                systemService.findAllSystemList().then(resp =>{
                    if(this.serviceForm.companySystemList.length == 0){
                        this.serviceList = resp;
                        resp.forEach((item,index) => {
                            if(item.isDefault.value && item.isDefault.value == 1){
                                let startTime = new Date()
                                let endTime = new Date(startTime.getTime() + 3600 * 1000 * 24 * 30)

                                this.serviceForm.companySystemList.splice(0, 0, {
                                    isDefault:resp[index].isDefault,
                                    systemId: resp[index].systemId,
                                    systemName: resp[index].systemName,
                                    validDates: [startTime,endTime],
                                });
                                this.serviceList.splice(index, 1);
                            }
                        });
                    }
                })
            },
            //添加选中服务
            changeService(index){
                let num = this.serviceForm.companySystemList.length;
                let startTime = new Date()
                let endTime = new Date(startTime.getTime() + 3600 * 1000 * 24 * 30)

                this.serviceForm.companySystemList.splice(num, 0, {
                    isDefault:this.serviceList[index].isDefault,
                    systemId: this.serviceList[index].systemId,
                    systemName: this.serviceList[index].systemName,
                    validDates: [startTime,endTime],
                });
                this.serviceList.splice(index, 1);
            },
            //删除服务
            deleteService(index){
                let name = this.serviceForm.companySystemList[index].systemName
                let systemId = this.serviceForm.companySystemList[index].systemId
                let isDefault = this.serviceForm.companySystemList[index].isDefault
                if (this.serviceForm.companySystemList.length > 0) {
                    this.serviceForm.companySystemList.splice(index, 1);
                }

                let num = this.serviceList.length;
                this.serviceList.splice(num, 0, {
                    systemName: name,
                    systemId: systemId,
                    isDefault:isDefault,
                });
                console.log(this.serviceList)
            },

            //图片上传成功
            uploadImgSuccess(file) {
                this.companyInfoForm.logoName = file.fileName;
                this.companyInfoForm.companyLogo = file.fileKey;
                this.companyIconUrl = this.getImgUrl(file.fileKey);
            },
            //图片验证
            beforeImgUpload(file) {
                const isPNG = file.type === "image/png";
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isPNG) {
                    this.$message.warning(this.$t('message.Base.confirmIconType'));
                }
                if (!isLt2M) {
                    this.$message.warning(this.$t('message.Manager.confirmIconSize2'));
                }
                return isPNG && isLt2M;
            },
            //获取图片
            getImgUrl(filekey) {
                if (filekey == null || filekey == '') {
                    return false;
                }
                return (
                    this.serverUrl + this.viewFileUrl + filekey + "?access_token=" + this.$store.getters.tokenInfo.access_token
                );
            },

            //时间排序
            handleSortChange(column, prop, order) {
                if (column.order === "ascending") {
                    this.sortType = 1;
                } else if (column.order === "descending") {
                    this.sortType = 2;
                }
                this.findCompanyByPage();
            },

            //查找企业列表
            findCompanyByPage(isSearch) {
                this.listLoading = true;
                isSearch = !!isSearch;
                let params = {
                    page: this.pageResult.pageNum,
                    rows: this.pageResult.pageSize,
                    cnNameLike: this.searchComForm.cnNameLike,
                    sortType: this.sortType
                };
                companyService.findCompanyByPage(params).then(resp => {
                    this.pageResult = resp.data || resp;
                    this.listLoading = false;
                    this.isSearch = isSearch;
                    this.isReload = true;
                }).catch(() => {
                    this.listLoading = false;
                });
            },

            //跳转页面
            changePage(page) {
                this.pageResult.pageNum = page;
                this.findCompanyByPage();
            },
            //根据页码切换页面
            goChangePageSize(pageSize) {
                this.pageResult.pageSize = pageSize;
                this.findCompanyByPage();
            },
            //执行我的企业页面的搜索
            searchCompany() {
                this.findCompanyByPage(true);
            },

            //刷新页面
            refreshPage(){
                this.pageResult.pageNum = 1
                this.pageResult.pageSize = 10
                this.searchComForm.cnNameLike = ''
                this.sortType = 2
                this.findCompanyByPage()
            },
            //新增企业
            goAddCompany() {
                this.dialogTitle = this.$t('message.Manager.addCompany');
                this.active = 0
                this.isEdit = false
                this.isEditSystem = false;
                this.saveCompanyLoading = false
                this.serviceList = []
                this.serviceForm.companySystemList = []
                this.companyIconUrl = ''
                this.resetForm("companyInfoForm");
                this.resetForm("adminVO");
                this.companyFormVisible = true;
                this.companyInfoForm.companyId = "";
                this.companyInfoForm.cnName = "";
                this.companyInfoForm.enName = "";
                this.companyInfoForm.contactPhone = "";
                this.companyInfoForm.contactAddress = "";
                this.companyInfoForm.contactPerson = "";
                this.companyInfoForm.companyLogo = "";
                this.adminVO.userId = ''
                this.adminVO.userName = ''
                this.adminVO.realName = ''
                this.adminVO.mobilephone = ''
                this.adminVO.email = ''
            },

            //保存企业及用户信息
            addCompany(){
                let companySystemList = [];
                let _this = this;
                _this.serviceForm.companySystemList.forEach(function (item, index) {
                    companySystemList.push({
                        systemId: item.systemId,
                        startTime: dateformat(item.validDates[0], 'yyyy-mm-dd'),
                        endTime: dateformat(item.validDates[1], 'yyyy-mm-dd')
                    });
                });

                let company = this.companyInfoForm;
                let companyVO = {
                    companyId: company.companyId,
                    cnName: this.trim(company.cnName),
                    enName: this.trim(company.enName),
                    contactPerson: this.trim(company.contactPerson),
                    contactPhone: this.trim(company.contactPhone),
                    contactAddress: this.trim(company.contactAddress),
                    companyLogo: company.companyLogo,
                    adminVO:this.adminVO,
                    companySystemList:companySystemList
                };
                this.saveCompanyLoading = true;

                companyService.addCompany(companyVO).then(resp => {
                    this.saveCompanyLoading = false;
                    if (resp.status == 500) {
                        this.$message({
                            type: 'error',
                            message: resp.message
                        })
                        return;
                    }else{
                        this.companyFormVisible = false;
                        this.$message({
                            message: this.$t('message.saveSuccess'),
                            type: "success"
                        });
                        this.findCompanyByPage();
                    }
                }).catch(() => {
                    this.saveCompanyLoading = false;
                });
                /*    }
                });*/
            },

            //去除空格
            trim(val) {
                return val.replace(/(^\s*)|(\s*$)/g, "");
            },
            //修改并保存企业信息
            saveCompanyOrUpdate(formName) {
                let company = this.companyInfoForm;
                let companyVO = {
                    companyId: company.companyId,
                    cnName: this.trim(company.cnName),
                    enName: this.trim(company.enName),
                    contactPerson: this.trim(company.contactPerson),
                    contactPhone: this.trim(company.contactPhone),
                    contactAddress: this.trim(company.contactAddress),
                    logoName: company.logoName,
                    companyLogo: company.companyLogo
                };
				//2019年4月29日16:10:37
                //如果LogoName长度超过50 保存后台会提示长度过长，因此参数无实际意义，故在此判断截取


                if (companyVO.logoName == null) return 0;
                if (typeof companyVO.logoName != "string"){
                    companyVO.logoName += "";
                }
                //把字符串中中文替换成01
                let text=companyVO.logoName.replace(/[^x00-xff]/g,"aa")
                if(text.length>50){
                    //此处如果是字母加中文混合截取0-50会有问题，暂时防止全中文截取0-25
                    companyVO.logoName.substring(0,25)
                }
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        this.saveCompanyLoading = true;

                        companyService.saveAndUpdateCompany(companyVO).then(resp => {
                            this.saveCompanyLoading = false;
                            if (resp.status == 500) {
                                this.$message({
                                    type: 'error',
                                    message: resp.message
                                })
                                return;
                            }else{
                                this.companyFormVisible = false;
                                let message = '';
                                companyVO.companyId == '' ? message = this.$t('message.Manager.addCnSuccess')
                                    : message = this.$t('message.Manager.editCnSuccess');
                                this.$message({
                                    message: message,
                                    type: "success"
                                });
                                this.findCompanyByPage();
                            }
                        });
                    }
                });
            },
            //修改企业
            goEditCompany(index, row) {
                this.companyFormVisible = true;
                this.dialogTitle = this.$t('message.edit');
                this.isEdit = true
                this.active = 0
                this.saveCompanyLoading = false
                this.companyInfoForm.companyId = row.companyId;
                this.companyInfoForm.cnName = row.cnName;
                this.companyInfoForm.enName = row.enName;
                this.companyInfoForm.contactPerson = row.contactPerson;
                this.companyInfoForm.contactPhone = row.contactPhone;
                this.companyInfoForm.contactAddress = row.contactAddress;
                this.companyInfoForm.logoName = row.logoName;
                if(row.companyLogo){
                    this.companyIconUrl = this.getImgUrl(row.companyLogo)
                }else{
                    this.companyIconUrl = ''
                }
            },

            //修改服务配置
            EditSystem(index,row){
                this.companyFormVisible = true;
                this.dialogTitle = this.$t('message.Manager.serverConfig');
                this.isEdit = true
                this.active = 2
                this.companyInfoForm.companyId = row.companyId;
                this.serviceForm.companySystemList = []
                this.serviceList = []
                this.findCompanySystemList(row.companyId)
            },

            //获取选中企业的所有服务
            findCompanySystemList(companyId){
                systemService.findSystemListByCompanyId(companyId).then(resp =>{
                    resp.forEach((items,indexs) => {
                        items.systemList.forEach((item,index) => {
                            let companySystem = {
                                isDefault:item.isDefault,
                                systemId: item.systemId,
                                systemName: item.systemName,
                                validDates: [item.startTime,item.endTime],
                            }
                            this.serviceForm.companySystemList.push(companySystem)
                        })
                    });

                    //筛选可选企业服务
                    systemService.findAllSystemList().then(resp =>{
                        if(resp) {
                            resp.forEach((system,index) => {
                                this.serviceForm.companySystemList.forEach((item,num) => {
                                    if(system.systemId == item.systemId){
                                        resp[index] = ''
                                        this.serviceList = resp
                                    }
                                })
                            })
                            /*for (var i = 0; i < this.serviceList.length; i++) {
                             if (this.serviceList[i] != "") {
                             this.serviceList.push(this.serviceList[i])
                             }
                             }*/
                        }
                    })
                })
            },

            //保存修改企业服务配置
            saveOrUpdateSystem(){
                let companySystemList = [];
                let _this = this;
                _this.serviceForm.companySystemList.forEach(function (item, index) {
                    companySystemList.push({
                        systemId: item.systemId,
                        startTime: dateformat(item.validDates[0], 'yyyy-mm-dd'),
                        endTime: dateformat(item.validDates[1], 'yyyy-mm-dd')
                    });
                });

                let companyVO = {
                    companyId: this.companyInfoForm.companyId,
                    companySystemList:companySystemList
                };
                this.saveCompanyLoading = true;

                companyService.updateCompanySystem(companyVO).then(resp => {
                    this.saveCompanyLoading = false;
                    if (resp.status == 500) {
                        this.$message({
                            type: 'error',
                            message: resp.message
                        })
                        return;
                    }else{
                        this.companyFormVisible = false;
                        this.$message({
                            message: this.$t('message.saveSuccess'),
                            type: "success"
                        });
                        this.findCompanyByPage();
                    }
                }).catch(() => {
                    this.saveCompanyLoading = false;
                });
            },

            //删除企业
            deleteCompany(index, row) {
                this.$confirm(this.$t('message.confirmRequest')+' [ '+row.cnName +'] ？', this.$t('message.delClue'), {
                    cancelButtonClass:"message-cancel-button",
                    confirmButtonText: this.$t('message.confirm'),
                    cancelButtonText: this.$t('message.cancel'),
                    type: "warning"
                }).then(() => {
                    companyService.deleteCompanyById(row.companyId).then(res => {
                        if (res.status == 500) {
                            this.$message({
                                type: 'error',
                                message: res.message
                            })
                            return;
                        }else{
                            this.$message({
                                message: this.$t('message.delSuccess'),
                                type: "success"
                            });
                            this.findCompanyByPage();
                        }
                    });
                }).catch(() => { });
            },

            resetForm(formName) {
                if (this.$refs[formName] !== undefined) {
                    this.$refs[formName].resetFields();
                }
            }
        },
        mounted() {
            this.findCompanyByPage();
            let self = this;
            document.getElementById("enterSearch").addEventListener("keydown", function (event) {
                if (event.keyCode === 13) {
                    self.searchCompany(event);
                }
            }, false);
        }
    };
</script>

<style lang="less" scoped>
    .tip-text {
        font-size: 12px;
        color: #aaaeb2;
        margin-bottom: -15px;
        margin-top: -5px;
    }

    .first-wait,.last-wait,.process,.first-success,.last-success,.last-process{
        position:relative;
        flex-basis: 33.3%;
        margin-right: 0px;
        text-align: center
    }
    .first-wait,.last-wait{
        background-color: #EBEEF2;
        color: #AAAEB2;
    }
    .process,.last-process{
        background-color: #33AA44;
        color: #ffffff;
    }
    .first-success,.last-success{
        background-color: #dcf5e2;
        color: #33AA44;
    }
    .process:after{
        border: solid transparent;
        content: ' ';
        height: 0;
        left: 100%;    //根据三角形的位置，可以随意更改。
        position: absolute;
        width: 0;

        border-width: 18px;
        border-left-color: #33AA44;
        top: 0px;//根据三角的位置改变
        z-index: 3;
    }
    .last-success:before{
        border: solid transparent;
        content: ' ';
        height: 0;
        left: 2px;    //根据三角形的位置，可以随意更改。
        position: absolute;
        width: 0;

        border-width: 20px;
        border-left-color: #fff;
        top: -2px;//根据三角的位置改变
        z-index: 1;
    }
    .last-success:after{
        border: solid transparent;
        content: ' ';
        height: 0;
        left: 100%;    //根据三角形的位置，可以随意更改。
        position: absolute;
        width: 0;

        border-width: 18px;
        border-left-color: #dcf5e2;
        top: 0px;//根据三角的位置改变
        z-index: 1;
    }
    .first-success:after{
        border: solid transparent;
        content: ' ';
        height: 0;
        left: 100%;    //根据三角形的位置，可以随意更改。
        position: absolute;
        width: 0;

        border-width: 18px;
        border-left-color: #dcf5e2;
        top: 0px;//根据三角的位置改变
        z-index: 2;
    }
    .last-wait:before{
        border: solid transparent;
        content: ' ';
        height: 0;
        left: 0;    //根据三角形的位置，可以随意更改。
        position: absolute;
        width: 0;

        border-width: 20px;
        border-left-color: #fff;
        top: -2px;//根据三角的位置改变
        z-index: 1;
    }
    .first-wait:after{
        border: solid transparent;
        content: ' ';
        height: 0;
        left: 99%;    //根据三角形的位置，可以随意更改。
        position: absolute;
        width: 0;

        border-width: 18px;
        border-left-color: #EBEEF2;
        top: 0px;//根据三角的位置改变
        z-index: 2;
    }
    .icon-step{
        width:18px;
        height:18px;
        margin-right: 10px;
        border: 1px solid;
        .el-step__icon-inner{
            font-size: 9px;
            font-weight: 400;
        }
    }
    .icon-wait{
        background: #EBEEF2 ;
    }
    .icon-process{
        background: #33AA44;
    }
    .icon-success{
        vertical-align: middle;
        margin-right: 10px;
    }

    .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>


