<script lang="ts" setup>
/**
 * @Name: CompanyDetail.vue
 * @Description: 公司详情
 * @Author: Cheney
 */

import { Edit, Link, Picture as IconPicture } from '@element-plus/icons-vue';
import { companyColumns } from '../useColumns';
import { usePagination } from '/@/utils/usePagination';
import { useTableData } from '/@/utils/useTableData';
import * as api from '../api';
import router from '/@/router';
import { useResponse } from '/@/utils/useResponse';
import EditDrawer from '../components/EditDrawer.vue';


const route = useRoute();
const companyId = route.query.id;
const companyOverview: any = ref([]);
const overviewLoading = ref();
const { tableOptions, handlePageChange } = usePagination(fetchCompanyDetail);
const platformTableData = ref([]);
const gridOptions: any = reactive({
  border: false,
  round: true,
  stripe: true,
  currentRowHighLight: true,
  height: 870,
  toolbarConfig: {
    custom: true
  },
  rowConfig: {
    isHover: true
  },
  columnConfig: {
    resizable: true
  },
  pagerConfig: {
    total: tableOptions.value.total,
    page: tableOptions.value.page,
    limit: tableOptions.value.limit
  },
  loading: false,
  loadingConfig: {
    icon: 'vxe-icon-indicator roll',
    text: '正在拼命加载中...'
  },
  columns: companyColumns,
  data: platformTableData
});

const isOpen = ref(false);

onBeforeMount(() => {
  fetchCompanyOverview();
  fetchCompanyDetail();
});

async function fetchCompanyDetail() {
  const query = {
    id: companyId,
    page: gridOptions.pagerConfig.page,
    limit: gridOptions.pagerConfig.limit
  };
  await useTableData(api.getTableData, query, gridOptions);
}

async function fetchCompanyOverview() {
  const res = await useResponse({ companyId }, api.getCompanyOverview, overviewLoading);
  companyOverview.value = res.data;
}

function handleNavigate(item: any) {
  router.push({
    path: '/shop/detail',
    query: { platformNumber: item.platformNumber }
  });
}

function drawerOpen() {
  isOpen.value = true;
}

function handleRefresh() {
  fetchCompanyOverview();
}

const contactGroups = computed(() => {
  const contacts = companyOverview.value?.companyPhoneEmail || [];
  if (!Array.isArray(contacts)) {
    console.error('companyPhoneEmail is not an array:', contacts);
    return [];
  }

  const groups = [];

  if (contacts.length > 0) {
    groups.push(contacts.slice(0, 2));
  }

  for (let i = 2; i < contacts.length; i += 3) {
    groups.push(contacts.slice(i, i + 3));
  }

  return groups;
});
</script>

<template>
  <div class="p-2.5">
    <el-card v-loading="overviewLoading" body-class="flex items-center gap-10" shadow="hover" style="border: none">
      <el-image :src="`/src/assets/platformImg/${ companyId }.png`" class="mr-7 rounded-2xl" fit="contain"
                style="height: 120px; width: 120px;">
        <template #error>
          <div class="mr-3.5 flex items-center justify-center text-5xl"
               style="height: 100%; width: 100%; background-color: #f5f5f5">
            <el-icon>
              <icon-picture/>
            </el-icon>
          </div>
        </template>
      </el-image>
      <div class="text-lg whitespace-nowrap">
        <div class="font-semibold relative">
          <el-button class="absolute" link style="left: -24px;" type="warning"
                     @click="drawerOpen"><el-icon style="font-size: 20px !important"><Edit /></el-icon></el-button>
          公司名称:
          <span class="font-medium italic ml-1.5" style="color: #64748b;"> 
            {{ companyOverview?.company ? companyOverview?.company : '--' }} 
          </span>
        </div>
        <div class="font-semibold">
          公司英文名:
          <span class="font-medium italic ml-1.5" style="color: #64748b">
            {{ companyOverview?.companyEnglishName ? companyOverview?.companyEnglishName : '--' }} 
          </span>
        </div>
        <div class="font-semibold">
          公司地址:
          <span class="font-medium italic ml-1.5" style="color: #64748b">
            {{ companyOverview?.address ? companyOverview?.address : '--' }}
          </span>
        </div>
      </div>
      <div class="text-lg whitespace-nowrap">
        <div class="font-semibold">
          公司法人:
          <span class="font-medium italic ml-1.5" style="color: #64748b"> 
            {{ companyOverview?.juridicalPerson ? companyOverview?.juridicalPerson : '--' }} 
          </span>
        </div>
        <div class="font-semibold">
          VAT税号:
          <span class="font-medium italic ml-1.5" style="color: #64748b"> 
            {{ companyOverview?.vatNumber ? companyOverview?.vatNumber : '--' }} 
          </span>
        </div>
        <div class="font-semibold">
          VAT税号公司:
          <span class="font-medium italic ml-1.5" style="color: #64748b"> 
            {{ companyOverview?.vatCompany ? companyOverview?.vatCompany : '--' }} 
          </span>
        </div>
      </div>
      <div v-if="contactGroups.length > 0" class="flex flex-wrap whitespace-nowrap">
        <div v-for="(group, groupIndex) in contactGroups" :key="groupIndex">
          <div class="text-lg font-semibold">
            <template v-if="groupIndex === 0">
              公司联系方式:
            </template>
            <div v-for="(item, itemIndex) in group" :key="itemIndex"
                 class="font-medium italic mr-3" style="color: #64748b">
              {{ item.phone }} - {{ item.email }}
            </div>
          </div>
        </div>
      </div>
      <div v-else class="text-lg font-semibold">
        暂无联系方式
      </div>
    </el-card>

    <el-card body-style="padding-top: 10px" class="mt-2.5" shadow="hover" style="border: none">
      <vxe-grid v-bind="gridOptions">
        <template #platformNumber="{ row }">
          <el-button link style="font-weight: 700" type="primary" @click="handleNavigate(row)">
            <el-icon>
              <Link/>
            </el-icon>
            {{ row.platformNumber ? row.platformNumber : '--' }}
          </el-button>
        </template>
        <template #pager>
          <vxe-pager
              v-model:currentPage="gridOptions.pagerConfig.page"
              v-model:pageSize="gridOptions.pagerConfig.limit"
              :total="gridOptions.pagerConfig.total"
              @page-change="handlePageChange"
          >
          </vxe-pager>
        </template>
      </vxe-grid>
    </el-card>

    <EditDrawer
        v-if="isOpen"
        v-model="isOpen"
        :company="companyOverview.company"
        :companyOverview
        :formSelect
        @refresh="handleRefresh"
    />
  </div>
</template>

<style scoped>

</style>
