<!--
 * @Descripttion : 当前组件信息
 * @Author       : 无尘
 * @Date         : 2020-02-13 16:13:59
 * @LastEditors: 无尘
 * @LastEditTime: 2020-08-26 09:50:41
 * @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">
        <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>
              <el-select v-model="partForm.version" class="w-95" @change="changeVersion">
                <el-option v-for="(item, index) in versionList" :label="item.label" :value="item.value" :key="index + 'option'">{{ item.value }}</el-option> </el-select
              ><el-popover placement="bottom" title="" trigger="click" popper-class="company-select-pop" width="267">
                <div class="company-select">
                  <div class="el-scrollbar define-search-select">
                    <div class="el-select-dropdown__wrap el-scrollbar__wrap" style="margin-bottom: -5px; margin-right: -5px;">
                      <ul class="el-scrollbar__view el-select-dropdown__list">
                        <li class="el-select-dropdown__item" v-for="(item, index) in searchArray" :key="index + 'search'" @click="handleSelect(item)">
                          <div class="flex flex-space-between">
                            <div style="line-height: 26px;">
                              <span class="block text-ellipsis">{{ item.enterpriseName }}</span>
                              <div class="text-ellipsis font-12 color-909399">{{ item.brandName || '--' }}</div>
                            </div>
                            <span v-if="item.enterpriseId == partForm.enterpriseId" class="font-12 color-2f54eb el-icon-check flex-align-center" style="display:flex;"></span>
                          </div>
                        </li>
                        <li v-if="!searchArray.length" class="el-select-dropdown__item text-center">暂无商户数据</li>
                      </ul>
                    </div>
                  </div>
                </div>
                <div class="select-search-input cursor-pointer" slot="reference">
                  <div>
                    <el-input class="w-267" placeholder="请搜索选择商户" maxlength="50" v-model="searchSelect" @keyup.native="value => querySearchAsync(value, searchSelect)"> </el-input>
                  </div>
                </div>
              </el-popover>
            </div>
          </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;" maxlength="20" 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'
          }
        ]
      },
      searchSelect: '',
      searchArray: [],
      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(String(that.partForm.phoneNumber))) {
        showMsg.showmsg(`超级管理员手机号不正确，请到 GIC 商户后台修改`, 'warning');
        return false;
      }
      /* if (that.partForm.nationCode == '' || isNaN(String(that.partForm.nationCode))) {
        showMsg.showmsg(`国家码不存在`, 'warning');
        return false;
      } */
      let params = {
        phoneNumber: that.partForm.phoneNumber,
        nationCode: that.partForm.nationCode || '86',
        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 || '86'}-${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
            });
          });
      });
    },
    /**
     * @description: 选择版本
     * @author: 无尘
     */
    changeVersion() {
      const that = this;
      that.partForm.enterpriseName = '';
      that.partForm.enterpriseId = '';
      that.partForm.clerkName = '';
      that.partForm.nationCode = '';
      that.partForm.phoneNumber = '';
      that.partForm.code = '';
      that.searchSelect = '';
      that.searchArray = [];
    },
    /**
     * 搜索查询列表
     */
    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() {
      const that = this;
      if (String(that.searchSelect).trim() == '') {
        that.searchArray = [];
        return false;
      }
      const res = await that.getSearchList(that.searchSelect);
      that.searchArray = res;
    },
    handleSelect(item) {
      const that = this;
      that.partForm.enterpriseName = item.enterpriseName;
      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="scss" 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;
}

.w-267 {
  width: 267px;
}

.m-l-30 {
  margin-left: 30px;
}

.company-select-pop {
  display: inline-block;
}

.select-search-input {
  display: inline-block;
  position: relative;
  left: -2px;
}

.company-select {
  position: relative;
  .el-select-dropdown__item {
    height: 52px;
    line-height: 52px;
  }
  .text-ellipsis {
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
