<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item :label="t('newHosts.hostsId')" prop="hostsId">
        <el-input v-model="queryParams.hostsId" :placeholder="t('newHosts.placeHostId')" clearable
          @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item :label="t('newHosts.hostsLevel')" prop="hostsLevel">
        <el-select v-model="queryParams.hostsLevel" :placeholder="t('newHosts.placeHostLevel')" clearable
          class="!w-240px">
          <el-option v-for="dict in getStrDictOptions(DICT_TYPE.HOST_LEVEL)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('newHosts.hostsCoins')" prop="hostsCoins">
        <el-input v-model="queryParams.hostsCoinsMin" :placeholder="t('newHosts.min')" clearable
          @keyup.enter="handleQuery" class="!w-115px" />
        <span>
          &nbsp;-&nbsp;
        </span>
        <el-input v-model="queryParams.hostsCoinsMax" :placeholder="t('newHosts.max')" clearable
          @keyup.enter="handleQuery" class="!w-115px" />
      </el-form-item>

      <el-form-item :label="t('newHosts.onlineFans')" prop="onlineFans">
        <el-input v-model="queryParams.onlineFansMin" :placeholder="t('newHosts.min')" clearable
          @keyup.enter="handleQuery" class="!w-115px" />
        <span>
          &nbsp;-&nbsp;
        </span>
        <el-input v-model="queryParams.onlineFansMax" :placeholder="t('newHosts.max')" clearable
          @keyup.enter="handleQuery" class="!w-115px" />

      </el-form-item>
      <el-form-item :label="t('newHosts.fans')" prop="fans">
        <el-input v-model="queryParams.fansMin" :placeholder="t('newHosts.min')" clearable @keyup.enter="handleQuery"
          class="!w-115px" />
        <span>
          &nbsp;-&nbsp;
        </span>
        <el-input v-model="queryParams.fansMax" :placeholder="t('newHosts.max')" clearable @keyup.enter="handleQuery"
          class="!w-115px" />
      </el-form-item>
      <el-form-item :label="t('newHosts.fllowernum')" prop="fllowernum">

        <el-input v-model="queryParams.fllowernumMin" :placeholder="t('newHosts.min')" clearable
          @keyup.enter="handleQuery" class="!w-115px" />
        <span>
          &nbsp;-&nbsp;
        </span>
        <el-input v-model="queryParams.fllowernumMax" :placeholder="t('newHosts.max')" clearable
          @keyup.enter="handleQuery" class="!w-115px" />


      </el-form-item>
      <!-- <el-form-item label="昨日金币" prop="yesterdayCoins">

        <el-input
          v-model="queryParams.yesterdayCoins"
          placeholder="最小值"
          clearable
          @keyup.enter="handleQuery"
          class="!w-115px"
        />
        <span>
          &nbsp;-&nbsp;
        </span>
        <el-input
          v-model="queryParams.yesterdayCoins"
          placeholder="最大值"
          clearable
          @keyup.enter="handleQuery"
          class="!w-115px"
        />

      </el-form-item> -->
      <el-form-item :label="t('newHosts.hostsCountry')" prop="country">
        <el-select v-model="queryParams.country" :placeholder="t('newHosts.placeHostsCountry')" clearable
          class="!w-240px">
          <el-option v-for="dict in getStrDictOptions(DICT_TYPE.COUNTRY_GROUP)" :key="dict.value"
            :label="$t(dict.label)" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('newHosts.hostsKind')" prop="hostsKind">
        <el-input v-model="queryParams.hostsKind" :placeholder="t('newHosts.placeHostsKind')" clearable
          @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item :label="t('newHosts.isAssigned')" prop="isAssigned">
        <el-select v-model="queryParams.isAssigned" :placeholder="t('newHosts.placeIsAssigned')" clearable
          class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.INT_TRUE_FLASE)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('newHosts.createTime')" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" value-format="YYYY-MM-DD HH:mm:ss" type="date"
          class="!w-240px" />
      </el-form-item>
      <!-- <el-form-item label="用户 Id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户 Id"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item :label="t('newHosts.invitationType')" prop="invitationType">
        <el-select v-model="queryParams.invitationType" :placeholder="t('newHosts.placeInvitationType')" clearable
          class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HOSTS_INVITATION_TYPE)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('newHosts.allocationUser')" prop="allocationUser">
        <el-select v-model="queryParams.userId" :placeholder="t('newHosts.placeAllocationUser')" clearable
          class="!w-240px">
          <el-option v-for="(user, index) in allocationUserList" :key="index" :label="user.label" :value="user.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> {{ t('newHosts.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> {{ t('newHosts.reset') }}
        </el-button>
        <!-- <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['server:new-hosts:create']">
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('newHosts.newAdd') }}
        </el-button> -->
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['server:new-hosts:export']">
          <Icon icon="ep:download" class="mr-5px" /> {{ t('newHosts.export') }}
        </el-button>
        <el-button @click="dialogAllocation = true">
          <Icon icon="ep:refresh" class="mr-5px" /> {{ t('newHosts.allocation') }}
        </el-button>

      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column :label="t('newHosts.hostsId')" align="center" prop="hostsId" />
      <el-table-column :label="t('newHosts.hostsLevel')" sortable align="center" prop="hostsLevel" />
      <el-table-column :label="t('newHosts.hostsCoins')" sortable align="center" prop="hostsCoins" />
      <el-table-column :label="t('newHosts.invitationType')" align="center" prop="invitationType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.HOSTS_INVITATION_TYPE" :value="scope.row.invitationType" />
        </template>
      </el-table-column>
      <el-table-column :label="t('newHosts.onlineFans')" sortable align="center" prop="onlineFans" />
      <el-table-column :label="t('newHosts.fans')" sortable align="center" prop="fans" />
      <el-table-column :label="t('newHosts.fllowernum')" sortable align="center" prop="fllowernum" />
      <el-table-column :label="t('newHosts.yesterdayCoins')" sortable align="center" prop="yesterdayCoins" />
      <el-table-column :label="t('newHosts.hostsCountry')" align="center" prop="country" />
      <el-table-column :label="t('newHosts.hostsKind')" align="center" prop="hostsKind" />
      <el-table-column :label="t('newHosts.isAssigned')" align="center" prop="isAssigned">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INT_TRUE_FLASE" :value="scope.row.isAssigned" />
        </template>
      </el-table-column>
      <el-table-column :label="t('newHosts.createTime')" align="center" prop="createTime" :formatter="dateFormatter"
        width="180px" />
      <!-- <el-table-column label="员工 Id" align="center" prop="userId" /> -->
      <el-table-column :label="t('newHosts.operate')" align="center" min-width="120px">
        <template #default="scope">
          <!-- <el-button link type="primary" @click="openForm('update', scope.row.id)"
            v-hasPermi="['server:new-hosts:update']">
            {{ t('newHosts.edit') }}
          </el-button> -->
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['server:new-hosts:delete']">
            {{ t('newHosts.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" :page-sizes="[10, 20, 30, 50, 100, 500, 1000]" v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

  </ContentWrap>
  <!-- 分配弹窗 -->
  <el-dialog v-model="dialogAllocation" :title="t('newHosts.allocationUser')">
    <!-- <div style="padding: 0px 0px 30px  0px ;">
      <el-alert title="分配成功数量可能会小于选择数量，同id主播无法被重复分配" type="warning" />
    </div> -->

    <el-select v-model="allocationUser" :placeholder="t('newHosts.placeAllocationUser')" clearable>
      <el-option v-for="(user, index) in allocationUserList" :key="index" :label="user.label" :value="user.value" />
    </el-select>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogAllocation = false">{{ t('newHosts.cancel') }}</el-button>
        <el-button type="primary" @click="AllocationFun">
          {{ t('newHosts.confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 表单弹窗：添加/修改 -->
  <NewHostsForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { NewHostsApi, NewHostsVO } from '@/api/server/newhosts'
import { getAllocation, getSimpleUserList } from '@/api/system/user'
import NewHostsForm from './NewHostsForm.vue'
import { useCache } from '@/hooks/web/useCache'
import { func } from 'vue-types'
const { wsCache } = useCache()

/** 主播数据管理 列表 */
defineOptions({ name: 'NewHosts' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<NewHostsVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  hostsId: undefined,
  hostsLevel: undefined,
  onlineFansMin: undefined,
  onlineFansMax: undefined,
  fansMin: undefined,
  fansMax: undefined,
  hostsCoinsMin: undefined,
  hostsCoinsMax: undefined,
  fllowernumMin: undefined,
  fllowernumMax: undefined,
  invitationType: undefined,
  yesterdayCoins: undefined,
  country: undefined,
  hostsKind: undefined,
  isAssigned: undefined,
  createTime: [],
  userId: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
let dialogAllocation = ref(false)//分配弹窗
let selectHostList = ref([{
  userId: '',
  isAssigned: 0,

}]) //选中的主播列表
let allocationUser = ref('') //选中的分配用户
let allocationUserList = ref([
  {
    label: '分配用户1',
    value: '1'
  }
]) //选中的分配用户

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    console.log('queryParams', queryParams)
    const data = await NewHostsApi.getNewHostsPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 查询员工 */
const getAllocationList = async () => {
  loading.value = true
  allocationUserList.value = []
  try {
    const data = await getSimpleUserList()
    console.log('data', data)
    data.forEach((item) => {
      if (wsCache.get('user').user.id == item.id) {

      } else {
        allocationUserList.value.push({
          label: item.nickname,
          value: item.id
        })
      }


    })
    console.log(allocationUserList.value)
  } finally {
    loading.value = false
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.fansMin = undefined
  queryParams.fansMax = undefined
  queryParams.hostsCoinsMin = undefined
  queryParams.hostsCoinsMax = undefined
  queryParams.fllowernumMin = undefined
  queryParams.fllowernumMax = undefined
  queryParams.onlineFansMin = undefined
  queryParams.onlineFansMax = undefined
  queryParams.yesterdayCoins = undefined
  queryParams.isAssigned = undefined

  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await NewHostsApi.deleteNewHosts(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await NewHostsApi.exportNewHosts(queryParams)
    download.excel(data, '主播数据管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
//分配按钮操作
const handleSelectionChange = (val) => {

  selectHostList.value = val
  console.log(selectHostList.value)
}

//分配确认
function AllocationFun() {
  if (selectHostList.value.length == 0) {
    message.error('请选择要分配的主播')
    return
  }
  if (allocationUser.value == '') {
    message.error('请选择分配用户')
    return
  }
  selectHostList.value.forEach((item) => {
    item.userId = allocationUser.value;
    item.isAssigned = 1;
  })
  console.log('数组', selectHostList.value)
  NewHostsApi.Allocation(selectHostList.value).then((res) => {
    message.success(`分配${selectHostList.value.length}个，成功${res}个`)
    dialogAllocation.value = false
    getList()
  })
}


/** 初始化 **/
onMounted(() => {
  getList()
  getAllocationList();
})
</script>