<template>
  <div class="auth-merchant-add">
    <nav-crumb :navpath="navpath"> </nav-crumb>
    <div class="right-content">
      <div class="right-box" style="min-height: calc(100vh - 104px);">
        <div class="apps-content flex" style="min-height: calc(100vh - 104px);">
          <div class="apps-content-right">
            <div class="overstore-tip w-718">
              <div role="alert" class="el-alert el-alert--info flex flex-align-center">
                <i class="el-alert__icon el-icon-warning font-13 color-2f54eb"></i>
                <div class="el-alert__content color-303133 font-13">
                  <p class="line-22">商户授权须知：</p>
                  <p class="line-22">1. 商户授权支持 1 个商户授权多个企业以及多个商户授权 1 个企业；</p>
                  <p class="line-22">2. 商户授权需经过商户管理员同意后，才会授权成功；</p>
                  <p class="line-22">3. 商户授权结束后，导购可通过企业微信好办小程序关联导购账号后登录；</p>
                  <p class="line-22">4. 商户授权门店绑定或修改，默认次日生效，如需立即生效可在商户授权列表手动刷新。</p>
                </div>
              </div>
            </div>
            <div class="m-t-24">
              <el-form :model="partForm" :rules="rules" ref="form" label-width="128px" class="dialog-form">
                <el-form-item label="企业名称">
                  {{ corpName }}
                </el-form-item>
                <el-form-item>
                  <el-tooltip slot="label" class="item" effect="dark" :open-delay="200" placement="top-start" content="输入品牌/商户的企业名称，只支持精确搜素。">
                    <span style="cursor: pointer;padding-bottom: 2px; border-bottom: 1px dashed #2F54EB;" class="font-14 color-606266">选择商户</span>
                  </el-tooltip>
                  <el-popover placement="bottom" title="" :disabled="type === 'edit'" trigger="click" popper-class="authMerchant-select-pop" width="253">
                    <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 auth-merchant-add">
                            <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 == 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-form-item prop="searchSelect">
                          <el-input class="w-287" placeholder="请搜索选择商户" maxlength="50" :disabled="type === 'edit'" v-model="partForm.searchSelect" @keyup.native="querySearchAsync('search')"> </el-input>
                        </el-form-item>
                      </div>
                    </div>
                  </el-popover>
                </el-form-item>
                <el-form-item>
                  <el-tooltip slot="label" class="item" effect="dark" :open-delay="200" placement="top-start" content="拥有选中的门店管理权限，以及导购账号绑定权限">
                    <span style="cursor: pointer;padding-bottom: 2px; border-bottom: 1px dashed #2F54EB;" class="font-14 color-606266">门店绑定</span>
                  </el-tooltip>
                  <gic-select-group-auth :brandId="enterpriseId" width="287px" :authMerchant="true" :selectData="partForm.storeGroup" @checkGroupIds="checkGroupIds"> </gic-select-group-auth>
                </el-form-item>
                <el-form-item style="margin-top:-10px;margin-bottom:12px;">
                  <el-tooltip slot="label" class="item" effect="dark" :open-delay="200" placement="top-start">
                    <div slot="content" style="line-height:18px;">
                      ①选择同一开平，通过企业微信添加客户，可以直接更新会员信息（一码两用）。<br />
                      原因：因为获取的用户unionid相同，可以将客户身份（企微客户）和会员（微信会员）身份直接关联；<br />
                      ②选择不同开平，通过企业微信添加客户，无法直接更新会员信息（一码两用）。<br />
                      原因：因为获取的用户unionid不同，无法将客户身份（企微客户）和会员（微信会员）身份直接关联
                    </div>
                    <span style="cursor: pointer;padding-bottom: 2px; border-bottom: 1px dashed #2F54EB;" class="font-14 color-606266">开放平台类型</span>
                  </el-tooltip>
                  <div style="padding-top: 10px;">
                    <el-radio v-model="partForm.memberOpenCardFlag" :label="0" :disabled="type === 'edit'">
                      <div class="m-b-20" style="display:inline-block;vertical-align:top;">
                        <p class="l-h-1 m-b-5 color-303133">同一开平</p>
                        <p class="tip">(授权商户的小程序/公众号，和当前企业【客户联系】微信开发者ID绑在同一开放平台 。例：绑定同一开平的集团企业）</p>
                      </div>
                    </el-radio>
                  </div>
                  <div>
                    <el-radio v-model="partForm.memberOpenCardFlag" :label="1" :disabled="type === 'edit'">
                      <div style="display:inline-block;vertical-align:top;">
                        <p class="l-h-1 m-b-5 color-303133">不同开平</p>
                        <p class="tip">(授权商户的小程序/公众号，和当前企业【客户联系】微信开发者ID绑在不同开放平台。例：没绑定同一开平的代理商企业）</p>
                      </div>
                    </el-radio>
                  </div>
                </el-form-item>
                <el-form-item label="企业类型">
                  <el-radio v-model="partForm.wxEnterpriseType" :label="0" :disabled="type === 'edit'">总部</el-radio>
                  <el-radio v-model="partForm.wxEnterpriseType" :label="1" :disabled="type === 'edit'">代理</el-radio>
                </el-form-item>
                <el-button type="primary" style="display:block;margin:38px 0 0 128px;" @click="addShow = true" :disabled="!(enterpriseId && partForm.storeGroup.length && partForm.searchSelect)">授权校验并{{ type === 'edit' ? '保存' : '新建' }}</el-button>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <vue-gic-footer></vue-gic-footer> -->
    <authMerchant-dailog v-if="addShow" @refreshData="refreshData" :item="dailogForm"></authMerchant-dailog>
  </div>
</template>
<script>
import authMerchantDailog from './authMerchant-dailog.vue';
import gicSelectGroupAuth from '@/components/common/gic-select-group-auth.vue';
import navCrumb from '@/components/nav/nav.vue';
import { getRequest, postRequest } from '@/api/api';
import errMsg from '@/common/js/error';
// import { _debounce } from '@/common/js/public';
export default {
  name: 'authMerchantAdd',
  data() {
    const checkEnterpriseId = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请先搜索商户！'));
      } else if (!this.enterpriseId) {
        callback(new Error('请选择商户！'));
      } else {
        callback();
      }
    };
    return {
      bgHeight: window.screen.availHeight - 104 + 'px',
      // 面包屑参数
      navpath: [
        {
          name: '首页',
          path: '/index'
        },
        {
          name: '通讯录',
          path: '/contacts'
        },
        {
          name: '授权商户',
          path: '/authMerchant'
        },
        {
          name: '新建授权商户',
          path: ''
        }
      ],
      partForm: {
        memberOpenCardFlag: 0,
        wxEnterpriseType: 0,
        searchSelect: '',
        storeGroup: []
      },
      rules: {
        searchSelect: [{ required: true, validator: checkEnterpriseId, trigger: 'blur' }]
      },
      checkedList: [],
      dailogForm: {},
      searchArray: [],
      enterpriseId: '',
      corpName: '',
      addShow: false
    };
  },
  computed: {},
  methods: {
    /**
     * 路由跳转
     *  @param {path} path
     */
    changeRoute(path) {
      this.$router.push(path);
    },
    handleSelect(item) {
      this.enterpriseId = item.enterpriseId;
      this.dailogForm = { ...item };
      this.$refs.form.validateField('searchSelect');
    },
    async querySearchAsync(type) {
      const that = this;
      if (String(that.partForm.searchSelect).trim() == '') {
        that.searchArray = [];
        return false;
      }
      if (type === 'search') {
        that.enterpriseId = '';
        that.partForm.storeGroup = [];
      }
      const res = await that.getSearchList(that.partForm.searchSelect);
      that.searchArray = res;
      if (type === 'edit' && res[0]) {
        that.handleSelect(res[0]);
      }
    },
    getSearchList(queryString) {
      const that = this;
      let params = {
        enterpriseName: queryString,
        version: '3.0'
      };
      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
            });
          });
      });
    },
    checkGroupIds: function(nodes) {
      const that = this;
      that.partForm.storeGroup = nodes;
    },
    formateGroupList() {
      const that = this;
      let storeGroup = [];
      that.partForm.storeGroup.map(item => {
        storeGroup.push({
          relationId: item.relationId,
          relationName: item.relationName,
          relationType: '1'
        });
      });
      return storeGroup;
    },
    confirmForm() {
      const that = this;
      const para = {
        enterpriseId: that.enterpriseId,
        wxEnterpriseId: JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId,
        version: '3.0',
        rangeType: '1',
        memberOpenCardFlag: that.partForm.memberOpenCardFlag,
        wxEnterpriseType: that.partForm.wxEnterpriseType
      };
      if (this.$route.query.enterprise) {
        para.wxEnterpriseRelatedId = that.partForm.wxEnterpriseRelatedId;
      }
      para.relations = JSON.stringify(that.formateGroupList());
      postRequest(`/haoban-manage3-web/wx-enterprise-bind`, para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.$message.success({
              duration: 1000,
              message: '授权商户新建成功！'
            });
            that.changeRoute('/authMerchant');
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    getCompanyName() {
      let that = this;
      let para = {
        wxEnterpriseId: localStorage.getItem('userInfos') ? JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId : ''
      };
      getRequest('/haoban-manage3-web/wxEnterprise-detail', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.corpName = resData.result.corpName;
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    refreshData(type) {
      const that = this;
      that.addShow = false;
      if (type == 'close') {
        return false;
      } else if (type == 'success') {
        that.confirmForm();
      }
    },
    getDeatil(enterpriseId) {
      const that = this;
      that.enterpriseId = enterpriseId;
      const para = {
        enterpriseId,
        wxEnterpriseId: JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId,
        version: '3.0'
      };
      postRequest(`/haoban-manage3-web/wx-enterprise-bind-detail`, para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            let checkedList = [];
            resData.result.relations && resData.result.relations.map(item => checkedList.push({ relationId: item.relationId }));
            that.partForm.storeGroup = checkedList;
            that.partForm.wxEnterpriseRelatedId = resData.result.wxEnterpriseRelatedId;
            that.partForm.memberOpenCardFlag = resData.result.memberOpenCardFlag;
            that.partForm.wxEnterpriseType = resData.result.wxEnterpriseType;
            that.partForm.searchSelect = resData.result.enterpriseName;
            that.querySearchAsync('edit');
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {},
  mounted() {
    this.getCompanyName();
    if (this.$route.query.enterprise) {
      this.type = 'edit';
      this.getDeatil(this.$route.query.enterprise);
    } else {
      this.type = 'add';
    }
    this.$nextTick(() => {
      this.getSearchList('');
    });
    document.documentElement.style.backgroundColor = '#f0f2f5';
  },
  destroyed() {
    document.documentElement.style.backgroundColor = '#fff';
  },
  components: {
    navCrumb,
    gicSelectGroupAuth,
    authMerchantDailog
  }
};
</script>
<style type="text/scss" lang="scss" scoped>
.w-287 {
  width: 287px;
}
.m-b-20 {
  margin-bottom: 20px;
}
.m-b-5 {
  margin-bottom: 5px;
}
.l-h {
  line-height: 1;
}
.tip {
  font-size: 12px;
  color: #909399;
  line-height: 22px;
}
.span-dot {
  display: inline-block;
  vertical-align: middle;
  width: 6px;
  height: 6px;
  margin-right: 6px;
  border-radius: 3px;
  &.bg-52c41a {
    background: #52c41a;
  }
  &.bg-f5222d {
    background: #f5222d;
  }
}
.tooltip-text {
  width: 100%;
  white-space: pre-wrap;
  word-break: break-all;
}
.w-287 {
  width: 287px;
}
.el-alert--info {
  background: rgba(240, 245, 255, 1);
  border-radius: 2px;
  border: 1px solid rgba(133, 165, 255, 1);
  -webkit-box-align: flex-start;
  -webkit-align-items: flex-start;
  -ms-flex-align: flex-start;
  align-items: flex-start;
  .el-alert__icon {
    font-size: 12px;
    padding-top: 3px;
  }
}
.my-customer-wrap {
  height: 100%;
}
.right-content {
  /*width: 100%;*/
  padding: 0 20px 20px 20px;
  min-height: calc(100% - 160px);
  .right-box {
    background: #fff;
    min-height: 500px;
    padding: 0px;
    .apps-content {
      .apps-content-right {
        min-height: 787px;
        box-sizing: border-box;
        width: 100%;
        padding: 20px;
        background: #fff;
        .overstore-body {
          background: #fff;
        }
        .daily-set-wrap {
          height: 100%;
          background: #fff;
        }
        .app-detail-wrap {
          height: 100%;
          background: #fff;
        }
        .common-set-wrap {
          height: 100%;
          background: #fff;
        }
      }
    }
  }
}
</style>
<style>
.auth-merchant-add .el-select-dropdown__item {
  height: 50px;
}
.authMerchant-select-pop {
  left: 168px !important;
}
</style>
