<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="客服名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入客服名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
                <el-option label="男" value="0" />
                <el-option label="女" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option label="空闲中" value="0" />
                <el-option label="停用" value="1" />
                <el-option label="工作中" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['talk:agent:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['talk:agent:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['talk:agent:remove']">删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="agentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="客服ID" align="center" prop="id" v-if="true" />
        <el-table-column label="客服名称" align="center" prop="name" />
        <el-table-column label="性别" align="center" prop="gender">
          <template #default="scope">
            <span>{{ scope.row.gender === '0' ? '男' : '女' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="欢迎语" align="center" prop="greetingMessage" show-overflow-tooltip />
        <el-table-column label="发音人" align="center" prop="ttsVcn">
          <template #default="scope">
            <span>{{ getDictLabel(ttsVcnOptions, scope.row.ttsVcn) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="语速" align="center" prop="ttsSpeed" />
        <el-table-column label="音调" align="center" prop="ttsPitch" />
        <el-table-column label="音量" align="center" prop="ttsVolume" />
        <el-table-column label="使用者" align="center" prop="userId">
          <template #default="scope">
            <span>{{ getUserNickname(scope.row.userId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : scope.row.status === '1' ? 'danger' : 'warning'">
              {{ scope.row.status === '0' ? '空闲中' : scope.row.status === '1' ? '停用' : '工作中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['talk:agent:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['talk:agent:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改客服对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="agentFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客服名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入客服名称" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio value="0">男</el-radio>
            <el-radio value="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="头像URL" prop="avatarUrl">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.avatarUrl" :src="getAvatarUrl(form.avatarUrl)" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="欢迎语" prop="greetingMessage">
          <el-input v-model="form.greetingMessage" type="textarea" placeholder="请输入欢迎语" />
        </el-form-item>
        <el-form-item label="发音人" prop="ttsVcn">
          <el-select v-model="form.ttsVcn" placeholder="请选择发音人">
            <el-option
              v-for="item in ttsVcnOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="语速" prop="ttsSpeed">
          <el-slider v-model="form.ttsSpeed" :min="0" :max="100" show-input />
        </el-form-item>
        <el-form-item label="音调" prop="ttsPitch">
          <el-slider v-model="form.ttsPitch" :min="0" :max="100" show-input />
        </el-form-item>
        <el-form-item label="音量" prop="ttsVolume">
          <el-slider v-model="form.ttsVolume" :min="0" :max="100" show-input />
        </el-form-item>
        <el-form-item label="背景音" prop="ttsBgs">
          <el-radio-group v-model="form.ttsBgs">
            <el-radio :value="0">无背景音</el-radio>
            <el-radio :value="1">有背景音</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用者" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择使用者" clearable filterable>
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.nickname"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="0">空闲中</el-radio>
            <el-radio value="1">停用</el-radio>
            <el-radio value="2">工作中</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Agent" lang="ts">
import { listAgent, getAgent, delAgent, addAgent, updateAgent, getTtsVcnDict } from '@/api/talk/agent';
import { AgentVO, AgentQuery, AgentForm } from '@/api/talk/agent/types';
import { listTalkUser } from '@/api/talk/user';
import { TalkUserVO } from '@/api/talk/user/types';
import { Plus } from '@element-plus/icons-vue';
import type { UploadProps } from 'element-plus';
import { getToken } from '@/utils/auth';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const agentList = ref<AgentVO[]>([]);
const userList = ref<TalkUserVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const ttsVcnOptions = ref<any[]>([]);
const uploadAction = ref(import.meta.env.VITE_APP_BASE_API + '/talk/admin/agent/avatar');
const uploadHeaders = ref({
  Authorization: 'Bearer ' + getToken(),
  clientid: import.meta.env.VITE_APP_CLIENT_ID
});

const queryFormRef = ref<ElFormInstance>();
const agentFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AgentForm = {
  id: undefined,
  name: undefined,
  gender: '0',
  avatarUrl: undefined,
  greetingMessage: undefined,
  status: '0',
  ttsVcn: 'x4_yezi',
  ttsSpeed: 50,
  ttsPitch: 50,
  ttsVolume: 50,
  ttsBgs: 0
}

const data = reactive<PageData<AgentForm, AgentQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    gender: undefined,
    status: undefined
  },
  rules: {
    name: [
      { required: true, message: "客服名称不能为空", trigger: "blur" }
    ],
    gender: [
      { required: true, message: "性别不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 获取字典数据 */
const fetchDictData = async () => {
  try {
    const ttsVcnRes = await getTtsVcnDict();
    ttsVcnOptions.value = ttsVcnRes.data || [];
  } catch (error) {
    console.error('获取字典数据失败:', error);
  }
}

/** 获取用户列表 */
const fetchUserList = async () => {
  try {
    const res = await listTalkUser({ pageNum: 1, pageSize: 1000 });
    userList.value = res.rows || [];
  } catch (error) {
    console.error('获取用户列表失败:', error);
  }
}

/** 根据用户ID获取用户昵称 */
const getUserNickname = (userId: number | undefined) => {
  if (!userId) return '-';
  const user = userList.value.find(u => u.id === userId);
  return user ? user.nickname : '-';
}

/** 查询客服列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAgent(queryParams.value);
  agentList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 头像上传成功回调 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  console.log('上传成功，response:', response);
  console.log('response.msg:', response.msg);
  form.value.avatarUrl = response.msg;
  console.log('设置后 form.avatarUrl:', form.value.avatarUrl);
}

/** 头像上传前校验 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/jpeg', 'image/png', 'image/gif'].includes(rawFile.type)) {
    proxy?.$modal.msgError('头像必须是 JPG/PNG/GIF 格式!');
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    proxy?.$modal.msgError('头像大小不能超过 2MB!');
    return false;
  }
  return true;
}

/** 获取头像完整URL */
const getAvatarUrl = (avatarUrl: string) => {
  console.log('getAvatarUrl 被调用, avatarUrl:', avatarUrl);
  console.log('VITE_APP_BASE_API:', import.meta.env.VITE_APP_BASE_API);
  if (!avatarUrl) {
    console.log('avatarUrl 为空，返回空字符串');
    return '';
  }
  if (avatarUrl.startsWith('http://') || avatarUrl.startsWith('https://')) {
    console.log('avatarUrl 已经是完整 URL，直接返回');
    return avatarUrl;
  }
  const fullUrl = import.meta.env.VITE_APP_BASE_API + avatarUrl;
  console.log('拼接后的完整 URL:', fullUrl);
  return fullUrl;
}

/** 根据字典值获取字典标签 */
const getDictLabel = (options: any[], value: string) => {
  const item = options.find(opt => opt.dictValue === value);
  return item ? item.dictLabel : value;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  agentFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AgentVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  fetchUserList();
  dialog.visible = true;
  dialog.title = "添加客服";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AgentVO) => {
  reset();
  fetchUserList();
  const _id = row?.id || ids.value[0]
  const res = await getAgent(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改客服";
}

/** 提交按钮 */
const submitForm = () => {
  agentFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAgent(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addAgent(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: AgentVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除客服编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAgent(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

onMounted(() => {
  fetchDictData();
  fetchUserList();
  getList();
});
</script>

<style scoped lang="scss">
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
