<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { Page } from '@vben/common-ui';
import { useAccessStore, useUserStore } from '@vben/stores';

import {
  deleteBd,
  listMembers,
  pageBdTable,
} from '#/api/legacy/team';
import AccountInput from '#/components/account-input.vue';
import SysOriginLabel from '#/components/sys-origin-label.vue';
import SysOriginSelect from '#/components/sys-origin-select.vue';
import TeamCreateDrawer from '#/views/team/components/team-create-drawer.vue';
import {
  formatDate,
  getAllowedSysOrigins,
} from '#/views/system/shared';

import {
  Button,
  Card,
  Input,
  Modal,
  Pagination,
  Select,
  Space,
  Table,
  message,
} from 'antdv-next';

import BdBindLeaderModal from './components/bd-bind-leader-modal.vue';
import BdBindTeamModal from './components/bd-bind-team-modal.vue';
import BdFormModal from './components/bd-form-modal.vue';
import BdMemberDrawer from './components/bd-member-drawer.vue';
import SystemRegionSelect from './components/system-region-select.vue';

defineOptions({ name: 'OperateBusinessDevelopment' });

const router = useRouter();
const accessStore = useAccessStore();
const userStore = useUserStore();
const sysOriginOptions = computed(() => {
  const options = getAllowedSysOrigins(accessStore.accessCodes || []);
  return options.length > 0 ? options : getAllowedSysOrigins([]);
});

const loading = ref(false);
const membersLoading = ref(false);
const total = ref(0);
const list = ref<Array<Record<string, any>>>([]);
const members = ref<Array<Record<string, any>>>([]);
const formOpen = ref(false);
const bindLeaderOpen = ref(false);
const bindTeamOpen = ref(false);
const memberOpen = ref(false);
const createTeamOpen = ref(false);
const activeRow = ref<null | Record<string, any>>(null);

const query = reactive({
  bdLeadUserId: '',
  createUser: '',
  cursor: 1,
  limit: 20,
  memberQuantityRange: '',
  region: '',
  sysOrigin: '',
  userId: '',
});

const columns = [
  { dataIndex: 'sysOrigin', key: 'sysOrigin', title: '系统', width: 100 },
  { dataIndex: 'userProfile', key: 'userProfile', title: '用户', width: 240 },
  { dataIndex: 'regionName', key: 'regionName', title: '区域', width: 120 },
  { dataIndex: 'agentCount', key: 'agentCount', title: '团队数量', width: 110 },
  { dataIndex: 'bdLeadUserProfile', key: 'bdLeadUserProfile', title: 'BD Leader', width: 240 },
  { dataIndex: 'contact', key: 'contact', title: '联系方式', width: 180 },
  { dataIndex: 'createUserName', key: 'createUserName', title: '创建人', width: 140 },
  { dataIndex: 'updateUserName', key: 'updateUserName', title: '修改人', width: 140 },
  { dataIndex: 'createTime', key: 'createTime', title: '创建时间', width: 180 },
  { dataIndex: 'actions', key: 'actions', title: '操作', width: 280 },
];

function hasPermission(code: string) {
  const codes = accessStore.accessCodes || [];
  return codes.length === 0 || codes.includes(code);
}

const canQueryAll = computed(() => hasPermission('bd:list:query:all'));
const canQuerySelf = computed(() => hasPermission('bd:list:query:self'));
const canQuery = computed(() => canQueryAll.value || canQuerySelf.value);
const canCreate = computed(() => hasPermission('bd:list:add'));
const canEdit = computed(() => hasPermission('bd:list:edit'));
const canDelete = computed(() => hasPermission('bd:list:del'));
const canAddMember = computed(() => hasPermission('bd:list:add:member'));
const canBindMember = computed(() => hasPermission('bd:list:add:bind'));
const showOperationCol = computed(
  () =>
    canEdit.value ||
    canDelete.value ||
    canAddMember.value ||
    canBindMember.value,
);

function getUserText(profile?: Record<string, any>) {
  if (!profile) {
    return '-';
  }
  const nickname = profile.userNickname || profile.nickname || '-';
  const account = profile.actualAccount || profile.account || profile.id;
  return account ? `${nickname} / ${account}` : nickname;
}

function openUserDetails(userId?: number | string) {
  if (!userId) {
    return;
  }
  router.push(`/common/user/deatils/${userId}`);
}

async function loadMembers() {
  if (!canQueryAll.value) {
    members.value = [];
    return;
  }
  membersLoading.value = true;
  try {
    members.value = await listMembers();
  } finally {
    membersLoading.value = false;
  }
}

async function loadData(reset = false) {
  if (!canQuery.value) {
    list.value = [];
    total.value = 0;
    return;
  }
  if (reset) {
    query.cursor = 1;
  }
  loading.value = true;
  try {
    const result = await pageBdTable({ ...query });
    list.value = result.records || [];
    total.value = result.total || 0;
  } finally {
    loading.value = false;
  }
}

function handleSearch() {
  loadData(true);
}

function handlePageChange(page: number, pageSize: number) {
  query.cursor = page;
  query.limit = pageSize;
  loadData();
}

function openCreate() {
  activeRow.value = {
    sysOrigin: query.sysOrigin,
  };
  formOpen.value = true;
}

function openEdit(record: Record<string, any>) {
  activeRow.value = {
    ...record,
    sysOrigin: record.sysOrigin || query.sysOrigin,
  };
  formOpen.value = true;
}

function openBindLeader(record: Record<string, any>) {
  activeRow.value = { ...record };
  bindLeaderOpen.value = true;
}

function openBindTeam(record: Record<string, any>) {
  activeRow.value = { ...record };
  bindTeamOpen.value = true;
}

function openCreateTeam(record: Record<string, any>) {
  activeRow.value = { ...record };
  createTeamOpen.value = true;
}

function openMembers(record: Record<string, any>) {
  activeRow.value = { ...record };
  memberOpen.value = true;
}

function handleDelete(record: Record<string, any>) {
  Modal.confirm({
    title: '您确定要删除吗(将无法恢复, 解散当前团队成员)?',
    async onOk() {
      await deleteBd(record.id);
      message.success('删除成功');
      await loadData(true);
    },
  });
}

query.sysOrigin = String(sysOriginOptions.value[0]?.value || '');
if (canQuerySelf.value && !canQueryAll.value) {
  query.createUser = String(userStore.userInfo?.userId || '');
}

loadMembers();
loadData(true);
</script>

<template>
  <Page title="BD列表">
    <Card>
      <div v-if="canQuery" class="toolbar">
        <Space wrap>
          <SysOriginSelect
            v-model:value="query.sysOrigin"
            :options="sysOriginOptions"
            style="width: 140px"
            @change="handleSearch"
          />
          <AccountInput
            v-model:value="query.userId"
            :sys-origin="query.sysOrigin"
            placeholder="BD用户ID"
            style="width: 220px"
          />
          <AccountInput
            v-model:value="query.bdLeadUserId"
            :sys-origin="query.sysOrigin"
            placeholder="BD Lead用户ID"
            style="width: 220px"
          />
          <SystemRegionSelect
            v-model:value="query.region"
            :sys-origin="query.sysOrigin"
            clearable
            placeholder="区域"
            style="width: 160px"
            @change="handleSearch"
          />
          <Input
            v-model:value="query.memberQuantityRange"
            placeholder="开始~结束成员数量"
            style="width: 180px"
          />
          <Select
            v-if="canQueryAll"
            v-model:value="query.createUser"
            :loading="membersLoading"
            allow-clear
            :field-names="{ label: 'nickname', value: 'id' }"
            :options="members"
            placeholder="后台成员"
            show-search
            style="width: 160px"
            @change="handleSearch"
          />
          <Button :loading="loading" type="primary" @click="handleSearch">
            搜索
          </Button>
          <Button v-if="canCreate" @click="openCreate">新增BD</Button>
        </Space>
      </div>

      <div v-else class="permission-tip">
        抱歉您无权查看，请联系管理员开通查看权限【bd:list:query:all / bd:list:query:self】
      </div>

      <Table
        v-if="canQuery"
        :columns="columns"
        :data-source="list"
        :loading="loading"
        :pagination="false"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'sysOrigin'">
            <SysOriginLabel :value="record.sysOrigin" />
          </template>
          <template v-else-if="column.key === 'userProfile'">
            <Button
              v-if="record.userProfile?.id"
              type="link"
              @click="openUserDetails(record.userProfile?.id)"
            >
              {{ getUserText(record.userProfile) }}
            </Button>
            <span v-else>{{ getUserText(record.userProfile) }}</span>
          </template>
          <template v-else-if="column.key === 'agentCount'">
            <Button
              v-if="Number(record.agentCount || 0) > 0"
              size="small"
              type="link"
              @click="openMembers(record)"
            >
              {{ record.agentCount }}
            </Button>
            <span v-else>0</span>
          </template>
          <template v-else-if="column.key === 'bdLeadUserProfile'">
            <Button
              v-if="record.bdLeadUserProfile?.id"
              type="link"
              @click="openUserDetails(record.bdLeadUserProfile?.id)"
            >
              {{ getUserText(record.bdLeadUserProfile) }}
            </Button>
            <span v-else>{{ getUserText(record.bdLeadUserProfile) }}</span>
          </template>
          <template v-else-if="column.key === 'contact'">
            {{ canEdit ? record.contact || '-' : '-' }}
          </template>
          <template v-else-if="column.key === 'createTime'">
            {{ formatDate(record.createTime) }}
          </template>
          <template v-else-if="column.key === 'actions' && showOperationCol">
            <Space wrap>
              <Button
                v-if="canAddMember"
                size="small"
                type="link"
                @click="openCreateTeam(record)"
              >
                新增代理
              </Button>
              <Button
                v-if="canBindMember"
                size="small"
                type="link"
                @click="openBindTeam(record)"
              >
                绑定代理
              </Button>
              <Button
                v-if="canEdit"
                size="small"
                type="link"
                @click="openEdit(record)"
              >
                编辑
              </Button>
              <Button
                v-if="canEdit"
                size="small"
                type="link"
                @click="openBindLeader(record)"
              >
                换绑BD Leader
              </Button>
              <Button
                v-if="canDelete"
                danger
                size="small"
                type="link"
                @click="handleDelete(record)"
              >
                删除
              </Button>
            </Space>
          </template>
        </template>
      </Table>

      <div v-if="canQuery" class="pagination">
        <Pagination
          :current="query.cursor"
          :page-size="query.limit"
          :total="total"
          show-size-changer
          @change="handlePageChange"
          @showSizeChange="handlePageChange"
        />
      </div>
    </Card>

    <BdFormModal
      :open="formOpen"
      :row="activeRow"
      :sys-origin="query.sysOrigin"
      @close="formOpen = false"
      @success="loadData(true)"
    />

    <BdBindLeaderModal
      :open="bindLeaderOpen"
      :row="activeRow"
      @close="bindLeaderOpen = false"
      @success="loadData(true)"
    />

    <BdBindTeamModal
      :open="bindTeamOpen"
      :row="activeRow"
      @close="bindTeamOpen = false"
      @success="loadData(true)"
    />

    <BdMemberDrawer
      :open="memberOpen"
      :row="activeRow"
      @close="memberOpen = false"
    />

    <TeamCreateDrawer
      :default-bd-user-id="String(activeRow?.userProfile?.id || activeRow?.userId || '')"
      :default-region="String(activeRow?.region || '')"
      :lock-bind-bd="true"
      :open="createTeamOpen"
      :sys-origin="String(activeRow?.sysOrigin || query.sysOrigin || '')"
      @close="createTeamOpen = false"
      @success="loadData(true)"
    />
  </Page>
</template>

<style scoped>
.toolbar {
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.permission-tip {
  color: #64748b;
  padding: 24px 0;
  text-align: center;
}
</style>
