<template>
  <PageContainer title="企业管理">
    <QueryToolbar>
      <el-button v-if="canManage" type="primary" @click="openCreateDrawer">新增企业</el-button>
      <el-button v-if="canRead" @click="load">刷新</el-button>
    </QueryToolbar>

    <el-table :data="rows" class="mt-md" empty-text="暂无数据">
      <!-- <el-table-column prop="id" label="ID" width="90" /> -->
      <el-table-column prop="enterpriseName" label="企业名称" width="220" />
      <el-table-column prop="enterpriseUrl" label="企业网址" />
      <el-table-column prop="logoUrl" label="Logo地址">

        <template #default="{ row }">
          <img
            v-if="row.logoUrl"
            :src="row.logoDisplayUrl || row.logoUrl"
            alt="enterprise-logo"
            style="max-height: 36px; max-width: 140px; object-fit: contain;"
          />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" :formatter="statusFormatter" />
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column label="操作" width="260">
        <template #default="{ row }">
          <el-button v-if="canManage" size="small" @click="openEdit(row)">编辑</el-button>
          <el-button
            v-if="canManage && row.status === 'ENABLED'"
            size="small"
            type="warning"
            @click="handleDisable(row.id)"
          >
            停用
          </el-button>
          <el-button
            v-else-if="canManage"
            size="small"
            type="success"
            @click="handleEnable(row.id)"
          >
            启用
          </el-button>
          <el-button
            v-if="canDelete && row.status === 'DISABLED'"
            size="small"
            type="danger"
            @click="handleDelete(row.id, row.enterpriseName)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="mt-md"
      background
      layout="total, prev, pager, next, sizes"
      :total="totalCount"
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      @size-change="load"
      @current-change="load"
    />

    <el-drawer v-model="createVisible" title="新增企业" :size="DRAWER_SIZE.md" destroy-on-close>
      <el-form ref="formRef" :model="form" label-position="left" :label-width="LABEL_WIDTH.md" :rules="formRules">
        <el-form-item label="企业名称" prop="enterpriseName">
          <el-input v-model="form.enterpriseName" />
        </el-form-item>
        <el-form-item label="企业网址">
          <el-input v-model="form.enterpriseUrl" />
        </el-form-item>
        <el-form-item label="Logo地址">
          <el-input v-model="form.logoUrl" />
        </el-form-item>
        <el-form-item label="Logo文件">
          <el-upload
            :auto-upload="false"
            :show-file-list="false"
            :limit="1"
            accept="image/*"
            :on-change="onCreateLogoFileChange"
          >
            <el-button>选择Logo文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button v-if="canManage" :disabled="!createLogoFile" @click="uploadCreateLogo">
            上传Logo到OSS
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button v-if="canManage" type="primary" @click="handleCreate">创建</el-button>
      </template>
    </el-drawer>

    <el-dialog v-model="editVisible" title="编辑企业" :width="DIALOG_WIDTH.md">
      <el-form ref="editFormRef" :model="editForm" label-position="left" :label-width="LABEL_WIDTH.md" :rules="formRules">
        <el-form-item label="企业名称" prop="enterpriseName">
          <el-input v-model="editForm.enterpriseName" />
        </el-form-item>
        <el-form-item label="企业网址">
          <el-input v-model="editForm.enterpriseUrl" />
        </el-form-item>
        <el-form-item label="Logo地址">
          <el-input v-model="editForm.logoUrl" />
        </el-form-item>
        <el-form-item label="Logo文件">
          <el-upload
            :auto-upload="false"
            :show-file-list="false"
            :limit="1"
            accept="image/*"
            :on-change="onEditLogoFileChange"
          >
            <el-button>选择Logo文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button v-if="canManage" :disabled="!editLogoFile" @click="uploadEditLogo">
            上传Logo到OSS
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import PageContainer from "../../components/PageContainer.vue";
import QueryToolbar from "../../components/QueryToolbar.vue";
import { DRAWER_SIZE, DIALOG_WIDTH, LABEL_WIDTH } from "../../constants/ui";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  createEnterprise,
  deleteEnterprise,
  disableEnterprise,
  enableEnterprise,
  fetchEnterpriseLogoUploadSign,
  fetchEnterprises,
  updateEnterprise,
} from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";
import { fetchFilePresignDownload } from "../../api/modules";
import { toZhStatus } from "../../utils/status";

const authStore = useAuthStore();
const canRead = computed(() => authStore.hasPermission(PERMS.enterprise.read));
const canManage = computed(() => authStore.hasPermission(PERMS.enterprise.manage));
const canDelete = computed(() => authStore.hasPermission(PERMS.enterprise.delete));
const rows = ref<any[]>([]);
const pageNo = ref(1);
const pageSize = ref(20);
const totalCount = ref(0);
const createVisible = ref(false);
const editVisible = ref(false);
const editId = ref<number | null>(null);
const editForm = ref<any>({});
const createLogoFile = ref<File | null>(null);
const editLogoFile = ref<File | null>(null);
const form = ref({
  enterpriseName: "",
  enterpriseUrl: "",
  logoUrl: "",
});
const formRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();
const formRules = ref<FormRules>({
  enterpriseName: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
});
const statusFormatter = (_row: any, _column: any, value: unknown) => toZhStatus(value);

const load = async () => {
  const resp = await fetchEnterprises({ pageNo: pageNo.value, pageSize: pageSize.value });
  const list = resp?.data?.list || [];
  rows.value = list;
  totalCount.value = Number(resp?.data?.total || 0);
  await Promise.all(
    rows.value.map(async (row) => {
      const objectKey = String(row?.logoUrl || "");
      if (!objectKey) {
        row.logoDisplayUrl = "";
        return;
      }
      if (objectKey.startsWith("http://") || objectKey.startsWith("https://")) {
        row.logoDisplayUrl = objectKey;
        return;
      }
      try {
        const presignResp = await fetchFilePresignDownload({ objectKey });
        row.logoDisplayUrl = String(presignResp?.data?.signedUrl || "");
      } catch (_e) {
        row.logoDisplayUrl = "";
      }
    }),
  );
};

const openCreateDrawer = () => {
  form.value = {
    enterpriseName: "",
    enterpriseUrl: "",
    logoUrl: "",
  };
  createLogoFile.value = null;
  createVisible.value = true;
};

const putToSignedUrl = async (url: string, file: File, contentType: string) => {
  const result = await fetch(url, {
    method: "PUT",
    headers: {
      "Content-Type": contentType || "application/octet-stream",
    },
    body: file,
  });
  if (!result.ok) {
    throw new Error(`上传失败: ${result.status}`);
  }
};

const onCreateLogoFileChange = (uploadFile: any) => {
  createLogoFile.value = (uploadFile?.raw as File) || null;
};

const onEditLogoFileChange = (uploadFile: any) => {
  editLogoFile.value = (uploadFile?.raw as File) || null;
};

const uploadCreateLogo = async () => {
  if (!createLogoFile.value) {
    ElMessage.warning("请先选择Logo文件");
    return;
  }
  const resp = await fetchEnterpriseLogoUploadSign({
    fileName: createLogoFile.value.name,
    contentType: createLogoFile.value.type,
  });
  const uploadUrl = resp?.data?.uploadUrl;
  const objectKey = resp?.data?.objectKey;
  const contentType = resp?.data?.contentType || createLogoFile.value.type || "application/octet-stream";
  if (!uploadUrl || !objectKey) {
    ElMessage.error("获取Logo上传签名失败");
    return;
  }
  await putToSignedUrl(uploadUrl, createLogoFile.value, contentType);
  form.value.logoUrl = objectKey;
  ElMessage.success("Logo已上传并回填");
};

const uploadEditLogo = async () => {
  if (!editLogoFile.value) {
    ElMessage.warning("请先选择Logo文件");
    return;
  }
  const resp = await fetchEnterpriseLogoUploadSign({
    fileName: editLogoFile.value.name,
    contentType: editLogoFile.value.type,
  });
  const uploadUrl = resp?.data?.uploadUrl;
  const objectKey = resp?.data?.objectKey;
  const contentType = resp?.data?.contentType || editLogoFile.value.type || "application/octet-stream";
  if (!uploadUrl || !objectKey) {
    ElMessage.error("获取Logo上传签名失败");
    return;
  }
  await putToSignedUrl(uploadUrl, editLogoFile.value, contentType);
  editForm.value.logoUrl = objectKey;
  ElMessage.success("Logo已上传并回填");
};

const handleCreate = async () => {
  if (!formRef.value) return;
  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) return;

  await createEnterprise({
    enterpriseName: form.value.enterpriseName.trim(),
    enterpriseUrl: form.value.enterpriseUrl.trim(),
    logoUrl: form.value.logoUrl.trim(),
  });
  ElMessage.success("企业创建成功");
  createVisible.value = false;
  await load();
};

const openEdit = (row: any) => {
  editId.value = row.id;
  editForm.value = { ...row };
  editLogoFile.value = null;
  editVisible.value = true;
};

const handleSave = async () => {
  if (!editId.value) return;
  if (!editFormRef.value) return;
  const valid = await editFormRef.value.validate().catch(() => false);
  if (!valid) return;

  await updateEnterprise(editId.value, {
    enterpriseName: String(editForm.value.enterpriseName || "").trim(),
    enterpriseUrl: String(editForm.value.enterpriseUrl || "").trim(),
    logoUrl: String(editForm.value.logoUrl || "").trim(),
  });
  ElMessage.success("企业更新成功");
  editVisible.value = false;
  await load();
};

const handleEnable = async (id: number) => {
  await enableEnterprise(id);
  ElMessage.success("企业已启用");
  await load();
};

const handleDisable = async (id: number) => {
  await disableEnterprise(id);
  ElMessage.success("企业已停用");
  await load();
};

const handleDelete = async (id: number, name: string) => {
  await ElMessageBox.confirm(`确认删除企业「${name}」？删除后不可恢复。`, "删除企业", {
    type: "warning",
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
  });
  await deleteEnterprise(id);
  ElMessage.success("企业已删除");
  await load();
};

onMounted(async () => {
  if (canRead.value) {
    await load();
  }
});
</script>
