<template>
  <div class="border">
    <div class="organization-box">
      <div class="label-box">
        <span class="label-title">新建成员</span>
      </div>
      <div class="button-common">
        <el-button type="primary" @click="save('ruleForm',false)">保存并继续新建</el-button>
        <el-button @click="save('ruleForm',true)">保存</el-button>
        <el-button @click="cancel">返回</el-button>
      </div>
      <div class="main-list">
        <div class="uphead">
          <span class="imghead font">头像：</span>
          <img :src="ruleForm.userHeadimg === '' ? url:ruleForm.userHeadimg" class="img" >
          <input type="file" class="kyc-passin" @change="uploadPhoto($event)" >
          <span class="talk">支持上传jpj/png文件，大小不能超过1M</span>
        </div>
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" class="demo-ruleForm">
          <el-form-item label="中文名：" prop="staffName">
            <el-input v-model="ruleForm.staffName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="英文：">
            <el-input v-model="ruleForm.staffNameEn" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="账号：" prop="staffAccount">
            <el-input v-model="ruleForm.staffAccount" placeholder="登录账号唯一标识，创建后不允许修改" />
          </el-form-item>
          <el-form-item label="密码：">
            <el-input v-model="ruleForm.loginPassword" type="password" disabled placeholder="******"/>
          </el-form-item>
          <el-form-item label="手机号：" prop="staffMobilePhone">
            <el-input v-model="ruleForm.staffMobilePhone" placeholder="请输入常用手机号" />
          </el-form-item>
          <el-form-item label="性别：">
            <el-radio v-model="ruleForm.staffSex" label="FEMALE">男</el-radio>
            <el-radio v-model="ruleForm.staffSex" label="MALE">女</el-radio>
          </el-form-item>
          <el-form-item label="部门：" prop="deptId" required>
            <el-select v-model="ruleForm.deptId" :placeholder="$t('common.selected')" disabled>
              <el-option
                v-for="item in deptNameList"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="职务：" prop="roleId" required>
            <el-select v-model="ruleForm.roleId" :placeholder="$t('common.selected')">
              <el-option
                v-for="item in roleList"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId">
              </el-option>
            </el-select>
            <el-radio class="zhiwuradio" v-model="roleId_isMajor" label="1">主要职务</el-radio>
            <el-radio class="zhiwuradio" v-model="roleId_isMajor" label="2">次要职务</el-radio>
          </el-form-item>
          <el-form-item label="关联船舶：" prop="vesselId" required>
            <el-select v-model="ruleForm.vesselId" :placeholder="$t('common.selected')">
              <el-option
                v-for="item in shipList"
                :key="item.vesselId"
                :label="item.vesselName"
                :value="item.vesselId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
    import urladdress from './url';
    import {shipList, findRolesShip} from '../../api/organization/orgAddMan';
    import {getVesselDeptByCompId} from '../../api/organization/tree';
    import {getOssInterimCredentials, GotOssAccessConfig} from '../../api/upload';
    import {client} from '../../utils/alioss';
    import {getUsegMsg} from '../../api/organization/showMessage';
    import {changeInfo} from '../../api/organization/orgEdit';

    export default {
        name: 'OrgAddMan',
        data() {
            const staffName = (rule, value, callback) => {
                if (!value) {
                    callback(
                        this.$message({
                            type: 'error',
                            message: '带星号的不能为空',
                            showClose: true,
                        })
                    );
                } else {
                    callback();
                }
            };
            const validcodeId = (rule, value, callback) => {
                const reg = /[0-9a-zA-Z]$/;
                if (value === '') {
                    callback(
                        this.$message({
                            type: 'error',
                            message: '带星号的不能为空',
                            showClose: true,
                        })
                    );
                } else if (!reg.test(value)) {
                    callback(
                        this.$message({
                            type: 'error',
                            message: '账号必须是由数字和字母组合',
                            showClose: true,
                        })
                    );
                } else {
                    callback();
                }
            };
            const validcodeName = (rule, value, callback) => {
                const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/;
                if (value === '') {
                    callback(
                        this.$message({
                            type: 'error',
                            message: '带星号的不能为空',
                            showClose: true,
                        })
                    );
                } else if (!reg.test(value)) {
                    callback(
                        this.$message({
                            type: 'error',
                            message: '密码必须是由6位数字和字母组合',
                            showClose: true,
                        })
                    );
                } else {
                    callback();
                }
            };
            const validcodePhonee = (rule, value, callback) => {
                const reg = /^1[34578]\d{9}$/;
                if (value === '') {
                    callback(
                        this.$message({
                            type: 'error',
                            message: '带星号的不能为空',
                            showClose: true,
                        })
                    );
                } else if (!reg.test(value)) {
                    callback(
                        this.$message({
                            type: 'error',
                            message: '手机号格式填写错误',
                            showClose: true,
                        })
                    );
                } else {
                    callback();
                }
            };
            return {
                deptNameList:[],
                roleList:[],
                roleId_isMajor:'1',
                shipList:[],

                compId: localStorage.getItem('enterprise-front-companyId'),
                datamsg: '',
                /* 页面传递来的数据 */
                checklist: [{
                    value: ''
                }],
                /* 设置部门 */
                checklist1: [{
                    key: '',
                    value: ''
                }],
                Department1: '',
                Departmentname1: '',
                zwmsg: '',
                /* 设置职务 */
                checklist2: [{
                    id: '',
                    label: ''
                }],
                /* 设置关联船舶 */
                addmanId: '',
                url: urladdress.urlmsg,
                setDuty: false,
                chargeShip: false,
                ruleForm: {
                    userHeadimg: '',
                    deptId: '',
                    /* 部门id */
                    base: '',
                    staffName: '',
                    staffNameEn: '',
                    staffAccount: '',
                    loginPassword: '',
                    staffMobilePhone: '',
                    staffSex: 'FEMALE',
                    staffHeadimg: '',
                    roles: [{
                        roleId: '',
                        major: ''
                    }],
                    vessels: [{
                        vesselId:''
                    }]
                },
                rules: {
                    staffName: [{required: true, validator: staffName, trigger: 'blur'}],
                    staffAccount: [{required: true, validator: validcodeId, trigger: 'blur'}],
                    loginPassword: [{required: true, validator: validcodeName, trigger: 'blur'}],
                    staffMobilePhone: [{required: true, validator: validcodePhonee, trigger: 'blur'}]
                },
                data: [],
                data1: [{
                    id: '',
                    label: '',
                    disabled: true,
                    children: []
                }],
            };
        },
        created() {
            this.datamsg = this.$route.params
            this.ruleForm.deptId = this.$route.params.deptId
            this.getZhiwu()
            this.getbumenmsg()
        },
        mounted(){
            this.$nextTick(()=>{
                const staffId = localStorage.getItem('enterprise-front-showMsg');
                this.getmsg(staffId);
            })
        },
        methods: {
            getZhiwu() {
                findRolesShip({deptId:this.$route.params.deptId}).then((response) => {
                    this.data1[0].children = []
                    for (let i = 0; i < response.length; i++) {
                        const idname = response[i].roleId;
                        const label = response[i].roleName;
                        this.data1[0].children.push({
                            id: idname,
                            label,
                            children: [],
                            state: false
                        });
                    }
                });
                shipList().then((response) => {
                    this.shipList = response.records
                });
            },
            uploadPhoto(e) {
                let ossInter = null;
                let ossAccessConfig = null;
                let fileName = null;
                const fileTypes = ['.jpg', '.png'];
                const filePath = e.target.value;
                if (filePath) {
                    let isNext = false;
                    const fileEnd = filePath.substring(filePath.indexOf('.'));
                    for (let i = 0; i < fileTypes.length; i++) {
                        if (fileTypes[i] === fileEnd) {
                            isNext = true;
                            break;
                        }
                    }
                    if (!isNext) {
                        this.$message({
                            type: 'error',
                            message: '不接受此类型文件!',
                            showClose: true,
                        });
                        e.target.value = '';
                        return false;
                    }
                } else {
                    return false;
                }
                const that = this;
                const file = e.target.files[0];
                const filesize = file.size;
                fileName = file.name;
                if (filesize > 1048576) {
                    this.$message({
                        type: 'error',
                        message: '图片大于1M',
                        showClose: true,
                    });
                  return false
                }
                getOssInterimCredentials().then((response) => {
                    ossInter = response;
                    GotOssAccessConfig().then((res) => {
                        ossAccessConfig = res;

                        client(ossInter, ossAccessConfig)
                            .put(fileName, file)
                            .then((result) => {
                                this.ruleForm.userHeadimg = result.url;
                                that.$message({
                                    type: 'success',
                                    message: that.$t('upload.saveSuccessfully')
                                });
                            });
                    });
                });
            },
            cancel() {
                this.$router.go(-1);
            },
            save(formName, tf) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.ruleForm.roles = [{
                            roleId: this.ruleForm.roleId,
                            major: this.roleId_isMajor
                        }]
                        this.ruleForm.vessels[0].vesselId = this.ruleForm.vesselId
                        changeInfo(this.ruleForm).then((res) => {
                            this.$message({message: '保存成功', type: 'success'});
                            this.$router.back();
                        }).catch((code) => {
                            if (code === 'MANAGEMENT_002') {
                                this.$message({type: 'error', message: '手机号冲突'});
                                return false;
                            }else if (code === 'MANAGEMENT_001') {
                                this.$message({type: 'error', message: '账号冲突'});
                                return false;
                            }else if (code === 'MANAGEMENT_003') {
                                this.$message({type: 'error', message: '邮箱冲突'});
                                return false;
                            }
                        });
                    } else {
                        this.$message({
                            message: '带*为必填项',
                            type: 'error',
                            showClose: true,
                        });
                        return false;
                    }
                });
            },
            /* 获取职务左侧树 */
            setwork() {
                this.setDuty = true;
            },
            /* 获取关联船舶左侧树 */
            setChargeShip() {
                this.chargeShip = true;
            },
            /* 设置部门 */
            getbumenmsg() {
                getVesselDeptByCompId({compId: this.compId}).then((response) => {
                    this.deptNameList = response
                });
                findRolesShip({deptId:this.$route.params.deptId}).then((response) => {
                    this.roleList = response;
                });
            },
            getmsg(staffId) {
                getUsegMsg({staffId}).then((response) => {
                    this.ruleForm =  response
                    const roles = JSON.parse(JSON.stringify(response.roles[0]))
                    if(roles){
                        this.ruleForm.roles = [{
                            roleId: roles.roleId,
                            major: ''}]
                        this.ruleForm.roleId = roles.roleId
                    }
                    this.ruleForm.deptId = response.deptId
                    this.ruleForm.vesselId = response.vessels[0].vesselId

                });
            },
        }
    };
</script>
<style scoped lang="scss">
  .border {
    width: 960px;
    height: 100%;
    border-left: 1px solid #cccccc;
  }
  .organization-box {
    height: calc(86vh - 10px);
    overflow-y: auto;
    border: none;
  }
  .uphead {
    margin: 20px 0;
    height: 60px;
    line-height: 60px;
  }
  .img {
    display: inline-block;
    height: 60px;
    width: 60px;
    border-radius: 50%;
  }
  .kyc-passin {
    margin-left: 20px;
    width: 170px;
  }
  .talk {
    font-size: 12px;
    color: #999999;
  }
  .department {
    padding-top: 25px;
    border-top: 1px dashed #999999;
  }
  /*000000*/
  /deep/.el-dialog__body {
    padding: 0;
  }
  /deep/ .el-dialog--center .el-dialog__body {
    padding: 0;
  }
  .adddepartment {
    height: 400px;
    display: flex;
    justify-content: space-between;
  }
  .adddepartment1 {
    padding: 20px;
    width: 50%;
    overflow-y: auto;
  }
  .adddepartment2 {
    padding: 20px;
    width: 50%;
    background-color: #eeeeee;
  }
  /deep/.el-tree-node__content {
    height: 40px;
  }
  .adddepartment3 {
    height: 36px;
    line-height: 36px;
    background-color: #ffffff;
    position: relative;
    margin-bottom: 5px;
  }
  .adddepartment4 {
    display: inline-block;
    margin-bottom: 20px;
  }
  .adddepartmentLeft {
    width: 195px;
    display: inline-block;
    position: absolute;
    left: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .shipName {
    padding: 4px 8px;
    background-color: #dde9fc;
    margin-right: 10px;
    margin-bottom: 10px;
  }
  .ddv1 {
    //width: 730px;
    vertical-align: top;
    margin-top: 2px;
  }
  .ddv1 > span {
    float: left;
  }
  .adddepartmentDel {
    display: inline-block;
    position: absolute;
    right: 20px;
    color: #1d6ced;
    cursor: pointer;
  }
  /deep/.el-form-item .el-input__inner {
    width: 420px;
  }
  .main-list {
    height: calc(42vh);
  }
  .primaryzw{
    width: 100%;
    margin-bottom: 30px;
  }
  .zhiwu{
    margin-left: 40px;
    width: 180px;
  }
  .zhiwuCheck{
    display: block;
    margin-top: 10px;
  }
  .zhuyaozhiwu{
    margin-top: 10px;
    background-color: #ffffff;
    padding: 3px 8px;
    // display: inline-block;
  }
  .ciyaozhiwu{
    background-color: #ffffff;
    padding: 5px 10px;
    // display: inline-block;
    margin-top: 10px;
  }
  .zhiwuradio{
    margin-top: 5px;
    margin-right: 10px;
  }
  .zhiwuDel{
    margin-inline-start: 10px;
    color: #1d6ced;
    cursor: pointer;
    float:right;
  }
  .lastspan{
    display: flex;
  }
  .ddv1{
    flex: 1;
  }
</style>
