<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 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 === 'operation')?.show" fixed="right" label="操作"
                align="center" min-width="220">
                <template #default="scope">
                  <!-- <el-button v-hasPerm="['module_payment:enterprise:detail']" type="info" size="small" link icon="View"
                    @click="handleOpenDialog('detail')">
                    详情
                  </el-button>
                  <el-button v-hasPerm="['module_payment:enterprise:update']" type="primary" size="small" link
                    icon="edit" :disabled="scope.row.status !== 'ENTERPRISE_CREATE'"
                    @click="handleOpenDialog('update')">
                    编辑
                  </el-button>
                  <el-button v-hasPerm="['module_payment:enterprise:unsign']" type="warning" size="small" link
                    icon="Close" :disabled="scope.row.status !== 'ENTERPRISE_ACTIVATED'"
                    @click="handleUnsign(scope.row.enterprise_id)">
                    解约
                  </el-button>
                  <el-button v-hasPerm="['module_payment:enterprise:delete']" type="danger" size="small" link
                    icon="delete" :disabled="scope.row.status !== 'ENTERPRISE_UNSIGN'"
                    @click="handleDelete(scope.row.enterprise_id)">
                    注销
                  </el-button> -->
                  <!-- <el-button v-hasPerm="['module_payment:enterprise:invite']" type="info" size="small" link icon="Link"
                    @click="">
                    继续签约
                  </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="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 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 } from "vue";
import { useEnterpriseStore } from "@/store/modules/enterprise.store";

const router = useRouter();

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: "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,
  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);
    return {
      list: res.data?.data?.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);

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;
  }
  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;
  });
}
</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>