<template>
  <div class="common-set-wrap">
    <nav-crumb :navpath="navpath"></nav-crumb>
    <div class="right-content">
      <div class="right-box">
        <div class="administrative-estrutura-container">
          <template v-if="menuData.length > 0">
            <search-menu @handleSearchKey="handleSearchKey" @handleTreeSelection="handleTreeSelection" :treeData="menuData" :searchResult="searchResult" @handleEmployeeSelection="handleEmployeeSelection" @getEmployeeFirst="getEmployeeFirst">
            </search-menu>
            <employee-info v-if="showEmployee == 'employee'" :info="selectedEmployee"></employee-info>
            <!-- <div class="af-right-container" v-loading="loading" v-else-if="groupInfo.level !=0 || groupInfo.isStoreGroup != 1 || !groupInfo.isMine"> -->
            <div class="af-right-container" v-loading="loading" v-else>
              <div class="af-right-header">
                <span class="title-span">{{groupInfo.groupName}}（{{total}}人）<span class="not-show-app">本企业通讯录APP中不展示</span></span>
                <template v-if="!!groupInfo.isMine">
                  <span class="handle-area" v-if="groupInfo.isStoreGroup == 1">
                    <a class="a-href" @click="dlgTitle = '分组'; dlgShow = true;">添加子分组</a>
                    <span class="hurdle"></span>
                    <a @click="dlgTitle = '分组'; editDlgShow = true;" class="J_edit a-href" v-if="groupInfo.level != 0">编辑</a>
                  </span>
                  <span class="handle-area" v-else>
                    <a @click="dlgTitle = '部门'; dlgShow = true;" class="J_add-child a-href">添加子部门</a>
                    <template v-if="groupInfo.level != 0">
                      <span class="hurdle"></span>
                      <a @click="dlgTitle = '部门'; editDlgShow = true;" class="J_edit a-href">编辑</a>
                    </template>
                  </span>
                </template>
                <template v-else><a class="a-href fr">设置可见权限</a></template>
              </div>
              <template v-if="employeeList.length > 0">
                <div class="af-right-button-box">
                  <template v-if="!!groupInfo.isMine">
                    <el-button v-if="groupInfo.isStoreGroup == 1" type="primary" @click="$refs.storeSelector.treeSet.dialogVisible = true;sldType = 2;">添加门店</el-button>
                    <el-button v-else type="primary" @click="callEmployeeSelector" :disabled="disabled">添加成员</el-button>
                    <el-button type="danger" plain @click="delMembers" :disabled="disabledDel">批量删除</el-button>
                  </template>
                  <el-button class="J_show-children">
                    <el-checkbox class="m-r-10" v-model="showChildMember" @change="setChildMemberShow"></el-checkbox><a class="a-href">显示子成员</a>
                  </el-button>
                </div>
                <clerk-view v-if="groupInfo.isStoreGroup == 1" :tableData="employeeList" @selectMember="selectMember"></clerk-view>
                <employee-list v-else :employeeList="employeeList" @selectMember="selectMember"></employee-list>
                <div class="pagination">
                  <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[20, 40, 60, 80]" :page-size="pageSize" :current-page="currentPage" layout="total, sizes, prev, pager, next" :total="total">
                  </el-pagination>
                </div>
              </template>
              <template v-else>
                <div class="af-right-button-box">
                  <template v-if="!!groupInfo.isMine">
                    <el-button v-if="groupInfo.isStoreGroup == 1" type="primary" @click="$refs.storeSelector.treeSet.dialogVisible = true;sldType = 2;">添加门店</el-button>
                    <el-button v-else type="primary" @click="callEmployeeSelector" :disabled="disabled">添加成员</el-button>
                  </template>
                  <el-button class="J_show-children">
                    <el-checkbox class="m-r-10" v-model="showChildMember" @change="setChildMemberShow"></el-checkbox><a class="a-href">显示子成员</a>
                  </el-button>
                </div>
                <add-new-guid :groupInfo="groupInfo" @addEmployee="callEmployeeSelector" @addStoreEmployee="$refs.storeSelector.treeSet.dialogVisible = true;sldType = 2;"></add-new-guid>
              </template>
            </div>
            <!-- <div class="af-right-container" v-else-if="groupInfo.isStoreGroup == 1 && groupInfo.level == 0 && !!groupInfo.isMine">
              <p style="margin: 20px 0;">是否共享门店及成员数据</p>
              <el-checkbox v-model="shareSale">销售数据</el-checkbox>
              <el-checkbox v-model="shareMember">会员数据</el-checkbox>
              <div style="margin: 20px 0;">
                <el-button type="primary" @click="subShareSet">确定</el-button>
              </div>
            </div> -->
            <!-- <permission-set :groupInfo="groupInfo"></permission-set> -->
          </template>
          <template v-else>
            <guid-div></guid-div>
          </template>
        </div>
      </div>
    </div>
    <el-dialog :title="'添加子' + dlgTitle" :visible.sync="dlgShow" width="30%">
      <div style="padding: 30px;">
        <el-input v-model="newGroupName" :placeholder="'请输入'+dlgTitle+'名称'"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dlgShow = false">取 消</el-button>
        <el-button type="primary" @click="subSonGroupAdd">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="'编辑' + dlgTitle" :visible.sync="editDlgShow" width="30%">
      <div style="padding: 30px;">
        <el-input v-model="newGroupName" :placeholder="'请输入'+dlgTitle+'名称'"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dlgShow = false">取 消</el-button>
        <el-button type="primary" @click="subSonGroupAdd(true)">确 定</el-button>
      </span>
    </el-dialog>
    <vue-select-employee ref="selectEmployee" :onlyPerson="true" @handleSelectedList="handleSelectedList" :treeData="treeData"></vue-select-employee>
    <!-- <vue-select-store ref="storeSelector" @handleSelectedList="handleSelectedList"></vue-select-store> -->
  </div>
</template>
<script>
import navCrumb from '@/components/nav/nav.vue';
import searchMenu from "components/contacts/share/searchMenu";
import employeeInfo from "components/contacts/employeeInfo";
import employeeList from "components/contacts/share/employeeList";
import clerkView from "components/contacts/share/clerkView";
import guidDiv from "components/contacts/share/guid";
import addNewGuid from "components/contacts/share/addNewGuid";
import { getRequest, postRequest, postJsonRequest, postJson } from '@/api/api';
import vueSelectEmployee from "components/common/vueSelectEmployee";
import vueSelectStore from "components/common/vueSelectStore";
import permissionSet from "components/contacts/share/permissionSet";
export default {
  name: "shareContact",
  components: {
    navCrumb,
    searchMenu,
    employeeInfo,
    employeeList,
    guidDiv,
    clerkView,
    vueSelectEmployee,
    vueSelectStore,
    permissionSet,
    addNewGuid
  },
  data() {
    return {
      // 面包屑参数
      navpath: [{
          name: '首页',
          path: '/index'
        },
        {
          name: '企业通讯录',
          path: '/administrativeFrame'
        },
        {
          name: '共享通讯录',
          path: ''
        }
      ],
      showChildMember: false,
      setDisabledDel: false,
      menuData: [],
      pageSize: 20,
      currentPage: 1,
      selectedList: [],
      total: 0,
      loading: true,
      groupInfo: {
        groupName: "",
        departmentId: ""
      },
      employeeList: [],
      searchResult: {},
      showEmployee: false,
      selectedEmployee: {},
      sharedContactRelationId: [],
      shareMember: false,
      shareSale: false,
      disabled: true,
      treeData: {},
      sldType: 1,
      dlgTitle: "",
      dlgShow: false,
      editDlgShow: false,
      newGroupName: ""
    };
  },
  created() {},
  beforeMount() {
    this.getShareRelation();
  },
  methods: {
    subSonGroupAdd(edit) {
      let ths = this;
      let newGroupName = ths.newGroupName;
      if (newGroupName == "") {
        ths.$message.error({
          message: "名称不能为空"
        });
      } else {
        let params = {
          parentSharedContactGroupId: edit ? ths.groupInfo.parentId : ths.groupInfo.id,
          name: ths.newGroupName
        };
        if (edit) {
          params.sharedContactGroupId = ths.groupInfo.id;
        }
        getRequest("/haoban-manage-web/shared-contact/set-shared-group", params)
        .then(res => {
          if (res.data.errorCode == 1) {
            ths.$message.success({
              message: res.data.message
            });
            ths.getShareRelation();
            ths.dlgShow = false;
            ths.editDlgShow = false;
          } else {
            ths.$message.error({
              message: res.data.message
            });
          }
        })
        .catch(e => {
          ths.$message.error({
            message: e.message
          });
        });
      }
    },
    callEmployeeSelector() {
      this.sldType = 1;
      this.$refs.selectEmployee.treeSet.dialogVisible = true;
    },
    handleStoreSelectedList() {},
    handleSelectedList(list) {
      let ths = this;
      let arr = [];
      list.forEach(item => {
        arr.push({
          id: item.id,
          type: ths.sldType
        });
      });
      let params = {
        overwrite: true,
        sharedContactMemberList: [
          {
            sharedContactGroupId: ths.groupInfo.id,
            memberList: arr
          }
        ]
      }
      postJson("/haoban-manage-web/shared-contact/add-shared-member", params)
      .then(res => {
        if (res.data.errorCode == 1) {
          ths.$message.success({
            message: res.data.message
          });
          ths.getEmployee();
        } else {
          ths.$message.error({
            message: res.data.message
          });
        }
      })
      .catch(e => {
        ths.$message.error({
          message: e.message
        });
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getEmployee();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getEmployee();
    },
    /**
     * 设置是否共享门店及成员数据
     */
    subShareSet() {
      let _this = this;
      let params = {
        visibleData: {
          shareMember: _this.shareMember * 1,
          shareSale: _this.shareSale * 1,
          sharedContactRelationId: _this.sharedContactRelationId.join(",")
        }
      };
      postJson("/haoban-manage-web/shared-contact/set-shared-store-visible-data", params)
      .then(res => {
        _this.$message.error({
          message: res.data.message
        });
      })
      .catch(e => {
        _this.$message.error({
          message: e.message
        });
      });
    },
    /**
     * 树形菜单搜索
     */
    handleSearchKey(keyWord) {
      let params = {
        keyWord
      };
      getRequest("/haoban-manage-web/emp/searchpage", params)
        .then(res => {
          console.log(res, "search result");
          this.searchResult = res.data.result;
        })
        .catch(e => {
        });
    },

    /**
     * 树形菜单选择项处理
     */
    handleTreeSelection(obj, node, showEmployee) {
      console.log(obj, node, "selection");
      this.groupInfo = obj;
      this.groupInfo.departmentId = obj.id;
      this.groupInfo.groupName = obj.name;
      this.showEmployee = showEmployee;
      this.loading = true;
      this.getEmployee();
    },
    /**
     * 树形搜索结果选人处理
     */
    handleEmployeeSelection(employee, showEmployee) {
      this.selectedEmployee = employee;
      this.showEmployee = showEmployee;
    },
    /**
     * table选择员工
     */
    selectMember(selection) {
      this.selectedList = selection;
    },
    /**
     * 批量删除成员
     */
    delMembers() {
      let _this = this;
      _this.$confirm("是否要删除选中的员工？", "提示", {
        type: "warning"
      }).then(() => {
        let arr = [];
        _this.selectedList.forEach(li => {
          arr.push(li.sharedContactEmployeeStoreId);
        });
        let params = {
          sharedContactEmployeeStoreIdList: arr
        }
        postJson("/haoban-manage-web/shared-contact/del-shared-member", params)
          .then(res => {
            if (res.data.errorCode == 1) {
              _this.$message.success({
                message: res.data.message
              });
              _this.getEmployee();
            } else {
              _this.$message.error({
                message: res.data.message
              });
            }
          })
          .catch(e => {
            _this.$message.error({
              message: e.message
            });
          });
      })
    },

    /**
     * 设置是否显示子成员
     */
    setChildMemberShow() {
      this.getEmployee();
    },

    /**
     * 获取分组架构
     */
    getGroupData(fn) {
      let _this = this;
      let params = {
        isStoreGroup: 0
      };
      getRequest("/haoban-manage-web/shared-contact/find-shared-group", {})
        .then(res => {
          res.data.result.forEach(li => {
            li.groupId = li.sharedContactGroupId;
          });
          _this.menuData = res.data.result || [];
          _this.menuData.some(li => {
            if (li.level == 0) {
              _this.groupInfo.departmentId = li.groupId;
              _this.groupInfo.groupName = li.name;
            }
            return li.level == 0;
          });
          _this.getEmployee();
          _this.getRelationIds( _this.menuData);
        })
        .catch(e => {
        });
    },
    getRelationIds(data) {
      let userInfo = window.localStorage.getItem("userInfo");
      let enterpriseId = JSON.parse(userInfo).enterpriseId;
      let arr = [];
      data.forEach(group => {
        if (group.level == 0) {
          if (group.enterpriseId != enterpriseId) {
            arr.push(group.enterpriseId);
          }
        }
      });
      arr = [...new Set(arr)];
      this.sharedContactRelationId = arr;
    },
    getShareRelation() {
      let ths = this;
      getRequest("/haoban-manage-web/shared-contact/find-shared-contact-relation", {searchGroup: 1})
      .then(res => {
        console.log(res, "getShareRelation");
        ths.menuData = res.data.result || [];
      }).catch(e => {
        ths.$message.error({
          message: e.message
        });
      });
    },
    /**
     * 获取员工列表
     */
    getEmployeeFirst(obj) {
      this.groupInfo = obj;
      this.getEmployee();
    },
    getEmployee() {
      let _this = this;
      let params = {
        sharedContactGroupId: _this.groupInfo.id,
        findChildren: _this.showChildMember,
      };
      postJson("/haoban-manage-web/shared-contact/find-shared-member", params)
        .then(res => {
          let list = [];
          let total = 0;
          if (res.data.errorCode == 1) {
            list = res.data.result.list || [];
            total = res.data.result.pageInfo.total || 0;
          }
          _this.employeeList = list;
          _this.total = total;
          _this.loading = false;
        })
        .catch(e => {
          _this.loading = false;
        });
    }
  },
  computed: {
    disabledDel() {
      return this.selectedList.length < 1 && !this.setDisabledDel;
    }
  }
};

</script>
<style lang="scss">
.administrative-estrutura-container {
  display: flex;

  .af-right-container {
    height: 690px;
    background: #fff;
    flex: 1;
    padding: 0 24px;

    .af-right-header {
      height: 70px;
      line-height: 70px;
      font-weight: 400;
      font-size: 14px;
      color: #606266;

      .title-span {
        color: #303133;
        font-size: 20px;

        .not-show-app {
          font-size: 14px;
          color: rgba(144, 147, 153, 1);
        }
      }

      .handle-area {
        float: right;

        .hurdle {
          width: 1px;
          height: 16px;
          display: inline-block;
          background: #DCDFE6;
          margin: 0 10px;
          vertical-align: sub;
        }
      }
    }

    .af-right-button-box {
      padding: 8px 15px;
      background: #EBEEF5;
    }

    .pagination {
      margin-top: 30px;
      text-align: right;
    }

    .status-icon {
      width: 34px;
      height: 32px;
      line-height: 32px;
      text-align: center;
      background: #ECF5FF;
      border: 1px solid #D9ECFF;
      border-radius: 4px;

      &.is-active {
        .iconfont {
          color: #409EFF;
        }
      }
    }
  }
}

</style>
