<template>
  <div
    class="toast-layout"
    :style="{background:false?'none':'rgba(0, 0, 0, 0.3)'}"
    :class="{'toast-active':visible}"
  >
    <div class="toast-con bind-con" :style="{minWidth:'600px'}">
      <div class="t-header ">
        <span>{{lang==='en'?'Invite collaborator':'协作设置'}}</span>
        <i class="iconfont icon-cuowu" @click="handleClick"></i>
      </div>
      <div class="binding-con" :style="{height:(Math.ceil(auth.length/4)*30 + 140)+'px'}">
        <div class="binding-body cooperation">
          <template >
            <div class="toclient">{{lang==='en'?'Collaborator':`协作用户`}}</div>
            <div class="b-input" >
              <input v-model="userName" :placeholder="lang==='en'?'User name':'请输入用户账号'" type="text">
            </div>
          </template>

          <!-- <template v-else>
            <div class="toclient">{{lang==='en'?'Collaborator':`协作用户`}}</div>
            <div class="b-input" >
              {{cooName}}
            </div>
          </template> -->

          <div class="toclient"><span>{{lang==='en'?'Permission':'协作权限'}}</span><div @click="handleSelectAll"><span :class="{check_active:selectAll}" class="fdcheck">{{lang==='en'?'All':'全选'}}</span></div></div>
          <ul class="auth-list">
            <li v-for="(item,i) in auth" :key="i"><span @click="selectItem(item,i)" class="fdcheck" :class="{check_active:item.hasAuth}">{{lang==='en'?item.keyWord:item.name}}</span></li>
          </ul>
        </div>
      </div>

      <div class="bind-btn coo-btn" >
        <template v-if="!cooName">
          <span class="default" @click="handleClick">{{i18n.t('common.cancle')}}</span>
          <span @click="addCooperation">{{i18n.t('common.save')}}</span>
        </template>

        <template v-else>
          <span class="default" @click="unbind">{{ i18n.t('manage.cancleCollaborator') }}</span>
          <span @click="addCooperation">{{ i18n.t('common.save') }}</span>
        </template>
      </div>

    </div>

  </div>
</template>

<script>
import toastZH from '@/store/language/cn/toast'
import toastEN from '@/store/language/en/toast'
import temp from '../../page/navs/temp.vue'
import { i18n } from '@/lang'
export default {
  components: { temp },
  props: ['sceneNum', 'ids', 'cooName', 'visible', 'cooType', 'getListData'],
  data () {
    return {
      i18n,
      lock: true,
      userName: '',
      auth: [],
      lang: localStorage.getItem('language'),
      toastCode: localStorage.getItem('language') === 'en' ? toastEN : toastZH
    }
  },
  computed: {
    selectAll () {
      return this.auth.filter(item => !item.hasAuth).length === 0
    }
  },
  watch: {
    visible: function (newVal) {
      if (newVal) {
        this.getResoureList()
      }
      this.userName = this.cooName || ''
      this.lang = localStorage.getItem('language')
      this.toastCode = this.lang === 'en' ? toastEN : toastZH
    }
  },
  mounted () {

  },
  methods: {
    async unbind () {
      let token = localStorage.getItem('token')
      let url = this.cooType === 'scene' ? '/user/scene/cooperation/delete' : '/user/camera/deleteCooperationUser'
      let params = this.cooType === 'scene' ? {
        sceneNum: this.sceneNum
      } : {
        cameraId: this.sceneNum
      }

      let result = await this.$http({
        method: 'post',
        headers: {
          token
        },
        data: params,
        url: url
      })

      let data = result.data
      if (data.code === 0) {
        this.handleClick('getList')
        this.$toast.show('success', this.toastCode['45'])
      } else {
        return this.$toast.show('warn', this.toastCode[data.code], () => {})
      }
    },

    handleSelectAll () {
      // if (this.cooName) {
      //   return
      // }
      this.lock = false
      let isSelected = !this.selectAll
      this.auth.forEach(item => {
        item.hasAuth = isSelected
      })
    },
    selectItem (item, i) {
      // if (this.cooName) {
      //   this.userName = this.cooName
      //   return
      // }
      item.hasAuth = !item.hasAuth
      this.$set(this.auth, i, item)
      this.lock = true
    },
    handleClick (type = '') {
      this.$emit('closePoint', type)
    },
    async getResoureByNum () {
      let token = localStorage.getItem('token')
      let url = this.cooType === 'scene' ? '/user/scene/cooperation/findSceneResource' : '/user/camera/sceneResourceByCameraId'
      let params = this.cooType === 'scene' ? {
        sceneNum: this.sceneNum
      } : {
        cameraId: this.sceneNum
      }

      let res = await this.$http({
        method: 'post',
        headers: {
          token
        },
        data: params,
        url: url
      })

      if (res.data.code !== 0) {
        return
      }
      let data = res.data.data || []
      setTimeout(() => {
        let arr = data.map(sub => sub.id)
        let tmp = this.auth.map(item => {
          item.hasAuth = true
          if (arr.length > 0) {
            item.hasAuth = arr.indexOf(item.id) > -1
          }
          return item
        })

        this.auth = tmp
      })
    },
    async getResoureList () {
      let token = localStorage.getItem('token')
      let res = await this.$http({
        method: 'post',
        headers: {
          token
        },
        url: '/user/scene/cooperation/sceneResourceList',
        data: this.getListData || {}
      })
      
      if (res.data.code !== 0) {
        return this.handleClick()
      }
      let { include, exclude } = res.data.data
      let filterKeyWords = exclude.map(item => item.keyWord)
      let list = include.filter(item => filterKeyWords.indexOf(item.keyWord) === -1)
      let tmp = list.map(item => {
        item.hasAuth = true
        return item
      })
      this.auth = tmp
      this.cooName && this.getResoureByNum()
    },
    async addCooperation () {
      let token = localStorage.getItem('token')

      if (!this.userName) {
        return this.$toast.show('error', `${this.lang === 'en' ? 'Please enter user name.' : '请输入用户账号'}`)
      }
      let resourceIds = []

      this.auth.forEach(item => {
        if (item.hasAuth) {
          resourceIds.push(item.id)
        }
      })

      if (resourceIds.length <= 0) {
        return this.$toast.show('warn', `${this.lang === 'en' ? 'Please select at least one.' : '请至少勾选一项权限'}`)
      }

      let url = this.cooType === 'scene' ? '/user/scene/cooperation/save' : '/user/camera/saveCooperationUser'
      let params = {
        userName: this.userName,
        resourceIds: resourceIds.join(',')
      }

      if (this.ids) {
        this.cooType === 'scene' ? (params['sceneNum'] = this.ids) : (params['ids'] = this.ids)
      } else {
        this.cooType === 'scene' ? (params['sceneNum'] = this.sceneNum) : (params['cameraId'] = this.sceneNum)
      }

      let result = await this.$http({
        method: 'post',
        data: params,
        headers: {
          token
        },
        url: url
      })
      let data = result.data
      if (data.code === 0) {
        this.handleClick('getList')
        this.$toast.show('success', this.toastCode['44'])
      } else if (data.code === 3004) {
        this.handleClick()
      } else {
        return this.$toast.show('warn', this.toastCode[data.code], () => {
          return false
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
