<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" label-width="140px">
            <el-form-item :label="t('tenantPackage.search.packageName')" prop="packageName">
              <el-input v-model="queryParams.packageName" :placeholder="t('tenantPackage.search.packageNamePlaceholder')" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">{{ t('tenantPackage.search.search') }}</el-button>
              <el-button icon="Refresh" @click="resetQuery">{{ t('tenantPackage.search.reset') }}</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenantPackage:add']" type="primary" plain icon="Plus" @click="handleAdd"> {{ t('tenantPackage.button.add') }} </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenantPackage:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">
              {{ t('tenantPackage.button.edit') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenantPackage:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">
              {{ t('tenantPackage.button.delete') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenantPackage:export']" type="warning" plain icon="Download" @click="handleExport">{{ t('tenantPackage.button.export') }} </el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="tenantPackageList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" :label="t('tenantPackage.table.packageId')" align="center" prop="packageId" />
        <el-table-column :label="t('tenantPackage.table.packageName')" align="center" prop="packageName" />
        <el-table-column :label="t('tenantPackage.table.remark')" align="center" prop="remark" />
        <el-table-column :label="t('tenantPackage.table.status')" align="center" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @click="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column :label="t('tenantPackage.table.operation')" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip :content="t('tenantPackage.tooltip.edit')" placement="top">
              <el-button v-hasPermi="['system:tenantPackage:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip :content="t('tenantPackage.tooltip.delete')" placement="top">
              <el-button v-hasPermi="['system:tenantPackage:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 添加或修改企业套餐对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="900px" append-to-body>
      <el-form ref="tenantPackageFormRef" :model="form" :rules="rules" label-width="180px">
        <el-form-item :label="t('tenantPackage.form.packageName')" prop="packageName">
          <el-input v-model="form.packageName" :placeholder="t('tenantPackage.form.packageNamePlaceholder')" />
        </el-form-item>
        <el-form-item :label="t('tenantPackage.form.relatedMenu')">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">{{ t('tenantPackage.form.expandCollapse') }}</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">{{ t('tenantPackage.form.selectAll') }} </el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">{{ t('tenantPackage.form.parentChild') }} </el-checkbox>
          <el-tree
            ref="menuTreeRef"
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            :empty-text="t('tenantPackage.form.loading')"
            :props="{ label: 'label', children: 'children' } as any"
          ></el-tree>
        </el-form-item>
        <el-form-item :label="t('tenantPackage.form.remark')" prop="remark">
          <el-input v-model="form.remark" :placeholder="t('tenantPackage.form.remarkPlaceholder')" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">{{ t('tenantPackage.button.submit') }}</el-button>
          <el-button @click="cancel">{{ t('tenantPackage.button.cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TenantPackage" lang="ts">
import {
  listTenantPackage,
  getTenantPackage,
  delTenantPackage,
  addTenantPackage,
  updateTenantPackage,
  changePackageStatus
} from '@/api/system/tenantPackage';
import { tenantPackageMenuTreeselect } from '@/api/system/menu';
import { TenantPkgForm, TenantPkgQuery, TenantPkgVO } from '@/api/system/tenantPackage/types';
import { MenuTreeOption } from '@/api/system/menu/types';
import to from 'await-to-js';
import { useI18n } from 'vue-i18n';
import { useAppStore } from '@/store/modules/app';

const { t } = useI18n();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const appStore = useAppStore();

const tenantPackageList = ref<TenantPkgVO[]>([]);
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 menuExpand = ref(false);
const menuNodeAll = ref(false);
const menuOptions = ref<MenuTreeOption[]>([]);

const menuTreeRef = ref<ElTreeInstance>();
const queryFormRef = ref<ElFormInstance>();
const tenantPackageFormRef = ref<ElFormInstance>();

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

const initFormData: TenantPkgForm = {
  packageId: undefined,
  packageName: '',
  menuIds: '',
  remark: '',
  menuCheckStrictly: true
};
const data = reactive<PageData<TenantPkgForm, TenantPkgQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    packageName: ''
  },
  rules: {
    packageId: [{ required: true, message: t('tenantPackage.rule.packageIdRequired'), trigger: 'blur' }],
    packageName: [{ required: true, message: t('tenantPackage.rule.packageNameRequired'), trigger: 'blur' }]
  }
});

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

/** 解析多语言标签 */
const parseI18nLabel = (label: string): string => {
  try {
    // 尝试解析JSON格式的多语言标签
    const parsed = JSON.parse(label);
    // 获取当前语言，如果没有对应的翻译则使用中文，再没有则返回原始标签
    const currentLang = appStore.language;
    return parsed[currentLang] || parsed['zh_CN'] || label;
  } catch (e) {
    // 如果不是JSON格式，直接返回原标签
    return label;
  }
};

/** 递归处理菜单树的标签国际化 */
const processMenuTreeI18n = (menus: MenuTreeOption[]): MenuTreeOption[] => {
  return menus.map(menu => {
    const processedMenu = {
      ...menu,
      label: parseI18nLabel(menu.label)
    };
    if (menu.children && menu.children.length > 0) {
      processedMenu.children = processMenuTreeI18n(menu.children);
    }
    return processedMenu;
  });
};

// 所有菜单节点数据
const getMenuAllCheckedKeys = (): any => {
  // 目前被选中的菜单节点
  const checkedKeys = menuTreeRef.value?.getCheckedKeys();
  // 半选中的菜单节点
  const halfCheckedKeys = menuTreeRef.value?.getHalfCheckedKeys();
  if (halfCheckedKeys) {
    checkedKeys?.unshift(...halfCheckedKeys);
  }
  return checkedKeys;
};

/** 根据企业套餐ID查询菜单树结构 */
const getPackageMenuTreeselect = async (packageId: string | number) => {
  const res = await tenantPackageMenuTreeselect(packageId);
  // 处理菜单树的国际化标签
  menuOptions.value = processMenuTreeI18n(res.data.menus);
  return Promise.resolve(res);
};

/** 查询企业套餐列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTenantPackage(queryParams.value);
  tenantPackageList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

// 企业套餐状态修改
const handleStatusChange = async (row: TenantPkgVO) => {
  const text = row.status === '0' ? t('tenantPackage.message.statusEnable') : t('tenantPackage.message.statusDisable');
  const [err] = await to(proxy?.$modal.confirm(t('tenantPackage.message.statusChangeConfirm', { text, name: row.packageName })) as Promise<any>);
  if (err) {
    row.status = row.status === '0' ? '1' : '0';
  } else {
    await changePackageStatus(row.packageId, row.status);
    proxy?.$modal.msgSuccess(t('tenantPackage.message.statusChangeSuccess', { text }));
  }
};

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

// 表单重置
const reset = () => {
  menuTreeRef.value?.setCheckedKeys([]);
  menuExpand.value = false;
  menuNodeAll.value = false;
  form.value = { ...initFormData };
  tenantPackageFormRef.value?.resetFields();
};

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

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

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

// 树权限（展开/折叠）
const handleCheckedTreeExpand = (value: CheckboxValueType, type: string) => {
  if (type == 'menu') {
    const treeList = menuOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      if (menuTreeRef.value) {
        menuTreeRef.value.store.nodesMap[treeList[i].id].expanded = value as boolean;
      }
    }
  }
};

// 树权限（全选/全不选）
const handleCheckedTreeNodeAll = (value: CheckboxValueType, type: string) => {
  if (type == 'menu') {
    menuTreeRef.value?.setCheckedNodes(value ? (menuOptions.value as any) : []);
  }
};

// 树权限（父子联动）
const handleCheckedTreeConnect = (value: CheckboxValueType, type: string) => {
  if (type == 'menu') {
    form.value.menuCheckStrictly = value as boolean;
  }
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  await getPackageMenuTreeselect(0);
  dialog.visible = true;
  dialog.title = t('tenantPackage.dialog.add');
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TenantPkgVO) => {
  reset();
  const _packageId = row?.packageId || ids.value[0];
  const response = await getTenantPackage(_packageId);
  form.value = response.data;
  const res = await getPackageMenuTreeselect(_packageId);
  dialog.visible = true;
  dialog.title = t('tenantPackage.dialog.edit');
  res.data.checkedKeys.forEach((v) => {
    nextTick(() => {
      menuTreeRef.value?.setChecked(v, true, false);
    });
  });
};

/** 提交按钮 */
const submitForm = () => {
  tenantPackageFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.menuIds = getMenuAllCheckedKeys();
      if (form.value.packageId != null) {
        await updateTenantPackage(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTenantPackage(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess(t('tenantPackage.message.operationSuccess'));
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TenantPkgVO) => {
  const _packageIds = row?.packageId || ids.value;
  await proxy?.$modal.confirm(t('tenantPackage.message.deleteConfirm', { ids: _packageIds })).finally(() => {
    loading.value = false;
  });
  await delTenantPackage(_packageIds);
  loading.value = true;
  await getList();
  proxy?.$modal.msgSuccess(t('tenantPackage.message.deleteSuccess'));
};

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

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