<!--
 * @Descripttion : 当前组件信息
 * @Author       : 无尘
 * @Date         : 2020-02-13 16:13:59
 * @LastEditors: 无尘
 * @LastEditTime: 2020-03-05 18:01:17
 * @FilePath     : \Hapi-demoj:\公司\haoban-3\src\components\company\add-member.vue
 -->
<!--

  <add-member :memberObj="memberObj" @refreshData="refreshData"></add-member>
  import addMember from '@/components/company/add-member.vue';
  -->

<template>
  <el-dialog width="600px" :title="partForm.staffId ? '成员详情' : '新增成员'" :visible.sync="memberVisible" append-to-body :before-close="handleClose">
    <div class="add-title m-b-20 font-14 color-303133 font-w-500">基本信息</div>
    <el-form :model="partForm" :rules="rules" ref="form" label-width="100px" class="dialog-form">
      <el-form-item label="姓名" prop="staffName">
        <limitInput :inputWidth="357" :inputValue.sync="partForm.staffName" :getByType="'char'" :holder="'请输入姓名'" :maxLength="12"> </limitInput>
      </el-form-item>
      <el-form-item label="昵称">
        <limitInput :inputWidth="357" :inputValue.sync="partForm.nickName" :getByType="'char'" :holder="'请输入昵称'" :maxLength="12"> </limitInput>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio v-model="partForm.sex" :label="1">男</el-radio>
        <el-radio v-model="partForm.sex" :label="2">女</el-radio>
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <countryMobile :disflag="partForm.staffId && partForm.activeFlag ? true : false" :inputWidth="357" :nationCode.sync="partForm.nationcode" :limitClass="'limit-color'" v-model="partForm.phoneNumber" :holder="'请输入手机号码'"> </countryMobile>
      </el-form-item>
      <el-form-item label="部门" prop="departmentList">
        <select-department :selectData="partForm.departmentList" @checkGroupIds="checkGroupIds"> </select-department>
      </el-form-item>
      <el-form-item label="职务" prop="postion">
        <limitInput :inputWidth="357" :inputValue.sync="partForm.postion" :getByType="'char'" :holder="'请输入职务'" :maxLength="12"> </limitInput>
      </el-form-item>
      <el-form-item v-if="partForm.staffId && !partForm.activeFlag" label="激活状态"> <span class="span-dot"></span><span>未激活</span><el-button @click="postInvite(memberObj)" type="text" class="m-l-30">邀请</el-button> </el-form-item>
      <div class="m-b-20 font-14 color-303133 font-w-500">对外信息</div>
      <el-form-item label="职务" prop="extendPostionDefine">
        <el-radio-group v-model="partForm.syncPostionFlag" @change="changeExtendPostion">
          <div style="line-height: 32px;">
            <el-radio :label="1">同步公司内职务</el-radio>
          </div>
          <div><el-radio :label="2" class="m-r-10">自定义</el-radio><limitInput v-if="partForm.syncPostionFlag == 2" :inputWidth="285" :inputValue.sync="partForm.extendPostionDefine" :getByType="'char'" :holder="'请输入职务'" :maxLength="12"> </limitInput></div>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-checkbox v-if="!partForm.staffId" v-model="partForm.activeFlag" style="margin: -8px 24px 0 0;">通过邮件或短信发送企业邀请</el-checkbox
      ><!-- <span class="font-14 color-606266">通过邮件或短信发送企业邀请</span> -->
      <el-button @click="cancel('form')">取消</el-button>
      <el-button v-if="!partForm.staffId" type="primary" @click="submitForm('form')">新建</el-button>
      <el-button v-if="partForm.staffId" type="primary" @click="submitForm('form')">保存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import limitInput from '@/components/limit-input.vue';
import countryMobile from '@/components/common/country-mobile.vue';
import selectDepartment from '@/components/company/select-department.vue';
import { getRequest, postRequest } from '@/api/api';
import errMsg from '@/common/js/error';
import showMsg from '@/common/js/showmsg';
import PhoneNumber from 'awesome-phonenumber';
export default {
  name: 'add-member',
  components: {
    limitInput,
    countryMobile,
    selectDepartment
  },
  props: {
    memberObj: {
      type: [Object, Array],
      default() {
        return {};
      }
    },
    defaultDepart: {
      type: [Object, Array],
      default() {
        return [];
      }
    }
  },
  data() {
    let checkPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else {
        let pn = new PhoneNumber('+' + this.partForm.nationCode + value);
        if (!pn.isValid() || !pn.isMobile()) {
          callback(new Error('手机号格式不正确'));
        } else {
          callback();
        }
      }
    };
    let checkExposition = (rule, value, callback) => {
      if (value === '' && this.partForm.syncPostionFlag == 2) {
        callback(new Error('请输入对外职务名称'));
      } else {
        callback();
      }
    };

    return {
      memberVisible: true,
      rules: {
        staffName: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }
        ],
        extendPostionDefine: [
          {
            required: true,
            validator: checkExposition,
            trigger: 'blur'
          }
        ],
        phoneNumber: [
          {
            required: true,
            validator: checkPhone,
            trigger: 'blur'
          }
        ],
        departmentList: [
          {
            type: 'array',
            required: true,
            message: '请选择部门',
            trigger: 'change'
          }
        ]
      },
      partForm: {
        staffId: '',
        staffName: '',
        nickName: '',
        nationCode: '86',
        phoneNumber: '',
        postion: '',
        activeFlag: false,
        departmentList: [],
        departmentIds: '',
        sex: 1,
        syncPostionFlag: 1,
        extendPostion: '',
        extendPostionDefine: ''
      }
    };
  },
  methods: {
    /**
     * 选择部门
     */
    checkGroupIds: function(nodes) {
      const that = this;
      that.partForm.departmentList = nodes;
    },
    /**
     * 改变对外职务
     */
    changeExtendPostion(e) {
      const that = this;
      if (e == 1) {
        that.partForm.extendPostion = that.partForm.postion;
      } else {
        // that.partForm.extendPostionDefine = '';
        that.partForm.extendPostion = '';
      }
    },
    /**
     * 关闭弹窗
     */
    handleClose(done) {
      const that = this;
      that.$refs['form'].resetFields();
      done();
      that.$emit('refreshData', 'close');
    },
    cancel() {
      const that = this;
      that.$refs['form'].resetFields();
      that.$emit('refreshData', 'close');
    },
    postInvite(item) {
      const that = this;
      let params = {
        staffIds: item.staffId
      };
      postRequest('/haoban-manage3-web/staff-invite', params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('邀请成功', 'success');
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 确定保存
     */
    submitForm(form) {
      const that = this;
      if (that.partForm.syncPostionFlag == 1) {
        that.partForm.extendPostion = that.partForm.postion;
      }
      if (that.partForm.syncPostionFlag == 2) {
        that.partForm.extendPostion = that.partForm.extendPostionDefine;
      }
      that.$refs[form].validate(valid => {
        if (valid) {
          that.toAddPost();
        } else {
          return false;
        }
      });
    },
    toAddPost() {
      const that = this;
      let params = {
        staffId: that.partForm.staffId,
        staffName: that.partForm.staffName,
        nickName: that.partForm.nickName,
        sex: that.partForm.sex,
        nationCode: that.partForm.nationCode,
        phoneNumber: that.partForm.phoneNumber,
        departmentIds: that.partForm.departmentList.map(ele => ele.departmentId).join(','),
        postion: that.partForm.postion,
        extendPostion: that.partForm.extendPostion,
        activeFlag: that.partForm.activeFlag ? 1 : 0,
        syncPostionFlag: that.partForm.syncPostionFlag
      };
      postRequest(that.partForm.staffId ? '/haoban-manage3-web/staff-edit' : '/haoban-manage3-web/staff-add', params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg(that.partForm.staffId ? '修改成功！' : '添加成功！', 'success');
            that.$emit('refreshData');
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 获取数据
     */
    getData() {
      const that = this;
      let params = {
        staffId: that.partForm.staffId
      };
      getRequest('/haoban-manage3-web/staff-sel', params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            resData.result.activeFlag = resData.result.activeFlag == 0 ? false : true;
            if (resData.result.syncPostionFlag == 2) {
              resData.result.extendPostionDefine = resData.result.extendPostion;
            }
            that.partForm = resData.result;
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    memberObj(newData, oldData) {
      const that = this;
      if (Object.keys(newData).length) {
        that.partForm = newData;
        that.partForm.departmentList = [];
        that.getData();
      } else {
        that.partForm.departmentList = that.defaultDepart || [];
      }
    }
  },
  mounted() {
    const that = this;
    if (Object.keys(that.memberObj).length) {
      that.partForm = that.memberObj;
      that.partForm.departmentList = [];
      that.getData();
    } else {
      that.partForm.departmentList = that.defaultDepart || [];
    }
  }
};
</script>
<style lang="less" scoped>
.span-dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  margin-right: 5px;
  background: rgba(217, 217, 217, 1);
  border-radius: 50%;
}

.m-l-30 {
  margin-left: 30px;
}
</style>
