<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">下一步</el-button>
                    </div>
                </div>
                <el-steps :active="stepIndex" align-center>
                    <el-step title="基本信息" description="填写用户基本信息">
                        <svg-icon icon-class="dot" slot="icon" class="svg-dot"></svg-icon>
                    </el-step>
                    <el-step title="权限设置" description="设置用户权限">
                        <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="registerForm" :rules="rulesRegister" ref="registerForm" label-width="100px" class="registerForm" v-if="stepIndex===0">
                    <el-form-item label="头像" prop="cover_image_url">
                        <upload :datafileList="registerForm.cover_image_list" :changeFillId="handleAvatarSuccess" :fileName="'cover'" :showList="true" uploadType="image" :filleNumber="1" v-if="!registerForm.cover_image_url" styleType="upload" />
                        <div class="cover-box" v-else @mouseover="Imagemouseover('coverFlag',true)" @mouseout="Imagemouseover('coverFlag',false)">
                            <el-image :src="registerForm.cover_image_url" fit="cover" style="width:100px;height:100px;"></el-image>
                            <p v-show="coverFlag" @click="handleDeleteFile('cover',0)"><i class="el-icon-delete"></i></p>
                        </div>
                    </el-form-item>
                    <el-form-item label="用户名" prop="name">
                        <el-input v-model="registerForm.name" placeholder="请输入用户名" @blur="handleTrim('registerForm','name')" ></el-input>
                    </el-form-item>
                    <el-form-item label="真实姓名" prop="realName">
                        <el-input v-model="registerForm.realName" placeholder="请输入真实姓名" @blur="handleTrim('registerForm','realName')"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <el-radio-group v-model="registerForm.sex">
                            <el-radio :label="1">男</el-radio>
                            <el-radio :label="0">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="所在省市" prop="selectedOptions">
                        <el-cascader
                            size="medium"
                            :options="$provinceCityList"
                            v-model="registerForm.selectedOptions"
                            @change="handleCity">
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="备注" prop="desc">
                        <el-input type="textarea" v-model="registerForm.desc" placeholder="请输入备注" maxlength="100" :rows="4" show-word-limit @blur="handleTrim('registerForm','desc')"></el-input>
                    </el-form-item>
                    <el-divider content-position="left"></el-divider>
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="registerForm.phone" autocomplete="off" placeholder="请输入完整手机号" @blur="handleTrim('registerForm','phone')" >
                            <template slot="prepend">+86</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="registerForm.email" autocomplete="off" placeholder="请输入邮箱地址" @blur="handleTrim('registerForm','email')" >
                        </el-input>
                    </el-form-item>
                    <el-form-item label="账号密码" prop="newPwd">
                        <el-input v-model="registerForm.newPwd" :type="newPwdFlag?'text':'password'" autocomplete="off" placeholder="请输入密码" @blur="handleTrim('registerForm','newPwd')" >
                            <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="registerForm.confirmPwd" :type="comfirmPwdFlag?'text':'password'" autocomplete="off" placeholder="请输入密码" @blur="handleTrim('registerForm','confirmPwd')" >
                            <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 class="step-div-1" v-if="stepIndex===1">
                    <table class="step-table">
                        <tr>
                            <td rowspan="2" class="step-table-header">管理权限</td>
                            <td>系统用户</td>
                            <td>机构管理</td>
                        </tr>
                        <tr>
                            <td><el-checkbox v-model="manageAuth" :label="10001"><br/></el-checkbox></td>
                            <td><el-checkbox v-model="manageAuth" :label="10002"><br/></el-checkbox></td>
                        </tr>
                    </table>
                    <table class="step-table">
                        <tr>
                            <td rowspan="2" class="step-table-header">内容权限</td>
                            <td class="td1">报纸管理</td>
                            <td class="td1">画刊管理</td>
                            <td class="td1">专辑管理</td>
                            <td class="td1">评测管理</td>
                            <td class="td1">练习册管理</td>
                            <td class="td1">课程管理</td>
                            <td class="td1">广告管理</td>
                        </tr>
                        <tr>
                            <td class="td1"><el-checkbox v-model="manageAuth" :label="20001"><br/></el-checkbox></td>
                            <td class="td1"><el-checkbox v-model="manageAuth" :label="20002"><br/></el-checkbox></td>
                            <td class="td1"><el-checkbox v-model="manageAuth" :label="20003"><br/></el-checkbox></td>
                            <td class="td1"><el-checkbox v-model="manageAuth" :label="20004"><br/></el-checkbox></td>
                            <td class="td1"><el-checkbox v-model="manageAuth" :label="20005"><br/></el-checkbox></td>
                            <td class="td1"><el-checkbox v-model="manageAuth" :label="20006"><br/></el-checkbox></td>
                            <td class="td1"><el-checkbox v-model="manageAuth" :label="20007"><br/></el-checkbox></td>
                        </tr>
                    </table>
                    <table class="step-table">
                        <tr>
                            <td rowspan="2" class="step-table-header">兑换码权限</td>
                            <td>生成兑换码</td>
                            <td>查看兑换码使用情况</td>
                        </tr>
                        <tr>
                            <td><el-checkbox v-model="manageAuth" :label="30001"><br/></el-checkbox></td>
                            <td>
                                <el-radio-group v-model="codeAuth.viewCode">
                                    <el-radio :label="1">全部</el-radio>
                                    <el-radio :label="0">自己生成的</el-radio>
                                </el-radio-group>
                            </td>
                        </tr>
                    </table>
                    <table class="step-table">
                        <tr>
                            <td rowspan="2" class="step-table-header">财务权限</td>
                            <td>查看数据</td>
                            <td>导出数据</td>
                            <td>授权地区</td>
                        </tr>
                        <tr>
                            <td><el-checkbox v-model="manageAuth" :label="40001"><br/></el-checkbox></td>
                            <td><el-checkbox v-model="manageAuth" :label="40002"><br/></el-checkbox></td>
                            <td>
                                <el-cascader
                                    class="step-cascader"
                                    size="medium"
                                    :props="props"
                                    collapse-tags
                                    clearable
                                    :options="$provinceCityListAll"
                                    v-model="financeAuth.selectedOptions">
                                </el-cascader>
                            </td>
                        </tr>
                    </table>
                </div>
                <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 Upload from "../../components/Upload.vue"
import { getLogin } from "@/api/ajax";
import { mapState } from 'vuex';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: { Header, NavMenu, Breadcrumb, Upload },
  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.registerForm.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 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: "people_manage",
        breadcrumbList:[
            {
                icon:'contacts-line',
                url:'',
                text:''
            },
            {
                icon:'',
                url:'/people_manage',
                text:'系统用户'
            }
        ],
        id:this.$route.query.id?this.$route.query.id:'',
        stepIndex:0, // 步骤索引
        props: { multiple: true },
        registerForm:{
            cover_image_url: '',
            cover_image_list: [],
            cover_image_id: null,
            name:'',
            realName:'',
            sex:1,
            selectedOptions:[],
            desc:'',
            phone:'',
            email:'',
            newPwd:'', // 密码
            confirmPwd:'', // 确认密码
            userAgreeCheck: [],
            region:''
        },
        rulesRegister:{
            name:[
                { required: true, validator: validateName, trigger: 'blur' },
                { max: 20, message: '用户名最多20位', trigger:'change' },
            ],
            realName:[
                { required: true, message: '请输入真实姓名', trigger: 'blur' },
            ],
            sex:[
                { required: true, message: '请选择性别', trigger: 'change' },
            ],
            selectedOptions: [
                { type: 'array', required: true, message: '请选择所在省市', 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' }
            ],
            userAgreeCheck:[
                { type: 'array', required: true, message: '请阅读并同意《用户协议》', trigger: 'change' }
            ],
            region: [
                { required: true, message: '请选择机构', trigger: 'change' }
            ],
            email:[
                { required: true, validator: validateEmail, trigger: 'blur' },
            ],
        },
        newPwdFlag: false, // 查看新密码
        comfirmPwdFlag: false, // 查看确认密码
        manageAuth:[], // 管理权限
        contentAuth:[], // 内容权限
        codeAuth:{
            auth:[],
            viewCode:0
        }, // 兑换码权限
        financeAuth:{
            auth: [],
            selectedOptions:[]
        }, // 财务权限
        coverFlag: false,
    }
  },
  //计算属性 类似于data概念
  computed: {
    ...mapState(['$provinceCityList','$provinceCityListAll']),
  },
  //监控data中数据变化
  watch: {
    
  },
  //方法集合
  methods: {
    // 上一步下一步
    handleStep(type){
        if(type=='-'){
            if(this.stepIndex>0) this.stepIndex--
        }else{
            if(this.stepIndex===0){
                this.$refs['registerForm'].validate((valid) => {
                    if (valid) {
                        this.stepIndex++
                    } else {
                        return false;
                    }
                });
            }else if(this.stepIndex===1){
                this.handleAdd()
            }
        }
    },
    // 级联选择器
    handleCity(value){
        if(this.financeAuth.selectedOptions.length===0){
            this.financeAuth.selectedOptions = [value]
        }
    },
    changeIcon(flag){
        this[flag] = !this[flag]
    },
    // 返回列表
    handleback(){
        localStorage.setItem("pageNumber",1)
        this.$router.push({
            path: "/people_manage",
            query: {
                
            },
        });
    },
    //继续创建
    handleCreate(){
        this.$router.replace('/createPerson')
        location.reload()
    },
    handleAvatarSuccess(fileList,name) {
        if(name==='cover'){
            this.registerForm.cover_image_list = fileList
            this.registerForm.cover_image_id = fileList[0]&&fileList[0].response&&fileList[0].response.file_info_list&&fileList[0].response.file_info_list[0]?fileList[0].response.file_info_list[0].file_id:''
            this.registerForm.cover_image_url = fileList[0]&&fileList[0].response&&fileList[0].response.file_info_list&&fileList[0].response.file_info_list[0]?fileList[0].response.file_info_list[0].file_url:''
        }
    },
    Imagemouseover(item,flag) {
      this[item] = flag
    },
    handleDeleteFile(item,i) {
      this.$confirm("确定删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if(item==='cover'){
            this.registerForm.cover_image_list.splice(i, 1);
            this.registerForm.cover_image_url = ''
            this.registerForm.cover_image_id = null
        }
      });
    },
    handleAdd(){
        let MethodName = "/OrgServer/Manager/SysUserManager/AddSysUser";
        let form = this.registerForm
        let finance_popedom_data_scope = {}
        if(this.financeAuth.selectedOptions.length>0){
            if(this.financeAuth.selectedOptions[0][0]&&this.financeAuth.selectedOptions[0][0]==='0'){
                finance_popedom_data_scope.is_all = 'true'
            }else{
                finance_popedom_data_scope.is_all = 'false'
                let province_id_list = []
                let city_id_list = []
                this.financeAuth.selectedOptions.forEach(item => {
                    if(province_id_list.indexOf(item[0])===-1){
                        province_id_list.push(item[0])
                    }
                    city_id_list.push(item[1]?item[1]:'')
                });
                finance_popedom_data_scope.province_id_list = province_id_list
                finance_popedom_data_scope.city_id_list = city_id_list
            }
        }
        let data = {
            sys_user:{
                image_id: form.cover_image_id,
                user_name: form.name,
                real_name: form.realName,
                sex: form.sex,
                city_id: form.selectedOptions[1],
                email: form.email,
                phone: form.phone,
                memo: form.desc,
                password: form.newPwd
            },
            popedom_code_list: this.manageAuth,
            data_scope:{
                discount_code_view_scope: this.codeAuth.viewCode,
                finance_popedom_data_scope: finance_popedom_data_scope
            }
        }
        getLogin(MethodName, data)
        .then((res) => {
            if(res.status===1){
               this.stepIndex++
            }
        })
        .catch(() => {
            this.loading = false
        });
    },
    // 去掉前后空格
    handleTrim(form,fild){
        this[form][fild] = this[form][fild].trim()
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    let obj = {
        icon:'',
        url:'',
        text:'创建用户'
    }
    if(this.id){
        obj.text = '编辑用户'
    }
    this.breadcrumbList.push(obj)
  },
  //生命周期 - 挂载完成（可以访问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;
        }
    }
}
.cover-box{
    position: relative;
    width: 100px;
    height: 100px;
    p{
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 100px;
        line-height: 100px;
        font-size: 20px;
        text-align: center;
        cursor: pointer;
        background: rgba(0, 0, 0, 0.3);
        color: #F2F3F5;
        margin: 0;
    }
}
</style>

<style lang="scss">
.registerForm{
    .show-icon{
        color: #4E5969;
    }
    .el-divider{
        margin: 24px 0;
        width: 460px;
    }
}
.step-cascader{
    .el-input{
        width: 100%;
        height: 30px;
    }
    .el-tag .el-icon-close{
        top: 1px;
    }
}
</style>