<script setup lang="ts">
import '@/styles/common.scss';
import { getSupplyAreaList, getSupplyCountryList, getSupplyList } from "@/api/companyPages/index.js";
import { onMounted, ref } from 'vue';
import { ElCheckbox, ElCheckboxGroup, ElRow, ElCol, ElMessage, ElRadioGroup, ElRadioButton } from 'element-plus';
import ColorPrefixTitle from '@/components/base/texts/ColorPrefixTitle.vue';
import GraphChart from './GraphChart.vue'
import { forEach } from 'lodash';
import AiTipPane from '@/components/base/panes/AiTipPane.vue';
import ColorSvg from '@/components/base/images/ColorSvg.vue'
import MachineImg from '../../assets/images/机械设备.svg'
import FundImg from '../../assets/images/资金管理.svg'
const CompanyImg = "/icon/company/普通企业节点.svg"
const CompanyImg2 = "/icon/company/普通企业节点2.svg"

import { getSingleSanctionEntityEquity } from '@/api/exportControlV2.0';

// 定义组件属性
const props = defineProps({
    enterpriseInfo: {
        type: Object,
        default: {}
    }
});

const supplyAreaList = ref([]);
const supplyCountryList = ref([]);
const supplyTypeList = [{
    name: '上游', id: 'supply'
}, {
    name: '下游', id: 'customer'
}];
const dataTypeList = ref([{
    name: '供应链', id: 'supply',
    icon: MachineImg
}, {
    name: '股权', id: 'equity',
    icon: FundImg
}])
const selectedSupplyAreas = ref([]);
const selectedSupplyCountries = ref([]);
const selectedSupplyTypes = ref([]);
const selectedDataType = ref('supply')

const nodes = ref([])
const links = ref([])


onMounted(async () => {
    await initData()
    await updateData()
})

async function initData() {
    const { data } = await getSupplyAreaList(props.enterpriseInfo.id);
    supplyAreaList.value = data ?? [];
    const { data: countryData } = await getSupplyCountryList(props.enterpriseInfo.id);
    supplyCountryList.value = countryData ?? [];
}

async function updateData() {
    if (selectedDataType.value === 'supply') {
        await updateDataSupply()
    } else if (selectedDataType.value === 'equity') {
        await updateDataEquity()
    }
}

async function updateDataSupply() {
    const params = {
        arealist: selectedSupplyAreas.value ? selectedSupplyAreas.value.join(",") : null,
        countrylist: selectedSupplyCountries.value ? selectedSupplyCountries.value.join(",") : null,
        type: selectedSupplyTypes.value.length === 2 ? 'all' : selectedSupplyTypes.value ? selectedSupplyTypes.value : null,
        id: props.enterpriseInfo.id
    }
    const { data } = await getSupplyList(params)
    if (!data) {
        ElMessage.error('获取供应链数据失败')
        return
    }
    // 提取所有公司名称
    const companyMap: Map<string, any> = new Map();
    data.forEach(item => {
        companyMap.set(item.orgId, { name: item.orgName, type: item.type })
        companyMap.set(item.otherOrgId, { name: item.otherOrgName, type: item.type })
    })


    // 创建nodes数组
    nodes.value = Array.from(companyMap).map(([orgId, item]) => (createNode(orgId, item.name, item.type, false)));

    const linksData = []
    forEach(data, item => {
        const link = createLink(item.orgId, item.otherOrgId, '供应商', false)
        if (item.type === 'from') {
            link.source = item.otherOrgId
            link.target = item.orgId
            link.label.formatter = '客户'
        }
        linksData.push(link)
    })
    // 创建links数组
    links.value = linksData
}
function createNode(orgId: string, orgName: string, type: string, isSanctioned: boolean) {
    return {
        id: orgId,
        name: orgName,
        type: type,
        symbolSize: 50,
        symbol: `image://${isSanctioned ? CompanyImg2 : CompanyImg}`,
        isSanctioned
    }
}
function createLink(source: string, target: string, formatter: string, isSanctioned: boolean) {
    return {
        source: source,
        target: target,
        label: {
            show: true,
            formatter: formatter,
            color: isSanctioned ? 'rgba(255, 102, 102, 1)' : 'rgba(137, 193, 255, 1)',
            backgroundColor: isSanctioned ? 'rgba(255, 102, 102, 0.2)' : 'rgba(137, 193, 255, 0.2)',
            padding: [4, 4],
            borderRadius: 10
        },
    }
}

async function updateDataEquity() {
    const { data } = await getSingleSanctionEntityEquity({ orgId: props.enterpriseInfo.id, rule: true })
    if (!data) {
        ElMessage.error('获取股权数据失败')
        return
    }
    const cnode = createNode(data.orgId, data.orgName, "to", false)
    const linksData = []
    const nodesData = [cnode]
    const { parentOrgList, childrenOrgList } = data

    childrenOrgList.forEach((item, i) => {
        if (!item.id) item.id = i
        nodesData.push(createNode(item.id, item.name, "to", item.isSanctioned))
        linksData.push(createLink(cnode.id, item.id, item.description, item.isSanctioned))
    })

    parentOrgList.forEach((item, i) => {
        if (!item.id) item.id = i
        nodesData.push(createNode(item.id, item.name, "from", item.isSanctioned))
        linksData.push(createLink(item.id, cnode.id, item.description, item.isSanctioned))
    })
    nodes.value = nodesData
    links.value = linksData

    console.log(nodesData, linksData)
}

async function handleOptionsChnage() {

    await updateData()
}

async function handleDataTypeChange() {
    await updateData()
}

</script>

<template>
    <div class="flex-display box-div">
        <div class="background-as-card options-pane">
            <color-prefix-title>科技领域</color-prefix-title>
            <el-checkbox-group class="checkbox-group" v-model="selectedSupplyAreas" @change="handleOptionsChnage">
                <el-row>
                    <el-col v-for="item in supplyAreaList" :span="12">
                        <el-checkbox :label="item.name + '(' + item.num + ')'" :value="item.id" />
                    </el-col>
                </el-row>
            </el-checkbox-group>
            <color-prefix-title>国家/地区</color-prefix-title>
            <el-checkbox-group class="checkbox-group" v-model="selectedSupplyCountries" @change="handleOptionsChnage">
                <el-row>
                    <el-col v-for="item in supplyCountryList" :span="12">
                        <el-checkbox :label="item.name + '(' + item.num + ')'" :value="item.id" />
                    </el-col>
                </el-row>
            </el-checkbox-group>
            <color-prefix-title>上下游</color-prefix-title>
            <el-checkbox-group class="checkbox-group" v-model="selectedSupplyTypes" @change="handleOptionsChnage">
                <el-row>
                    <el-col v-for="item in supplyTypeList" :span="12">
                        <el-checkbox :label="item.name" :value="item.id" />
                    </el-col>
                </el-row>
            </el-checkbox-group>
        </div>
        <div class="background-as-card flex-fill">
            <el-radio-group v-model="selectedDataType" class="data-type-group" @change="handleDataTypeChange">
                <el-radio-button v-for="item in dataTypeList" :label="item.id" :value="item.id">
                    <color-svg :size="16" :svg-url="item.icon"
                        :color="item.id === selectedDataType ? 'var(--bg-white-100)' : 'var(--color-primary-100)'">
                    </color-svg>
                    <span class="text-title-3">
                        {{ item.name }}
                    </span>
                </el-radio-button>
            </el-radio-group>
            <graph-chart :nodes="nodes" :links="links" />
            <ai-tip-pane v-if="enterpriseInfo.id === '914403001922038216'">
                华为构建了覆盖全球的复杂供应链网络，以自身为核心，辐射芯片、显示、摄像头等关键领域。其供应链深度扎根中国，同时整合美国高通、韩国三星、日本索尼等国际顶尖供应商，形成多元化供应格局。面对外部技术封锁，华为通过扶持海思等子公司强化垂直整合，并积极拓展本土替代资源，在保持技术领先的同时增强供应链韧性，展现出卓越的全球资源调配与风险管控能力。
            </ai-tip-pane>
        </div>
    </div>
</template>

<style lang="css" scoped>
.options-pane {
    width: 360px;
    padding-top: 16px;
    margin-right: 16px;
}

.chart-box {
    padding: 10px 0px;
    background-color: var(--bg-white-100);
}

.checkbox-group {
    padding: 0px 25px;
    margin-bottom: 20px;
}

.data-type-group {
    padding: 10px 16px;
    top: 16px;
}
</style>