<template>
  <div v-loading="pageLoading" class="app-container" :element-loading-text="loadingText">

    <el-tabs type="card" style="height: 400px" class="employee-tabs">
      <el-tab-pane label="员工信息">
        <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 :remove-ids="removeIds" :perm-create="['module_payment:employee:create']">
              <el-button v-hasPerm="['module_payment:employee:create']" type="primary" icon="Plus"
                @click="handleOpenDialog('create')">
                添加员工
              </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 === 'employee_id')?.show" key="employee_id"
                  label="员工ID" prop="employee_id" min-width="150" show-overflow-tooltip /> -->
                <el-table-column v-if="contentCols.find((col) => col.prop === 'employee_name')?.show"
                  key="employee_name" label="员工姓名" prop="employee_name" min-width="120" show-overflow-tooltip />
                <el-table-column v-if="contentCols.find((col) => col.prop === 'employee_no')?.show" key="employee_no"
                  label="员工工号" prop="employee_no" min-width="120" show-overflow-tooltip />
                <el-table-column v-if="contentCols.find((col) => col.prop === 'employee_mobile')?.show"
                  key="employee_mobile" label="手机号" prop="employee_mobile" min-width="120" />
                <el-table-column v-if="contentCols.find((col) => col.prop === 'employee_email')?.show"
                  key="employee_email" label="邮箱" prop="employee_email" min-width="150" 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="160">
                  <template #default="scope">
                    <el-button v-hasPerm="['module_payment:employee:detail']" type="info" size="small" link :icon="View"
                      @click="handleOpenDialog('detail', scope.row.employee_id)">
                      详情
                    </el-button>
                    <el-button v-hasPerm="['module_payment:employee:update']" type="primary" size="small" link
                      @click="handleOpenDialog('update', scope.row.employee_id)">
                      编辑
                    </el-button>
                    <el-button v-hasPerm="['module_payment:employee:invite']" type="success" size="small" link
                      @click="handleGetInviteLink(scope.row)">
                      签约链接
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </PageContent>
      </el-tab-pane>

      <el-tab-pane label="部门信息">
        <PageSearch ref="deptSearchRef" :search-config="deptSearchConfig" @query-click="handleDeptQueryClick"
          @reset-click="handleDeptResetClick" />

        <PageContent ref="deptContentRef" :content-config="deptContentConfig">
          <template #toolbar="{ toolbarRight, onToolbar, removeIds, cols }">
            <CrudToolbarLeft :remove-ids="removeIds" :perm-create="['module_payment:department:create']">
              <el-button v-hasPerm="['module_payment:department:create']" type="primary" icon="Plus"
                @click="handleOpenDeptDialog('create')">
                添加部门
              </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="deptContentCols.find((col) => col.prop === 'selection')?.show" type="selection"
                  min-width="55" align="center" />
                <el-table-column v-if="deptContentCols.find((col) => col.prop === 'name')?.show" key="name" label="部门名称"
                  prop="name" min-width="150" show-overflow-tooltip />
                <el-table-column v-if="deptContentCols.find((col) => col.prop === 'code')?.show" key="code" label="部门编码"
                  prop="code" min-width="120" show-overflow-tooltip />
                <el-table-column v-if="deptContentCols.find((col) => col.prop === 'created_time')?.show"
                  key="created_time" label="创建时间" prop="created_time" min-width="160" sortable />
                <el-table-column v-if="deptContentCols.find((col) => col.prop === 'operation')?.show" fixed="right"
                  label="操作" align="center" min-width="160">
                  <template #default="scope">
                    <el-button v-hasPerm="['module_payment:department:detail']" type="info" size="small" link
                      :icon="View" @click="handleOpenDeptDialog('detail', scope.row.department_id)">
                      详情
                    </el-button>
                    <el-button v-hasPerm="['module_payment:department:update']" type="primary" size="small" link
                      @click="handleOpenDeptDialog('update', scope.row.department_id)">
                      编辑
                    </el-button>
                    <el-button v-hasPerm="['module_payment:department:delete']" type="danger" size="small" link
                      @click="handleDeleteDepartment(scope.row.department_id, scope.row.name)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </PageContent>
      </el-tab-pane>
    </el-tabs>

    <EnhancedDialog v-model="dialogVisible.visible" :title="dialogVisible.title" @close="handleCloseDialog">
      <template v-if="dialogVisible.type === 'detail'">
        <template v-if="dialogVisible.entity === 'employee'">
          <EmployeeDetail :employee-id="currentEmployeeId" :enterprise-id="currentEnterpriseId" />
        </template>
        <template v-else-if="dialogVisible.entity === 'department'">
          <DepartmentDetail :department-id="currentDepartmentId" :enterprise-id="currentEnterpriseId" />
        </template>
      </template>

      <template v-else>
        <template v-if="dialogVisible.entity === 'employee'">
          <EmployeeForm ref="formRef" :type="dialogVisible.type" :employee-id="currentEmployeeId"
            :enterprise-id="currentEnterpriseId" @success="handleFormSuccess" />
        </template>
        <template v-else-if="dialogVisible.entity === 'department'">
          <DepartmentForm ref="deptFormRef" :type="dialogVisible.type" :department-id="currentDepartmentId"
            :enterprise-id="currentEnterpriseId || enterpriseIdFromUrl.value" @success="handleDeptFormSuccess" />
        </template>
      </template>

      <template #footer>
        <div class="dialog-footer">
          <template v-if="dialogVisible.entity === 'employee'">
            <el-button v-if="dialogVisible.type !== 'detail'" @click="handleResetForm">
              重置
            </el-button>
            <el-button v-if="dialogVisible.type !== 'detail' && dialogVisible.type === 'create'" type="primary"
              @click="handleSaveAndAddNext">
              保存并添加下一个
            </el-button>
            <el-button v-if="dialogVisible.type !== 'detail'" type="primary" @click="handleSubmit">
              保存
            </el-button>
            <el-button v-else type="primary" @click="handleCloseDialog">确定</el-button>
          </template>

          <template v-else-if="dialogVisible.entity === 'department'">
            <el-button v-if="dialogVisible.type !== 'detail'" type="primary" @click="handleDeptSubmit">
              保存
            </el-button>
            <el-button v-if="dialogVisible.type === 'create'" type="primary" @click="handleDeptSubmit(true)">
              保存并添加下一个
            </el-button>
            <el-button v-else type="primary" @click="handleCloseDialog">确定</el-button>
          </template>
          <!-- <el-button @click="handleCloseDialog">取消</el-button> -->
        </div>
      </template>
    </EnhancedDialog>

    <!-- 签约链接对话框 -->
    <el-dialog v-model="inviteDialogVisible.visible" :title="inviteDialogVisible.title" width="600px"
      @close="inviteDialogVisible.data = null">
      <div v-if="inviteDialogVisible.data" class="invite-link-container">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="邀请链接">
            <div class="link-item">
              <el-link type="primary" :href="inviteDialogVisible.data.sign_url" target="_blank">
                {{ inviteDialogVisible.data.sign_url }}
              </el-link>
              <el-button type="text" size="small" @click="copyInviteLink(inviteDialogVisible.data.sign_url)">
                复制
              </el-button>
            </div>
          </el-descriptions-item>

          <!-- <el-descriptions-item label="小程序签约二维码">
            <div class="qrcode-item">
              <div v-if="miniAppQrCode" class="qrcode-container">
                <img :src="miniAppQrCode" alt="小程序签约二维码" class="qrcode" />
                <p class="qrcode-tip">请使用支付宝扫码</p>
              </div>
              <div v-else class="qrcode-error">
                二维码生成失败
              </div>
              <el-button type="text" size="small" @click="copyInviteLink(inviteDialogVisible.data.mini_app_sign_url)">
                复制链接
              </el-button>
            </div>
          </el-descriptions-item> -->

          <el-descriptions-item v-if="inviteDialogVisible.data.share_code" label="签约吱口令">
            <div class="link-item">
              <span>{{ inviteDialogVisible.data.share_code }}</span>
              <el-button type="text" size="small" @click="copyInviteLink(inviteDialogVisible.data.share_code)">
                复制
              </el-button>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

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

import { View } from "@element-plus/icons-vue";
import EmployeeAPI, {
  EmployeePageQuery,
  STATUS_TAG_TYPE,
  STATUS_LABEL,
} from "@/api/module_payment/employee";
import DepartmentAPI, {
  DepartmentPageQuery,
  DEPARTMENT_STATUS_TAG_TYPE,
  DEPARTMENT_STATUS_LABEL,
} from "@/api/module_payment/department";
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 EmployeeDetail from "./components/EmployeeDetail.vue";
import EmployeeForm from "./components/EmployeeForm.vue";
import DepartmentDetail from "./components/DepartmentDetail.vue";
import DepartmentForm from "./components/DepartmentForm.vue";
import type { ISearchConfig, IContentConfig } from "@/components/CURD/types";
import { useCrudList } from "@/components/CURD/useCrudList";
import { useLoadingAction } from "@/composables/useLoadingAction";
import { useRoute } from "vue-router";
import { ref, reactive, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useEnterpriseStore } from "@/store/modules/enterprise.store";

const route = useRoute();

const { searchRef, contentRef, handleQueryClick, handleResetClick, refreshList } = useCrudList();
const { searchRef: deptSearchRef, contentRef: deptContentRef, handleQueryClick: handleDeptQueryClick, handleResetClick: handleDeptResetClick, refreshList: refreshDeptList } = useCrudList();

const formRef = ref();
const deptFormRef = ref();

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

const enterpriseIdFromUrl = computed(() => route.query.enterprise_id as string | undefined);

const searchConfig = reactive<ISearchConfig>({
  permPrefix: "module_payment:employee",
  colon: true,
  isExpandable: true,
  showNumber: 3,
  form: { labelWidth: "auto" },
  formItems: [
    {
      prop: "employee_name",
      label: "员工姓名",
      type: "input",
      attrs: { placeholder: "请输入员工姓名", clearable: true },
    },
    {
      prop: "employee_mobile",
      label: "手机号",
      type: "input",
      attrs: { placeholder: "请输入手机号", clearable: true },
    },
    {
      prop: "employee_no",
      label: "员工工号",
      type: "input",
      attrs: { placeholder: "请输入员工工号", clearable: true },
    },
  ],
});

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

const inviteDialogVisible = reactive({
  visible: false,
  title: "员工签约激活链接",
  data: null as any,
});

const useEnterprise = useEnterpriseStore();

const currentEmployeeId = ref<string>("");
const currentDepartmentId = ref<string>("");
const currentEnterpriseId = computed(() => enterpriseIdFromUrl.value || useEnterprise.getCurrentEnterprise?.enterprise_id || "");

// 部门搜索配置
const deptSearchConfig = reactive<ISearchConfig>({
  permPrefix: "module_payment:department",
  colon: true,
  isExpandable: true,
  showNumber: 3,
  form: { labelWidth: "auto" },
  formItems: [
    {
      prop: "name",
      label: "部门名称",
      type: "input",
      attrs: { placeholder: "请输入部门名称", clearable: true },
    },
    // {
    //   prop: "code",
    //   label: "部门编码",
    //   type: "input",
    //   attrs: { placeholder: "请输入部门编码", clearable: true },
    // },
    // {
    //   prop: "status",
    //   label: "状态",
    //   type: "select",
    //   options: Object.entries(DEPARTMENT_STATUS_LABEL).map(([value, label]) => ({
    //     label,
    //     value,
    //   })),
    //   attrs: { placeholder: "请选择状态", clearable: true },
    // },
  ],
});

// 部门列表列配置
const deptContentCols = reactive<
  Array<{
    prop?: string;
    label?: string;
    show?: boolean;
  }>
>([
  { prop: "selection", label: "选择框", show: false },
  // { prop: "index", label: "序号", show: true },
  { prop: "name", label: "部门名称", show: true },
  // { prop: "code", label: "部门编码", show: true },
  // { prop: "parent_name", label: "上级部门", show: true },
  // { prop: "leader_employee_name", label: "部门负责人", show: true },
  // { prop: "sort_order", label: "排序值", show: true },
  // { prop: "status", label: "状态", show: true },
  { prop: "created_time", label: "创建时间", show: true },
  { prop: "operation", label: "操作", show: true },
]);

const contentCols = reactive<
  Array<{
    prop?: string;
    label?: string;
    show?: boolean;
  }>
>([
  { prop: "selection", label: "选择框", show: false },
  { prop: "index", label: "序号", show: true },
  { prop: "employee_name", label: "员工姓名", show: true },
  { prop: "employee_no", label: "员工工号", show: true },
  { prop: "employee_id", label: "员工ID", show: true },
  { prop: "employee_mobile", label: "手机号", show: true },
  { prop: "employee_email", label: "邮箱", show: true },
  { prop: "status", label: "激活状态", show: true },
  { prop: "created_time", label: "创建时间", show: true },
  { prop: "operation", label: "操作", show: true },
]);

const contentConfig = reactive<IContentConfig<EmployeePageQuery>>({
  permPrefix: "module_payment:employee",
  pk: "employee_id",
  cols: contentCols as IContentConfig["cols"],
  hideColumnFilter: false,
  toolbar: [],
  defaultToolbar: ["refresh", "filter", "import", "export"],
  pagination: {
    pageSize: 10,
    pageSizes: [10, 20, 30, 50],
  },
  request: { page_no: "page", page_size: "page_size" },
  indexAction: async (params) => {
    const query: EmployeePageQuery = {
      page_no: params.page_no,
      page_size: params.page_size,
    };
    const eid = enterpriseIdFromUrl.value || useEnterprise.getCurrentEnterprise?.enterprise_id;
    if (eid) query.enterprise_id = eid;
    if (params.employee_name) query.employee_name = params.employee_name;
    if (params.employee_mobile) query.employee_mobile = params.employee_mobile;
    if (params.employee_no) query.employee_no = params.employee_no;
    const res = await EmployeeAPI.listEmployee(query);
    return {
      list: res.data.data?.items || [],
      total: Number(res.data.data?.total) || 0,
    };
  },
});

// 部门列表配置
const deptContentConfig = reactive<IContentConfig<DepartmentPageQuery>>({
  permPrefix: "module_payment:department",
  pk: "department_id",
  cols: deptContentCols as IContentConfig["cols"],
  hideColumnFilter: false,
  toolbar: [],
  defaultToolbar: ["refresh", "filter", "import", "export"],
  pagination: {
    pageSize: 10,
    pageSizes: [10, 20, 30, 50],
  },
  request: { page_no: "page", page_size: "page_size" },
  initialParams: computed(() => ({
    enterprise_id: enterpriseIdFromUrl.value,
  })) as Record<string, unknown>,
  indexAction: async (params) => {
    const query: DepartmentPageQuery = {
      page_no: params.page_no,
      page_size: params.page_size,
    };
    if (params.enterprise_id) query.enterprise_id = params.enterprise_id;
    if (params.name) query.department_name = params.name;
    if (params.code) query.department_code = params.code;
    if (params.status) query.status = params.status;
    const res = await DepartmentAPI.listDepartment(query);
    // 转换数据结构以匹配前端表格显示
    const items = res.data.data?.items.map((item: any) => ({
      department_id: item.department_id,
      name: item.department_name,
      code: item.department_code,
      parent_id: item.parent_department_id,
      parent_name: '', // 可以根据parent_id查询上级部门名称
      leader_employee_name: item.leader_employee_name,
      sort_order: item.sort_order,
      status: item.status,
      created_time: item.created_time,
      updated_time: item.updated_time
    })) || [];
    return {
      list: items,
      total: Number(res.data.data?.total) || 0,
    };
  },
});

function handleOpenDialog(type: "create" | "update" | "detail", employeeId: string) {
  dialogVisible.type = type;
  dialogVisible.entity = "employee";
  currentEmployeeId.value = employeeId;
  if (type === "create") {
    dialogVisible.title = "添加员工";
  } else if (type === "update") {
    dialogVisible.title = "编辑员工";
  } else {
    dialogVisible.title = "员工详情";
  }
  dialogVisible.visible = true;
}

function handleOpenDeptDialog(type: "create" | "update" | "detail", departmentId: string) {
  dialogVisible.type = type;
  dialogVisible.entity = "department";
  currentDepartmentId.value = departmentId;
  if (type === "create") {
    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 handleResetForm() {
  formRef.value?.resetForm();
}

function handleSaveAndAddNext() {
  formRef.value?.handleSaveAndAddNext();
}

function handleDeptSubmit(isContinue = false) {
  deptFormRef.value?.submitForm(isContinue);
}

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

function handleDeptFormSuccess() {
  dialogVisible.visible = false;
  refreshDeptList();
}

async function handleDeleteDepartment(departmentId: string, departmentName: string) {
  try {
    const enterpriseId = currentEnterpriseId.value || enterpriseIdFromUrl.value;
    if (!enterpriseId) {
      ElMessage.warning("请先选择企业");
      return;
    }

    await ElMessageBox.confirm(
      `确定要删除部门「${departmentName}」吗？`,
      "删除部门",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const res = await DepartmentAPI.deleteDepartment(departmentId, enterpriseId);
    if (res.data.code === 200) {
      ElMessage.success("删除部门成功");
      refreshDeptList();
    } else {
      ElMessage.error(res.data.message || "删除部门失败");
    }
  } catch (error: any) {
    if (error.message !== "cancel") {
      console.error("删除部门失败:", error);
      ElMessage.error("删除部门失败");
    }
  }
}

// 获取员工签约激活链接
async function handleGetInviteLink(row: any) {
  try {
    const enterpriseId = row.enterprise_id || currentEnterpriseId.value || enterpriseIdFromUrl.value;
    if (!enterpriseId) {
      ElMessage.warning("请先选择企业");
      return;
    }

    const res = await EmployeeAPI.inviteQuery({
      enterprise_id: enterpriseId,
      employee_id: row.employee_id,
      create_share_code: "Y", // 默认生成签约吱口令
    });

    if (res.data.data) {
      inviteDialogVisible.data = res.data.data;
      inviteDialogVisible.visible = true;
    }
  } catch (error) {
    ElMessage.error("获取签约链接失败");
  }
}

// 复制链接
async function copyInviteLink(text: string) {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success("链接已复制到剪贴板");
  } catch (err) {
    ElMessage.error("复制失败，请手动复制");
  }
}
</script>

<style scoped lang="scss">
.employee-tabs {
  .el-tabs__nav {
    background-color: #fff;
  }

  .el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
  }
}

.invite-link-container {
  .link-item {
    display: flex;
    align-items: center;
    gap: 8px;

    .el-link {
      flex: 1;
      word-break: break-all;
    }
  }

  .qrcode-item {
    display: flex;
    align-items: flex-start;
    gap: 16px;
  }

  .qrcode-container {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .qrcode {
    width: 200px;
    height: 200px;
    border: 1px solid #e0e0e0;
  }

  .qrcode-tip {
    margin-top: 8px;
    font-size: 14px;
    color: #666;
  }

  .qrcode-error {
    padding: 20px;
    color: #f56c6c;
  }
}
</style>