<script setup>
import { onMounted, ref, getCurrentInstance } from 'vue'
import Search from '@/components/icon/search.vue'
import Warning from '@/components/icon/warning.vue'
import { get, _delete, downLoad } from '../../../utils/request'
import { userStore } from '@/store/userInfo'

const { proxy } = getCurrentInstance()
const tableData = ref([])
const teamList = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const dialogVisible = ref(false)
const teamId = ref('')
const queryString = ref('')
const deleteTeamName = ref('')
const deleteTeamId = ref('')
const deleteTeamIndex = ref('')
const role = ref('')
const toggleKey = ref(0)
const showFiled = ref([
  'Team Name',
  'Team Members',
  'License Amount',
  'Team Description',
  'Remaining Activatable Devices',
  'Number of Activated Devices',
  'Team Admin',
  'Actions'
])
const fieldSelect = ref([
  'Team Name',
  'Team Members',
  'License Amount',
  'Team Description',
  'Remaining Activatable Devices',
  'Number of Activated Devices',
  'Team Admin',
  'Actions'
])
const fieldOptions = ref([
  {
    value: 'Team Name',
    label: 'Team Name'
  },
  {
    value: 'Team Members',
    label: 'Team Members'
  },
  {
    value: 'License Amount',
    label: 'License Amount'
  },
  {
    value: 'Team Description',
    label: 'Team Description'
  },
  {
    value: 'Remaining Activatable Devices',
    label: 'Remaining Activatable Devices'
  },
  {
    value: 'Number of Activated Devices',
    label: 'Number of Activated Devices'
  },
  {
    value: 'Team Admin',
    label: 'Team Admin'
  },
  {
    value: 'Created Date',
    label: 'Created Date'
  },
  {
    value: 'Actions',
    label: 'Actions'
  }
])
//限制用户点击
let click = true

//打开对话框
const handleClick = (index, val) => {
  deleteTeamName.value = val.name
  deleteTeamId.value = val.id
  deleteTeamIndex.value = index
  dialogVisible.value = true
}

function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
  getManageTeamList()
}
function handleCurrentChange(val) {
  currentPage.value = val
  getManageTeamList()
}
// 获取团队管理列表
function getManageTeamList() {
  //初始化表格
  tableData.value = []
  get('/pdf-tech/vppTeam/getManageTeamList', {
    page: currentPage.value,
    pageSize: pageSize.value,
    teamId: teamId.value,
    keyword: queryString.value
  }).then((res) => {
    if (res.data.code === 200) {
      tableData.value = res.data.result.list
      total.value = res.data.result.total
    }
  })
}
// 修改列表展示字段
const changeTableField = () => {
  toggleKey.value++
  showFiled.value = fieldSelect.value.concat()
}
const removeTag = (val) => {
  if (val === 'all') {
    fieldSelect.value = []
  }
}
const changeSelectField = (val) => {
  if (!val.includes('all') && val.length === fieldOptions.value.length) {
    fieldSelect.value.unshift('all')
  } else if (
    val.includes('all') &&
    val.length - 1 < fieldOptions.value.length
  ) {
    fieldSelect.value = fieldSelect.value.filter((item) => {
      return item !== 'all'
    })
  }
}
// 列表展示字段 - 全选功能
const selectAllField = () => {
  if (fieldSelect.value.length < fieldOptions.value.length) {
    fieldSelect.value = []
    fieldOptions.value.map((item) => {
      fieldSelect.value.push(item.value)
    })
    fieldSelect.value.unshift('all')
  } else {
    fieldSelect.value = []
  }
}
// 团队管理列表导出
function exportManageTeamList() {
  if (click) {
    click = false
    downLoad(
      '/pdf-tech/vppTeam/exportManageTeamList?teamId=' +
        teamId.value +
        '&' +
        'keyword=' +
        queryString.value
    ).then((res) => {
      //限制点击
      setTimeout(() => {
        click = true
      }, 2000)
      let url = window.URL.createObjectURL(
        new Blob([res.data], { type: '.xlsx' })
      )
      let a = document.createElement('a')
      a.style.display = 'none'
      a.href = url
      // 自定义文件名
      a.setAttribute('download', `Team Information.xlsx`)
      document.body.appendChild(a)
      // 下载文件
      a.click()
      // 释放内存
      url = window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
    })
  }
}
// 删除
function handleDelete() {
  if(!click){return}
  click = false
  setTimeout(() => {
    click = true
  }, 2000)
  _delete('/pdf-tech/vppTeam/deleteTeam', {
    teamId: deleteTeamId.value
  }).then((res) => {
    if (res.data.code === 200) {
      proxy.$message({
        duration: 5000,
        message: 'Delete Successfully',
        type: 'success'
      })
      // tableData.value.splice(deleteTeamIndex.value, 1)
      getManageTeamList()
    } else proxy.$message.error(res.data.msg)
    dialogVisible.value = false
  })
}
//筛选
const searchInfo = () => {
  click = false
  currentPage.value = 1
  getManageTeamList()
}
onMounted(() => {
  role.value = userStore().user.role
  let pageText = document.getElementsByClassName('el-pagination__jump')[0]
  if (pageText) {
    pageText.childNodes[0].nodeValue = 'Jump to Page '
  }
  getManageTeamList()
})
</script>

<template>
  <div>
    <h1>Manage Team</h1>
    <div class="mt-36px mb-16px flex justify-between">
      <h2>Content</h2>
      <div class="flex">
        <el-tooltip
          class="item"
          effect="dark"
          content="Export Data (.xlsx)"
          placement="bottom"
        >
          <div class="w-28px h-28px border-1 border-[#D9D9D9] rounded-4px bg-[#F9FAFB] flex justify-center items-center mr-12px cursor-pointer" @click="exportManageTeamList">
            <img src="@/assets/images/download.svg" alt="download" />
          </div>
        </el-tooltip>
        <router-link
          v-if="role?.indexOf('1') !== -1"
          :to="{ name: 'CreateManageTeam', query: { flag: 'create' } }"
        >
          <div class="h-28px px-10px py-4px bg-[#1460F3] rounded-4px text-14px leading-20px font-400 text-[#fff] cursor-pointer hover:opacity-80">Create Team</div>
        </router-link>
      </div>
    </div>
    <div class="w-full bg-[#fff] rounded-t-8px pt-32px px-24px">
      <span>Header Display Fields</span>
      <el-select v-model="fieldSelect" @change='changeSelectField' @remove-tag='removeTag' multiple placeholder="Please select" class="w-600px mx-20px">
        <el-option v-if="fieldOptions.length" value="all" label="all" @click.native='selectAllField'></el-option>
        <el-option
          v-for="item in fieldOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button type="primary" @click="changeTableField">Confirm</el-button>
    </div>
    <div class="flex flex-col bg-[#fff] pt-32px px-24px w-full" :class="fieldSelect ? 'p-20px rounded-b-8px' : ''">
      <div class="flex">
        <select v-model="teamId" name="team" class="min-w-140px mr-16px" :class="{ '!text-[#232A40]': teamId !== '' }">
          <option value="">Team</option>
          <option v-for="item in teamList" :value="item.id" :key="item.id">
            {{ item.name }}
          </option>
        </select>
        <div class="relative mr-16px">
          <el-input
            v-model="queryString"
            size="mini"
            class="!w-316px input-with-select"
            placeholder="Search Team Description / Team Admin"
          >
          </el-input>
          <button
            type="button"
            @click="searchInfo()"
            class="absolute top-8px right-8px"
          >
            <Search />
          </button>
        </div>
        <button
          type="button"
          @click="searchInfo()"
          class="w-70px h-28px border-[#1460F3] border-1px rounded-4px px-10px py-4px text-14px leading-20px text-[#1460F3] cursor-pointer hover:opacity-80"
        >
          Confirm
        </button>
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column v-if="showFiled.includes('Team Name')" prop="name" label="Team Name">
        </el-table-column>
        <el-table-column v-if="showFiled.includes('Team Members')" prop="memberAmount" label="Team Members" label-class-name="wordBreak">
        </el-table-column>
        <el-table-column v-if="showFiled.includes('License Amount')"
          prop="licenseAmount"
          label="License Amount"
        >
        </el-table-column>
        <el-table-column v-if="showFiled.includes('Team Description')"
          prop="description"
          label="Team Description"
        >
        </el-table-column>
        <el-table-column v-if="showFiled.includes('Remaining Activatable Devices')"
          prop="availableDevices"
          label="Remaining Activatable Devices"
        >
        </el-table-column>
        <el-table-column v-if="showFiled.includes('Number of Activated Devices')"
          prop="activatedDevices"
          label="Number of Activated Devices"
        >
        </el-table-column>
        <el-table-column v-if="showFiled.includes('Team Admin')" label="Team Admin">
          <template slot-scope="scope">
            <span v-for="(item, index) in scope.row.teamAdmin" :key="index">{{ item }}<br /></span>
          </template>
        </el-table-column>
        <el-table-column v-if="showFiled.includes('Created Date')"
          prop="createTime"
          label="Created Date"
          label-class-name="wordBreak"
        >
        </el-table-column>
        <el-table-column v-if="showFiled.includes('Actions')" label="Actions"  min-width="120">
          <template slot-scope="scope">
            <div v-show="Number(scope.row.isChange)">
              <router-link :to="{ name: 'EditManageTeam', query: { flag: 'edit', teamId: scope.row.id } }">
                <div class="w-61px h-20px border-1 border-[#1460F3] rounded-4px text-center text-14px leading-20px text-[#1460F3] cursor-pointer mb-8px">Edit</div>
              </router-link>
              <div
                class="w-61px h-20px border-1 border-[#1460F3] rounded-4px text-center text-14px leading-20px text-[#1460F3] cursor-pointer"
                @click="handleClick(scope.$index, scope.row)"
                v-if="role?.indexOf('1') !== -1 && scope.row.type === 2"
              >
                Delete
              </div>
            </div>
          </template>
        </el-table-column>
        <p slot="empty">No Data Available</p>
      </el-table>
    </div>
    <el-dialog
      title=""
      :visible.sync="dialogVisible"
      width="376px"
      top="30vh"
      center
      :show-close="false"
    >
      <Warning class="inline-block" />
      <div class="mt-16px text-16px leading-24px text-[#232A40]">
        <p>Are you sure you want to delete this team?</p>
        <p>
          Team Name: <span class="font-bold">{{ deleteTeamName }}</span>
        </p>
      </div>
      <div class="el-dialog__footer_div flex w-full justify-between">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="handleDelete()">Delete</el-button>
      </div>
    </el-dialog>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :page-sizes="[5, 10, 20]"
      :page-size="pageSize"
      :background="true"
      layout="prev, pager, next, sizes, jumper"
      :total="total"
      class="px-24px !rounded-0 rounded-b-8px flex justify-end"
    >
    </el-pagination>
  </div>
</template>

<style lang="scss" scoped>
.el-table::v-deep thead {
  color: #000 !important;
}

.el-table::v-deep .el-table__cell {
  padding-right: 20px !important;
  padding-left: 20px !important;
}

::v-deep .input-with-select .el-input__inner {
  padding: 0 20px 0 8px;
  border-color: #d9d9d9;
  font-size: 14px;
  color: #232a40;
}

::v-deep .input-with-select .el-input__inner::placeholder {
  font-size: 14px;
  font-weight: 400;
  color: #808185;
}
.el-table::v-deep .el-table__cell .wordBreak {
  word-break: normal !important;
}
.el-table::v-deep .cell {
  word-break: break-word;
}
</style>