<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item :label="t('bigBrother.displayId')" prop="displayId">
        <el-input v-model="queryParams.displayId" :placeholder="t('bigBrother.displayId')" clearable
          @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <!-- <el-form-item label="大哥的uid" prop="userIdStr">
        <el-input v-model="queryParams.userIdStr" placeholder="请输入大哥的uid" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="大哥的昵称" prop="nickname">
        <el-input v-model="queryParams.nickname" placeholder="请输入大哥的昵称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item> -->
      <el-form-item :label="t('bigBrother.level')" prop="level">
        <!-- <el-input v-model="queryParams.level" placeholder="请输入大哥的等级" clearable @keyup.enter="handleQuery"
          class="!w-240px" /> -->

        <el-input v-model="queryParams.levelMin" :placeholder="t('newHosts.min')" clearable @keyup.enter="handleQuery"
          class="!w-115px" />
        <span>
          &nbsp;-&nbsp;
        </span>
        <el-input v-model="queryParams.levelMax" :placeholder="t('newHosts.max')" clearable @keyup.enter="handleQuery"
          class="!w-115px" />
      </el-form-item>
      <el-form-item :label="t('bigBrother.fansLevel')" prop="level">
        <el-input v-model="queryParams.fansLevelMin" :placeholder="t('newHosts.min')" clearable
          @keyup.enter="handleQuery" class="!w-115px" />
        <span>
          &nbsp;-&nbsp;
        </span>
        <el-input v-model="queryParams.fansLevelMax" :placeholder="t('newHosts.max')" clearable
          @keyup.enter="handleQuery" class="!w-115px" />
      </el-form-item>
      <!-- <el-form-item label="大哥打赏的金币" prop="hostcoins">
        <el-input v-model="queryParams.hostcoins" placeholder="请输入大哥打赏的金币" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="大哥的粉丝数" prop="followerCount">
        <el-input v-model="queryParams.followerCount" placeholder="请输入大哥的粉丝数" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="大哥的关注数" prop="followingCount">
        <el-input v-model="queryParams.followingCount" placeholder="请输入大哥的关注数" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item> -->
      <el-form-item :label="t('bigBrother.region')" prop="region">
        <!-- <el-input v-model="queryParams.region" placeholder="请输入大哥所在的地区" clearable @keyup.enter="handleQuery"
          class="!w-240px" /> -->
        <el-select v-model="queryParams.region" :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="大哥的国家" prop="countryName">
        <el-input v-model="queryParams.countryName" placeholder="请输入大哥的国家" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item> -->
      <el-form-item :label="t('bigBrother.historicHighCoins')" prop="historicHighCoins">
        <!-- <el-input v-model="queryParams.historicHighCoins" placeholder="请输入大哥打赏的历史最高金币" clearable
          @keyup.enter="handleQuery" class="!w-240px" /> -->

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

        <el-input v-model="queryParams.totalGiftCoinsMin" :placeholder="t('newHosts.min')" clearable
          @keyup.enter="handleQuery" class="!w-115px" />
        <span>
          &nbsp;-&nbsp;
        </span>
        <el-input v-model="queryParams.totalGiftCoinsMax" :placeholder="t('newHosts.max')" clearable
          @keyup.enter="handleQuery" class="!w-115px" />
      </el-form-item>
      <el-form-item :label="t('bigBrother.hostDisplayId')" prop="hostDisplayId">
        <el-input v-model="queryParams.hostDisplayId" :placeholder="t('bigBrother.hostDisplayId')" clearable
          @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item :label="t('bigBrother.ownerId')" prop="ownerId">
        <el-input v-model="queryParams.ownerId" :placeholder="t('bigBrother.ownerId')" clearable
          @keyup.enter="handleQuery" class="!w-240px" />
      </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="daterange"
          :start-placeholder="t('newHosts.startTimeText')" :end-placeholder="t('newHosts.endTimeText')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </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="t(dict.label)" :value="dict.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:big-brother:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['server:big-brother:export']">
          <Icon icon="ep:download" class="mr-5px" /> {{ t('newHosts.export') }}
        </el-button>
        <el-button @click="exportAi(1)">
          <Icon icon="ep:copy-document" class="mr-5px" /> {{ t('bigBrother.batchCopyBigId') }}
        </el-button>
        <el-button @click="exportAi(2)">
          <Icon icon="ep:copy-document" class="mr-5px" /> {{ t('bigBrother.batchCopyHostId') }}
        </el-button>
        <el-button @click="dialogAllocation = true">
          <Icon icon="ep:refresh" class="mr-5px" /> {{ t('newHosts.allocation') }}
        </el-button>
        <el-button type="danger" plain :disabled="checkedIds.length === 0" @click="handleDeleteBatch"
          v-hasPermi="['server:new-hosts:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> {{ t('common.delDataMessage') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column label="主键id" align="center" prop="id" /> -->
      <el-table-column :label="t('bigBrother.displayId')" align="center" prop="displayId" />
      <el-table-column :label="t('bigBrother.uid')" align="center" prop="userIdStr" />
      <el-table-column :label="t('bigBrother.nickname')" align="center" prop="nickname" />
      <el-table-column :label="t('bigBrother.level')" align="center" prop="level" />
      <el-table-column :label="t('bigBrother.fansLevel')" align="center" prop="fansLevel" />
      <el-table-column :label="t('bigBrother.hostCoins')" align="center" prop="hostcoins" />
      <el-table-column :label="t('bigBrother.followerCount')" align="center" prop="followerCount" />
      <el-table-column :label="t('bigBrother.followingCount')" align="center" prop="followingCount" />
      <el-table-column :label="t('bigBrother.region')" align="center" prop="region">
        <template #default="scope">
          {{ currentLang === 'zh-CN' ? scope.row.region : (scope.row.regionEng || scope.row.region) }}
        </template>
      </el-table-column>
      <el-table-column :label="t('bigBrother.historicHighCoins')" align="center" prop="historicHighCoins" />
      <el-table-column :label="t('bigBrother.totalGiftCoins')" align="center" prop="totalGiftCoins" />
      <el-table-column :label="t('bigBrother.hostDisplayId')" align="center" prop="hostDisplayId">
        <template #default="scope">
          <div style="color: green; text-decoration: underline;" @click="openHtml(scope.row, scope.row.hostDisplayId)">
            {{ scope.row.hostDisplayId }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="t('bigBrother.ownerId')" align="center" prop="ownerId" />
      <el-table-column :label="t('newHosts.isAssigned')" align="center" prop="isAssigned">
        <template #default="scope">
          <el-tag size="small" :type="scope.row.isAssigned == 1 ? 'success' : 'info'">
            {{ dictLabelI18n(DICT_TYPE.INT_TRUE_FLASE, scope.row.isAssigned) || '-' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column :label="t('newHosts.createTime')" align="center" prop="createTime" :formatter="dateFormatter"
        width="180px" />
      <el-table-column :label="t('action.action')" align="center" min-width="120px">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)"
            v-hasPermi="['server:big-brother:update']">
            {{ t('action.edit') }}
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['server:big-brother:delete']">
            {{ t('action.del') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>
  <!-- 分配弹窗 -->
  <el-dialog v-model="dialogAllocation" :title="t('newHosts.allocationUser')">
    <div style="display: flex;">
      <el-select v-if="wsCache.get('roleRouters').find(item => item.id === 1).children.find(item => item.id === 103)"
        v-model="allocationDept" :placeholder="t('newHosts.placeAllocationDept')" clearable
        @change="getAllocationUserList">
        <el-option v-for="(dept, index) in allocationdeptList" :key="index" :label="dept.name" :value="dept.id" />
      </el-select>

      <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>
    </div>
    <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>
  <!-- 表单弹窗：添加/修改 -->
  <BigBrotherForm 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 { BigBrotherApi, BigBrotherVO } from '@/api/server/bigbrother'
import * as DeptApi from '@/api/system/dept'
import { getAllocation, getSimpleUserList, getSimpleUserListPage } from '@/api/system/user'
import { useCache } from '@/hooks/web/useCache'
import BigBrotherForm from './BigBrotherForm.vue'
import { useDictStore } from '@/store/modules/dict'  // 如果你项目里有字典 store
import { useLocaleStoreWithOut } from '@/store/modules/locale'
const dictStore = useDictStore?.() // 有就用；没有的话把 dictStore 相关行删掉
const localeStore = useLocaleStoreWithOut()
const currentLang = computed(() => localeStore.getCurrentLocale.lang)

// 统一用字符串比较，自动识别并翻译 i18n key
function dictLabelI18n(type: string, val: any) {
  const v = val == null ? '' : String(val)

  // 优先从 store 取；若没有，就从你现有的工具取（getIntDictOptions / getStrDictOptions）
  const opts =
    (dictStore?.getDictOptions?.(type) as any[]) ||
    getIntDictOptions(type) ||
    getStrDictOptions(type) ||
    []

  const hit = opts.find(o => String(o.value) === v)
  const label = hit?.label ?? ''
  // 形如 a.b 或包含点号的，大概率是 i18n key，则用 t() 翻
  return label && label.includes('.') ? t(label) : label
}
const { wsCache } = useCache()
/** 大哥数据 列表 */
defineOptions({ name: 'BigBrother' })

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

const loading = ref(true) // 列表的加载中
const list = ref<BigBrotherVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  displayId: undefined,
  userIdStr: undefined,
  nickname: undefined,
  levelMin: undefined,
  levelMax: undefined,
  fansLevelMin: undefined,
  fansLevelMax: undefined,
  hostcoins: undefined,
  followerCount: undefined,
  followingCount: undefined,
  region: undefined,
  historicHighCoins: undefined,
  historicHighCoinsMin: undefined,
  historicHighCoinsMax: undefined,
  totalGiftCoinsMin: undefined,
  totalGiftCoinsMax: undefined,
  hostDisplayId: undefined,
  ownerId: undefined,
  isAssigned: undefined,
  createTime: [],
  createTimeStart: '',
  createTimeEnd: '',
  countryName: undefined,
  deleteFlag: false,  //导出 是否删除
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
let dialogAllocation = ref(false)//分配弹窗
let selectBigList = ref([]) //选中的主播列表
let allocationUser = ref('') //选中的分配用户
let allocationDept = ref('') //选中的分配部门
let allocationUserList = ref([
  {
    label: '分配用户1',
    value: 1
  }
]) //选中的分配用户
let allocationdeptList = ref([
  {
    name: '分配用户1',
    id: 1
  }
]) //选中的分配部门
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.createTimeStart = queryParams.createTime?.[0]
    queryParams.createTimeEnd = queryParams.createTime?.[1]
    const data = await BigBrotherApi.getBigBrotherPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 查询部门 */
const getAlldeptList = async () => {
  loading.value = true
  try {
    const data = await DeptApi.getDeptPage(queryParams)
    allocationdeptList.value = data
    // console.log('=========================================', allocationdeptList)
  } finally {
    loading.value = false
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.levelMin = undefined
  queryParams.levelMax = undefined
  queryParams.totalGiftCoinsMin = undefined
  queryParams.totalGiftCoinsMax = undefined
  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 BigBrotherApi.deleteBigBrother(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 导出按钮操作 - 前端导出当前页数据 */
const handleExport = async () => {
  try {
    exportLoading.value = true

    // 定义表头（根据表格列顺序）
    const headers = [
      t('bigBrother.displayId'),
      t('bigBrother.uid'),
      t('bigBrother.nickname'),
      t('bigBrother.level'),
      t('bigBrother.fansLevel'),
      t('bigBrother.hostCoins'),
      t('bigBrother.followerCount'),
      t('bigBrother.followingCount'),
      t('bigBrother.region'),
      t('bigBrother.historicHighCoins'),
      t('bigBrother.totalGiftCoins'),
      t('bigBrother.hostDisplayId'),
      t('bigBrother.ownerId'),
      t('newHosts.isAssigned'),
      t('newHosts.createTime')
    ]

    // 将当前页数据转换为 CSV 行
    const rows = list.value.map(row => [
      row.displayId || '',
      row.userIdStr || '',
      row.nickname || '',
      row.level || '',
      row.fansLevel || '',
      row.hostcoins || '',
      row.followerCount || '',
      row.followingCount || '',
      currentLang.value === 'zh-CN' ? (row.region || '') : (row.regionEng || row.region || ''),
      row.historicHighCoins || '',
      row.totalGiftCoins || '',
      row.hostDisplayId || '',
      row.ownerId || '',
      row.isAssigned == 1 ? (currentLang.value === 'zh-CN' ? '是' : 'Yes') : (currentLang.value === 'zh-CN' ? '否' : 'No'),
      row.createTime ? new Date(row.createTime).toLocaleString(currentLang.value === 'zh-CN' ? 'zh-CN' : 'en-US') : ''
    ])

    // 组装 CSV 内容（添加 BOM 以支持 Excel 正确显示中文）
    const BOM = '\uFEFF'
    const csvContent = BOM + [headers, ...rows]
      .map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
      .join('\n')

    // 创建 Blob 并下载
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${t('bigBrother.exportFileName')}_${new Date().toISOString().split('T')[0]}.csv`
    link.click()
    URL.revokeObjectURL(url)

    message.success(t('bigBrother.exportSuccess'))
  } catch (error) {
    console.error('导出失败:', error)
  } finally {
    exportLoading.value = false
  }
}

/* ======== 后端导出代码（已注释，保留备用）========
const handleExportBackend = async () => {
  try {

    // 先确认是否删除导出的数据
    await ElMessageBox.confirm(
      t('bigBrother.exportDeleteConfirmMessage'),
      t('bigBrother.exportDeleteConfirmTitle'),
      {
        distinguishCancelAndClose: true,
        confirmButtonText: t('bigBrother.exportDeleteAndExport'),
        cancelButtonText: t('bigBrother.exportOnlyExport'),
        type: 'warning',
      }
    ).then(async () => {
      queryParams.deleteFlag = true
      exportLoading.value = true
      const data = await BigBrotherApi.exportBigBrother(queryParams)
      download.excel(data, '主播数据管理.xls')
    }).catch(async (err) => {
      if (err === 'cancel' || err?.action === 'cancel') {
        queryParams.deleteFlag = false
        exportLoading.value = true
        const data = await BigBrotherApi.exportBigBrother(queryParams)
        download.excel(data, '主播数据管理.xls')
      }

    });

  } catch {
  } finally {
    exportLoading.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 getAllocationUserList = async () => {
  const data = await getSimpleUserListPage({ pageSize: 1000, pageNo: 1, deptId: allocationDept.value })
  allocationUserList.value = []
  console.log("----------------------------------------------------", data.list)
  data.list.forEach((item) => {
    allocationUserList.value.push({
      label: item.nickname,
      value: item.id
    })
  })
}
//分配按钮操作
const handleSelectionChange = (val) => {
  checkedIds.value = val.map((row) => row.id)
  selectBigList.value = val
  console.log(selectBigList.value)
}

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

function exportAi(type) {
  if (selectBigList.value.length === 0) {
    ElMessage.error('请选择主播')
    return
  }
  let data = ''
  if (type == 1) {
    data = selectBigList.value.map(item => item.displayId).join('\n')
  } else {
    data = selectBigList.value.map(item => item.hostDisplayId).join('\n')
  }


  const copyToClipboard = async (text) => {
    // 优先使用 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      try {
        await navigator.clipboard.writeText(text)
        ElMessage.success('✅ 复制成功 ' + selectBigList.value.length + ' 条数据')
      } catch (err) {
        ElMessage.error('❌ 复制失败')
        console.error(err)
      }
    } else {
      // fallback 兼容方案
      const textarea = document.createElement('textarea')
      textarea.value = text
      textarea.style.position = 'fixed' // 避免跳动
      textarea.style.opacity = '0'
      document.body.appendChild(textarea)
      textarea.select()
      try {
        const result = document.execCommand('copy')
        if (result) {
          ElMessage.success('✅（兼容模式）复制成功 ' + selectBigList.value.length + ' 条数据')
        } else {
          ElMessage.error('❌（兼容模式）复制失败')
        }
      } catch (err) {
        ElMessage.error('❌（兼容模式）复制异常')
        console.error(err)
      } finally {
        document.body.removeChild(textarea)
      }
    }
  }

  copyToClipboard(data)
}

function openHtml(item, id) {
  window.open(`https://www.tiktok.com/@${id}`)

}
/** 批量删除按钮操作 */
const checkedIds = ref<number[]>([])
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起批量删除
    await BigBrotherApi.deleteBigBrotherList(checkedIds.value)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getAllocationList();
  if (wsCache.get('roleRouters').find(item => item.id === 1).children.find(item => item.id === 103)) {
    getAlldeptList();
  }
})
</script>