<template>
  <div class="app-container">

    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="归属系统"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in permissionsSysOriginPlatforms"
          :key="index"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left;"> <sys-origin-icon :icon="item.value" :desc="item.value" /></span>
          <span style="float: left;margin-left:10px">{{ item.label }}</span>
        </el-option>
      </el-select>
      <el-select
        v-model="listQuery.del"
        placeholder="注销状态"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          label="未注销"
          value="0"
        />
        <el-option
          label="已注销"
          value="1"
        />
      </el-select>
      <el-select
        v-model="listQuery.event"
        placeholder="房间状态"
        style="width: 120px"
        class="filter-item"
        clearable
        @change="handleSearch"
      >
        <el-option v-for="item in roomEvents" :key="item.value" :label="item.name" :value="item.value" />
      </el-select>
      <el-input
        v-model.trim="listQuery.roomId"
        placeholder="房间ID"
        clearable
        style="width: 200px;"
        class="filter-item"
      />
      <el-input
        v-model.trim="listQuery.roomAccount"
        placeholder="房间账号"
        clearable
        style="width: 200px;"
        class="filter-item"
      />
      <div class="filter-item">
        <account-input v-model="listQuery.userId" :sys-origin="listQuery.sysOrigin" placeholder="用户ID" />
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="listLoading"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleRemoveOrPullBlack"
      >
        移除/拉黑成员
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleChangeRole"
      >
        权限变更
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column label="封面" align="center" min-width="200">
        <template slot-scope="scope">
          <div class="room-profile flex-l">
            <div class="avatar">
              <el-image
                style="width: 100%; height: 100%;"
                :src="scope.row.roomCover"
                :preview-src-list="[scope.row.roomCover]"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>
            </div>
            <div class="info nowrap-ellipsis">
              <div class="nickname">
                <el-link v-if="scope.row.roomName" @click="queryRoomDetails(scope.row.id)">
                  {{ scope.row.roomName }}
                </el-link>
              </div>
              <div class="account">
                账号: {{ scope.row.roomAccount }}
              </div>
              <div class="desc">
                {{ scope.row.roomDesc }}
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="房间信息" align="left" min-width="200">
        <template slot-scope="scope">
          <div style="margin: auto;">
            <div>状态:
              <el-tag v-if="scope.row.event === 'AVAILABLE'" size="mini" type="success">正常</el-tag>
              <el-tag v-else-if="scope.row.event === 'ID_CHANGE'" size="mini" type="info">ID变更</el-tag>
              <el-tag v-else-if="scope.row.event === 'WAITING_CONFIRMED'" size="mini" type="warning">等待确认</el-tag>
              <el-tag v-else-if="scope.row.event === 'CLOSE'" size="mini" type="danger">关闭</el-tag>
              <el-tag v-else size="mini" type="danger">未知</el-tag>
            </div>
            <div>ID: {{ scope.row.id }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="event" label="时间" align="center" width="200">
        <template slot-scope="scope">
          <div>创建: {{ scope.row.createTime | dateFormat }}</div>
          <div>修改: {{ scope.row.updateTime | dateFormat }}</div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="50">
        <template slot-scope="scope">
          <el-dropdown>
            <span class="el-dropdown-link">
              <i class="el-icon-more" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="copyContent(scope.row.id)">复制ID</el-dropdown-item>
              <el-dropdown-item v-if="buttonPermissions.includes('room:profile:table:edit')" @click.native="handleUpdate(scope.row)">编辑资料</el-dropdown-item>
              <el-dropdown-item v-if="buttonPermissions.includes('room:profile:table:query:member:list')" @click.native="queryRoomUserDetails(scope.row.id)">成员列表</el-dropdown-item>
              <el-dropdown-item v-if="buttonPermissions.includes('room:profile:table:query:visitor:list')" @click.native="queryRoomVisitorLog(scope.row.id)">访客记录</el-dropdown-item>
              <!-- <el-dropdown-item v-if="buttonPermissions.includes('room:profile:table:query:active:index')" @click.native="clickRoomActive(scope.row)">活跃指标</el-dropdown-item> -->
              <el-dropdown-item v-if="buttonPermissions.includes('room:profile:table:log')" @click.native="clickQueryRolesChangeLog(scope.row)">操作日志</el-dropdown-item>
              <el-dropdown-item v-if="buttonPermissions.includes('room:profile:table:approval')" @click.native="editApproval(scope.row, 'ROOM_NICKNAME')">审批房间昵称</el-dropdown-item>
              <el-dropdown-item v-if="buttonPermissions.includes('room:profile:table:approval')" @click.native="editApproval(scope.row, 'ROOM_AVATAR')">审批房间头像</el-dropdown-item>
              <el-dropdown-item v-if="buttonPermissions.includes('room:profile:table:approval')" @click.native="editApproval(scope.row, 'ROOM_NOTICE')">审批房间公告</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div class="load-more flex-c">
      <el-button v-if="!listNotData" type="text" :disabled="listLoading" @click="renderData">点击加载更多</el-button>
      <span v-else>已加载全部</span>
    </div>
    <room-deatils-drawer
      v-if="roomDeatilsDrawerVisible"
      :room-id="roomId"
      @close="roomDeatilsDrawerVisible=false"
    />
    <profile-user-drawer
      v-if="roomUserDeatilsDrawerVisible"
      :room-id="roomId"
      :sys-origin="listQuery.sysOrigin"
      @close="roomUserDeatilsDrawerVisible=false"
    />
    <visitor-log-drawer
      v-if="roomVisitorLogVisible"
      :room-id="roomId"
      :sys-origin="listQuery.sysOrigin"
      @close="roomVisitorLogVisible=false"
    />
    <el-dialog
      title="编辑房间资料"
      :visible.sync="formVisible"
      :before-close="handleClose"
      width="450px"
    >
      <div v-loading="submitLoading">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="margin-right: 28px">
          <el-form-item label="封面" prop="roomCover">
            <el-upload
              class="upload-demo"
              action=""
              :http-request="httpRequest"
              :show-file-list="false"
              accept="image/png,image/jpg,image/jpeg"
            >
              <el-image v-if="form.roomCover" :src="form.roomCover" fit="fill" style="width: 50px; height: 50px" />
              <el-button v-loading="uploadLoading" size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="名称" prop="roomName">
            <el-input v-model.trim="form.roomName" type="text" placeholder="房间名称" show-word-limit minlength="1" maxlength="24" resize="none" rows="6" />
          </el-form-item>
          <el-form-item label="公告">
            <el-input v-model.trim="form.roomDesc" type="textarea" placeholder="房间公共" show-word-limit maxlength="160" resize="none" rows="6" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="form.event"
              placeholder="房间状态"
              style="width:100%;"
              class="filter-item"
            >
              <el-option v-for="item in roomEvents" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()">保存</el-button>
            <el-button @click="handleClose()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog
      :title="textOptTitle3"
      :visible.sync="formVisible3"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="400px"
    >
      <div v-loading="submitLoading3">
        <el-form ref="form" :model="form3" label-width="50px" style="margin-left: 15px;">
          <el-form-item label="平台">
            <el-input v-model.trim="listQuery.sysOrigin" :disabled="true" type="text" />
          </el-form-item>
          <el-form-item label="房间" prop="roomAccount">
            <el-input v-model.trim="form3.roomAccount" placeholder="房间账号" type="text" />
          </el-form-item>
          <el-form-item label="用户" prop="userAccount">
            <el-input v-model.trim="form3.userAccount" placeholder="用户账号" type="text" />
          </el-form-item>
          <el-form-item label="事件">
            <el-select
              v-model="form3.event"
              placeholder="事件"
              style="width:100%;"
              class="filter-item"
            >
              <el-option v-for="item in sysOperatingRoomUserEvent" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitRemoveOrPullBlackForm()">保存</el-button>
            <el-button @click="handleClose()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog
      :title="textOptTitle4"
      :visible.sync="formVisible4"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="400px"
    >
      <div v-loading="submitLoading4">
        <el-form ref="form" :model="form4" label-width="50px" style="margin-left: 15px;">
          <el-form-item label="平台">
            <el-input v-model.trim="listQuery.sysOrigin" :disabled="true" type="text" />
          </el-form-item>
          <el-form-item label="房间" prop="roomAccount">
            <el-input v-model.trim="form4.roomAccount" placeholder="房间账号" type="text" />
          </el-form-item>
          <el-form-item label="用户" prop="userAccount">
            <el-input v-model.trim="form4.userAccount" placeholder="用户账号" type="text" />
          </el-form-item>
          <el-form-item label="权限">
            <el-select
              v-model="form4.roles"
              placeholder="权限"
              style="width:100%;"
              class="filter-item"
            >
              <el-option
                v-for="(item, index) in roomRoles"
                :key="index"
                :label="item.name"
                :value="item.value"
                :disabled="item.value == 'HOMEOWNER'"
              />
              <el-option
                :key="roomRoles.length"
                label="游客"
                value="TOURIST"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitChangeRoleForm()">保存</el-button>
            <el-button @click="handleClose()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <room-active-charts
      v-if="roomActiveVisible"
      :room-id="roomId"
      @close="roomActiveVisible=false"
    />
    <room-operation-log
      v-if="roomOperationLogVisible"
      :room-id="roomId"
      @close="roomOperationLogVisible=false"
    />

    <el-dialog
      :title="textOptTitle"
      :visible="textOptVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="500px"
      top="170px"
    >
      <div v-loading="submitLoading">
        <div class="form-contetn">
          <el-form ref="form" :model="form" :rules="rules" label-width="110px" style="text-align: center;">
            <el-button type="primary" style="margin: auto 20px;" plain @click="pass()">鉴定通过</el-button>
            <el-button type="danger" style="margin: auto 20px;" plain @click="notpass()">鉴定违规</el-button>
          </el-form>
        </div>
        <div slot="footer" style="text-align: right;">
          <el-button @click="handleClose()">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pofileTable, updateProfile, removeOrPullBlackRoomUser, changeRole } from '@/api/room'
import { getAccessImgUrl } from '@/api/oss'
import { roomEvents, sysOperatingRoomUserEvent, roomRoles } from '@/constant/type'
import RoomDeatilsDrawer from '@/components/data/RoomDeatilsDrawer'
import ProfileUserDrawer from './user-drawer'
import VisitorLogDrawer from './room-visitor-log'
import { mapGetters } from 'vuex'
import RoomActiveCharts from './room-active-charts'
import RoomOperationLog from './room-operation-log'
import { approvalData } from '@/api/approval'
import { copyText } from '@/utils'
function getFormData() {
  return {
    id: '',
    roomCover: '',
    roomName: '',
    roomDesc: '',
    countryCode: '',
    event: ''
  }
}
// 权限变更
function getFormData4() {
  return {
    roomId: '',
    userAccount: '',
    roles: ''
  }
}
// 移除/拉黑成员
function getFormData3() {
  return {
    sysOrigin: '',
    roomAccount: '',
    userAccount: '',
    event: ''
  }
}
export default {
  components: { RoomDeatilsDrawer, ProfileUserDrawer, VisitorLogDrawer, RoomActiveCharts, RoomOperationLog },
  data() {
    return {
      updateProfileRow: {},
      roomRoles,
      roomOperationLogVisible: false,
      roomActiveVisible: false,
      pushTextHistoryLoading: false,
      pushTextHistory: [],
      list: [],
      listNotData: false,
      roomDeatilsDrawerVisible: false,
      roomUserDeatilsDrawerVisible: false,
      roomVisitorLogVisible: false,
      roomId: '',
      roomEvents,
      textOptVisible: false,
      textOptTitle: '',
      approveType: '',
      approvalUserId: '',
      approvalContent: '',
      approvalRoomId: '',
      sysOperatingRoomUserEvent,
      listQuery: {
        limit: 20,
        lastId: '',
        sysOrigin: '',
        roomId: '',
        roomAccount: '',
        userId: '',
        del: '0',
        event: ''
      },
      formVisible: false,
      form: getFormData(),
      form4: getFormData4(),
      submitLoading: false,
      submitLoading3: false,
      formVisible3: false,
      textOptTitle3: '',
      submitLoading4: false,
      formVisible4: false,
      textOptTitle4: '',
      form3: getFormData3(),
      rules: {
        roomCover: [
          { required: true, message: '请上传封面', trigger: 'blur' }
        ],
        roomName: [
          { required: true, message: '请填写房间名称', trigger: 'blur' }
        ],
        countryId: [
          { required: true, message: '请选择国家', trigger: 'blur' }
        ]
      },
      listLoading: true,
      uploadLoading: false
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms', 'buttonPermissions'])
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    this.renderData()
  },
  methods: {
    renderData(isClean) {
      const that = this
      if (isClean === true) {
        that.list = []
        that.listQuery.lastId = null
      }
      that.listLoading = true
      pofileTable(that.listQuery).then(res => {
        that.listLoading = false
        that.list = that.list.concat(res.body || [])
        that.listNotData = !res.body || res.body.length <= 0
        if (that.list && that.list.length > 0) {
          that.listQuery.lastId = that.list[that.list.length - 1].id
        }
      }).catch(er => {
        console.error(er)
        that.listLoading = false
      })
    },
    copyContent(conent) {
      const that = this
      if (!conent) {
        that.$opsMessage.fail()
        return
      }
      copyText(conent).then(res => {
        that.$opsMessage.success()
      }).catch(er => {
        that.$opsMessage.fail()
      })
    },
    editApproval(row, type) {
      this.approveType = type
      this.approvalUserId = row.userId
      this.approvalRoomId = row.id
      if (type === 'ROOM_NICKNAME') {
        this.approvalContent = row.roomName
        this.textOptTitle = '房间昵称审批'
      }
      if (type === 'ROOM_AVATAR') {
        this.approvalContent = row.roomCover
        this.textOptTitle = '房间头像审批'
      }
      if (type === 'ROOM_NOTICE') {
        this.textOptTitle = '房间公告审批'
        this.approvalContent = row.roomDesc
      }
      this.textOptVisible = true
    },
    pass() {
      const that = this
      that.listLoading = true
      approvalData({
        approvalType: that.approveType,
        approvalStatus: 'PASS',
        waitApprovalUser: that.getApprovalParams()
      }).then((res) => {
        that.listLoading = false
        that.textOptVisible = false
        that.$opsMessage.success()
        that.renderData()
      }).catch(() => { that.listLoading = false })
    },
    notpass() {
      const that = this
      that.listLoading = true
      approvalData({
        approvalType: that.approveType,
        approvalStatus: 'NOT_PASS',
        waitApprovalUser: that.getApprovalParams()
      }).then((res) => {
        that.listLoading = false
        that.textOptVisible = false
        that.$opsMessage.success()
        that.renderData()
      }).catch(() => { that.listLoading = false })
    },
    getApprovalParams() {
      const that = this
      const approvalParams = [{
        userId: that.approvalUserId,
        contentId: that.approvalRoomId,
        content: that.approvalContent
      }]
      return approvalParams
    },
    handleSearch() {
      this.renderData(true)
    },
    renderDataSuccess() {
      this.$message({
        message: 'Successful',
        type: 'success'
      })
      this.renderData()
    },
    handleRemoveOrPullBlack() {
      this.textOptTitle3 = '移除/拉黑成员'
      this.formVisible3 = true
      this.form3 = {}
    },
    queryUserDetails(row) {
      this.userDeatilsDrawer = true
      this.thatSelectedUserId = row.id
    },
    handleChangeRole() {
      this.textOptTitle4 = '房间内权限变更'
      this.formVisible4 = true
      this.form4 = {}
    },
    submitChangeRoleForm() {
      const that = this
      that.submitLoading4 = true
      that.form4.sysOrigin = that.listQuery.sysOrigin
      changeRole(that.form4).then(res => {
        if (res.status !== 200) {
          that.$opsMessage.fail(res.errorMsg)
        } else {
          that.$opsMessage.success()
        }
        that.submitLoading4 = false
        that.formVisible4 = false
        this.form4 = getFormData3()
        this.renderData()
      }).catch(er => {
        that.submitLoading4 = false
        console.error(er)
        this.$emit('fail')
      })
    },
    httpRequest(file) {
      const that = this
      that.uploadLoading = true
      this.$simpleUploadFlie(file).then(res => {
        that.uploadLoading = false
        //console.log('2222', getAccessImgUrl(res.name))
        that.form.roomCover = getAccessImgUrl(res.name)
        // getAccessImgUrl(res.name).then((result) => {
        //   console.log('111111', result)
        //   that.form.roomCover = result.result
        // })
      }).catch(er => {
        that.uploadLoading = false
      })
    },
    submitForm() {
      const that = this
      that.$refs.form.validate(valid => {
        if (valid) {
          that.submitLoading = true
          if (that.form.id) {
            updateProfile(that.form).then(res => {
              that.submitLoading = false
              that.formVisible = false
              that.updateProfileRow.roomCover = that.form.roomCover
              that.updateProfileRow.roomName = that.form.roomName
              that.updateProfileRow.roomDesc = that.form.roomDesc
              that.updateProfileRow.event = that.form.event
              that.form = getFormData()
            }).catch(er => {
              that.submitLoading = false
              that.$emit('fial', er)
            })
            return
          }
        } else {
          console.error('error submit!!')
          return false
        }
      })
    },
    queryRoomDetails(roomId) {
      this.roomDeatilsDrawerVisible = true
      this.roomId = roomId
    },
    queryRoomUserDetails(roomId) {
      this.roomUserDeatilsDrawerVisible = true
      this.roomId = roomId
    },
    handleClose() {
      this.textOptVisible = false
      this.formVisible = false
      this.formVisible2 = false
      this.formVisible3 = false
      this.formVisible4 = false
      this.resetForm()
    },
    resetForm() {
      this.form = getFormData()
      this.form3 = getFormData3()
      this.form4 = getFormData4()
    },
    submitRemoveOrPullBlackForm() {
      const that = this
      that.submitLoading3 = true
      that.form3.sysOrigin = that.listQuery.sysOrigin
      removeOrPullBlackRoomUser(that.form3).then(res => {
        that.submitLoading3 = false
        that.formVisible3 = false
        that.resetForm()
        that.renderData(true)
      }).catch(er => {
        that.submitLoading3 = false
        console.error(er)
        this.$emit('fail')
      })
    },
    handleUpdate(row) {
      this.formVisible = true
      this.updateProfileRow = row
      this.form = Object.assign(this.form, row)
    },
    queryRoomVisitorLog(roomId) {
      this.roomVisitorLogVisible = true
      this.roomId = roomId
    },
    clickRoomActive(row) {
      this.roomId = row.id
      this.roomActiveVisible = true
    },
    clickQueryRolesChangeLog(row) {
      this.roomId = row.id
      this.roomOperationLogVisible = true
    }
  }
}
</script>

<style scoped lang="scss">
.load-more {
  padding: 10px 0px;
}
.room-profile {
  text-align: left;
  .avatar {
    width: 60px;
    height: 60px;
    border-radius: 10px;
    overflow: hidden;
    flex-shrink: 0;
  }
  .info {
    padding: 0px 5px;
    width: 100%;
  }
 }
</style>
