<template>
  <div class="bf-rolelist">
    <!-- 角色列表 -->
    <div class="cont">
      <div v-if="title" class="paren_header">
        <p>{{ title }}</p>
      </div>
      <template v-if="dataList.length">
        <div :class="active ? 'bgActive' : 'bgActivecheckbox'" class="paren_content">
          <template v-if="!type">
            <el-scrollbar class="scrollBar" style="height: 100%">
              <el-row v-infinite-scroll="load" :infinite-scroll-distance="20" infinite-scroll-disabled="disabled" class="scCont scrollbar" :gutter="16">
                <el-checkbox-group @change="checkChange" v-model="checkList">
                  <el-col :span="number" v-for="(item, index) in dataList" :key="index">
                    <div @click="handleBg(item, index)" :class="active && msg === index ? 'bgColor' : ''" class="cide">
                      <div class="cide_header">
                        <p :title="item.name">{{ item.name }}</p>
                        <el-checkbox :label="index"></el-checkbox>
                      </div>
                    </div>
                  </el-col>
                </el-checkbox-group>
              </el-row>
            </el-scrollbar>
          </template>
          <template v-if="total > 1">
            <p class="center" v-if="loading">加载中...</p>
            <p class="center" v-if="noMore">没有更多数据了~</p>
          </template>
        </div>
      </template>
      <template v-else-if="mainData.length">
        <div :class="active ? 'bgActive' : 'bgActivecheckbox'" class="paren_content">
          <template v-if="type">
            <el-scrollbar class="scrollBar" style="height: 100%">
              <el-row :gutter="16">
                <el-radio-group style="display: block" @change="radioChange" v-model="radio">
                  <el-col :span="number" v-for="(item, index) in mainData" :key="index">
                    <div @click.stop="handleBg(index)" :class="active && msg === index ? 'bgColor' : ''" class="cide">
                      <div class="cide_header">
                        <p>{{ item.name }}</p>
                        <el-radio :label="index"></el-radio>
                      </div>
                    </div>
                  </el-col>
                </el-radio-group>
              </el-row>
            </el-scrollbar>
          </template>
        </div>
      </template>
      <template v-else>
        <el-empty :imageSize="imageSize" description="暂无数据"></el-empty>
      </template>
    </div>
  </div>
</template>
<script>
import { GetAccountList } from '@/api/Account'
import { GetRoleByGroup } from '@/api/AccountGroup'
import { QueryRole } from '@/api/apiAuthority'
export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    type: {
      type: Boolean,
      default: false
    },
    number: {
      type: Number,
      default: 3
    },
    active: {
      type: Boolean,
      default: false
    },
    checkBoxList: {
      type: Array,
      default: () => []
    },
    mainData: {
      type: Array,
      default: () => []
    },
    radioCheck: {
      type: Number,
      default: 0
    },
    imageSize: {
      type: Number,
      default: 200
    },
    roleType: {
      type: String,
      default: ''
    },
    needType: {
      type: String,
      default: ''
    },
    queryAll: {
      type: String,
      default: ''
    },
    needId: [String, Number],
    GroupIds: {
      type: Array,
      default: () => []
    },
    selectedRoleId: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      radio: null,
      checkList: [],
      dataList: [],
      arrsList: [],
      msg: null,
      pageSize: 100,
      pageNum: 1,
      total: '',
      loading: false,
      asyncData: [],
      msgDatas: [],
      capDatas: [],
      grpDatas: [],
      OpenGroup: null
    }
  },
  watch: {
    radioCheck: {
      handler (num) {
        this.radio = num
      },
      deep: true
    },
    roleType: {
      handler (msg) {
        if (msg === 'group') {
          return
        }
        const obj = {}
        obj[msg] = msg
        this.msgDatas.push(obj)
      },
      deep: true
    },
    dataList: {
      handler (arr) {
        if (arr && arr.length) {
          this.asyncData.push(true)
        }
      },
      deep: true
    },
    checkBoxList: {
      handler (arr) {
        if (arr && arr.length) {
          this.asyncData.push(true)
        }
      },
      deep: true
    },
    asyncData: {
      handler (arr) {
        if (arr && arr.length >= 2) {
          if (this.roleType == 'account') {
            this.checkBoxs('UserId')
          }
          if (
            (this.roleType == 'onlyRole' && !this.GroupIds.length) ||
            (this.roleType == 'onlyRole' && this.GroupIds.length === 1 && this.GroupIds[0] === -1) ||
            (this.roleType === 'group' && this.GroupIds.length)
          ) {
            this.checkBoxs('RoleId')
          }
        }
      },
      deep: true
    },
    GroupIds: {
      handler (val) {
        if (val.length === 1 && val[0] === -1) {
          return
        }
        const obj = {}
        obj['GroupIds'] = 'GroupIds'
        this.msgDatas.push(obj)
      },
      deep: true
    },
    msgDatas: {
      handler (arr) {
        if (this.roleType === 'group' && this.GroupIds.length) {
          this.getRoleDataByUpId()
          return
        } else if (this.roleType === 'onlyRole' && this.GroupIds.length === 1 && this.GroupIds[0] === -1) {
          this.getRoleData('RoleId', 'RoleName')
          return
        }
        if (arr && arr.length >= 2) {
          this.getRoleDataByUpId()
        } else {
          if (this.roleType == 'account') {
            this.getRoleData('UserId', 'UserName')
          }
          if (!this.OpenGroup || this.needType) {
            if (this.roleType == 'onlyRole') {
              this.getRoleData('RoleId', 'RoleName')
            }
          }
        }
      },
      deep: true
    },
    selectedRoleId: {
      handler (val) {
        if (val === -1) {
          this.msg = -1
        }
      }
    },
  },
  computed: {
    noMore () {
      return this.pageNum >= this.total
    },
    disabled () {
      return this.loading || this.noMore
    }
  },
  created () {
    const obj = this.$store.state.app.systemSet
    const { OpenGroup } = typeof obj === 'string' ? JSON.parse(obj) : obj
    this.OpenGroup = OpenGroup
  },
  methods: {
    // 选中
    handleBg (item, i) {
      this.msg = i
      this.$emit('checkClick', item)
    },
    //多选框
    checkChange (arr) {
      const datas = this.formatChecks(arr)
      const arrs = []
      arr.forEach(item => {
        arrs.push(this.dataList[item])
      })
      this.capDatas = arrs
      // if (this.roleType == 'account') {
      //   datas = this.formatChecks(arr, 'UserId');
      // }
      this.$emit('checkChange', datas)
    },
    //单选框
    radioChange (val) {
      this.$emit('radioChange', val)
    },
    //格式化选中回调
    formatChecks (arr, key) {
      const datas = []
      // const ids = []
      this.dataList.forEach((item, index) => {
        arr.forEach(p => {
          if (index == p) {
            datas.push(item)
          }
        })
      })
      // datas.forEach(item => {
      //   ids.push(item[key])
      // })
      return datas
    },
    //多选框默认选中
    checkBoxs (ids) {
      const datas = []
      const type = typeof this.checkBoxList[0]
      if (type == 'object') {
        this.dataList.forEach((item, index) => {
          this.checkBoxList.forEach(p => {
            if (item[ids] == p[ids]) {
              datas.push(index)
            }
          })
        })
      } else {
        this.dataList.forEach((item, index) => {
          this.checkBoxList.forEach(p => {
            if (item[ids] == p) {
              datas.push(index)
            }
          })
        })
      }
      this.checkList = datas
    },
    checkRole () {
      const datas = []
      this.dataList.forEach((item, index) => {
        this.checkBoxList.forEach(p => {
          if (item.RoleId == p.RoleId) {
            datas.push(index)
          }
        })
      })
      this.checkList = datas
    },
    //获取列表
    async getRoleData (ids, names) {
      try {
        this.loading = true
        const obj = {
          QueryName: '',
          PageIndex: this.pageNum,
          PageSize: this.pageSize
        }
        let result = null
        if (this.roleType == 'account') {
          result = await GetAccountList(obj)
        }
        if (this.roleType == 'onlyRole') {
          result = await QueryRole(obj)
        }
        if (result.code === 0) {
          const datas = result.returnData.records
          const num = result.returnData.pages
          this.arrsList.push(datas)
          const arrs = this.arrsList.flat()
          const msgs = _.unionBy(arrs, ids)
          msgs.forEach(item => {
            item.name = item[names]
          })
          if (this.needId) {
            const yrts = msgs.filter(item => item.RoleId != this.needId)
            this.dataList = yrts
          } else {
            this.dataList = msgs
          }
          this.total = num
          this.loading = false
          this.$emit('role-list-change', msgs)
        } else {
          this.$message.error(result.message)
          this.loading = false
        }
      } catch (error) {
        console.log('出错了', error)
        this.loading = false
      }
    },
    formatCheckBox () {
      const caps = []
      const arrs = this.capDatas.concat(this.checkBoxList)
      this.dataList.forEach((item, index) => {
        arrs.forEach(p => {
          if (item['RoleId'] == p['RoleId']) {
            caps.push(index)
          }
        })
      })
      this.checkList = caps
    },
    //获取列表2
    async getRoleDataByUpId () {
      try {
        this.loading = true
        const obj = {
          GroupIds: this.GroupIds
        }
        this.grpDatas.push(this.GroupIds)
        const result = await GetRoleByGroup(obj)
        if (result.code === 0) {
          const datas = result.returnData
          const msgs = []
          if (datas.length) {
            datas.forEach(item => {
              item.name = item.RoleName
              if (item.IsSelected) {
                msgs.push(item)
              }
            })
            this.dataList = msgs
          } else {
            this.dataList = msgs
          }
          this.$emit('role-list-change', msgs)
          if (this.dataList.length) {
            this.formatCheckBox()
            const grpDatasTs = this.grpDatas;
            if (grpDatasTs.length > 1) {
              if (grpDatasTs[grpDatasTs.length - 1].length < grpDatasTs[grpDatasTs.length - 2].length) {
                const wts = []
                this.dataList.forEach(item => {
                  this.capDatas.forEach(p => {
                    if (item.RoleId == p.RoleId) {
                      wts.push(item)
                    }
                  })
                })
                this.capDatas = wts
              }
            }
          } else {
            this.capDatas = []
            this.msg = null
          }
          this.loading = false
        } else {
          this.$message.error(result.message)
          this.loading = false
        }
      } catch (error) {
        console.log('出错了', error)
        this.loading = false
      }
    },

    //滚动加载数据
    load () {
      this.pageNum += 1
      if (this.roleType == 'account') {
        this.getRoleData('UserId', 'UserName')
      }
      if (this.roleType == 'onlyRole') {
        this.getRoleData('RoleId', 'RoleName')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "./rolelist.scss";
.paren_content {
  ::v-deep .el-radio__label {
    display: none;
  }
  ::v-deep .el-checkbox__label {
    display: none;
  }
  // .scCont {
  //   height: 65vh;
  //   overflow-x: hidden;
  //   overflow-y: auto;
  // }
}
</style>
