<!--
 * @Descripttion : 当前组件信息
 * @Author       : 无尘
 * @Date         : 2020-02-13 16:13:59
 * @LastEditors: 无尘
 * @LastEditTime: 2020-06-09 16:40:18
 * @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">
    <div>
      <div class="font-12 color-909399 m-b-20">提示：授权商户成功后，导购可通过企业微信好办小程序绑定导购账号后登录</div>
      <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">
              <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> -->
        <div :class="['el-form-item el-form-item--large is-required', showError ? 'is-error' : '']" style="position:relative;">
          <label for="name" class="el-form-item__label" style="width: 140px; cursor: pointer;">
            <el-tooltip class="item" effect="dark" content="卡券限制每个会员最大发放次数" placement="top-start">
              <div slot="content">因企业微信仅支持获取同一主体下客户unionid，<br />请授权商户确认同步的多个商户的授权绑定公众号为同一主体下，且与企业微信认证主体相同。<br />参考链接： https://work.weixin.qq.com/api/doc/90001/90143/92265</div>
              <span style="cursor: pointer;padding-bottom: 2px; border-bottom: 1px dashed #2F54EB;">选择商户</span>
            </el-tooltip>
          </label>
          <div class="el-form-item__content" style="margin-left: 140px;">
            <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">
                <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>
          </div>
          <div v-if="showError" class="el-form-item__error" style="margin-left: 140px;">请选择商户</div>
        </div>
        <el-form-item label="超级管理员">
          {{ partForm.clerkName | formatName }}
        </el-form-item>
        <el-form-item label="超级管理员手机号" prop=""
          ><span v-if="partForm.phoneNumber">{{ partForm.nationCode }}-</span>{{ partForm.phoneNumber | formatPhoneNum }} <el-button class="m-l-35" :disabled="disableBtn" type="text" @click="sendCode()">{{ (disableBtn && countNum == 60) || (!disableBtn && !!countNum) ? '点击短信验证' : countNum + 's' }}</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 v-if="false" class="company-auth">
        <div><span class="font-14 font-w-500">商户授权信息</span><span class="font-12 color-909399">请确保公众号主体与企业微信绑定主体一致。</span><el-button type="text" @click="toLink">主体查询公众号方法</el-button></div>
        <el-table :data="tableData" style="width: 100%" height="350">
          <el-table-column prop="date" label="公众号/小程序" show-overflow-tooltip> </el-table-column>
          <el-table-column prop="name" label="账号类型" show-overflow-tooltip> </el-table-column>
          <el-table-column prop="address" label="第三方绑定appid" show-overflow-tooltip> </el-table-column>
        </el-table>
      </div>
    </div>
    <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 { _debounce } from '@/common/js/public';
// 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('userInfos')).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'
          }
        ]
      },
      disableBtn: true, // 发验证码.默认无手机号，不可点击
      countNum: 60,
      tableData: [],
      showError: false
    };
  },
  methods: {
    toLink() {
      window.open(`https://kf.qq.com/faq/171219Mn2qmi171219vY3mmI.html`);
    },
    /**
     * 倒计时
     */
    countDown() {
      const that = this;
      let time = setInterval(function() {
        if (that.countNum === 0) {
          clearInterval(time);
          that.countNum = 60;
          that.disableBtn = false;
          return false;
        }
        that.countNum--;
      }, 1000);
    },
    /**
     * 发送验证码
     */
    sendCode: _debounce(function() {
      const that = this;
      if (that.partForm.phoneNumber == '' || isNaN(that.partForm.phoneNumber)) {
        showMsg.showmsg(`超级管理员手机号不正确，请到 GIC 商户后台修改`, 'warning');
        return false;
      }
      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) {
            that.disableBtn = true;
            that.countDown();
            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
          });
        });
    }, 300),
    /**
     * 校验验证码
     */
    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 = '';
      if (item.phoneNumber) {
        that.disableBtn = false;
      }
    },
    /**
     * 改变对外职务
     */
    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;
      if (!that.partForm.enterpriseId) {
        that.showError = true;
        return false;
      } else {
        that.showError = false;
      }
      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>
.m-l-35 {
  margin-left: 35px;
}
.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>
