<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-03-20 14:36:37
 * @LastEditors: 无尘
 * @LastEditTime: 2020-11-03 17:08:32
 -->
<template>
  <div class="my-customer-wrap common-set-wrap">
    <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="new-auth-body">
              <div v-if="activeStep != 2">
                <auth-step :active-step="activeStep"></auth-step>
              </div>
              <div v-if="activeStep == 0" class="auth-tip-body">
                <auth-tip class="m-t-30"></auth-tip>
                <el-form :model="authForm" :rules="rules" ref="authForm" label-width="110px" class="dialog-form m-t-20" @submit.native.prevent>
                  <el-form-item prop="enterpriseId">
                    <span slot="label">
                      <el-tooltip class="item" effect="dark" placement="top-start">
                        <div slot="content">因企业微信仅支持获取同一开放平台的客户unionid。需要：<br />1.确认授权的的多个企业绑定的公众号或小程序存在同一开放平台内；<br />2.绑定微信开发者的小程序或公众号与企业微信认证企业主体相同。<br />参考链接： https://work.weixin.qq.com/api/doc/90001/90143/92265</div>
                        <span class="font-14 color-606266 common-bottom-border">选择商户</span>
                      </el-tooltip>
                    </span>
                    <div class="el-input-group__prepend">GIC4.0</div><el-popover v-if="!$route.query.enterpriseId" 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="overflow: auto;">
                            <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="getAdmin(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.companyName || '--' }}</div>
                                  </div>
                                  <span v-if="item.enterpriseId == authForm.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" :disabled="$route.query.enterpriseId? true:false" placeholder="请搜索选择商户" maxlength="50" v-model="searchSelect" @keyup.native="value => querySearchAsync(value, searchSelect)"> </el-input>
                        </div>
                      </div>
                    </el-popover><div v-if="$route.query.enterpriseId" class="select-search-input"><el-input class="w-267" :disabled="$route.query.enterpriseId? true:false" placeholder="请搜索选择商户" maxlength="50" v-model="authForm.enterpriseName"> </el-input></div>
                  </el-form-item>
                  <el-form-item prop="bindRange">
                    <span slot="label">
                      <el-tooltip class="item" effect="dark" content="拥有选中的门店管理权限，以及导购账号绑定权限" placement="top-start">
                        <span class="font-14 color-606266 common-bottom-border">门店绑定</span>
                      </el-tooltip>
                    </span>
                    <div class="el-select store-item-content" @click="showStore(1)">
                      <div v-if="authForm.bindStoreMode > 0" class="el-select__tags">
                        <span style="display:block;">
                          <template v-for="(item, index) in authForm.bindRange">
                            <span class="el-tag el-tag--info el-tag--small" :key="index+'bind'">
                              <span class="el-select__tags-text">{{ item.storeInfoName || item.storeGroupName }}</span>
                              <i class="el-tag__close el-icon-close" @click.stop="delStore(index, authForm.bindRange)"></i>
                            </span>
                          </template>
                        </span>
                      </div>
                      <span v-if="authForm.bindStoreMode == 0 && authForm.bindStoreMode !== '' " class="p-l-10 font-14 color-909399">已选全部</span>
                    </div>
                  </el-form-item>
                  <el-form-item prop="shareRange">
                    <span slot="label">
                      <el-tooltip class="item" effect="dark" content="拥有选中的门店查看权限" placement="top-start">
                        <span class="font-14 color-606266 common-bottom-border">门店共享</span>
                      </el-tooltip>
                    </span>
                    <div class="el-select store-item-content" @click="showStore(2)">
                      <div v-if="authForm.shareStoreMode > 0" class="el-select__tags">
                        <span style="display:block; ">
                          <template v-for="(item, index) in authForm.shareRange">
                            <span class="el-tag el-tag--info el-tag--small" :key="index+'bind'">
                              <span class="el-select__tags-text">{{ item.storeInfoName || item.storeGroupName }}</span>
                              <i class="el-tag__close el-icon-close" @click.stop="delStore(index, authForm.shareRange)"></i>
                            </span>
                          </template>
                        </span>
                      </div>
                      <span v-if="authForm.shareStoreMode == 0 && authForm.shareStoreMode !== ''" class="p-l-10 font-14 color-909399">已选全部</span>
                    </div>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="cancel">取消</el-button>
                    <el-button :disabled="!changeFlag || (authForm.shareStoreMode === '' && authForm.bindStoreMode === '')" type="primary" @click="submitForm('authForm')">下一步</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <!-- 审核员授权 -->
              <div v-if="activeStep == 1" class="commit-success-body m-t-35">
                <auth-commit :admin-list="adminList" :reason="authForm.auditReason" @changeStep="changeStep" @returnStep="returnStep"></auth-commit>
              </div>
              <!-- 已提交审核 -->
              <div v-if="activeStep == 2" class="commit-success-body">
                <auth-commit-success :enterprise-id="authForm.enterpriseId"></auth-commit-success>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <store-auth-dialog v-if="setVisible" :enterprise-id="authForm.enterpriseId" :is-select-all="isSelectAll" :select-mode="selectMode" :range-data="rangeData" :bind-type="bindType" @closeSet="closeSet"></store-auth-dialog>
    <check-name-dialog v-if="checkShow" :sync-data="syncData" @closeSet="closeCheckSet"></check-name-dialog>
    <!-- <vue-gic-footer></vue-gic-footer> -->
  </div>
</template>
<script>
import navCrumb from '@/components/nav/nav.vue';
import authStep from '@/components/company/auth-step.vue';
import authTip from '@/components/company/auth-tip.vue';
import authCommitSuccess from '@/components/company/auth-commit-success.vue';
import authCommit from '@/components/company/auth-commit.vue';
import storeAuthDialog from '@/components/company/store-auth-dialog.vue';
import checkNameDialog from '@/components/company/check-name-dialog.vue';
import api from '@/api/merchant-auth.js';
const { getAuthDetail, getEnterprise, getEnterpriseDetail, getGicAdmin, postEnterpriseAuth } = api;
import { emojiToStr } from '@/common/js/public';
export default {
  name: 'NewAuthMerchant',
  components: {
    navCrumb,
    authStep,
    authTip,
    authCommitSuccess,
    authCommit,
    storeAuthDialog,
    checkNameDialog
  },
  data() {
    return {
      // 面包屑参数
      navpath: [
        /* {
          name: '首页',
          path: '/index'
        }, */
        {
          name: '通讯录',
          path: '/contactsList'
        },
        {
          name: '授权商户',
          path: '/authMerchant'
        },
        {
          name: !!this.$route.query.enterpriseId ? '编辑授权'  : '新建授权',
          path: ''
        }
      ],
      wxEnterpriseId: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '',
      auditorName: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).staffName : '',
      activeStep: '0',
      brandOptions: [], // 商户列表
      searchSelect: '',
      searchArray: [],
      authForm: {
        storeRangeAuditId: '',
        enterpriseId: '',
        enterpriseName: '',
        bindRange: [],
        shareRange: [],
        shareStoreMode: '',
        bindStoreMode: '',
        auditReason: ''
      },
      rules: {
        enterpriseId: [
          {
            required: true,
            message: '请选择商户',
            trigger: 'change'
          }
        ]
      },
      checkShow: false, // 是否显示姓名校验
      syncData: {},
      isSelectAll: 0, // 用来判断禁用选择所有门店
      changeFlag: false, // 用来判断编辑时候数据有没有变化
      setVisible: false,
      selectMode: '0', // 选择 全部、分组、门店
      rangeData: [], // 选择的数据
      bindType: 1,
      adminList: [] // 审核管理员
    };
  },
  mounted() {
    const that = this;
    if (!!that.$route.query.enterpriseId) {
      that.getData();
    }
    document.documentElement.style.backgroundColor = '#f0f2f5';
  },
  destroyed() {
    document.documentElement.style.backgroundColor = '#fff';
  },
  methods: {
    /**
     * @description: 关闭姓名校验
     * @param {String} res
     * @return {Boolean}
     * @author: 无尘
     */
    closeCheckSet(res) {
      const that = this;
      that.checkShow = false;
      if (res == 'close') {
        return false;
      }
      that.authForm.enterpriseId = that.syncData.enterpriseId;
      that.authForm.enterpriseName = that.syncData.enterpriseName;
      that.$refs['authForm'].validate(valid => {
        if (valid) {
          return;
        } else {
          return false;
        }
      });
    },
    /**
     * @description: closeSet
     * @param {String} type
     * @param {Array} arr
     * @return {Boolean}
     * @author: 无尘
     */
    closeSet(type, arr) {
      const that = this;
      that.setVisible = false;
      if (type == 'close') {
        return false;
      }
      that.selectMode = String(type); // 0 全部 1部分分组 2 部分门店
      if (that.bindType == 1) {
        that.authForm.bindStoreMode = String(type);
        that.authForm.bindRange = JSON.parse(JSON.stringify(arr));
      }else {
        that.authForm.shareStoreMode = String(type);
        that.authForm.shareRange = JSON.parse(JSON.stringify(arr));
      }
      that.changeFlag = true;
    },
    /**
     * @description: 显示门店选择
     * @param {String} type
     * @return {Boolean}
     * @author: 无尘
     */
    showStore(type) {
      const that = this;
      if (!that.authForm.enterpriseId) {
        return false;
      }
      that.selectMode =  type == 1 ? that.authForm.bindStoreMode : that.authForm.shareStoreMode;
      that.rangeData = type == 1 ? that.authForm.bindRange : that.authForm.shareRange;
      that.bindType = type;
      that.setVisible = true;
      that.getEnterpriseData();
    },
    /**
     * @description: 搜索查询列表
     * @param {String} queryString
     * @return {Array}
     * @author: 无尘
     */
    getSearchList(queryString) {
      let params = {
        enterpriseName: queryString
      };
      if (queryString == '') {
        return [];
      }
      return new Promise((resolve, reject) => {
        getEnterprise(params)
          .then(res => {
            if (res.code == '0000') {
              if (res.result) {
                res.result.forEach(ele => {
                  ele.value = ele.enterpriseName;
                });
              }
              resolve(res.result);
            }else {
              resolve([]);
            }
          })
          .catch(function(error) {
            resolve([]);
          });
      });
    },
    /**
     * @description: 搜索查询列表
     * @author: 无尘
     */
    async querySearchAsync() {
      const that = this;
      if (String(that.searchSelect).trim() == '') {
        that.authForm.enterpriseId = '';
        that.searchArray = [];
        that.authForm.bindRange = [];
        that.authForm.shareRange = [];
        that.authForm.shareStoreMode = '';
        that.authForm.bindStoreMode = '';
        that.adminList = [];
        return false;
      }
      const res = await that.getSearchList(that.searchSelect);
      that.searchArray = res;
    },
    /**
     * @description: 第二步取消
     * @author: 无尘
     */
    returnStep() {
      const that = this;
      that.activeStep = 0;
    },
    /**
     * @description: 取消
     * @author: 无尘
     */
    cancel() {
      const that = this;
      that.$router.push('/authMerchant');
    },
    /**
     * @description: 下一步
     * @param {string} form
     * @author: 无尘
     */
    submitForm(form) {
      const that = this;
      that.$refs[form].validate(valid => {
        if (valid) {
          that.activeStep = 1;
        } else {
          return false;
        }
      });
    },
    /**
     * @description: 删除门店
     * @param {Number} index
     * @param {Array} arr
     * @author: 无尘
     */
    delStore(index, arr) {
      const that = this;
      arr.splice(index, 1);
      that.changeFlag = true;
      that.authForm.shareStoreMode = !that.authForm.shareRange.length && that.authForm.shareStoreMode > 0 ? '' : String(that.authForm.shareStoreMode); // 0 全部 1部分分组 2 部分门店
      that.authForm.bindStoreMode = !that.authForm.bindRange.length && that.authForm.bindStoreMode > 0 ? '' : String(that.authForm.bindStoreMode);
    },
    /**
     * @description: 选择商户，获取审核管理员
     * @param {Object} item
     * @returns {Boolean}
     * @author: 无尘
     */
    getAdmin(item) {
      const that = this;
      if (that.authForm.enterpriseId == item.enterpriseId) {
        return false;
      }
      that.syncData = item; // 显示检验姓名弹窗
      that.checkShow = true;
      that.authForm.enterpriseId = '';
      that.authForm.enterpriseName = '';
      that.authForm.bindRange = [];
      that.authForm.shareRange = [];
      that.authForm.shareStoreMode = '';
      that.authForm.bindStoreMode = '';
      that.adminList = [];
      that.getAdminList(item.enterpriseId);
    },
    getAdminList(val) {
      const that = this;
      getGicAdmin({ enterpriseId: val })
        .then(res => {
          if (!!res.result && !!res.result.length) {
            that.adminList = res.result || [];
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 改变步骤
     * @param {String} auditReason
     * @author: 无尘
     */
    changeStep(auditReason) {
      const that = this;
      that.authForm.auditReason = emojiToStr(auditReason);
      const para = {
        enterpriseId: that.authForm.enterpriseId,
        wxEnterpriseId: that.wxEnterpriseId,
        shareRange: that.authForm.shareStoreMode > 0 ? that.authForm.shareStoreMode == 1 ? that.authForm.shareRange.map(ele=>ele.storeGroupId).join(',') : that.authForm.shareRange.map(ele=>ele.storeInfoId).join(',') : '',
        bindRange: that.authForm.bindStoreMode > 0 ? that.authForm.bindStoreMode == 1 ? that.authForm.bindRange.map(ele=>ele.storeGroupId).join(',') : that.authForm.bindRange.map(ele=>ele.storeInfoId).join(',') : '',
        auditReason: that.authForm.auditReason,
        shareStoreMode: !that.authForm.shareRange.length && that.authForm.shareStoreMode > 0 ? '' : String(that.authForm.shareStoreMode), // 0 全部 1部分分组 2 部分门店
        bindStoreMode: !that.authForm.bindRange.length && that.authForm.bindStoreMode > 0 ? '' : String(that.authForm.bindStoreMode),
        auditorName: that.auditorName
      };
      postEnterpriseAuth(para)
        .then(res => {
          if (res.code == '0000') {
            that.activeStep = 2;
          }else {
            that.$message({
              message: res.message || '接口异常',
              type: 'warning'
            });
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 路由跳转
     * @param {String} path
     * @author: 无尘
     */
    changeRoute(path) {
      this.$router.push(path);
    },
    /**
     * @description: 获取商户是否选择所有信息
     * @author: 无尘
     */
    getEnterpriseData() {
      const that = this;
      getEnterpriseDetail({ enterpriseId: that.$route.query.enterpriseId || that.authForm.enterpriseId })
        .then(res => {
          that.isSelectAll = res.result.bindFlag;
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 获取编辑数据
     * @author: 无尘
     */
    getData() {
      const that = this;
      let para = {
        enterpriseId: that.$route.query.enterpriseId,
        wxEnterpriseId: that.wxEnterpriseId,
      };
      getAuthDetail(para)
        .then(res => {
          if (res.code == '0000') {
            if (!!res.result.bindRange) {
              res.result.bindRange = JSON.parse(res.result.bindRange);
            }else {
              res.result.bindRange = [];
            }
            if (!!res.result.shareRange) {
              res.result.shareRange = JSON.parse(res.result.shareRange);
            }else {
              res.result.shareRange = [];
            }
            that.authForm = res.result || {};
            // 获取审核员数据
            that.getAdminList(res.result.enterpriseId);
          }
        })
        .catch(function(error) {

        });
    }
  }
};
</script>
<style type="text/less" lang="less" scoped>
.w-267 {
  width: 267px;
}

.m-t-35 {
  margin-top: 35px;
}

.common-bottom-border {
  cursor: pointer;
  padding-bottom: 2px;
  border-bottom: 1px dashed #2f54eb;
}

.el-input-group__prepend {
  display: inline-block;
  width: 86px;
  height: 32px;
  line-height: 32px;
  vertical-align: top;
  border-color: #c4c6cf;
}
.select-search-input {
  display: inline-block;
  margin-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;
  }
}

.my-customer-wrap {
  height: 100%;
  .w-227 {
    width: 227px;
  }
  .auth-tip-body {
    width: 645px;
    margin: 0 auto;
  }
  .enterprise-version {
    display: inline-block;
    vertical-align: top;
    width: 76px;
    height: 32px;
    margin-right: -1px;
    background: rgba(245,247,250,1);
    border-radius: 2px 0px 0px 2px;
    border: 1px solid rgba(196,198,207,1);
    border-right: 0px;
    font-size: 14px;
    color: #c0c4cc;
    text-align: center;
  }
  .store-item-content {
    position: relative;
    width: 350px;
    height: 32px;
    overflow: hidden;
    white-space: nowrap;
    border-radius: 2px;
    border: 1px solid #c4c6cf;
    cursor: pointer;
    box-sizing: border-box;
    .el-select__tags {
      max-width: 348px;
      white-space: nowrap;
      overflow: hidden;
    }
  }
}
.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 {
        width: 100%;
        padding: 20px;
        background: #fff;
        .common-set-wrap {
          height: 100%;
          background: #fff;
        }
      }
    }
  }
}


</style>
