<!--
 * @Descripttion : 当前组件信息
 * @Author       : 无尘
 * @Date         : 2020-02-13 16:13:59
 * @LastEditors  : 无尘
 * @LastEditTime : 2020-02-24 15:47:10
 * @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="enterpriseName">
        <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.nationCode }}-{{ partForm.phoneNumber | formatPhoneNum }} <el-button :disabled="!partForm.phoneNumber ? true : false" 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() {
    return {
      versionList: [
        {
          label: 'GIC 3.0',
          value: '3.0'
        },
        {
          label: 'GIC 4.0',
          value: '4.0'
        }
      ],
      wxEnterpriseId: JSON.parse(localStorage.getItem('userInfo')).wxEnterpriseId,
      memberVisible: true,
      partForm: {
        version: '3.0',
        clerkName: '',
        enterpriseId: '',
        enterpriseName: '',
        nationCode: '86',
        phoneNumber: '',
        code: ''
      },
      rules: {
        enterpriseName: [
          {
            required: true,
            message: '请选择商户',
            trigger: 'blur'
          }
        ],

        code: [
          {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  methods: {
    /**
     * 发送验证码
     */
    sendCode() {
      const that = this;
      let params = {
        phoneNumber: that.partForm.phoneNumber,
        nationCode: that.partForm.nationCode,
        type: 1,
        isTest: 1
      };
      getRequest('/haoban-manage3-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: 1,
        code: that.partForm.code
      };

      return new Promise((resolve, reject) => {
        getRequest('/haoban-manage3-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(queryString) {
      const that = this;
      let params = {
        enterpriseName: queryString,
        version: that.partForm.version
      };
      return new Promise((resolve, reject) => {
        getRequest('/haoban-manage3-web/enterprise-search', params)
          .then(res => {
            let resData = res.data;
            if (resData.errorCode == 1) {
              if (resData.result) {
                resData.result.value = resData.result.enterpriseName;
              }
              resolve(resData.result ? [resData.result] : []);
              return false;
            }
            errMsg.errorMsg(resData);
            resolve([]);
          })
          .catch(function(error) {
            resolve([]);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },
    /**
     * 搜索查询列表
     */
    async querySearchAsync(queryString, cb) {
      const that = this;
      if (queryString == '') {
        cb([]);
      }
      const res = await that.getSearchList(queryString);
      cb(res);
      // console.log(res);
      // clearTimeout(that.timeout);
      // that.timeout = setTimeout(() => {
      //   cb(res);
      // }, 300);
    },
    handleSelect(item) {
      // console.log(item);
      const that = this;
      that.partForm.enterpriseId = item.enterpriseId;
      that.partForm.clerkName = item.clerkName;
      that.partForm.nationCode = item.nationCode;
      that.partForm.phoneNumber = item.phoneNumber;
      that.partForm.code = '';
    },
    /**
     * 改变对外职务
     */
    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.$emit('refreshData', 'close');
      done();
    },
    cancel() {
      const that = this;
      that.$refs['form'].resetFields();
      that.$emit('refreshData', 'close');
    },
    /**
     * 确定保存
     */
    async submitForm(form) {
      const that = this;

      that.$refs[form].validate(async valid => {
        if (valid) {
          const flag = await that.checkCode();
          if (!flag) {
            return false;
          }
          that.toAddPost();
        } else {
          return false;
        }
      });
    },
    toAddPost() {
      const that = this;
      let params = {
        enterpriseId: that.partForm.enterpriseId,
        wxEnterpriseId: that.wxEnterpriseId,
        version: that.partForm.version
      };
      postRequest('/haoban-manage3-web/wx-enterprise-bind', 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-manage3-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>
