<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="serviceName">
              <el-input v-model="queryParams.serviceName" placeholder="请输入客服名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="手机号" prop="phonenumber">
              <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号" clearable @keyup.enter="handleQuery" />
            </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="['system:sysService:add']">新增客服</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="sysServiceList" @selection-change="handleSelectionChange">
        <el-table-column label="序号" type="index" width="80px" align="center" />
        <el-table-column label="客服名称" align="center" prop="serviceName" />
        <el-table-column label="二维码" align="center" prop="qrCode">
          <template #default="scope">
            <img :src="scope.row.qrCode" style="width: 40px; height: 40px" class="qr-code" />
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="phonenumber" />
        <el-table-column label="创建时间" align="center" prop="createTime" />

        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              v-if="scope.row.isDefault == '0'"
              @click="setDefaultService(scope.row)"
              v-hasPermi="['system:sysService:edit']"
              >设为默认</el-button
            >
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:sysService:edit']">编辑</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:sysService:remove']">删除</el-button>
          </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="sysServiceFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客服二维码" prop="qrCode">
          <div class="image-upload-container">
            <div class="upload-item" v-if="form.qrCode">
              <el-image :src="form.qrCode" fit="cover" class="upload-image" />
              <div class="upload-mask">
                <el-icon @click="openFileSelector()" class="mask-icon">
                  <Edit />
                </el-icon>
                <el-icon @click="form.qrCode = ''" class="mask-icon">
                  <Delete />
                </el-icon>
              </div>
            </div>
            <div v-else class="upload-placeholder" @click="openFileSelector()">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-hint">建议尺寸</div>
              <div class="upload-size">430 × 430</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="客服名称" prop="serviceName">
          <el-input v-model="form.serviceName" placeholder="请输入客服名称" />
        </el-form-item>
        <el-form-item label="客服手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号" />
        </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>

    <!-- 文件选择器 -->
    <FileSelector
      v-model="showFileSelector"
      :allowed-types="[1]"
      :multiple="false"
      title="选择客服二维码"
      @confirm="handleFileSelect"
    />
  </div>
</template>

<script setup name="SysService" lang="ts">
import { listSysService, getSysService, delSysService, addSysService, updateSysService, setDefault } from '@/api/store/sysService/index';
import { SysServiceVO, SysServiceQuery, SysServiceForm } from '@/api/store/sysService/types';
import FileSelector from '@/components/FileSelector/index.vue';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const sysServiceList = ref<SysServiceVO[]>([]);
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 showFileSelector = ref(false);

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

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

const initFormData: SysServiceForm = {
  id: undefined,
  serviceName: undefined,
  qrCode: undefined,
  phonenumber: undefined,
  isDefault: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<SysServiceForm, SysServiceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    serviceName: undefined,
    qrCode: undefined,
    phonenumber: undefined,
    isDefault: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    serviceName: [{ required: true, message: '客服名称不能为空', trigger: 'blur' }],
    qrCode: [{ required: true, message: '客服二维码不能为空', trigger: 'blur' }],
    phonenumber: [{ required: true, message: '手机号不能为空', trigger: 'blur' }]
  }
});

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

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

const setDefaultService = async (row: SysServiceVO) => {
  const res = await setDefault(row.id);
  if (res.code === 200) {
    ElMessage.success('设置成功');
    getList();
  }
};

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

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

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

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

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

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

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

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

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

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/sysService/export',
    {
      ...queryParams.value
    },
    `sysService_${new Date().getTime()}.xlsx`
  );
};

/** 打开文件选择器 */
const openFileSelector = () => {
  showFileSelector.value = true;
};

/** 处理文件选择 */
const handleFileSelect = (files: any[]) => {
  if (files && files.length > 0) {
    const file = files[0];
    form.value.qrCode = file.url || file.path;
  }
};

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

<style scoped lang="scss">
.image-upload-container {
  display: inline-block;
}

.upload-item {
  position: relative;
  width: 148px;
  height: 148px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  
  .upload-image {
    width: 100%;
    height: 100%;
  }
  
  .upload-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 15px;
    opacity: 0;
    transition: opacity 0.3s;
    
    .mask-icon {
      font-size: 20px;
      color: #fff;
      cursor: pointer;
      transition: transform 0.3s;
      
      &:hover {
        transform: scale(1.2);
      }
    }
  }
  
  &:hover .upload-mask {
    opacity: 1;
  }
}

.upload-placeholder {
  width: 148px;
  height: 148px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: border-color 0.3s;
  gap: 6px;
  
  .upload-icon {
    font-size: 28px;
    color: #8c939d;
  }
  
  .upload-hint {
    font-size: 12px;
    color: #8c939d;
    margin-top: 4px;
  }
  
  .upload-size {
    font-size: 12px;
    color: #606266;
    font-weight: 500;
  }
  
  &:hover {
    border-color: #409eff;
    
    .upload-icon {
      color: #409eff;
    }
    
    .upload-hint {
      color: #409eff;
    }
    
    .upload-size {
      color: #409eff;
    }
  }
}
</style>
