<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';
import { getFilterOptions } from '/@/views/shop-information/api'
import {hasPermission} from "/@/utils/hasPermission";

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: 680,
	toolbarConfig: {
		custom: true,
    slots: {
      buttons: 'toolbar_buttons',
    }
	},
	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);

const platformNumber = ref('');
const platform = ref('');
const country = ref('');
const status = ref('');

const countryOption = ref([]);
const platformOption = ref([]);
const statusOption = ref([
  {
    value: 1,
    label: '启用',
  },
  {
    value: 0,
    label: '暂停',
  },
]);

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

async function fetchFilterOptions() {
  const res = await useResponse({}, getFilterOptions);
  countryOption.value = res.data.country;
  platformOption.value = res.data.platform;
}

async function fetchCompanyDetail() {
	const query = {
		id: companyId,
    platform: platform.value,
    status: status.value,
    country:country.value.toString(),
    platformNumber:platformNumber.value,
		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;
});


function handleQuery() {
  gridOptions.pagerConfig.page = 1;
  fetchCompanyDetail()
}

</script>

<template>
	<div class="p-2.5">
		<el-card v-loading="overviewLoading" body-class="flex items-center gap-10" shadow="hover" style="border: none; position: relative" >
			<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">
					公司名称:
					<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">
            <el-tooltip effect="dark" :content="companyOverview?.companyEnglishName || '--'" placement="top">
							<span class="truncate">
									{{ companyOverview?.companyEnglishName ? companyOverview?.companyEnglishName : '--' }}
							</span>
						</el-tooltip>
					</span>
				</div>
				<div class="font-semibold">
					公司注册地址:
					<span class="font-medium italic ml-1.5 truncate" style="color: #64748b">
						<el-tooltip effect="dark" :content="companyOverview?.address || '--'" placement="top">
							<span class="truncate">
								{{ companyOverview?.address ? companyOverview?.address : '--' }}
							</span>
						</el-tooltip>
					</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">
					法人信用卡号:
					<span class="font-medium italic ml-1.5" style="color: #64748b">
						{{ companyOverview?.juridicalPersonCreditCard ? companyOverview?.juridicalPersonCreditCard : '--' }}
					</span>
				</div>
				<div class="font-semibold">
					法人信用卡地址:
					<span class="font-medium italic ml-1.5" style="color: #64748b">
             <el-tooltip effect="dark" :content="companyOverview?.juridicalPersonCreditCardAddress || '--'" placement="top">
							<span class="truncate">
										{{ companyOverview?.juridicalPersonCreditCardAddress ? companyOverview?.juridicalPersonCreditCardAddress : '--' }}
							</span>
						</el-tooltip>
					</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?.shopEmail ? companyOverview.shopEmail : '--' }}
					</span>
        </div>

        <div class="font-semibold">
          主账户电话:
          <span class="font-medium italic ml-1.5" style="color: #64748b">
            {{ companyOverview?.shopPhone ? companyOverview.shopPhone : '--' }}
					</span>
        </div>
        <div class="font-semibold">
          <el-button class="absolute" link style="right: 10px; top: 20px; transition: all 0.3s ease"
                     type="warning" @click="drawerOpen"
                     v-if="hasPermission('COMPANY_UPDATE')">
            <Edit style="width: 1.5em; height: 1.5em;"/>
          </el-button>
          IP地址:
          <span class="font-medium italic ml-1.5" style="color: #64748b">
             <el-tooltip effect="dark" :content="companyOverview?.ipaddress || '--'" placement="top">
							<span class="truncate">
										{{ companyOverview?.ipaddress ? companyOverview?.ipaddress : '--' }}
							</span>
						</el-tooltip>
					</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>

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

		<el-card body-style="padding-top: 10px" class="mt-2.5" shadow="hover" style="border: none">
			<vxe-grid v-bind="gridOptions">
        <template #toolbar_buttons>
          <el-row :gutter="20" class="w-full whitespace-nowrap">
            <el-col :span="4">
              <div class="flex items-center gap-1.5">
                <span class="font-medium">平 台</span>
                <el-select v-model="platform" clearable @change="handleQuery">
                  <el-option v-for="item in platformOption" :label="item" :value="item" />
                </el-select>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="flex items-center gap-1.5">
                <span class="font-medium">店铺编号</span>
                <el-input v-model="platformNumber" clearable placeholder="请输入店铺编号" @change="handleQuery" />
              </div>
            </el-col>
            <el-col :span="4">
              <div class="flex items-center gap-1.5">
                <span class="font-medium">状 态</span>
                <el-select v-model="status" clearable @change="handleQuery">
                  <el-option  v-for="item in statusOption" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="flex items-center gap-1.5">
                <span class="font-medium">国 家</span>
                <el-select v-model="country" clearable collapse-tags collapse-tags-tooltip multiple
                           @blur="handleQuery">
                  <el-option v-for="item in countryOption" :label="item" :value="item" />
                </el-select>
              </div>
            </el-col>
          </el-row>
        </template>
				<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>
	</div>
</template>

<style scoped>
.truncate {
	display: inline-block;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	max-width: 250px; /* 添加固定宽度 */
	vertical-align: middle; /* 添加垂直对齐 */
}
</style>
