<template>
  <div class="manage-root personnel-create">
    <Header />
    <div class="manage-root-contain">
        <nav-menu class="manage-root-contain-left" :activeMenuIndex="activeMenuIndex"></nav-menu>
        <div class="manage-root-contain-right">
            <breadcrumb :breadcrumbList="breadcrumbList" class="breadcrumb-box"></breadcrumb>
            <div class="create-top">
                <div class="common-title-box">
                    <h3>{{id?'编辑机构':'创建机构'}}</h3>
                    <div class="btn-box" v-if="id||!id&&stepIndex!==2">
                        <el-button size="small" @click="handleStep('-')" :disabled="stepIndex===0">上一步</el-button>
                        <el-button type="primary" size="small" @click="handleStep('+')" :disabled="stepIndex===2" :loading="loading">下一步</el-button>
                    </div>
                </div>
                <el-steps :active="stepIndex" align-center>
                    <el-step title="机构信息" :description="id?'修改机构基本信息':'完善机构基本信息'">
                        <svg-icon icon-class="dot" slot="icon" class="svg-dot"></svg-icon>
                    </el-step>
                    <el-step title="设置管理账号" description="设置机构默认管理账号" v-if="!id">
                        <svg-icon icon-class="dot" slot="icon" class="svg-dot"></svg-icon>
                    </el-step>
                    <el-step :title="id?'完成修改':'完成创建'" :description="id?'机构修改完成':'机构创建完成'">
                        <svg-icon icon-class="dot" slot="icon" class="svg-dot"></svg-icon>
                    </el-step>
                </el-steps>
            </div>
            <div class="create-bottom">
                <el-form :model="organizeForm" :rules="rulesOrganize" ref="organizeForm" label-width="100px" class="registerForm" key="organizeForm" v-if="stepIndex===0">
                    <el-form-item label="机构名称" prop="name">
                        <el-input v-model="organizeForm.name" placeholder="请输入机构名称" @blur="handleTrim('organizeForm','name')" maxlength="200"></el-input>
                    </el-form-item>
                    <el-form-item label="机构代码" prop="sn">
                        <el-input v-model="organizeForm.sn" placeholder="请输入机构代码" @blur="handleTrim('organizeForm','sn')" maxlength="200"></el-input>
                        <p class="tips">4-8位英文或数字</p>
                    </el-form-item>
                    <el-form-item label="机构类型" prop="orgType">
                        <el-select v-model="organizeForm.orgType" placeholder="请选择">
                            <el-option
                                v-for="item in $orgType"
                                :key="item.type"
                                :label="item.type_name"
                                :value="item.type">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所在地区" prop="selectedOptions">
                        <el-cascader
                            size="medium"
                            :options="$provinceCityList"
                            v-model="organizeForm.selectedOptions"
                            @change="handleCity">
                            
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="人员上限" prop="personalCeil">
                        <el-input-number v-model="organizeForm.personalCeil" @change="handleChange" :min="1" size="small" class="personal-ceil" maxlength="20"></el-input-number>
                    </el-form-item>
                    <el-form-item label="机构有效期" prop="validity">
                        <el-date-picker
                            v-model="organizeForm.validity"
                            type="daterange"
                            size="small"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </el-form-item>
                </el-form>
                <el-form :model="managerForm" :rules="rulesManager" ref="managerForm" label-width="100px" class="registerForm" key="managerForm" v-if="stepIndex===1">
                    <el-form-item label="用户名" prop="name">
                        <el-input v-model="managerForm.name" placeholder="请输入用户名" @blur="handleTrim('managerForm','name')" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item label="真实姓名" prop="realName">
                        <el-input v-model="managerForm.realName" placeholder="请输入真实姓名" @blur="handleTrim('managerForm','realName')" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="managerForm.phone" autocomplete="off" placeholder="请输入完整手机号" @blur="handleTrim('managerForm','phone')" maxlength="20">
                            <template slot="prepend">+86</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="managerForm.email" autocomplete="off" placeholder="请输入邮箱地址" @blur="handleTrim('managerForm','email')"  maxlength="100">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="账号密码" prop="newPwd">
                        <el-input v-model="managerForm.newPwd" :type="newPwdFlag?'text':'password'" autocomplete="off" placeholder="请输入密码" @blur="handleTrim('managerForm','newPwd')" maxlength="200">
                            <i slot="suffix" class="el-icon-view show-icon" @click="changeIcon('newPwdFlag')" v-if="newPwdFlag"></i>
                            <i slot="suffix" class="show-icon" @click="changeIcon('newPwdFlag')" v-else>
                                <svg-icon icon-class="eye-invisible"></svg-icon>
                            </i>
                        </el-input>
                        <p class="tips">不少于6位，且必须同时包含数字和大小写字母</p>
                    </el-form-item>
                    <el-form-item label="再次输入" prop="confirmPwd">
                        <el-input v-model="managerForm.confirmPwd" :type="comfirmPwdFlag?'text':'password'" autocomplete="off" placeholder="请输入密码" @blur="handleTrim('managerForm','confirmPwd')" maxlength="200">
                            <i slot="suffix" class="el-icon-view show-icon" @click="changeIcon('comfirmPwdFlag')" v-if="comfirmPwdFlag"></i>
                            <i slot="suffix" class="show-icon" @click="changeIcon('comfirmPwdFlag')" v-else>
                                <svg-icon icon-class="eye-invisible"></svg-icon>
                            </i>
                        </el-input>
                        <p class="tips">再次输入密码，两次输入保持一致</p>
                    </el-form-item>
                </el-form>
                <div v-if="stepIndex===2">
                    <el-result icon="success" :subTitle="id?'机构编辑成功':'机构创建成功'">
                        <template slot="extra">
                            <el-button size="small" @click="handleback">返回列表</el-button>
                            <el-button type="primary" size="small" @click="handleCreate">继续创建</el-button>
                        </template>
                    </el-result>
                </div>
            </div>
        </div>
    </div>
  </div>
</template>

<script>
//这里可以导入其它文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》from ‘《组件路径》';
import Header from "../../components/Header.vue";
import NavMenu from "../../components/NavMenu.vue"
import Breadcrumb from '../../components/Breadcrumb.vue';
import { getLogin } from "@/api/ajax";
import { mapState } from 'vuex';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: { Header, NavMenu, Breadcrumb },
  props: {},
  data() {
    //这里存放数据
    const validatePhone = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入手机号'));
        } else {
            let reg = /^1[3-9]\d{9}$/;
            let result = reg.test(value);
            if (result) {
                callback();
            } else {
                callback(new Error('请输入正确的手机号'));
            }
        }
    };
    const validatePass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入密码'));
        } else {
            let reg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{6,16}$/;
            let result = reg.test(value);
            if (result) {
                callback();
            } else {
                callback(new Error('密码必须同时包含数字和大小写字母'));
            }
            
        }
    };
    const validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.managerForm.newPwd) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
    };
    const validateEmail = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入邮箱地址'));
        } else {
            let reg = /^[a-zA-Z0-9_\.-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
            let result = reg.test(value);
            if (result) {
                callback();
            } else {
                callback(new Error('请输入正确的邮箱地址'));
            }
        }
    };
    const validateCode = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入机构代码'));
        } else {
            let reg = /^[\da-zA-Z]{4,8}$/;
            let result = reg.test(value);
            if (result) {
                callback();
            } else {
                callback(new Error('机构代码只能包含英文或数字'));
            }
            
        }
    };
    const validateProvince = (rule, value, callback) => {
        if(value===[]){
            callback(new Error('请选择所在省市'));
        }else if(value.length===2){
            if(value[0]===''||value[1]===''){
                callback(new Error('请选择所在省市'));
            }else{
                callback();
            }
        }else {
            callback();
        }
    };
    const validateName = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入用户名'));
        } else {
            let reg = /^[a-zA-Z0-9_]{1,20}$/;
            let result = reg.test(value);
            if (result) {
                callback();
            } else {
                callback(new Error('不超过 20 位，可包含英文字符、数字、下划线'));
            }
        }
    };
    return {
        activeMenuIndex: "organize_manage",
        breadcrumbList:[
            {
                icon:'school-line',
                url:'',
                text:''
            },
            {
                icon:'',
                url:'/organize_manage',
                text:'机构管理'
            }
        ],
        id:this.$route.query.id?this.$route.query.id:'',
        stepIndex:0, // 步骤索引
        newPwdFlag: false, // 查看新密码
        comfirmPwdFlag: false, // 查看确认密码
        organizeForm:{
            name: '',
            sn: '',
            orgType: '',
            selectedOptions: [],
            personalCeil: 50,
            validity:''
        },
        managerForm:{
            name: '',
            realName: '',
            phone:'',
            email:'',
            newPwd:'', // 密码
            confirmPwd:'', // 确认密码
        },
        rulesOrganize:{
            name:[
                { required: true, message: '请输入机构名称', trigger: 'blur' }
            ],
            sn: [
                { required: true, validator: validateCode, trigger: 'blur' },
                { min: 4, max: 8, message: '请输入 4-8 位英文或数字', trigger:'change' }
            ],
            orgType: [
                { required: true, message: '请选择机构类型', trigger: 'change' }
            ],
            selectedOptions: [
                { type: 'array', required: true, validator: validateProvince, message: '请选择所在地区', trigger: 'change' }
            ],
            personalCeil:[
                { required: true, message: '请输入人员上限', trigger: 'blur' }
            ],
            validity:[
                { required: true, message: '请选择机构有效期', trigger: 'blur' }
            ]
        },
        rulesManager:{
            name:[
                { required: true, validator: validateName, trigger: 'blur' },
                { max: 20, message: '用户名最多20位', trigger:'change' },
            ],
            phone:[
                { required: true, validator: validatePhone, trigger: 'blur' }
            ],
            newPwd:[
                { required: true, validator: validatePass, trigger: 'blur' },
                { min: 6, max: 16, message: '请输入 6-16 位密码，且必须同时包含数字和大小写字母', trigger:'change' }
            ],
            confirmPwd:[
                { required: true, validator: validatePass2, trigger: 'blur' }
            ],
            email:[
                { required: true, validator: validateEmail, trigger: 'blur' },
            ]
        },
        province_list:[],
        props: {
          lazy: true,
          lazyLoad (node, resolve) {
            let MethodName = "/OrgServer/DictManager/GetCityList";
            let list = []
            if(node&&node.data){
                getLogin(MethodName, {province_id:node.data.id})
                .then((res) => {
                    if(res.status===1){
                        res.city_list.forEach(item=>{
                            item.leaf = true
                            item.label = item.name
                            item.value = item.id
                        })
                        list = res.city_list
                        resolve(list);
                    }
                })
            }
          }
        },
        loading: false
    }
  },
  //计算属性 类似于data概念
  computed: {
    ...mapState(['$orgType','$provinceCityList']),
  },
  //监控data中数据变化
  watch: {
    
  },
  //方法集合
  methods: {
    // 上一步下一步
    handleStep(type){
        if(type=='-'){ 
            if(this.id){
                if(this.stepIndex===2){
                    this.stepIndex = 0
                }
            }else{
                if(this.stepIndex>0) this.stepIndex--
            }
        }else{
            if(this.id){
                if(this.stepIndex===0){
                    this.$refs['organizeForm'].validate((valid) => {
                        if (!valid) {
                            return false;
                        }else{
                            // this.handleSetDefaultOrg()
                            this.editInfo()
                        }
                    });
                }
            }else{
                if(this.stepIndex===0){
                    this.$refs['organizeForm'].validate((valid) => {
                        if (!valid) {
                            return false;
                        }else{
                            this.stepIndex++
                        }
                    });
                }else if(this.stepIndex===1){
                    this.$refs['managerForm'].validate((valid) => {
                        if (!valid) {
                            return false;
                        }else{
                            this.handleSubmit()
                        }
                    });
                }
            }
        }
    },
    // 级联选择器
    handleCity(value){
        console.log(value)
    },
    changeIcon(flag){
        this[flag] = !this[flag]
    },
    // 返回列表
    handleback(){
        localStorage.setItem("pageNumber",1)
        this.$router.push({
            path: "/organize_manage",
            query: {
                
            },
        });
    },
    //继续创建
    handleCreate(){
        this.$router.replace('/createOrganize')
        location.reload()
    },
    handleChange(value) {
        // console.log(value);
    },
    // 获取省份列表
    getProvinceList(){
        let MethodName = "/OrgServer/DictManager/GetProvinceList";
        getLogin(MethodName, {})
        .then((res) => {
            if(res.status===1){
               res.province_list.forEach(item => {
                    item.children = []
                    item.label = item.name
                    item.value = item.id
               });
               this.province_list = res.province_list
            }
        })
        .catch(() => {
            this.loading = false
        });
    },
    // 提交
    handleSubmit(){
        this.loading = true
        let MethodName = "/OrgServer/Manager/OrgManager/AddOrg";
        let data = {
            org:{
                name: this.organizeForm.name,
                sn: this.organizeForm.sn,
                type: this.organizeForm.orgType,
                city_id: this.organizeForm.selectedOptions[1],
                max_person_count: this.organizeForm.personalCeil*1,
                effective_date_begin: this.organizeForm.validity[0],
                effective_date_end: this.organizeForm.validity[1]
            },
            manager:{
                user_name: this.managerForm.name,
                real_name: this.managerForm.realName,
                phone: this.managerForm.phone,
                email: this.managerForm.email,
                password: this.managerForm.newPwd
            }
        }
        getLogin(MethodName, data)
        .then((res) => {
            this.loading = false
            if(res.status===1){
                this.stepIndex++
            }
        })
        .catch(() => {
            this.loading = false
        });
    },
    // 去掉前后空格
    handleTrim(form,fild){
        this[form][fild] = this[form][fild].trim()
    },
    // 获取机构信息
    getInfo(){
        let MethodName = "/OrgServer/Manager/OrgManager/GetOrgInfo";
        let data = {
            id: this.id
        }
        getLogin(MethodName, data)
        .then((res) => {
            if(res.status===1){
                let form = this.organizeForm
                let result = res.org
                form.name = result.name
                form.sn = result.sn
                form.orgType = result.type
                form.selectedOptions = [result.province_id,result.city_id]
                form.personalCeil = result.max_person_count
                form.validity = [result.effective_date_begin,result.effective_date_end]
            }
        })
        .catch(() => {
            
        });
    },
    // 编辑信息
    editInfo(){
        this.loading = true
        let MethodName = "/OrgServer/Manager/OrgManager/UpdateOrg";
        let data = {
            id: this.id,
            name: this.organizeForm.name,
            sn: this.organizeForm.sn,
            type: this.organizeForm.orgType,
            city_id: this.organizeForm.selectedOptions[1],
            max_person_count: this.organizeForm.personalCeil*1,
            effective_date_begin: this.organizeForm.validity[0],
            effective_date_end: this.organizeForm.validity[1]
        }
        getLogin(MethodName, data)
        .then((res) => {
            this.loading = false
            if(res.status===1){
                this.stepIndex = 2
            }
        })
        .catch(() => {
            this.loading = false
        });
    },
    // 设置默认机构
    handleSetDefaultOrg(){
        let MethodName = "/OrgServer/Manager/OrgManager/SetIsDefaultOrg";
        let data = {
            id: this.id,
            is_default: 'true',
        }
        getLogin(MethodName, data)
        .then((res) => {
        
        })
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    let obj = {
        icon:'',
        url:'',
        text:'创建机构'
    }
    if(this.id){
        obj.text = '编辑机构'
        this.getInfo()
    }
    this.breadcrumbList.push(obj)
    this.getProvinceList()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  //生命周期-创建之前
  beforeCreated() { },
  //生命周期-挂载之前
  beforeMount() { },
  //生命周期-更新之前
  beforUpdate() { },
  //生命周期-更新之后
  updated() { },
  //生命周期-销毁之前
  beforeDestory() { },
  //生命周期-销毁完成
  destoryed() { },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() { }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
.create-top{
    background: #FFFFFF;
    border-radius: 4px;
    padding: 24px;
    .common-title-box{
        margin-bottom: 4px;
    }
}
.create-bottom{
    padding: 40px 40px;
    margin-top: 16px;
    background: #FFFFFF;
    border-radius: 4px;
    height: calc(100vh - 292px);
    overflow: auto;
    .tips{
        margin: 0;
        color: #86909C;
        font-size: 12px;
        line-height: 20px;
    }
    .step-table{
        border: 1px solid #E5E6EB;
        border-collapse: collapse;
        font-size: 14px;
        line-height: 22px;
        color: #1D2129;
        text-align: center;
        margin-bottom: 24px;
        &-header{
            background: #F7F8FA;
            width: 120px !important;
            color: #86909C;
            font-weight: 500;
        }
        td{
            height: 40px;
            width: 260px;
            border: 1px solid #E5E6EB;
            &.td1{
                width: 130px;
            }
        }
        .step-cascader{
            width: 250px;
            height: 32px;
            line-height: 32px;
        }
    }
}
</style>

<style lang="scss">
.registerForm{
    .show-icon{
        color: #4E5969;
    }
    .personal-ceil{
        .el-input__inner{
            width: 130px;
        }
    }
    .el-range-input{
        background: #F2F3F5;
    }
}
</style>