import { computed, onMounted, reactive, ref } from 'vue/dist/vue.esm-bundler.js';
import { ElMessage } from 'element-plus';
import { authState } from '../auth/auth-store.js';
import { createWecomAccount, listWecomAccounts, searchCompanyPersons, searchCompanyProfiles, searchPhoneAssets } from './wecom-api-client.js';

/** File purpose (plain language): renders the enterprise WeChat asset list and its creation dialog with reusable asset searches. */
export default {
  /** Code purpose (plain language): owns list, dialog, and selector state for this page. Related files: wecom-api-client.js, WecomAccountController.java. Data flow: route -> setup -> API -> Element Plus controls. */
  setup() {
    const loading = ref(false);
    const saving = ref(false);
    const dialogVisible = ref(false);
    const records = ref([]);
    const total = ref(0);
    const companyOptions = ref([]);
    const ownerOptions = ref([]);
    /** 代码作用（白话）：把企微页面的有效权限转换为新增按钮和弹窗是否可用；关联文件：auth-store.js、WecomAccountController.java。关联逻辑（调用链/数据流）：认证资料 -> EDIT 判断 -> 写操作控件 -> 后端 EDIT 校验。 */
    const canEdit = computed(() => authState.user?.pagePermissions?.['reference-wecom'] === 'EDIT');
    let searchTimer;
    const filters = reactive({ page: 1, size: 20, keyword: '', wecomAccount: '', phoneAssetId: new URLSearchParams(window.location.hash.split('?')[1] || '').get('phoneAssetId') || '', companyProfileId: 'ALL', realNameOwnerStatus: 'ALL' });
    const form = reactive({ wecomName: '', wecomAlias: '记忆力梅老师-助教老师', wecomAccount: '', companyProfileId: null, phoneNumber: '', realNameOwner: '', realNameOwnerStatus: '在职', gender: '', operatorPersonId: null });

    /** Code purpose (plain language): reloads the table using the active filters. Related files: wecom-api-client.js, WecomAccountService.java. Data flow: page action -> GET -> records/total -> table. */
    async function loadPage() {
      loading.value = true;
      try { const result = await listWecomAccounts(filters); records.value = result.records; total.value = result.total; } catch (error) { ElMessage.error(error.message); } finally { loading.value = false; }
    }

    /** Code purpose (plain language): resets the create form to the business defaults. Related files: WecomAccountSaveRequest.java. Data flow: add button -> reset -> dialog form. */
    function resetForm() { Object.assign(form, { wecomName: '', wecomAlias: '记忆力梅老师-助教老师', wecomAccount: '', companyProfileId: null, phoneNumber: '', realNameOwner: '', realNameOwnerStatus: '在职', gender: '', operatorPersonId: null }); }

    /** Code purpose (plain language): opens a clean creation dialog. Related files: WecomAccountView.js. Data flow: add button -> resetForm -> dialog visible. */
    function openCreate() { resetForm(); dialogVisible.value = true; }

    /** Code purpose (plain language): saves a new asset and refreshes the first page. Related files: wecom-api-client.js, WecomAccountService.java. Data flow: dialog submit -> POST -> transaction -> table refresh. */
    async function submitCreate() {
      if (!form.wecomName.trim() || !form.phoneNumber.trim()) { ElMessage.warning('请填写企微名称和注册手机号'); return; }
      saving.value = true;
      try { await createWecomAccount({ ...form, wecomName: form.wecomName.trim(), phoneNumber: form.phoneNumber.trim() }); ElMessage.success('新增成功'); dialogVisible.value = false; filters.page = 1; await loadPage(); } catch (error) { ElMessage.error(error.message); } finally { saving.value = false; }
    }

    /** Code purpose (plain language): supplies existing phone assets to the autocomplete while leaving a typed new number usable. Related files: wecom-api-client.js, WecomAccountService.java. Data flow: phone input -> lookup -> autocomplete suggestions. */
    async function fetchPhoneSuggestions(keyword, callback) {
      try { const rows = await searchPhoneAssets(keyword); callback(rows.map(row => ({ value: row.phoneNumber, label: `${row.phoneNumber}（${row.numberType === 'EXTERNAL' ? '外部号码' : '自有号码'}）` }))); } catch (_) { callback([]); }
    }

    /** Code purpose (plain language): looks up registration subjects by name or abbreviation. Related files: wecom-api-client.js, WecomAccountService.java. Data flow: remote select -> lookup -> option list. */
    async function loadCompanies(keyword) { companyOptions.value = await searchCompanyProfiles(keyword); }

    /** Code purpose (plain language): looks up possible WeCom owners. Related files: wecom-api-client.js, WecomAccountService.java. Data flow: remote select -> lookup -> option list. */
    async function loadOwners(keyword) { ownerOptions.value = await searchCompanyPersons(keyword); }

/** Code purpose (plain language): waits briefly for typing to stop before querying unified WeCom-name-or-phone keywords. Related files: WecomAccountView.js, WecomAccountService.java. Data flow: input -> 300ms timer -> submitSearch -> filtered table. */
    function scheduleSearch() { window.clearTimeout(searchTimer); searchTimer = window.setTimeout(submitSearch, 300); }

/** Code purpose (plain language): restores the registration-subject filter to its explicit All selection after the clear icon is clicked. Related files: WecomAccountView.js, wecom-api-client.js. Data flow: clear icon -> ALL -> query omits filter -> full list. */
    function restoreAllCompanyProfiles() { filters.companyProfileId = 'ALL'; submitSearch(); }

    /** Code purpose (plain language): restores the real-name-status filter to its explicit All selection after the clear icon is clicked. Related files: WecomAccountView.js, wecom-api-client.js. Data flow: clear icon -> ALL -> query omits filter -> full list. */
    function restoreAllRealNameStatuses() { filters.realNameOwnerStatus = 'ALL'; submitSearch(); }

    /** Code purpose (plain language): searches again from the first page. Related files: WecomAccountView.js. Data flow: filter change -> filters.page -> loadPage. */
    function submitSearch() { filters.page = 1; loadPage(); }

    /** Code purpose (plain language): clears list text filters but retains an incoming phone-asset route filter until the user explicitly removes it. Related files: WecomAccountView.js. Data flow: reset -> default filters -> loadPage. */
    function resetSearch() { window.clearTimeout(searchTimer); Object.assign(filters, { page: 1, size: 20, keyword: '', wecomAccount: '', phoneAssetId: '', companyProfileId: 'ALL', realNameOwnerStatus: 'ALL' }); loadPage(); }

    /** Code purpose (plain language): loads the chosen pagination page. Related files: WecomAccountView.js. Data flow: pagination -> filters.page -> loadPage. */
    function changePage(page) { filters.page = page; loadPage(); }

    /** Code purpose (plain language): formats an optional referenced ID for table display. Related files: WecomAccountResponse.java. Data flow: API record -> formatter -> table cell. */
    function formatRelation(name, id) { return id === null || id === undefined ? '—' : `${name || '—'}（ID：${id}）`; }

    onMounted(loadPage);
    return { canEdit, changePage, companyOptions, dialogVisible, fetchPhoneSuggestions, filters, form, formatRelation, loadCompanies, loadOwners, loading, openCreate, ownerOptions, records, resetSearch, restoreAllCompanyProfiles, restoreAllRealNameStatuses, saving, scheduleSearch, submitCreate, submitSearch, total };
  },
  template: `
    <section class="phone-asset-list-page wecom-account-page">
      <header class="phone-asset-list-page__header"><div><h2>企业微信资产</h2><p class="wecom-account-page__eyebrow">WECOM ACCOUNTS</p></div><el-button v-if="canEdit" class="phone-asset-list-page__add" type="primary" @click="openCreate">新增企业微信资产</el-button></header>
      <section class="phone-asset-list-page__panel phone-asset-list-page__search"><el-form class="phone-asset-list-page__filters" @submit.prevent="submitSearch"><el-input v-model="filters.keyword" placeholder="企微名称或手机号" clearable @input="scheduleSearch" @clear="scheduleSearch" /><el-select v-model="filters.companyProfileId" filterable remote clearable :remote-method="loadCompanies" placeholder="注册主体：" @change="submitSearch" @clear="restoreAllCompanyProfiles"><template #prefix>注册主体：</template><el-option label="全部" value="ALL" /><el-option v-for="item in companyOptions" :key="item.id" :label="item.shortName || item.companyName" :value="item.id" /></el-select><el-select v-model="filters.realNameOwnerStatus" clearable placeholder="实名状态：" @change="submitSearch" @clear="restoreAllRealNameStatuses"><template #prefix>实名状态：</template><el-option label="全部" value="ALL" /><el-option label="在职" value="在职" /><el-option label="离职" value="离职" /></el-select><el-button @click="resetSearch">重置</el-button></el-form></section>
      <section class="phone-asset-list-page__panel phone-asset-list-page__table"><header class="phone-asset-list-page__table-header"><h3>资产列表</h3><span>共 {{ total }} 条</span></header><el-table v-loading="loading" :data="records" empty-text="暂无匹配数据" class="phone-asset-list-page__grid wecom-account-page__grid"><el-table-column prop="id" label="企业微信资产 ID" min-width="140" /><el-table-column prop="wecomName" label="企微名称" min-width="150" show-overflow-tooltip /><el-table-column prop="wecomAlias" label="企微别名" min-width="180" show-overflow-tooltip /><el-table-column prop="wecomAccount" label="企微账号" min-width="160" show-overflow-tooltip /><el-table-column label="注册主体" min-width="180"><template #default="{ row }">{{ formatRelation(row.companyProfileName, row.companyProfileId) }}</template></el-table-column><el-table-column label="注册手机号" min-width="180"><template #default="{ row }">{{ formatRelation(row.phoneNumber, row.phoneAssetId) }}</template></el-table-column><el-table-column label="关联方式" min-width="120"><template #default="{ row }">{{ row.phoneLinkMode === 'CREATED' ? '新建号码' : '已有号码' }}</template></el-table-column><el-table-column prop="realNameOwner" label="实名人" min-width="120" /><el-table-column prop="realNameOwnerStatus" label="实名状态" min-width="110" /><el-table-column prop="gender" label="性别" min-width="90" /><el-table-column label="企微号归属人" min-width="180"><template #default="{ row }">{{ formatRelation(row.operatorPersonName, row.operatorPersonId) }}</template></el-table-column><el-table-column prop="createTime" label="创建时间" min-width="180" /></el-table><footer v-if="total" class="phone-asset-list-page__pagination"><span>共 {{ total }} 条</span><el-pagination layout="prev, pager, next" :current-page="filters.page" :page-size="filters.size" :total="total" @current-change="changePage" /></footer></section>
      <el-dialog v-model="dialogVisible" title="新增企业微信资产" width="640px" :close-on-click-modal="false"><el-form label-position="top" @submit.prevent="submitCreate"><el-row :gutter="16"><el-col :span="12"><el-form-item label="企微名称" required><el-input v-model="form.wecomName" /></el-form-item></el-col><el-col :span="12"><el-form-item label="企微别名"><el-input v-model="form.wecomAlias" /></el-form-item></el-col><el-col :span="12"><el-form-item label="企微账号"><el-input v-model="form.wecomAccount" /></el-form-item></el-col><el-col :span="12"><el-form-item label="注册手机号" required><el-autocomplete v-model="form.phoneNumber" :fetch-suggestions="fetchPhoneSuggestions" placeholder="输入或选择手机号" style="width:100%" /></el-form-item></el-col><el-col :span="12"><el-form-item label="注册主体"><el-select v-model="form.companyProfileId" filterable remote clearable :remote-method="loadCompanies" placeholder="输入公司名称或简称" style="width:100%"><el-option v-for="item in companyOptions" :key="item.id" :label="item.shortName || item.companyName" :value="item.id" /></el-select></el-form-item></el-col><el-col :span="12"><el-form-item label="企微号归属人"><el-select v-model="form.operatorPersonId" filterable remote clearable :remote-method="loadOwners" placeholder="输入人员姓名" style="width:100%"><el-option v-for="item in ownerOptions" :key="item.id" :label="item.personName" :value="item.id" /></el-select></el-form-item></el-col><el-col :span="12"><el-form-item label="实名人"><el-input v-model="form.realNameOwner" /></el-form-item></el-col><el-col :span="12"><el-form-item label="实名状态"><el-radio-group v-model="form.realNameOwnerStatus"><el-radio value="在职">在职</el-radio><el-radio value="离职">离职</el-radio></el-radio-group></el-form-item></el-col><el-col :span="12"><el-form-item label="性别"><el-radio-group v-model="form.gender"><el-radio value="男">男</el-radio><el-radio value="女">女</el-radio></el-radio-group></el-form-item></el-col></el-row></el-form><template #footer><el-button @click="dialogVisible = false">取消</el-button><el-button type="primary" :loading="saving" @click="submitCreate">保存</el-button></template></el-dialog>
    </section>
  `
};
