<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-03-20 14:36:37
 * @LastEditors: 无尘
 * @LastEditTime: 2020-10-23 16:34:17
 -->
<template>
  <div class="my-customer-wrap common-set-wrap">
    <nav-crumb :navpath="navpath"> </nav-crumb>
    <div class="right-content">
      <div class="apps-content-right border-box">
        <el-form :model="adminForm" :rules="rules" ref="adminForm" label-width="100px" >
          <el-form-item label="管理员" prop="adminList">
            <div v-if="$route.query.staffId">{{ adminName || '--'}}</div>
            <div v-if="!$route.query.staffId" class="admin-list-wrap">
              <div class="el-select store-item-content admin-select" @click="showAdmin">
                <div v-if="!!adminForm.adminList.length" class="el-select__tags">
                  <span style="display:block;">
                    <template v-for="(item, index) in adminForm.adminList">
                      <span class="el-tag el-tag--info el-tag--small" :key="index+'bind'">
                        <span class="el-select__tags-text">{{ item.levelName || '--' }}</span>
                        <i class="el-tag__close el-icon-close" @click.stop="delAdmin(index, adminForm.adminList)"></i>
                      </span>
                    </template>
                  </span>
                </div>
                <div v-if="!adminForm.adminList.length" class="add-admin-btn font-14 color-606266 cursor-pointer" @click="showAdmin">
                  <span class="iconfont icontianjiajiahaowubiankuang font-12"></span><span class="p-l-10">添加</span>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="资源范围" prop="enterpriseList">
            <el-table ref="multipleTable" v-loading="loading" :data="tableData" tooltip-effect="dark" style="width: 100%">
              <el-table-column label="商户名称" width="150">
                <template slot-scope="scope">
                  {{scope.row.enterpriseName || '--'}}
                </template>
              </el-table-column>
              <el-table-column label="授权范围">
                <template slot-scope="scope">
                  <el-radio v-model="scope.row.radio" label="1">授权</el-radio>
                  <div v-if="scope.row.radio==1" class="el-select store-item-content" @click="showAuth(scope.$index, scope.row)">
                    <div v-if="scope.row.bindStoreMode > 0" class="el-select__tags">
                      <span style="display:block;">
                        <template v-for="(item, index) in scope.row.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="delAuth(index, scope.row.bindRange)"></i>
                          </span>
                        </template>
                      </span>
                    </div>
                    <span v-if="scope.row.bindStoreMode < 0 || scope.row.bindStoreMode === '' || scope.row.bindStoreMode === null || ( scope.row.bindStoreMode > 0 && !scope.row.bindRange.length) " class="p-l-10 font-14 color-909399">添加授权范围</span>
                    <span v-if="scope.row.bindStoreMode == 0 && scope.row.bindStoreMode !== '' " class="p-l-10 font-14 color-909399">已选全部</span>
                  </div>
                  <el-radio class="m-l-10" v-model="scope.row.radio" label="2">不授权</el-radio>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item class="m-t-20" prop="">
            <el-button type="primary" :loading="loadBtn" @click="saveAdmin('adminForm')">确认{{ !!$route.query.staffId ? '编辑' : '新建' }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <select-admin :show-admin-flag="showAdminFlag" :select-admin="adminForm.adminList" @checkAdmins="checkAdmins"></select-admin>
    <select-admin-store :show-auth-flag="showAuthFlag" :enterprise-id="enterpriseId" :select-mode="selectMode" :range-data="rangeData" :bind-type="2"  @closeSet="closeSet"></select-admin-store>

    <!-- <vue-gic-footer></vue-gic-footer> -->
  </div>
</template>
<script>
import navCrumb from '@/components/nav/nav.vue';
import selectAdmin from '@/components/set/select-admin.vue';
import selectAdminStore from '@/components/set/select-admin-store.vue';
import fetch from '@/api/edit-admin.js';
const { getRoleRange, addAdmin } = fetch;
// import { _debounce } from '@/common/js/public';
import showMsg from '@/common/js/showmsg';
export default {
  name: 'EditAdminPage',
  components: {
    navCrumb,
    selectAdmin,
    selectAdminStore
  },
  data() {
    return {
      // 面包屑参数
      navpath: [
        {
          name: '管理员',
          path: '/admin-list'
        },
        {
          name: !!this.$route.query.staffId ? '编辑管理员' : '新建管理员',
          path: ''
        }
      ],
      wxEnterpriseId: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '',
      adminName: !!this.$route.query.staffName ? this.$route.query.staffName : '',
      adminForm: {
        adminList: [],
        enterpriseList: [],
      },
      rules: {
        adminList: [
          { type: 'array', required: true, message: '请选择管理员', trigger: 'change' },
        ],
        enterpriseList: [
          { type: 'array', required: true, message: '请选择授权范围', trigger: 'change' },
        ]
      },
      loadBtn: false,
      tableData: [ {
        // enterpriseId: '',
        // enterpriseName: '',
        // radio: '1',
        // bindStoreMode: '',
        // bindRange: [],
      } ],
      showAdminFlag: false, // 显示选择管理员
      showAuthFlag: false, // 显示右侧门店授权范围
      enterpriseId: '',
      selectMode: '', // 选择 全部、分组、门店
      rangeData: [], // 选择的数据
      editIndex: '',
      editRow: {
        bindRange: [],
        bindStoreMode: '',
        enterpriseId: '',
        enterpriseName: '',
        shareRange: [],
        shareStoreMode: ''
      }
    };
  },
  mounted() {
    const that = this;
    that.$emit('showAsideMenu', false);
    that.getTableList();
    if (that.$route.query.staffId) {
      that.adminForm.adminList = [
        {
          levelId: that.$route.query.staffId,
          levelName: that.$route.query.levelName
        }
      ];
    }
    document.documentElement.style.backgroundColor = '#f0f2f5';
  },
  destroyed() {
    document.documentElement.style.backgroundColor = '#fff';
  },
  methods: {
    /**
     * @description: 保存管理员
     * @param {String} formName
     * @author: 无尘
     */
    saveAdmin(formName) {
      const that = this;
      const arr = JSON.parse(JSON.stringify(that.tableData));
      let flag = true;
      arr.forEach(ele => {
        if (ele.radio == 2) {
          ele.bindStoreMode = '';
          ele.bindRange = '';
        }
        if (ele.radio == 1 && ele.bindStoreMode > 0 && ele.bindRange.length) {
          ele.bindGroupIds = ele.bindStoreMode == 1 ? ele.bindRange.map(ele => ele.storeGroupId).join(',') : '';
          ele.bindStoreIds =  ele.bindStoreMode == 2 ? ele.bindRange.map(ele => ele.storeInfoId).join(',') : '';
        }
        if(ele.radio == 1 && (ele.bindStoreMode > 0 && !ele.bindRange.length || ele.bindStoreMode === '' || String(ele.bindStoreMode) == 'null') ) {
          flag = false;
        }
      });
      arr.forEach(ele => {
        delete ele.bindRange;
      });
      if (!flag) {
        that.adminForm.enterpriseList = [];
      }else {
        that.adminForm.enterpriseList = arr;
      }
      that.loadBtn = true;
      that.$refs[formName].validate((valid) => {
        if (valid) {
          that.postSave(arr);
        } else {
          that.loadBtn = false;
          return false;
        }
      });
    },
    postSave(arr) {
      const that = this;
      let para = {
        roleId: that.$route.query.roleId,
        staffIds: that.$route.query.staffId || that.adminForm.adminList.map(ele => ele.levelId).join(','),
        enterpriseRange: JSON.stringify(arr),
        wxEnterpriseId: that.wxEnterpriseId
      };
      addAdmin(para)
        .then(res => {
          that.loadBtn = false;
          if (res.code == '0000') {
            showMsg.showmsg('保存成功', 'success');
            that.$router.push('/admin-list');
          }else {
            that.$message({
              message: res.message || '未知错误',
              type: 'warning'
            });
          }
        })
        .catch(function(error) {
          that.loadBtn = false;
        });
    },
    /**
     * @description: 显示选择管理员
     * @returns {Boolean}
     * @author: 无尘
     */
    showAdmin() {
      const that = this;
      // 编辑不可再选管理员
      if (that.$route.query.staffId) {
        return false;
      }
      that.showAdminFlag = true;
    },
    /**
     * @description: 删除已选管理员
     * @param {Number} index
     * @param {Array} arr
     * @author: 无尘
     */
    delAdmin(index, arr) {
      arr.splice(index, 1);
    },
    checkAdmins(res) {
      const that = this;
      that.showAdminFlag = false;
      if (res == 'close') {
        return false;
      }
      that.adminForm.adminList = res;
    },
    /**
     * @description: 显示授权
     * @param {Number} index
     * @param {Object} row
     * @author: 无尘
     */
    showAuth(index, row){
      const that = this;
      that.selectMode = '';
      that.editIndex = index;
      that.editRow = row;
      that.enterpriseId = row.enterpriseId;
      that.selectMode = row.bindStoreMode;
      that.rangeData = JSON.parse(JSON.stringify(row.bindRange)) || [];
      that.showAuthFlag = true;
    },
    closeSet(type, arr) {
      const that = this;
      that.showAuthFlag = false;
      that.selectMode = '';
      if (type == 'close') {
        return false;
      }
      that.editRow.bindStoreMode = String(type); // 0 全部 1部分分组 2 部分门店
      that.editRow.bindRange = JSON.parse(JSON.stringify(arr));

    },
    /**
     * @description: 删除已选授权
     * @param {Number} index
     * @param {Array} arr
     * @author: 无尘
     */
    delAuth(index, arr) {
      arr.splice(index, 1);
    },
    /**
     * @description: 路由跳转
     * @param {String} path
     * @author: 无尘
     */
    changeRoute(path) {
      this.$router.push(path);
    },

    /**
     * @description: 获取列表数据
     * @author: 无尘
     */
    getTableList() {
      const that = this;
      let para = {
        roleId: that.$route.query.roleId,
        staffId: that.$route.query.staffId,
        wxEnterpriseId: that.wxEnterpriseId
      };
      getRoleRange(para)
        .then(res => {
          if (!!res.result && !!res.result.length) {
            res.result.forEach(ele=> {
              ele.radio = (ele.bindStoreMode == null || ele.bindStoreMode === '') && (ele.bindRange == '[]' || ele.bindRange == '') || ele.bindStoreMode == -1 ? '2' : '1';
              if (!!ele.bindRange) {
                ele.bindRange = JSON.parse(ele.bindRange);
              }else {
                ele.bindRange = [];
              }
            });
          }
          that.tableData = res.result || [];
        })
        .catch(function(error) {

        });
    }
  }
};
</script>
<style type="text/less" lang="less" scoped>
.my-customer-wrap {
  height: 100%;
  .nav-wrap {
    padding-left: 0;
    background: #f0f2f5;
  }
  .apps-content-right {
    width: 100%;
    padding: 20px;
    .admin-list-wrap {
      .add-admin-btn {
        width: 114px;
        height: 32px;
        line-height: 32px;
        text-align: center;
        border: 1px solid rgba(228,231,237,1);

      }

    }
    .store-item-content {
      position: relative;
      display: inline-block;
      vertical-align: middle;
      width: 302px;
      height: 32px;
      line-height: 32px;
      overflow: hidden;
      white-space: nowrap;
      border-radius: 2px;
      border: 1px solid #c4c6cf;
      cursor: pointer;
      box-sizing: border-box;
      &.admin-select {
        border: none;
      }
      .el-select__tags {
        max-width: 348px;
        white-space: nowrap;
        overflow: hidden;
      }
    }
  }
}

</style>
