<template>
  <div class="companyAddress-wrap common-set-wrap">
    <nav-crumb :navpath="navpath"></nav-crumb>
    <div class="right-content">
      <div class="right-box">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="管理员角色" prop="name" class="">
            <el-input v-model="ruleForm.name" disabled placeholder="" class="w-380"></el-input>
          </el-form-item>
          <el-form-item label="选择人员" prop="name" class="">
            <div class="flex w-380 flex-wrap">
              <template v-for="(item,index) in ruleForm.peopleList">
                <div class="people-cell">
                  <img :src="item.headPic"/>
                  <p>{{item.name}}</p>
                  <i class="el-icon-circle-close" @click.stop="delField(index,item,ruleForm.peopleList)"></i>
                </div>
              </template>
              <div class="people-cell">
                <span class="add-icon" @click.stop="showDialogLayer('people',ruleForm.peopleList)"><i class="el-icon-plus"></i></span>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="选择管理范围" prop="name" class="m-b-0">
            <div class="flex w-380 flex-column item-cell-select">
              <!-- <template v-for="(item,index) in ruleForm.departList">
                <el-tag class="depart-cell">{{item.name}} <i class="el-icon-circle-close" @click.stop="delField(index,item,ruleForm.departList)"></i></el-tag>
              </template>
              <el-button class="el-tag m-l-8 depart-cell" @click.stop="showDialogLayer('depart')"><i class="el-icon-plus"></i>添加字段</el-button> -->
              <div>行政架构</div>
              <div class="depart-item-wrap">
                <div class="el-select el-select--large depart-item-content" @click="showDialogLayer('depart',ruleForm.departList)">
                  <div class="el-select__tags" style="max-width: 181px;">
                    <span>
                      <template v-for="(item,index) in ruleForm.departList">
                        <span class="el-tag el-tag--info el-tag--small" :key="index">
                          <span class="el-select__tags-text">{{item.name}}</span><i class="el-tag__close el-icon-close" @click.stop="delDepart(index,ruleForm.departList)"></i>
                        </span>
                      </template>
                    </span>
                  </div>
                </div>

              </div>
              <div>门店架构</div>
              <div class="store-item-wrap">
                <el-select v-model="ruleForm.brandValue" multiple placeholder="请选择">
                  <el-option
                    v-for="item in ruleForm.brandOptions"
                    :key="item.brandId"
                    :label="item.name"
                    :value="item.brandId">
                  </el-option>
                </el-select>
              </div>
            </div>
          </el-form-item>
          <el-form-item class="m-t-24">
            <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <vue-gic-footer></vue-gic-footer>
    <vue-select-employee
      :defaultSelection="defaultSelection"
      :treeSet="treeSet"
      :treeData="treeData"
      :onlyPerson="onlyPerson"
      @handleSelectedList="handleSelectedList">

    </vue-select-employee>
  </div>
</template>
<script>
import navCrumb from '@/components/nav/nav.vue';
import vueSelectEmployee from '@/components/common/vueSelectEmployee.vue';

import strLength from '@/common/js/strlen';
import showMsg from '@/common/js/showmsg';
import errMsg  from '@/common/js/error';
import { _debounce } from "@/common/js/public";
import { getRequest, postRequest, postJson, postForm } from '@/api/api';
export default {
  name: "addAdminRole",
  data() {

    return {
      // 面包屑参数
      navpath: [
        {
          name: '首页',
          path: '/index',
          relocation: true
        },
        {
          name: '设置',
          path: '/companyAddress'
        },
        {
          name: '设置子管理员',
          path: '/setChildAdmin'
        },
        {
          name: '添加成员',
          path: ''
        }
      ],

      ruleForm: {
        roleId: '',
        name: '企业管理员',
        peopleList: [
          // {
          //   id: '1',
          //   name: '张三',
          //   headPic: 'http://thirdwx.qlogo.cn/mmopen/j7nX4OeBsXRNyvh6micCywssVEYCaWiaicUZq5Vn2zWktWLAyRvEAH7icQmUhLze8rrQYpM5ptwZ2RL7cX0icyBbiavhYFNTIZhibKu/0'
          // }
        ],
        departList: [
          // {
          //   id: '1',
          //   name: '张三张三',
          // },
          // {
          //   id: '2',
          //   name: '张三张三',
          // },
          // {
          //   id: '3',
          //   name: '张三张三',
          // }
        ],
        brandValue: [],
        brandOptions: [
          // {
          //   name: 'A品牌',
          //   brandId: '1',
          // }
        ]
      },
      rules: {

      },

      treeSet: {
        isSelectPerson: true, // 控制只能选部门(false)
        dialogVisible: false, // 控制显示/隐藏
        isSingle: false // 是否单选
      },
      treeData: {},
      defaultSelection: [],
      onlyPerson: false, // 控制只能选人(true)

      selectType: '',
    }
  },
  computed: {

  },
  methods: {
    /**
     * 路由跳转
     */
    changeRoute(route) {
      this.$router.push(route);
    },

    /**
     * 保存
     */
    submitForm: _debounce(function(formName) {
      const that = this;
      that.$refs[formName].validate((valid) => {
        console.log(valid)
        if (valid) {
          let data = []
          let clerks = JSON.stringify(that.ruleForm.peopleList.map(item=>item.userId))
          that.postSave(data,clerks)
        } else {
          return false;
        }
      });
    },500),

    /**
     * 保存---api
     */
    postSave(data,clerks) {
      const that = this;
      let para = {
        data: data,
        roleId: that.ruleForm.roleId,
        clerks: clerks
      }

      postRequest('/haoban-manage-web/save-clerk-role',para)
      .then((res) => {
        // console.log(res,res.data,res.data.errorCode)
        var resData = res.data;
        if (resData.errorCode == 1) {
          showMsg.showmsg('操作成功','success')

          return;
        }

        errMsg.errorMsg(resData)

      })
      .catch(function (error) {
        console.log(error);

        that.$message.error({
          duration: 1000,
          message: error.message
        })
      });
    },

    /**
     * 删除字段
     */
    delField(index,item,list) {
      const that = this
      that.$alert('确定要删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        list.splice(index,1)
      }).catch(() => {

      });
    },

    /**
     * 删除选的部门
     */
    delDepart(index,item) {
      const that = this;
      item.splice(index,1)
    },

    /**
     * 弹窗显示事件
     */
    showDialogLayer(type,selData) {
      const that = this;

      console.log(type,selData)

      that.selectType = type;

      if (type === 'people') {
        that.onlyPerson = true;
      }else {
        that.onlyPerson = false;
      }

      that.treeSet = {
                    dialogVisible: true,
                    isSingle: false,
                    isSelectPerson: true
                };
      that.getDepartData(selData);
    },

    /**
     * 处理已选部门
     */
    handleSelectedList(group) {
      console.log(group);
      const that = this;

      if (that.selectType === 'people') {
        that.ruleForm.peopleList = group
      }else {
        that.ruleForm.departList = group
      }
    },

    /**
     * 获取行政架构
     */
    getDepartData(selData) {
      const that = this;
      postRequest('/haoban-manage-web/dept/deptListForCompany',{})
      .then((res) => {
        // console.log(res,res.data,res.data.errorCode)
        let resData = res.data;
        if (resData.errorCode == 1) {
          // showMsg.showmsg('操作成功','success')
          if (!!resData.result) {
            let treeData = [];
            let personData = [];
            if (res.data.errorCode == 1) {
                treeData = res.data.result.departmentList || [];
                personData = res.data.result.searchList || []
            }
            // _this.formatGroupData(treeData, personData);
            that.treeData = {
                treeData,
                personData
            };

            that.defaultSelection = selData;
          }else {
            that.$message.error({
              duration: 1000,
              message: '暂无数据'
            })
          }
          return;
        }

        errMsg.errorMsg(resData)

      })
      .catch(function (error) {
        console.log(error);

        that.$message.error({
          duration: 1000,
          message: error.message
        })
      });
    },

    /**
     * 获取品牌--门店架构
     */
    getBrandData() {
      const that = this;
      postRequest('/haoban-manage-web/brand/list',{})
      .then((res) => {
        // console.log(res,res.data,res.data.errorCode)
        let resData = res.data;
        if (resData.errorCode == 1) {
          // showMsg.showmsg('操作成功','success')
          if (!!resData.result && !!resData.result.length ) {
            that.ruleForm.brandOptions = resData.result
          }else {
            that.$message.error({
              duration: 1000,
              message: '暂无数据'
            })
          }
          return;
        }

        errMsg.errorMsg(resData)

      })
      .catch(function (error) {
        console.log(error);

        that.$message.error({
          duration: 1000,
          message: error.message
        })
      });
    }

  },
  mounted() {
    const that = this;
    that.getBrandData()
    if (!!that.$route.query.hasOwnProperty('roleId')) {
      that.ruleForm.roleId = that.$route.query.roleId;
      // that.getRoleDetail(that.ruleForm.roleId)
    }
  },
  components: {
    navCrumb,
    vueSelectEmployee
  }
}

</script>
<style lang="less" scoped>
.border-box {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

/* display */
.inline-block {
  display: inline-block;
}

.block {
  display: block;
}

.top {
  vertical-align: top;
}

.middle {
  vertical-align: middle;
}

/* flex */
.flex {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
}

.flex-1 {
  -webkit-box-flex: 1;
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
}

.flex-column {
  -webkit-flex-direction: column;
  -moz-flex-direction: column;
  -ms-flex-direction: column;
  -o-flex-direction: column;
  flex-direction: column;
}

.flex-row {
  -webkit-flex-direction: row;
  -moz-flex-direction: row;
  -ms-flex-direction: row;
  -o-flex-direction: row;
  flex-direction: row;
}

.flex-align-center {
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
}

.flex-pack-center {
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
}

.flex-between {
  -webkit-justify-content: space-between;
  justify-content: space-between;
}

.flex-wrap {
  -webkit-flex-wrap: wrap;
  -moz-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  -o-flex-wrap: wrap;
  flex-wrap: wrap;
}

.right-content {
  /*width: 100%;*/
  padding: 24px;
  min-height: calc(100% - 240px);

  .right-box {
    background: #fff;
    padding: 24px;
    min-height: 500px;

    h2 {
      font-size: 16px;
      color: #303133;
    }

    p {
      font-size: 14px;
      color: #909399;
    }

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

    .m-b-0 {
      margin-bottom: 0;
    }

    .w-380 {
      width: 380px;
    }

    .people-cell {
      position: relative;
      margin-right: 24px;
      img {
        width: 40px;
        height: 40px;
        border-radius: 4px;
      }

      .el-icon-circle-close {
        position: absolute;
        top: -10px;
        right: -10px;
        font-size: 16px;
        color: #808995;
        cursor: pointer;
      }
    }

    .depart-item-content {
      width: 213px;
      height: 32px;
      overflow: hidden;
      white-space: nowrap;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      cursor: pointer;
    }

    .item-cell-select {
      /deep/ .el-select__tags {
        white-space: nowrap;
        overflow: hidden;
      }
    }

    .depart-cell {
      position: relative;
      margin: 0 24px 24px 0;

      .el-icon-circle-close {
        position: absolute;
        top: -10px;
        right: -10px;
        font-size: 16px;
        color: #808995;
        cursor: pointer;
      }
    }

    .add-icon {
      display: block;
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      border-radius: 50%;
      border: 1px dashed #C0CCDA;
      cursor: pointer;
      i {
        font-size: 16px;
        color: #8C939D;
      }
    }
  }
}
</style>
