<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',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.staffHeadimg === '' ? url:ruleForm.staffHeadimg" 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"
              :disabled="true"
              placeholder="登录账号唯一标识，创建后不允许修改"
            />
          </el-form-item>
          <el-form-item label="密码：" prop="loginPassword">
            <el-input v-model="ruleForm.loginPassword" :disabled="true" 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>
        <div class="department">
          <div>
            <span class="star font">部门：</span>
            <span class="ontent">{{ Departmentname }}/{{ checklist[0].value }}</span>
            <span class="operaction" @click="setDepartment">更改</span>
          </div>
           <div>
            <span class="star font">职务：</span>
            <span class="ontent">{{ zhiwu11.roleName}}</span>
            <span class="operaction" @click="setwork">设置</span>
          </div>
          <div class="lastspan">
            <span class="star font">关联船舶：</span>
            <div class="ontent ddv1">
              <span
                v-for="(item,key) in checklist2"
                :key="key"
                v-show="item.vesselId"
                class="ontent shipName"
              >{{ item.vesselName }}</span>
              <span class="operaction shipSelectSet" @click="setChargeShip">设置</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--5.设置所属部门-->
    <el-dialog title="设置所属部门" :visible.sync="setUpTheDepartment" width="30%" center>
      <div class="adddepartment">
        <div class="adddepartment1">
          <el-tree
            ref="tree"
            :data="data"
            show-checkbox
            :default-checked-keys="selected"
            default-expand-all
            node-key="id"
            check-strictly
            highlight-current
            @check="check"
          />
        </div>
        <div class="adddepartment2">
          <span class="adddepartment4">成员将属于以下部门</span>
          <div
            v-for="(item,key) in checklist"
            v-show="item.value"
            :key="key"
            class="adddepartment3"
          >
            <span class="adddepartmentLeft">{{ item.value }}</span>
            <span class="adddepartmentDel" @click="adddepartmentDel">删除</span>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setUpTheDepartment = false">取 消</el-button>
        <el-button type="primary" @click="departmentsave">确 定</el-button>
      </span>
    </el-dialog>
    <!--6.设置成员职务-->
   <el-dialog title="设置成员职务" :visible.sync="setDuty" width="650px" center>
        <div class="adddepartment">
          <div class="adddepartment1">
            <div>{{Departmentname}}</div>
            <div class="zhiwu">
                <el-checkbox-group v-model="zhiwuCheckList" @change = 'zhiwuCheck'>
                <el-checkbox
                 class="zhiwuCheck"
                  v-for="(item,key) in data1[0].children"
                  :disabled='item.state'
                  :label="item.id" :key="key">
                  {{item.label}}
                  </el-checkbox>
                </el-checkbox-group>
            </div>
          </div>
          <div class="adddepartment2">
            <span class="adddepartment4">成员将属于以下职务</span>
            <div class="primaryzw">
              <el-radio @change="zhiwuRadio1(zhiwu1.roleId)" class="zhiwuradio" v-model="primaryzw" label="1">主要职务</el-radio>
              <div class="zhuyaozhiwu" v-show="zhiwu1.roleName">{{zhiwu1.roleName}}</div>
            </div>
            <div class="primaryzw">
              <el-radio @change="zhiwuRadio2(zhiwu2)" class="zhiwuradio" v-model="primaryzw" label="0">次要职务</el-radio>
              <div class="ciyaozhiwu"
               v-for="(item,index) in zhiwu2"
                :key='index'
                >{{item.roleName}}
                <span class="zhiwuDel" @click="delZhiWu(item.roleId)">删除</span></div>
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setDuty = false">取 消</el-button>
          <el-button type="primary" @click="setDutysave">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 7.关联船舶 -->
     <el-dialog title="负责船舶" :visible.sync="chargeShip" width="650px" center>
        <div class="adddepartment">
              <div class="adddepartment1">
            <div>{{Departmentname}}</div>
            <div class="zhiwu">
                <el-checkbox-group v-model="shipCheckList" @change = 'shipCheck'>
                <el-checkbox
                 class="zhiwuCheck"
                  v-for="(item,key) in checkboxmsg[0].children"
                  :disabled='item.state'
                  :label="item.id" :key="key">
                  {{item.label}}
                  </el-checkbox>
                </el-checkbox-group>
            </div>
          </div>
          <div class="adddepartment2">
            <span class="adddepartment4">成员将属于以下船舶</span>
            <div class="primaryzw">
              <div class="ciyaozhiwu"
               v-for="(item,index) in seleteShipList"
                :key='index'
                >{{item.vesselName}}
                <span class="zhiwuDel" @click="delShipSelect(item.vesselId)">删除</span></div>
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="chargeShip = false">取 消</el-button>
          <el-button type="primary" @click="saveChargeShip">确 定</el-button>
        </span>
      </el-dialog>
  </div>
</template>
<script>
import urladdress from './url';
import {
  getUsegMsg
} from '../../api/organization/showMessage';
import {
  getTreeList
} from '../../api/organization/tree';
import {
  shipList,
  findRoles
} from '../../api/organization/orgAddMan';
import {
  changeInfo
} from '../../api/organization/orgEdit';
import {
  getOssInterimCredentials,
  GotOssAccessConfig
} from '../../api/upload';
import {
  client
} from '../../utils/alioss';

export default {
  name: 'OrgAddMan',
  data() {
    const validcodeId = (rule, value, callback) => {
      const reg = /[0-9a-zA-Z]/;
      if (!reg.test(value)) {
        callback(new Error('密码必须是由6位数字和字母组合'));
      } else {
        callback();
      }
    };
    const validcodePhonee = (rule, value, callback) => {
      const reg = /^1[34578]\d{9}$/;
      if (!reg.test(value)) {
        callback(new Error('密码必须是由6位数字和字母组合'));
      } else {
        callback();
      }
    };
    return {
      selected: [], // 部门默认选中
      selected1: [], // 职务默认选中
      selected2: [], // 船舶默认选中
      compId: localStorage.getItem('enterprise-front-companyId'),
      datamsg: '',
      /* 页面传递来的数据 */
      checklist: [{
        key: '',
        value: ''
      }],
      Department: '',
      Departmentname: '',
      /* 设置部门 */
      checklist1: [{
        key: '',
        value: ''
      }],
      Department1: '',
      Departmentname1: '',
      /* 设置职务 */
      checklist2: [{
        id: '',
        label: ''
      }],
      Department2: '',
      Departmentname2: '',
      /* 设置关联船舶 */
      addmanId: '',
      url: urladdress.urlmsg,
      setUpTheDepartment: false,
      setDuty: false,
      chargeShip: false,
      ruleForm: {
        deptId: '',
        /* 部门id */
        base: '',
        userRealName: '',
        userRealNameEn: '',
        userAccount: '',
        userPassword: '',
        userCellPhone: '',
        userSex: '',
        staffHeadimg: '',
        roles: [{
          roleId: '',
          major: '1'
        }],
        vessels: [{
          vesselId: ''
        }]
      },
      rules: {
        staffName: [{
          required: true,
          message: '',
          trigger: 'blur'
        }],
        staffAccount: [{
          required: true,
          message: '',
          trigger: 'blur'
        },
        {
          validator: validcodeId,
          trigger: 'blur'
        }
        ],
        staffMobilePhone: [{
          required: true,
          message: '',
          trigger: 'blur'
        },
        {
          validator: validcodePhonee,
          trigger: 'blur'
        }]
      },
      data: [],
      data1: [{
        id: '',
        label: '',
        disabled: true,
        children: []
      }],
      checkboxmsg: [{
        id: '',
        label: '',
        disabled: true,
        children: []
      }],
      primaryzw: '1',
      zhiwuCheckList: [],
      zhiwu1: {},
      zhiwu2: [],
      zhiwu11: {},
      shipCheckList: [],
      seleteShipList: [],
    };
  },
  created() {
    const staffId = localStorage.getItem('enterprise-front-showMsg');
    this.datamsg = this.$route.params;
    this.ruleForm.deptId = this.datamsg.id;
    this.getbumenmsg();
    this.getmsg(staffId);
    this.getZhiwu()
  },
  methods: {
    getZhiwu() {
      this.getbumenmsg();
      this.data1[0].label = this.Departmentname;
      findRoles(this.addmanId).then((response) => {
        this.data1[0].children.length = 0;
        for (let i = 0; i < response.records.length; i++) {
          const idname = response.records[i].roleId;
          const label = response.records[i].roleName;
          this.data1[0].children.push({
            id: idname,
            label,
            children: [],
            state: false
          });
        }
      });

      this.checkboxmsg[0].label = this.Departmentname;
      shipList().then((response) => {
        this.checkboxmsg[0].children.length = 0;
        for (let i = 0; i < response.records.length; i++) {
          const shipid = response.records[i].vesselId;
          const shipname = response.records[i].vesselName;
          this.checkboxmsg[0].children.push({
            id: shipid,
            label: shipname,
            children: []
          });
        }
      });
    },
    getmsg(staffId) {
      getUsegMsg({
        staffId
      }).then((response) => {
        this.ruleForm = response;
        this.selected.push(response.deptId);// 部门默认选中
        // 船舶默认选中
        for (let i = 0; i < response.vessels.length; i++) {
          this.shipCheckList.push(response.vessels[i].vesselId);
          this.seleteShipList.push({
            vesselId: response.vessels[i].vesselId,
            vesselName: response.vessels[i].vesselName,
          })
        }
        this.checklist2 = this.seleteShipList
        if (response.staffHeadimg == null || response.staffHeadimg == undefined) {
          this.ruleForm.staffHeadimg = ''
        }
        this.checklist = [];
        this.checklist.push({
          key: this.ruleForm.deptId,
          value: this.ruleForm.deptName
        });
        for (let i = 0; i < response.roles.length; i++) {
          if (response.roles[i].major == '1') {
            this.zhiwu1 = {
              roleId: response.roles[i].roleId,
              roleName: response.roles[i].roleName,
              major: response.roles[i].major
            }
            this.zhiwu11 = this.zhiwu1
            this.zhiwuCheckList.push(response.roles[i].roleId)
          } else {
            this.zhiwu2.push({
              roleId: response.roles[i].roleId,
              roleName: response.roles[i].roleName,
              major: response.roles[i].major
            })
          }
        }
      });
    },
    uploadPhoto(e) {
      let ossInter = '';
      let ossAccessConfig = '';
      let fileName = '';
      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({
            message: '不接受此类型文件',
            type: 'error',
            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({
          message: '图片大于1M',
          type: 'error',
          showClose: true,
        });
        return false
      }
      getOssInterimCredentials().then((response) => {
        ossInter = response;
        GotOssAccessConfig().then((res) => {
          ossAccessConfig = res;
          client(ossInter, ossAccessConfig)
            .put(fileName, file)
            .then((result) => {
              this.ruleForm.staffHeadimg = result.url;
              that.$message({
                type: 'success',
                message: that.$t('upload.saveSuccessfully')
              });
            });
        });
      });
    },
    cancel() {
      this.$router.back();
    },
    save(formName, tf) {
      const rule1 = this.ruleForm.roles.length;
      const rules2 = this.ruleForm.vessels.length;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (rule1 == '0' || rules2 == '0') {
            this.$message({
              type: 'error',
              message: '请选择职务或关联船舶',
              showClose: true,
            });
            return false;
          }
          changeInfo(this.ruleForm).then(() => {
            this.$message({
              message: '保存成功',
              type: 'success',
              showClose: true,
            });
            if (tf) {
              this.$router.go(-1);
            }
          }).catch(() => {
            this.$message({
              message: '保存失败',
              type: 'error',
              showClose: true,
            });
          });
        } else {
          this.$message({
            message: '带*为必填项',
            type: 'error',
            showClose: true,
          });
          return false;
        }
      });
    },
    setDepartment() {
      this.setUpTheDepartment = true;
      getTreeList({
        compId: this.compId
      }).then((response) => {
        this.data = response;
        this.data[0].disabled = true;
      });
    },
    setwork() {
      this.zhiwuRadio1(this.zhiwu1.roleId)
      this.setDuty = true;
    },
    setChargeShip() {
      this.chargeShip = true;
      this.getbumenmsg();
      this.checkboxmsg[0].label = this.Departmentname;
      shipList().then((response) => {
        this.checkboxmsg[0].children.length = 0;
        for (let i = 0; i < response.records.length; i++) {
          const shipid = response.records[i].vesselId;
          const shipname = response.records[i].vesselName;
          this.checkboxmsg[0].children.push({
            id: shipid,
            label: shipname,
            children: []
          });
        }
      });
    },
    /* 设置部门 */
    getbumenmsg() {
      getTreeList({
        compId: this.compId
      }).then((response) => {
        this.Departmentname = response[0].label;
      });
    },
    adddepartmentDel() {
      this.resetChecked();
      this.checklist = [{
        key: '',
        value: ''
      }];
    },
    /* 删除 */
    resetChecked(key, value) {
      this.$refs.tree.setCheckedKeys([key]);
      this.checklist.push({
        key,
        value
      });
    },
    /* 清空 */
    check(data) {
      this.checklist = [];
      const key = data.id;
      const value = data.label;
      this.resetChecked(key, value);
    },
    departmentsave() {
      this.setUpTheDepartment = false;
      this.ruleForm.deptId = this.checklist[0].key;
    },
    /* 保存 */
    /* 设置职务 */
    setDutysave() {
      if (this.zhiwu1.roleId) {
        this.setDuty = false;
        this.zhiwu11 = this.zhiwu1
        const zhiwuAll = []
        zhiwuAll.push(this.zhiwu1)
        this.ruleForm.roles = zhiwuAll.concat(this.zhiwu2)
      } else {
        this.$message({
          type: 'error',
          message: '请选择主要职务',
        })
      }
    },
    /* 保存 */
    checklist1Del() {
      this.resetChecked1();
      this.checklist1 = [{
        key: '',
        value: ''
      }];
    },
    /* 删除 */
    resetChecked1(key, value) {
      this.$refs.tree1.setCheckedKeys([key]);
      this.checklist1.push({
        key,
        value
      });
    },
    /* 清空 */
    check1(data) {
      this.zwmsg = data;
      this.checklist1 = [];
      this.resetChecked1(this.zwmsg.id, this.zwmsg.label);
    },
    /* 设置关联船舶 */
    checkBoxList1Del(item) {
      this.resetChecked2(item.id);
    },
    saveChargeShip() {
      this.chargeShip = false;
      this.ruleForm.vessels = this.seleteShipList
      this.checklist2 = this.seleteShipList
    },
    /* 保存 */
    resetChecked2(key) {
      let ss = '';
      for (let i = 0; i < this.checklist2.length; i++) {
        if (key === this.checklist2[i].id) {
          ss = i;
        }
      }
      this.checklist2.splice(ss, 1);
      let nn = '';
      for (let j = 0; j < this.ruleForm.vessels.length; j++) {
        if (key === this.ruleForm.vessels[j].vesselId) {
          nn = j;
        }
      }
      this.ruleForm.vessels.splice(nn, 1);
    },
    /* 清空 */
    check2(data, check) {
      this.checklist2 = check.checkedNodes;
    },
    // 职务操作
    zhiwuCheck(data) {
      if (this.primaryzw == '1') {
        this.zhiwuCheckList = []
        this.zhiwuCheckList.push(data[data.length - 1])
        this.zhiwu1 = {
          roleId: data[data.length - 1],
          roleName: this.data1[0].children.find(item => item.id === data[data.length - 1]).label,
          major: '1',
        }
      } else {
        this.zhiwu2 = []
        for (let i = 0; i < data.length; i++) {
          this.zhiwu2.push({
            roleId: data[i],
            roleName: this.data1[0].children.find(item => item.id === data[i]).label,
            major: '0',
          })
        }
      }
    },
    zhiwuRadio1(data) {
      for (let i = 0; i < this.data1[0].children.length; i++) {
        this.data1[0].children[i].state = false
      }
      for (let i = 0; i < this.zhiwu2.length; i++) {
        for (let j = 0; j < this.data1[0].children.length; j++) {
          if (this.zhiwu2[i].roleId == this.data1[0].children[j].id) {
            this.data1[0].children[j].state = true
          }
        }
      }
      this.zhiwuCheckList = []
      this.zhiwuCheckList.push(data)
    },
    zhiwuRadio2(data) {
      for (let i = 0; i < this.data1[0].children.length; i++) {
        this.data1[0].children[i].state = false
      }
      for (let i = 0; i < this.data1[0].children.length; i++) {
        if (this.zhiwu1.roleId == this.data1[0].children[i].id) {
          this.data1[0].children[i].state = true
        }
      }
      this.zhiwuCheckList = []
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          this.zhiwuCheckList.push(data[i].roleId)
        }
      }
    },
    delZhiWu(data) {
      this.primaryzw = '0'
      this.zhiwuRadio2(this.zhiwu2)
      const num = this.zhiwuCheckList.indexOf(data)
      this.zhiwuCheckList.splice(num, 1)
      for (let i = 0; i < this.zhiwu2.length; i++) {
        if (data == this.zhiwu2[i].roleId) {
          this.zhiwu2.splice(i, 1)
        }
      }
      for (let i = 0; i < this.data1[0].children.length; i++) {
        if (data == this.data1[0].children[i].id) {
          this.data1[0].children[i].state = false
        }
      }
    },
    // 弹出框确认关闭
    handleClose(done) {
      this.clearZhiwu()
      done();
    },
    clearZhiwu() {
      this.zhiwu11 = []
      this.zhiwu1 = {}
      this.zhiwu2 = []
      this.zhiwuCheckList = []
      this.primaryzw = '1'
      this.shipCheckList = []
      this.seleteShipList = []
    },
    // 选船操作
    shipCheck(data) {
      this.seleteShipList = []
      for (let i = 0; i < data.length; i++) {
        this.seleteShipList.push({
          vesselId: data[i],
          vesselName: this.checkboxmsg[0].children.find(item => item.id === data[i]).label,
        })
      }
    },
    delShipSelect(data) {
      const num = this.shipCheckList.indexOf(data)
      this.shipCheckList.splice(num, 1)
      for (let i = 0; i < this.seleteShipList.length; i++) {
        if (this.seleteShipList[i].vesselId === data) {
          this.seleteShipList.splice(i, 1)
        }
      }
    }
  }
};

</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 {
  height: 20px;
  line-height: 20px;
  padding: 0 4px 0 8px;
  background-color: #dde9fc;
  margin-right: 10px;
  margin-bottom: 10px;
}
.ddv1 {
  //width: 730px;
  vertical-align: top;
}
.ddv1 > span {
  float: left;
}
.editShip:after {
  margin-left: 8px;
  font-size: 18px;
  content: "×";
  color: #ffffff;
  vertical-align: -2px;
  cursor: pointer;
}
.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;
}
</style>
