<template>
  <div class="app-container agent-config-page">
    <div class="bg-white p-4 rounded">
      <div class="header-bar flex justify-between items-center mb-4">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入"
          style="width: 320px"
          clearable
          class="search-input"
          @keyup.enter="handleQuery"
        >
          <template #append>
            <el-button @click="handleQuery">
              <el-icon><i-ep-search /></el-icon>
            </el-button>
          </template>
        </el-input>

        <div class="flex gap-2">
          <el-button type="primary" @click="handleAdd">创建坐席</el-button>
          <el-button type="primary" @click="handleGoTicket">客服工单</el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        header-cell-class-name="custom-header"
        class="custom-table"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="name" label="坐席名称" min-width="120" />
        <el-table-column prop="module" label="负责模块" min-width="120" />
        <el-table-column prop="customerNames" label="客服姓名" min-width="300" show-overflow-tooltip />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <div class="flex gap-2">
              <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper mt-4 flex justify-end">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          background
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 坐席编辑弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.type === 'add' ? '创建坐席' : '编辑座席'"
      width="520px"
      class="custom-dialog"
    >
      <el-form ref="formRef" :model="dialog.form" :rules="rules" label-width="100px">
        <el-form-item label="座席名称" prop="name">
          <el-input v-model="dialog.form.name" placeholder="客服0" />
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-switch v-model="dialog.form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="选择客服" prop="customerIds">
          <el-select
            v-model="dialog.form.customerIds"
            multiple
            placeholder="请选择客服（可选择多个）"
            class="w-full"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="`${item.name} (${item.phone})`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="负责模块" prop="module">
          <el-select v-model="dialog.form.module" placeholder="请选择" class="w-full">
            <el-option label="小程序" value="小程序" />
            <el-option label="官网" value="官网" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const loading = ref(false);
const total = ref(3);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
});

const tableData = ref([
  {
    id: '1',
    name: '客服小A',
    module: '小程序',
    customerNames: '张三 (184387575)、李四 (184387575)',
    customerIds: ['101', '102'],
    status: 1,
  },
  {
    id: '2',
    name: '客服小B',
    module: '官网',
    customerNames: '张三 (184387575)',
    customerIds: ['101'],
    status: 1,
  },
  {
    id: '3',
    name: '客服小C',
    module: '小程序',
    customerNames: '张三 (184387575)',
    customerIds: ['101'],
    status: 1,
  },
]);

const customerOptions = [
  { id: '101', name: '张三', phone: '184387575' },
  { id: '102', name: '李四', phone: '184387575' },
  { id: '103', name: '王五', phone: '184387575' },
];

const dialog = reactive({
  visible: false,
  type: 'add',
  form: {
    id: '',
    name: '',
    status: 1,
    customerIds: [] as string[],
    module: '',
  },
});

const rules = {
  name: [{ required: true, message: '请输入座席名称', trigger: 'blur' }],
  customerIds: [{ required: true, message: '请选择客服', trigger: 'change' }],
  module: [{ required: true, message: '请选择负责模块', trigger: 'change' }],
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const getList = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 300);
};

const handleSizeChange = () => getList();
const handleCurrentChange = () => getList();

const handleAdd = () => {
  dialog.type = 'add';
  dialog.form = { id: '', name: '', status: 1, customerIds: [], module: '小程序' };
  dialog.visible = true;
};

const handleEdit = (row: any) => {
  dialog.type = 'edit';
  dialog.form = { ...row };
  dialog.visible = true;
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该坐席吗？', '提示', {
    type: 'warning',
  }).then(() => {
    tableData.value = tableData.value.filter((i) => i.id !== row.id);
    ElMessage.success('删除成功');
  });
};

const handleStatusChange = (row: any) => {
  ElMessage.success(row.status === 1 ? '已启用' : '已禁用');
};

const submitForm = () => {
  if (dialog.type === 'add') {
    const names = dialog.form.customerIds.map(id => {
      const c = customerOptions.find(opt => opt.id === id);
      return `${c?.name} (${c?.phone})`;
    }).join('、');
    
    tableData.value.push({
      ...dialog.form,
      id: Date.now().toString(),
      customerNames: names
    } as any);
    ElMessage.success('创建成功');
  } else {
    const index = tableData.value.findIndex(i => i.id === dialog.form.id);
    if (index > -1) {
      const names = dialog.form.customerIds.map(id => {
        const c = customerOptions.find(opt => opt.id === id);
        return `${c?.name} (${c?.phone})`;
      }).join('、');
      tableData.value[index] = { ...dialog.form, customerNames: names } as any;
    }
    ElMessage.success('修改成功');
  }
  dialog.visible = false;
};

const handleGoTicket = () => {
  router.push('/system/agent/ticket');
};
</script>

<style scoped lang="scss">
.agent-config-page {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);

  .search-input {
    :deep(.el-input-group__append) {
      background-color: #007bff;
      border-color: #007bff;
      color: #fff;
      padding: 0;
      .el-button {
        border: none;
        margin: 0;
        padding: 0 15px;
        color: #fff;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 0;
        &:hover {
          background-color: #0069d9;
        }
      }
    }
  }

  :deep(.custom-header th) {
    background-color: #f7f8fa !important;
    color: #4e5969;
    font-weight: 500;
    padding: 12px 0;
    border-bottom: none !important;
  }

  .custom-table {
    :deep(.el-table__inner-wrapper::before) {
      display: none;
    }
  }
}

:deep(.custom-dialog) {
  .el-dialog__header {
    border-bottom: 1px solid #f0f2f5;
    margin-right: 0;
    padding: 15px 20px;
  }
  .el-dialog__body {
    padding: 30px 40px;
  }
}
</style>
