<template>
  <div class="page-contain"
       style="padding:0px 5px">
    <div class="people-options">
      <div>
        <van-tag round
                 v-for="(item, i) in defaultUsersSelect"
                 style="margin: 5px"
                 :key="i"
                 size="medium"
                 type="primary">
          {{ item }}
        </van-tag>
      </div>

      <van-icon name='add-o'
                class="add-icon"
                @click="handleMore" />
    </div>
    <van-popup v-model="showOrgPopup"
               position="bottom"
               get-container="#app"
               class="aws-org-popup">
      <top-nav title="选择人员"
               :showQuery="false"
               :backFunc="handleClose"></top-nav>
      <!-- <div style="border-bottom: 1px solid #e9e9e9; padding: 10px">
        选择人员
      </div> -->
      <van-search v-model="searchValue"
                  shape="round"
                  placeholder="请输入搜索关键词"
                  clearable
                  :style="{marginTop: paddingTop ? paddingTop + 'px' : '0'}"
                  @search="searchUsers" />
      <van-row style="height: 400px">
        <van-col span="12">
          <van-tree-select :items="depts"
                           :active-id.sync="activeIds"
                           height="400" />
        </van-col>
        <van-col span="12"
                 style="
            border-left: 1px solid #e9e9e9;
            height: 400px;
            overflow: scroll;
            font-size: 12px;
          ">
          <van-checkbox-group v-model="usersSelect">
            <van-checkbox shape="square"
                          icon-size="20px"
                          v-for="(item, i) in users"
                          :key="i"
                          :name="item.name"
                          style="padding: 5px"
                          @click="userClick(item)">{{ item.name + "（" + item.uid + "）" }}</van-checkbox>
          </van-checkbox-group>
        </van-col>
      </van-row>
      <div style="padding: 10px; border-top: 1px solid #e9e9e9">已选择人员
        <!-- <span v-if="defaultUsersSelectInfo.length===0"
              style="color:#b9b9b9">（历史选择记录）</span> -->
      </div>
      <div>
        <van-tag round
                 v-for="(item, i) in usersSelect"
                 style="margin: 5px"
                 :key="i"
                 closeable
                 size="medium"
                 type="primary"
                 @close="close(item)">
          {{ item }}
        </van-tag>
      </div>
      <div class="footer-btn2">
        <van-button @click="handleSure(true)"
                    type="info">确认({{ usersSelect.length }})</van-button>
        <van-button @click="handleSure(false)"
                    type="default">取消</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
export default {
  name: 'aws-org',
  props: {
    module: Object, // 模块，非必传， {moduleId:3102,type:'1','2','3',typeName:''} type用于区分同一模块中存在多个人员选择的情况,typeName为收集名称，
    indexNumber: Number, // 下标，返回给父组件
    sid: String, // sid
    onlyOne: Boolean, // 是否单选
    initActiveIds: Array, // 部门ID数组
    initUsersSelect: Array // 用户json包含userId、userName、email如[{userId: "xizhou.ye",userName: "叶锡洲",email: "xizhou.ye@longsys.com"}]
  },
  data () {
    return {
      showOrgPopup: false,
      searchValue: '',
      radio: '',
      activeIds: [],
      usersSelect: [],
      defaultUsersSelect: [], // 默认传进来的选择用户名称
      depts: [], // 部门列表
      users: [], // 所有用户列表
      usersSelectInfo: [],
      defaultUsersSelectInfo: [], // 默认传进来的选择的用户信息表
      paddingTop: localStorage.getItem('paddingTop'),
      curObj: null // 当前查询的保存常用的用户信息
    }
  },
  watch: {
    activeIds: {
      handler: function (depts) {
        this.users = []
        if (depts && depts.length !== 0) {
          depts.forEach((v) => {
            this.getUsers(v)
          })
        }
      },
      deep: true
    },
    defaultUsersSelectInfo: {
      handler: function (userInfo) {
        if (userInfo.length !== 0) {
          this.usersSelectInfo = []
        }
        this.initUserSelect(userInfo, true)
      },
      deep: true
    },
    usersSelectInfo: {
      handler: function (userInfo) {
        this.initUserSelect(userInfo, false)
      },
      deep: true
    }
  },
  created () {
    this.activeIds = this.initActiveIds || []
    this.defaultUsersSelectInfo = this.initUsersSelect || []
    // if (this.defaultUsersSelectInfo.length === 0) {
    //   this.getDefaultUser()
    // }
  },
  mounted () {
    this.getOrg('0')
  },
  methods: {
    // 手动刷新选择的部门
    refreshDeptId (deptIds) {
      this.activeIds = deptIds
    },
    // 手动刷新选择的用户
    refreshUser (users) {
      this.defaultUsersSelectInfo = users
    },
    initUserSelect (userInfo, isDefault) {
      if (userInfo.length !== 0) {
        let usersSelectName = []
        userInfo.forEach((v) => {
          usersSelectName.push(v.name)
        })
        if (isDefault) {
          this.defaultUsersSelect = usersSelectName
          this.usersSelect = usersSelectName
          this.usersSelectInfo = userInfo
        } else {
          this.usersSelect = usersSelectName
        }
      }
    },
    searchUsers () {
      this.getUsersByName(this.searchValue)
    },
    userClick (user) {
      if (this.onlyOne) {
        // 单选
        this.usersSelectInfo = [user]
        this.usersSelect = [user.name]
      } else {
        let find = this.usersSelectInfo.find((v) => v.id === user.id)
        if (find) {
          this.usersSelectInfo = this.usersSelectInfo.filter(
            (v) => v.id !== user.id
          )
        } else {
          this.usersSelectInfo.push(user)
        }
      }
    },
    close (name) {
      this.usersSelect = this.usersSelect.filter((v) => v !== name)
      this.usersSelectInfo = this.usersSelectInfo.filter(v => v.name !== name)
    },
    handleMore () {
      this.showOrgPopup = true
    },
    handleSure (status) {
      if (status) {
        this.defaultUsersSelect = this.usersSelect
        if (this.module) {
          this.saveDefaultUser()
        }
        this.$emit('orgClose', this.usersSelectInfo, this.indexNumber, status)
      } else {
        this.$emit('orgClose', [], this.indexNumber, status)
      }
      this.showOrgPopup = false
    },
    // 查询组织用户列表
    getOrg (id) {
      let param = {
        sid: this.$common.getUrlParams('sid') || this.sid,
        cmd: 'com.ls.apps.shr_api_tree_aws_org',
        id: id
      }
      this.$axios.get({
        domain: 'awsUrl',
        url: 'awsJd',
        data: param,
        success: function (res) {
          if (res.msg === 'Success') {
            let data = res.data || []
            if (data.length !== 0) {
              if (id === '0') {
                data.forEach((v) => {
                  this.depts.push({
                    id: v.id,
                    text: v.name,
                    children: []
                  })
                  this.getOrg(v.id)
                })
              } else {
                this.depts.map((m) => {
                  if (m.id === id) {
                    data.forEach((v) => {
                      m.children.push({
                        id: v.id,
                        text: v.name
                      })
                    })
                  }
                })
              }
            }
          }
        }.bind(this),
        error: function (res) {
          this.$toast.fail(res.msg)
        }.bind(this)
      })
    },
    // 根据部门查询用户列表
    getUsers (id) {
      let param = {
        sid: this.$common.getUrlParams('sid') || this.sid,
        cmd: 'com.ls.apps.shr_api_tree_aws_org',
        id: id
      }
      this.$axios.get({
        domain: 'awsUrl',
        url: 'awsJd',
        data: param,
        success: function (res) {
          if (res.msg === 'Success') {
            let data = res.data || []
            if (data.length !== 0) {
              data.forEach((v) => {
                if (v.type === 'department') {
                  this.getUsers(v.id)
                } else {
                  this.users.push(v)
                }
              })
            }
          }
        }.bind(this),
        error: function (res) {
          this.$toast.fail(res.msg)
        }.bind(this)
      })
    },
    // 根据名称查询用户列表
    getUsersByName (name) {
      let param = {
        sid: this.$common.getUrlParams('sid') || this.sid,
        cmd: 'com.ls.apps.shr_api_tree_query_user',
        param: name
      }
      this.$axios.get({
        domain: 'awsUrl',
        url: 'awsJd',
        data: param,
        success: function (res) {
          if (res.msg === 'Success') {
            let data = res.data || []
            this.users = data
          }
        }.bind(this),
        error: function (res) {
          this.$toast.fail(res.msg)
        }.bind(this)
      })
    },
    // 清除数据
    clear () {
      let obj = {
        searchValue: '',
        radio: '',
        activeIds: [],
        usersSelect: [],
        defaultUsersSelect: [], // 默认传进来的选择用户名称
        depts: [], // 部门列表
        users: [], // 所有用户列表
        usersSelectInfo: [],
        defaultUsersSelectInfo: [] // 默认传进来的选择的用户信息表
      }
      for (let key in obj) {
        this[key] = obj[key]
      }
    },
    handleClose () {
      this.showOrgPopup = false
    },
    // 新增操作查询默认用户
    getDefaultUser () {
      let that = this
      this.$axios.post({
        domain: 'crmUrl',
        url: 'collect.findCollect',
        data: {
          'collectId': '',
          'moduleId': this.module.moduleId
        },
        requestType: 'body',
        showLoad: false,
        success: function (res) {
          if (res.success) {
            let result = res.data || []
            let curObj = result.find(v => v.ext1 === that.module.type)
            if (curObj) {
              // that.usersSelectInfo = JSON.parse(curObj.collectData)
              that.defaultUsersSelectInfo = JSON.parse(curObj.collectData)
              that.curObj = curObj
            }
          } else {
            this.$toast.fail(res.msg)
          }
        }
      })
    },
    // 保存默认用户
    saveDefaultUser () {
      if (this.usersSelectInfo.length !== 0) {
        let param = {
          moduleId: this.module.moduleId, ext1: this.module.type, collectData: JSON.stringify(this.usersSelectInfo), collectName: this.module.typeName
        }
        if (this.curObj !== null) {
          param.id = this.curObj.id
        }
        this.$axios.post({
          domain: 'crmUrl',
          url: 'collect.saveCollect',
          data: param,
          requestType: 'body',
          showLoad: false,
          success: function (res) {
            if (res.errorCode === 200) {
            } else {
              this.$toast.fail(res.msg)
            }
          }.bind(this),
          error: function (res) {
            this.$toast.fail(res.msg)
          }
        })
      }
      // else {
      //   if (this.usersSelect.length === 0) {
      //     this.$toast('请选择人员！')
      //   }
      // }
    }
  }
}
</script>

<style lang="scss" >
.add-icon {
  color: #008cee;
}
.people-options {
  padding: 2px 0;
  display: flex;
  .item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #666;
    margin-right: 10px;
  }
  .icon-jia {
    font-size: 60px;
    color: #ddd;
  }
  .round {
    margin: 5px;
    padding: 0px 10px;
    display: inline-block;
    width: auto;
    min-width: 80px;
    height: 50px;
    background: #008cee;
    border-radius: 13.3rem;
    text-align: center;
    line-height: 50px;
  }
}

.aws-org-popup {
  height: 100%;
  padding-top: 82px;
  padding-bottom: 100px;

  .van-field__body {
    height: 60px;
  }
  .van-field__left-icon {
    line-height: 60px;
  }

  .result-item {
    padding: 20px;
    border-bottom: 1px solid #ddd;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .left {
      display: flex;

      > div {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-left: 20px;
      }
    }
  }
  .footer-tool {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 100px;
    border-top: 1px solid #ddd;
    display: flex;
    padding: 0 20px;
    align-items: center;
    .option {
      flex: 1;
      display: flex;
      height: 100%;
      align-items: center;
      margin-right: 20px;
      overflow: hidden;

      .item {
        position: relative;
        margin-right: 20px;

        .van-icon-clear {
          position: absolute;
          right: -10px;
          top: -4px;
          color: red;
          font-size: 16px;
          z-index: 999;
        }
      }
    }
  }
}
.van-tree-select__nav {
  -webkit-box-flex: 0;
  -webkit-flex: 0;
  flex: 0;
}
.van-tag--medium {
  padding: 10px;
}
.footer-btn2 {
  // position: fixed;
  // bottom: 50px;
  // left: 0;
  // right: 0;
  margin-top: 120px;
  margin-bottom: 100px;
  height: 100px;
  display: flex;
  .van-button {
    flex: 1;
    height: 100%;
  }

  .van-button--default {
    background: #f5f5f5;
    color: #008cee;
  }
}
.van-tree-select {
  height: 400px;
}
</style>
