<template>
  <div v-loading="pageLoading" class="app-container" :element-loading-text="loadingText">
    <div v-if="hasEnterprise">
      <PageSearch ref="searchRef" :search-config="searchConfig" @query-click="handleQueryClick"
        @reset-click="handleResetClick" />

      <PageContent ref="contentRef" :content-config="contentConfig">
        <template #toolbar="{ toolbarRight, onToolbar, removeIds, cols }">
          <CrudToolbarLeft v-if="!isAdmin" text="新增企业" :remove-ids="removeIds" :perm-create="['module_payment:enterprise:invite']">
            <el-button v-hasPerm="['module_payment:enterprise:invite']" type="primary" icon="Plus"
                @click="handleOpenDialog('apply')">
                新增企业
              </el-button>
          </CrudToolbarLeft>

          <div class="data-table__toolbar--right">
            <CrudToolbarRight :buttons="toolbarRight" :cols="cols" :on-toolbar="onToolbar" />
          </div>
        </template>

        <template #table="{ data, loading, tableRef, onSelectionChange }">
          <div class="data-table__content">
            <el-table :ref="tableRef as any" v-loading="loading" :data="data" height="100%" border
              @selection-change="onSelectionChange">
              <template #empty>
                <el-empty :image-size="80" description="暂无数据" />
              </template>
              <el-table-column v-if="contentCols.find((col) => col.prop === 'selection')?.show" type="selection"
                min-width="55" align="center" />
              <el-table-column v-if="contentCols.find((col) => col.prop === 'enterprise_id')?.show" key="enterprise_id"
                label="企业ID" prop="enterprise_id" min-width="150" show-overflow-tooltip />
              <el-table-column v-if="contentCols.find((col) => col.prop === 'name')?.show" key="name" label="企业名称"
                prop="name" min-width="150" show-overflow-tooltip />
              <el-table-column v-if="contentCols.find((col) => col.prop === 'short_name')?.show" key="short_name"
                label="企业简称" prop="short_name" min-width="100" show-overflow-tooltip />
              <el-table-column v-if="contentCols.find((col) => col.prop === 'status')?.show" key="status" label="状态"
                prop="status" min-width="100">
                <template #default="scope">
                  <el-tag :type="STATUS_TAG_TYPE[scope.row.status]">
                    {{ STATUS_LABEL[scope.row.status] || scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column v-if="contentCols.find((col) => col.prop === 'created_time')?.show" key="created_time"
                label="创建时间" prop="created_time" min-width="160" sortable />
              <el-table-column v-if="contentCols.find((col) => col.prop === 'f2f_status')?.show" key="f2f_status"
                label="当面付" prop="f2f_status" min-width="100">
                <template #default="scope">
                  <el-tag v-if="scope.row.f2f_status" :type="ORDER_STATUS_TAG_TYPE[scope.row.f2f_status]">
                    {{ ORDER_STATUS_LABEL[scope.row.f2f_status] }}
                  </el-tag>
                  <span v-else style="color: #909399">未开通</span>
                </template>
              </el-table-column>
              <el-table-column v-if="contentCols.find((col) => col.prop === 'operation')?.show" fixed="right" label="操作"
                align="center" min-width="280">
                <template #default="scope">
                  <el-button type="primary" size="small" link
                    @click="handleOpenDetail(scope.row)">
                    详情
                  </el-button>
                  <el-button
                    size="small" link
                    :type="scope.row.transfer_enabled ? 'danger' : 'success'"
                    :loading="scope.row._toggling"
                    @click="handleToggleTransfer(scope.row)">
                    {{ scope.row.transfer_enabled ? '关闭转账' : '开通转账' }}
                  </el-button>
                  <el-button v-if="!isAdmin && (!scope.row.f2f_status || scope.row.f2f_status === 'CLOSED')"
                    v-hasPerm="['module_payment:facetoface:apply']" type="success" size="small" link
                    @click="handleOpenF2fApply(scope.row)">
                    开通当面付
                  </el-button>
                  <el-button
                    v-if="scope.row.f2f_status === 'PENDING_AUTH'"
                    type="warning" size="small" link icon="Link"
                    @click="handleGetAuthUrl(scope.row)">
                    授权
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </PageContent>
    </div>

    <div v-else>
      <div class="enterprise-empty">
        <div class="empty-content">
          <div class="empty-icon">
            <el-icon class="empty-icon-large">
              <OfficeBuilding />
            </el-icon>
          </div>
          <h3 class="empty-title">企业入驻 & 签约</h3>
          <p class="empty-desc">
            还没有企业入驻企业，点击下方按钮开始申请
          </p>
          <el-button type="primary" size="large" @click="handleOpenDialog('apply')">
            <el-icon>
              <Plus />
            </el-icon>
            申请入驻
          </el-button>
        </div>
      </div>
    </div>

    <InviteDialog v-model="inviteDialogVisible" :invite-data="inviteData" />

    <EnhancedDialog v-model="dialogVisible.visible" :title="dialogVisible.title" @close="handleCloseDialog">
      <template v-if="dialogVisible.type === 'detail'">
        <EnterpriseDetail :out-biz-no="currentOutBizNo" />
      </template>
      <template v-else>
        <EnterpriseForm ref="formRef" :type="dialogVisible.type" :enterprise-id="currentOutBizNo"
          @success="handleFormSuccess" />
      </template>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="dialogVisible.type !== 'detail'" type="primary" @click="handleSubmit"
            :disabled="formRef?.value?.isSubmitting">
            提交
          </el-button>
          <el-button v-else type="primary" @click="handleCloseDialog">确定</el-button>
          <el-button @click="handleCloseDialog">取消</el-button>
        </div>
      </template>
    </EnhancedDialog>

    <!-- 当面付代开通弹窗 -->
    <EnhancedDialog v-model="f2fDialogVisible" title="开通当面付" width="520px" @close="handleCloseF2fDialog">
      <el-form ref="f2fFormRef" :model="f2fForm" :rules="f2fRules" label-width="130px">
        <el-form-item label="商户支付宝账号" prop="account">
          <el-input v-model="f2fForm.account" placeholder="支付宝账号或2088开头的pid" />
        </el-form-item>
        <el-form-item label="经营类目" prop="mcc_code">
          <el-select v-model="f2fForm.mcc_code" placeholder="请搜索选择经营类目" filterable clearable
            style="width: 100%">
            <el-option v-for="item in MCC_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人姓名" prop="contact_name">
          <el-input v-model="f2fForm.contact_name" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系人手机号" prop="contact_mobile">
          <el-input v-model="f2fForm.contact_mobile" placeholder="11位手机号码" maxlength="11" />
        </el-form-item>
        <el-form-item label="联系人邮箱">
          <el-input v-model="f2fForm.contact_email" placeholder="选填" />
        </el-form-item>
        <el-form-item label="店铺门头照">
          <input type="file" accept="image/*" @change="handleShopSignBoardPicChange" />
        </el-form-item>
        <el-form-item label="店铺内景照">
          <input type="file" accept="image/*" @change="handleShopScenePicChange" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="f2fForm.remark" type="textarea" :rows="2" placeholder="选填" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" :loading="f2fSubmitting" @click="handleSubmitF2f">提交</el-button>
        <el-button @click="handleCloseF2fDialog">取消</el-button>
      </template>
    </EnhancedDialog>

    <EnhancedDialog v-model="employeeDialogVisible" title="添加员工" @close="handleEmployeeDialogClose">
      <EmployeeForm ref="employeeFormRef" type="create" :enterprise-id="employeeDialogEnterpriseId"
        @success="handleEmployeeFormSuccess" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleEmployeeFormSubmit" :loading="isEmployeeSubmitting">
            提交
          </el-button>
          <el-button @click="handleEmployeeDialogClose">取消</el-button>
        </div>
      </template>
    </EnhancedDialog>

  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Enterprise",
  inheritAttrs: false,
});

import { OfficeBuilding, Plus } from "@element-plus/icons-vue";
import EnterpriseAPI, {
  STATUS_TAG_TYPE,
  STATUS_LABEL,
} from "@/api/module_payment/enterprise";
import FacetofaceAPI, {
  ORDER_STATUS_TAG_TYPE,
  ORDER_STATUS_LABEL,
} from "@/api/module_payment/facetoface";
import { MCC_OPTIONS } from "@/constants/mcc-codes";
import CrudToolbarLeft from "@/components/CURD/CrudToolbarLeft.vue";
import CrudToolbarRight from "@/components/CURD/CrudToolbarRight.vue";
import PageSearch from "@/components/CURD/PageSearch.vue";
import PageContent from "@/components/CURD/PageContent.vue";
import EnhancedDialog from "@/components/CURD/EnhancedDialog.vue";
import EnterpriseForm from "./components/EnterpriseForm.vue";
import EnterpriseDetail from "./components/EnterpriseDetail.vue";
import InviteDialog from "./components/InviteDialog.vue";
import EmployeeForm from "@/views/module_payment/employee/components/EmployeeForm.vue";
import type { ISearchConfig, IContentConfig } from "@/components/CURD/types";
import { useCrudList } from "@/components/CURD/useCrudList";
import { useLoadingAction } from "@/composables/useLoadingAction";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ref, reactive, computed } from "vue";
import { useEnterpriseStore } from "@/store/modules/enterprise.store";
import { useUserStore } from "@/store/modules/user.store";
import { ROLE_ROOT } from "@/constants/storage-keys";

const router = useRouter();
const userStore = useUserStore();
const isAdmin = computed(() => userStore.basicInfo?.roles?.some(r => r.code === ROLE_ROOT));

const { searchRef, contentRef, handleQueryClick, handleResetClick, refreshList } = useCrudList();
const formRef = ref();
const enterpriseStore = useEnterpriseStore();

const hasEnterprise = computed(() => enterpriseStore.hasEnterprise);

onMounted(async () => {});

const searchConfig = reactive<ISearchConfig>({
  permPrefix: "module_payment:enterprise",
  colon: true,
  isExpandable: true,
  showNumber: 2,
  form: { labelWidth: "auto" },
  formItems: [
    {
      prop: "name",
      label: "企业名称",
      type: "input",
      attrs: { placeholder: "请输入企业名称", clearable: true },
    },
    {
      prop: "enterprise_id",
      label: "企业ID",
      type: "input",
      attrs: { placeholder: "请输入企业ID", clearable: true },
    },
    {
      prop: "status",
      label: "状态",
      type: "select",
      options: [
        { label: "全部", value: "" },
        { label: "已创建", value: "ENTERPRISE_CREATE" },
        { label: "已签约", value: "ENTERPRISE_ACTIVATED" },
        { label: "已解约", value: "ENTERPRISE_UNSIGN" },
        { label: "已注销", value: "ENTERPRISE_WITHDRAW" },
      ],
      attrs: { placeholder: "请选择状态", clearable: true, style: { width: "167.5px" } },
    },
    {
      prop: "created_time",
      label: "创建时间",
      type: "date-picker",
      attrs: {
        type: "datetimerange",
        rangeSeparator: "至",
        startPlaceholder: "开始日期",
        endPlaceholder: "结束日期",
        format: "YYYY-MM-DD HH:mm:ss",
        valueFormat: "YYYY-MM-DD HH:mm:ss",
        style: { width: "340px" },
      },
    },
  ],
});

const contentCols = reactive<
  Array<{
    prop?: string;
    label?: string;
    show?: boolean;
  }>
>([
  { prop: "selection", label: "选择框", show: false },
  { prop: "index", label: "序号", show: true },
  { prop: "name", label: "企业名称", show: true },
  { prop: "short_name", label: "企业简称", show: true },
  { prop: "enterprise_id", label: "企业ID", show: true },
  { prop: "status", label: "状态", show: true },
  { prop: "f2f_status", label: "当面付", show: true },
  { prop: "created_time", label: "创建时间", show: true },
  { prop: "operation", label: "操作", show: true },
]);

const contentConfig = reactive<IContentConfig<any>>({
  permPrefix: "module_payment:enterprise",
  pk: "enterprise_id",
  cols: contentCols as IContentConfig["cols"],
  hideColumnFilter: false,
  toolbar: [],
  defaultToolbar: ["refresh", "filter"],
  pagination: true,
  request: { page_no: "page_no", page_size: "page_size" },
  indexAction: async (params) => {
    const search: Record<string, any> = {};
    if (params.name) search.name = params.name;
    if (params.enterprise_id) search.enterprise_id = params.enterprise_id;
    if (params.status) search.status = params.status;
    if (params.created_time && params.created_time.length === 2) {
      search.start_time = params.created_time[0];
      search.end_time = params.created_time[1];
    }
    const res = await EnterpriseAPI.list(params.page_no, params.page_size, search);
    const items = res.data?.data?.items || res.data?.data?.list || [];
    // 批量查询当面付状态
    if (items.length > 0) {
      const eids = items.map((it: any) => it.enterprise_id).filter(Boolean);
      if (eids.length > 0) {
        try {
          const statusRes = await FacetofaceAPI.batchStatus(eids);
          const statusMap = statusRes.data?.data || {};
          items.forEach((it: any) => {
            it.f2f_status = statusMap[it.enterprise_id] || null;
          });
        } catch { /* ignore */ }
      }
    }
    return {
      list: items,
      total: res.data?.data?.total || 0,
    };
  },
});

const dialogVisible = reactive({
  title: "",
  visible: false,
  type: "apply" as "apply" | "update" | "detail",
});

const currentOutBizNo = ref<string>();

const inviteDialogVisible = ref(false);
const inviteData = ref({
  pc_invite_url: "",
  expire_time: "",
});

const employeeDialogVisible = ref(false);
const employeeDialogEnterpriseId = ref<string>();
const employeeFormRef = ref();
const isEmployeeSubmitting = ref(false);

async function handleToggleTransfer(row: any) {
  row._toggling = true;
  try {
    await EnterpriseAPI.update(row.enterprise_id, { transfer_enabled: !row.transfer_enabled });
    row.transfer_enabled = !row.transfer_enabled;
    // 同步更新 store 中当前企业的缓存
    const current = enterpriseStore.currentEnterprise;
    if (current?.enterprise_id === row.enterprise_id) {
      enterpriseStore.currentEnterprise = { ...current, transfer_enabled: row.transfer_enabled };
    }
    ElMessage.success(row.transfer_enabled ? "已开通转账功能" : "已关闭转账功能");
  } catch {
    ElMessage.error("操作失败");
  } finally {
    row._toggling = false;
  }
}

function handleOpenDialog(type: "apply" | "update" | "detail") {
  dialogVisible.type = type;
  if (type === "apply") {
    dialogVisible.title = "申请入驻";
  } else if (type === "update") {
    dialogVisible.title = "编辑企业";
  } else {
    dialogVisible.title = "企业详情";
  }
  dialogVisible.visible = true;
}

async function handleCloseDialog() {
  dialogVisible.visible = false;
}

function handleSubmit() {
  formRef.value?.submitForm();
}

function handleFormSuccess() {
  dialogVisible.visible = false;
  refreshList();
}

const { pageLoading, loadingText, execute: loadingExecute } = useLoadingAction();

// async function handleApplyInvite(data: { identity_type: string; identity?: string; identity_open_id?: string }) {
//   const res = await loadingExecute({
//     loadingText: "正在申请入驻...",
//     action: () => EnterpriseAPI.applyInvite(data),
//   });
//   if (res) {
//     const inviteUrl = res.data?.data?.pc_invite_url;
//     if (inviteUrl) {
//       window.open(inviteUrl, "_blank");
//     }
//     refreshList();
//   }
// }

async function handleUnsign(enterpriseId: string) {
  await loadingExecute({
    confirmMessage: "确认进行企业解约?",
    confirmTitle: "警告",
    confirmType: "warning",
    loadingText: "正在解约...",
    action: () => EnterpriseAPI.unsign(enterpriseId),
    onSuccess: () => {
      ElMessage.success("解约申请已提交");
      refreshList();
    },
  });
}

async function handleDelete(enterpriseId: string) {
  await loadingExecute({
    confirmMessage: "确认进行企业注销?",
    confirmTitle: "警告",
    confirmType: "warning",
    loadingText: "正在注销...",
    action: () => EnterpriseAPI.delete(enterpriseId),
    onSuccess: () => {
      ElMessage.success("注销申请已提交");
      refreshList();
    },
  });
}

function handleGoToEmployee(enterpriseId?: string) {
  if (!enterpriseId) {
    ElMessage.warning("该企业暂无企业ID");
    return;
  }
  enterpriseStore.setCurrentEnterprise(enterpriseId);
  router.push({
    path: "/module_payment/employee",
    query: { enterprise_id: enterpriseId },
  });
}

function handleAddEmployee(enterpriseId?: string) {
  if (!enterpriseId) {
    ElMessage.warning("该企业暂无企业ID");
    return;
  }
  employeeDialogEnterpriseId.value = enterpriseId;
  employeeDialogVisible.value = true;
}

function handleEmployeeDialogClose() {
  employeeDialogVisible.value = false;
  employeeDialogEnterpriseId.value = undefined;
}

function handleEmployeeFormSuccess() {
  employeeDialogVisible.value = false;
  employeeDialogEnterpriseId.value = undefined;
  ElMessage.success("添加员工成功");
}

function handleEmployeeFormSubmit() {
  if (isEmployeeSubmitting.value) return;
  isEmployeeSubmitting.value = true;
  employeeFormRef.value?.submitForm().finally(() => {
    isEmployeeSubmitting.value = false;
  });
}

// ---------- 当面付开通 ----------
const f2fDialogVisible = ref(false);
const f2fFormRef = ref<FormInstance>();
const f2fSubmitting = ref(false);
const currentF2fEnterprise = ref<any>(null);

const f2fForm = reactive({
  account: "",
  mcc_code: "",
  contact_name: "",
  contact_mobile: "",
  contact_email: "",
  remark: "",
  shop_sign_board_pic_base64: "",
  shop_scene_pic_base64: "",
});

const f2fRules = reactive<FormRules>({
  account: [{ required: true, message: "请输入商户支付宝账号或pid", trigger: "blur" }],
  contact_name: [{ required: true, message: "请输入联系人姓名", trigger: "blur" }],
  contact_mobile: [
    { required: true, message: "请输入联系人手机号", trigger: "blur" },
    { pattern: /^1\d{10}$/, message: "请输入正确的11位手机号", trigger: "blur" },
  ],
});

function handleOpenDetail(row: any) {
  currentOutBizNo.value = row.enterprise_id;
  handleOpenDialog("detail");
}

function handleOpenF2fApply(enterprise: any) {
  currentF2fEnterprise.value = enterprise;
  Object.assign(f2fForm, {
    account: "",
    mcc_code: "",
    contact_name: "",
    contact_mobile: "",
    contact_email: "",
    remark: "",
    shop_sign_board_pic_base64: "",
    shop_scene_pic_base64: "",
  });
  f2fDialogVisible.value = true;
}

function handleCloseF2fDialog() {
  f2fDialogVisible.value = false;
  f2fFormRef.value?.resetFields();
}

function fileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve((reader.result as string).split(",")[1]);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

async function handleShopSignBoardPicChange(e: Event) {
  const input = e.target as HTMLInputElement;
  if (input.files?.[0]) {
    f2fForm.shop_sign_board_pic_base64 = await fileToBase64(input.files[0]);
  }
}

async function handleShopScenePicChange(e: Event) {
  const input = e.target as HTMLInputElement;
  if (input.files?.[0]) {
    f2fForm.shop_scene_pic_base64 = await fileToBase64(input.files[0]);
  }
}

async function handleSubmitF2f() {
  if (!f2fFormRef.value || !currentF2fEnterprise.value) return;
  try {
    await f2fFormRef.value.validate();
  } catch {
    return;
  }
  f2fSubmitting.value = true;
  try {
    const submitData: Record<string, any> = {
      enterprise_id: currentF2fEnterprise.value.enterprise_id,
      account: f2fForm.account,
      mcc_code: f2fForm.mcc_code,
      contact_name: f2fForm.contact_name,
      contact_mobile: f2fForm.contact_mobile,
    };
    if (f2fForm.contact_email) submitData.contact_email = f2fForm.contact_email;
    if (f2fForm.remark) submitData.remark = f2fForm.remark;
    if (f2fForm.shop_sign_board_pic_base64) submitData.shop_sign_board_pic_base64 = f2fForm.shop_sign_board_pic_base64;
    if (f2fForm.shop_scene_pic_base64) submitData.shop_scene_pic_base64 = f2fForm.shop_scene_pic_base64;

    await FacetofaceAPI.apply(submitData as any);
    ElMessage.success("当面付代开通申请已提交");
    handleCloseF2fDialog();
    refreshList();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.msg || "提交失败");
  } finally {
    f2fSubmitting.value = false;
  }
}

// ---------- 授权链接 ----------
async function handleGetAuthUrl(row: any) {
  try {
    const res = await EnterpriseAPI.getAuthUrl(row.enterprise_id);
    const authUrl = res.data?.data;
    if (authUrl) {
      window.location.href = authUrl;
    } else {
      ElMessage.error("未获取到授权链接");
    }
  } catch {
    ElMessage.error("获取授权链接失败");
  }
}
</script>

<style lang="scss" scoped>
.enterprise-empty {
  min-height: 60vh;
  display: flex;
  align-items: center;
  justify-content: center;

  .empty-content {
    text-align: center;
    padding: 40px 60px;
    background-color: #ffffff;
    border-radius: 2px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    max-width: 400px;

    .empty-icon {
      margin-bottom: 20px;

      .empty-icon-large {
        font-size: 64px;
        color: #409eff;
      }
    }

    .empty-title {
      font-size: 20px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 12px;
    }

    .empty-desc {
      font-size: 14px;
      color: #606266;
      margin-bottom: 30px;
      line-height: 1.5;
    }

    .el-button {
      padding: 10px 30px;
      font-size: 16px;
    }
  }
}
</style>