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

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

<template>
  <el-dialog width="600px" title="新增GIC商户授权" :visible.sync="memberVisible" append-to-body :before-close="handleClose">
    <el-form :model="partForm" :rules="rules" ref="form" label-width="140px" class="dialog-form">
      <el-form-item label="选择商户" prop="">
        <el-autocomplete style="width: 363px;" v-model="partForm.enterpriseName" :fetch-suggestions="querySearchAsync" @select="handleSelect">
          <el-select v-model="partForm.version" slot="prepend" class="w-95" :disabled="disflag" @change="changeCode">
            <el-option v-for="(item, index) in versionList" :label="item.label" :value="item.value" :key="index + 'option'">{{ item.value }}</el-option>
          </el-select>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="超级管理员">
        {{ partForm.clerkName }}
      </el-form-item>
      <el-form-item label="超级管理员手机号" prop="sex"> {{ partForm.phoneNumber | formatPhoneNum }} <el-button type="primary" @click="sendCode()">点击短信验证</el-button> </el-form-item>
      <el-form-item label="短信验证码" prop="code">
        <el-input style="width: 180px;" v-model="partForm.code" placeholder="请输入验证码"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel('form')">取消</el-button>
      <el-button 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-enterprise',
  components: {
    limitInput,
    countryMobile,
    selectDepartment
  },
  props: {
    memberObj: {
      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();
        }
      }
    };

    return {
      versionList: [
        {
          label: 'GIC 3.0',
          value: '3.0'
        },
        {
          label: 'GIC 4.0',
          value: '4.0'
        }
      ],
      memberVisible: true,
      partForm: {
        version: '3.0',
        enterpriseName: '',
        nationCode: '86',
        phoneNumber: '',
        code: ''
      },
      rules: {
        staffName: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }
        ],
        phoneNumber: [
          {
            required: true,
            validator: checkPhone,
            trigger: 'change'
          }
        ],
        department: [
          {
            type: 'array',
            required: true,
            message: '请选择部门',
            trigger: 'change'
          }
        ]
      }
    };
  },
  methods: {
    /**
     * 发送验证码
     */
    sendCode() {
      const that = this;
      let params = {
        phoneNumber: that.partForm.phoneNumber,
        nationCode: that.partForm.nationCode,
        type: ''
      };
      getRequest('/haoban-web/send-code', params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            const phone = String(that.partForm.phoneNumber);
            let handle = phone.substr(0, 3) + '****' + phone.substr(7, phone.length - 1);
            showMsg.showmsg(`已发送验证码到${that.partForm.nationCode}-${handle}`, 'success');
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 校验验证码
     */
    checkCode() {
      const that = this;
      let params = {
        phoneNumber: that.partForm.phoneNumber,
        nationCode: that.partForm.nationCode,
        type: '',
        code: that.partForm.code
      };

      return new Promise((resolve, reject) => {
        getRequest('/haoban-web/validate-code', params)
          .then(res => {
            let resData = res.data;
            if (resData.errorCode == 1) {
              resolve(true);
              return false;
            }
            errMsg.errorMsg(resData);
            resolve(false);
          })
          .catch(function(error) {
            resolve(false);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },
    /**
     * 搜索查询列表
     */
    getSearchList() {
      const that = this;
      let params = {
        version: that.partForm.version
      };
      return new Promise((resolve, reject) => {
        getRequest('/haoban-web/staff-add', params)
          .then(res => {
            let resData = res.data;
            if (resData.errorCode == 1) {
              resolve(resData.result);
              return false;
            }
            errMsg.errorMsg(resData);
            resolve(false);
          })
          .catch(function(error) {
            resolve(false);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },
    /**
     * 搜索查询列表
     */
    async querySearchAsync(queryString, cb) {
      const that = this;
      const res = await that.getSearchList();
      cb(res);
    },
    handleSelect(item) {
      console.log(item);
    },
    /**
     * 改变对外职务
     */
    checkGroupIds: function(nodes) {
      const that = this;
      that.partForm.departmentIds = nodes;
    },
    /**
     * 改变对外职务
     */
    changeExtendPostion(e) {
      const that = this;
      if (e == 1) {
        that.partForm.extendPostion = that.partForm.postion;
      } else {
        that.partForm.extendPostion = '';
      }
    },
    /**
     * 关闭弹窗
     */
    handleClose(done) {
      const that = this;
      that.$refs['form'].resetFields();
      that.memberVisible = false;
      that.$emit('refreshData', 'close');
      done();
    },
    cancel() {
      const that = this;
      that.$refs['form'].resetFields();
      that.memberVisible = false;
      that.$emit('refreshData', 'close');
    },
    /**
     * 确定保存
     */
    async submitForm(form) {
      const that = this;
      const flag = await that.checkCode();
      if (!flag) {
        return false;
      }
      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
      };
      postRequest(that.partForm.staffId ? '/haoban-web/staff-edit' : '/haoban-web/staff-add', params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            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-web/staff-add', params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.partForm = resData.result;
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {}
  /* mounted() {
      const that = this;

    } */
};
</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%;
}

.w-95 {
  width: 95px;
}

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