<template>
  <div class="view-box">
    <div class="right-main">
      <div class="right-main-content">
        <div class="hintWrap">
          <div class="icon1"></div>
          <div class="title">
            这项政令标志着中美AI竞争进入一个新阶段，其核心特征是 “精准封锁”与“体系输出”相结合。它短期内无疑会给中国AI产业链带来压力，但长期看，这场竞争更可能是一场围绕技术路线、生态系统和治理规则的持久战。
          </div>
          <div class="icon2Wrap">
            <div class="icon2"></div>
          </div>
        </div>
        <div class="right-main-content-main">
          <div class="fishbone-wrapper">
            <div class="fishbone-scroll-container" ref="scrollContainerRef">
              <div class="fishbone" v-if="dataList.length > 0">
                <div class="main-line" :style="{ width: dataList.length * 200 + 300 + 'px' }">
                  <!-- 主轴上的标签 -->
                  <div class="main-line-text" v-for="(item, index) in dataList" :key="'label-' + index"
                    :class="{
                      'blue-theme': index < 2,
                      'green-theme': index >= 2 && index < 4,
                      'purple-theme': index >= 4
                    }" :style="{ left: index * 200 + 220 + 'px' }">
                    {{ item.text }}
                  </div>
                </div>
                <!-- 奇数索引的数据组放在上方 -->
                <div v-for="(causeGroup, groupIndex) in onFilterData(1)" :key="'top-' + groupIndex"
                  :class="getTopBoneClass(groupIndex)" :style="{ left: groupIndex * 400 + 420 + 'px' }">
                  <div class="left-bone">
                    <div class="left-bone-item" v-for="(item, index) in getLeftItems(causeGroup.causes)" :key="'left-' + index">
                      <img :src="defaultIcon2 || item.picture" alt="" class="company-icon" />
                      <div class="text" :title="item.name">{{ item.name }}</div>
                      <div class="line"></div>
                    </div>
                  </div>
                  <div class="right-bone">
                    <div class="right-bone-item" v-for="(item, index) in getRightItems(causeGroup.causes)" :key="'right-' + index">
                      <div class="line"></div>
                      <img :src="defaultIcon2 || item.picture" alt="" class="company-icon" />
                      <div class="text" :title="item.name">{{ item.name }}</div>
                    </div>
                  </div>
                </div>

                <!-- 偶数索引的数据组放在下方 -->
                <div v-for="(causeGroup, groupIndex) in onFilterData(0)" :key="'bottom-' + groupIndex"
                  :class="getBottomBoneClass(groupIndex)" :style="{ left: groupIndex * 400 + 220 + 'px' }">
                  <div class="left-bone">
                    <div class="left-bone-item" v-for="(item, index) in getLeftItems(causeGroup.causes)" :key="'left-bottom-' + index">
                      <img :src="defaultIcon2 || item.picture" alt="" class="company-icon" />
                      <div class="text" :title="item.name">{{ item.name }}</div>
                      <div class="line"></div>
                    </div>
                  </div>
                  <div class="right-bone">
                    <div class="right-bone-item" v-for="(item, index) in getRightItems(causeGroup.causes)" :key="'right-bottom-' + index">
                      <div class="line"></div>
                      <img :src="defaultIcon2 || item.picture" alt="" class="company-icon" />
                      <div class="text" :title="item.name">{{ item.name }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else
                style="display: flex; justify-content: center; align-items: center; height: 200px; width: 100%">
                <el-empty description="暂无相关数据" />
              </div>
            </div>
          </div>
        </div>
        <div class="right-main-content-footer">
          <div class="footer-item footer-item1">
            <div class="footer-item-bottom">
              <div class="icon">
                <img :src="noticeIcon" alt="" />
              </div>
              <div class="text">
                {{
                  `中国企业${cnEntityOnChainData.upstreamInternalCount ||
                  0}家（${formatRate(cnEntityOnChainData.upstreamInternalRate)}%），受制裁${cnEntityOnChainData.upstreamEntityCount
                  || 0}家（${formatRate(cnEntityOnChainData.upstreamEntityRate)}%）`
                }}
              </div>
            </div>
            <div class="footer-item-top">{{ "上游" }}</div>
          </div>
          <div class="footer-item footer-item2">
            <div class="footer-item-bottom">
              <div class="icon">
                <img :src="noticeIcon" alt="" />
              </div>
              <div class="text">
                {{
                  `中国企业${cnEntityOnChainData.midstreamInternalCount ||
                  0}家（${formatRate(cnEntityOnChainData.midstreamInternalRate)}%），受制裁${cnEntityOnChainData.midstreamEntityCount
                  || 0}家（${formatRate(cnEntityOnChainData.midstreamEntityRate)}%）`
                }}
              </div>
            </div>
            <div class="footer-item-top">{{ "中游" }}</div>
          </div>
          <div class="footer-item footer-item3">
            <div class="footer-item-bottom">
              <div class="icon">
                <img :src="noticeIcon" alt="" />
              </div>
              <div class="text">
                {{
                  `中国企业${cnEntityOnChainData.downstreamInternalCount ||
                  0}家（${formatRate(cnEntityOnChainData.downstreamInternalRate)}%），受制裁${cnEntityOnChainData.downstreamEntityCount
                  || 0}家（${formatRate(cnEntityOnChainData.downstreamEntityRate)}%）`
                }}
              </div>
            </div>
            <div class="footer-item-top">{{ "下游" }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="ChartChain">
import { ref, onMounted } from "vue";
import defaultIcon2 from "@/assets/icons/default-icon2.png";
import noticeIcon from "./assets/images/notice-icon.png";
import { getDeepMiningSelect, getDeepMiningIndustry, getDeepMiningIndustryFishbone, getDeepMiningIndustryEntity } from "@/api/exportControlV2.0";

// 实体清单-深度挖掘-产业链中国企业实体信息查询
const cnEntityOnChainData = ref({});
const getCnEntityOnChainData = async () => {
	const currentSanction = sanctionList.value.find(item => item.id === currentSanctionId.value);
	const date = currentSanction ? currentSanction.date : '';
	// 确保 date 格式正确
	const formattedDate = date && date.includes('年') ? date.replace('年', '-').replace('月', '-').replace('日', '') : date;

	const params = {
		date: formattedDate
	};
	if (selectedIndustryId.value) {
		params.chainId = selectedIndustryId.value;
	}
	try {
		const res = await getDeepMiningIndustryEntity(params);
    console.log("企业信息", res)
		if (res.code === 200 && res.data) {
			cnEntityOnChainData.value = res.data;
		} else {
			cnEntityOnChainData.value = {};
		}
	} catch (error) {
		console.error("获取产业链中国企业实体信息失败:", error);
		cnEntityOnChainData.value = {};
	}
}

// 产业链鱼骨数据
const dataList = ref([]);
// 奇数索引的数据组放在上方, 偶数索引的数据组放在下方
const onFilterData = (num) => {
	return dataList.value.filter((_, index) => index % 2 === num);
};
// 获取左侧显示的项目（前半部分）
const getLeftItems = items => {
	const midpoint = Math.ceil(items.length / 2);
	return items.slice(0, midpoint);
};
// 获取右侧显示的项目（后半部分）
const getRightItems = items => {
	const midpoint = Math.ceil(items.length / 2);
	return items.slice(midpoint);
};
// 获取上方鱼骨图位置类名
const getTopBoneClass = index => {
	const positions = ["top-bone", "top-bone1", "top-bone2"];
	return positions[index % 3] || "top-bone";
};
// 获取下方鱼骨图位置类名
const getBottomBoneClass = index => {
	const positions = ["bottom-bone", "bottom-bone1", "bottom-bone2"];
	return positions[index % 3] || "bottom-bone";
};
const getFishboneData = async () => {
	const currentSanction = sanctionList.value.find(item => item.id === currentSanctionId.value);
	const date = currentSanction ? currentSanction.date : '';
	// 确保 date 格式正确
	const formattedDate = date && date.includes('年') ? date.replace('年', '-').replace('月', '-').replace('日', '') : date;

	const params = {
		date: formattedDate
	};
	if (selectedIndustryId.value) {
		params.chainId = selectedIndustryId.value;
	}
	try {
		const res = await getDeepMiningIndustryFishbone(params);
    console.log("获取产业链数据:", res);
		if (res.code === 200 && res.data?.causes?.length) {
			dataList.value = res.data.causes;
		} else {
			dataList.value = [];
		}
	} catch (error) {
		console.error("获取产业链鱼骨图数据失败:", error);
		dataList.value = [];
	}
}

// 实体清单-深度挖掘-产业链列表信息
const selectedIndustryId = ref(null);
const getIndustryList = async () => {
	try {
		const res = await getDeepMiningIndustry();
		if (res.code === 200 && res.data && res.data.length > 0) {

			selectedIndustryId.value = res.data[0].id;
			getFishboneData();
			getCnEntityOnChainData();
		} else {

			selectedIndustryId.value = null;
		}
	} catch (error) {
		console.error("获取产业链列表数据失败:", error);

		selectedIndustryId.value = null;
	}
}

// 获取选择制裁
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10000);

const getDeepMiningSelectData = async () => {
	loading.value = true;
	const params = {
		startDate: dateRange.value && dateRange.value[0] ? dateRange.value[0] : '',
		endDate: dateRange.value && dateRange.value[1] ? dateRange.value[1] : '',
		typeName: "实体清单",
		isCn: false,
		pageNum: currentPage.value,
		pageSize: pageSize.value
	};
	try {
		const res = await getDeepMiningSelect(params);
		if (res.code === 200 && res.data && res.data.content) {
			sanctionList.value = res.data.content.map(item => ({
				id: item.id,
				date: item.postDate,
				title: item.name,
				count: item.cnEntityCount,
				unit: '家中国实体', // 接口未返回单位，暂时固定
				summary: item.summary, // 保留额外信息备用
				techDomainList: item.techDomainList // 保留额外信息备用
			}));

			// 默认选中第一条
			if (sanctionList.value.length > 0) {
				currentSanctionId.value = sanctionList.value[0].id;
				// getFishboneData(); // 这里不需要调用，因为getIndustryList会调用
			}
		} else {
			sanctionList.value = [];
		}
	} catch (error) {
		console.error("获取选择制裁数据失败:", error);
		sanctionList.value = [];
	} finally {
		loading.value = false;
	}
}

const dateRange = ref(["2025-01-01", "2025-12-31"]);
const sanctionList = ref([
	{ id: 1, date: "2025年2月8日", title: "实体清单更新", count: 2, unit: "家中国实体" },
	{ id: 2, date: "2025年4月10日", title: "实体清单更新", count: 5, unit: "家中国实体" },
	{ id: 3, date: "2025年6月29日", title: "实体清单更新", count: 6, unit: "家中国实体" },
	{ id: 4, date: "2025年8月12日", title: "实体清单更新", count: 24, unit: "家中国实体" },
	{ id: 5, date: "2025年8月19日", title: "实体清单更新", count: 11, unit: "家中国实体" },
	{ id: 6, date: "2025年9月12日", title: "实体清单更新", count: 3, unit: "家中国实体" },
	{ id: 7, date: "2025年9月26日", title: "实体清单更新", count: 6, unit: "家中国实体" },
	{ id: 8, date: "2025年10月12日", title: "实体清单更新", count: 18, unit: "家中国实体" }
]);
const currentSanctionId = ref(5);

// 格式化比率
const formatRate = (rate, ratio=false) => {
	if (!rate) return '0.00';
	return (rate * 100).toFixed(2);
};

onMounted(() => {
	// 获取选择制裁
	getDeepMiningSelectData();
	// 获取产业链信息
	getIndustryList();
});
</script>

<style scoped lang="scss">
.view-box {
  width: 100%;
  height: 100%;
}
.right-main {
  height: 100%;
  padding: 11px 16px 20px;
  

  .right-main-content {
    height: 100%;
    display: flex;
    flex-direction: column;

    .hintWrap {
      display: flex;
      align-items: center;
      padding: 7px 12px;
      border: 1px solid rgba(231, 243, 255, 1);
      border-radius: 4px;
      background: rgba(246, 250, 255, 1);
      margin-bottom: 9px;

      .icon1 {
        width: 19px;
        height: 20px;
        background-image: url("./assets/images/ai.png");
        background-size: 100% 100%;
        flex-shrink: 0;
      }

      .title {
        color: rgb(5, 95, 194);
        font-size: 16px;
        font-weight: 400;
        line-height: 24px;
        margin-left: 13px;
        flex: 1;
      }

      .icon2Wrap {
        width: 24px;
        height: 24px;
        background-color: rgba(231, 243, 255, 1);
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 12px;
        margin-left: 20px;
        flex-shrink: 0;

        .icon2 {
          width: 24px;
          height: 24px;
          background-image: url("./assets/images/right.png");
          background-size: 100% 100%;
        }
      }
    }

    .right-main-content-main {
      flex: 1;
      position: relative;
      overflow: hidden;

      .fishbone-wrapper {
        position: relative;
        width: 100%;
        height: 100%;
      }

      .fishbone-scroll-container {
        display: flex;
        align-items: center;
        width: 100%;
        height: 100%;
        overflow-x: auto;
        overflow-y: hidden;
        scrollbar-width: thin;
        scrollbar-color: rgba(144, 202, 249, 0.5) transparent;

        &::-webkit-scrollbar {
          height: 6px;
        }

        &::-webkit-scrollbar-track {
          background: transparent;
        }

        &::-webkit-scrollbar-thumb {
          background-color: rgba(144, 202, 249, 0.5);
          border-radius: 3px;
        }
      }

      .fishbone {
        position: relative;
        width: fit-content;
        height: 100%;
        margin-top: 40px;
        min-width: 100%;
        padding-left: 275px;
        margin-left: 40px;

        .main-line {
          margin-top: 280px;
          width: 1888px;
          height: 3px;
          background: rgb(230, 231, 232);
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 100px;

          // 虚线
          &::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
          }

          // 添加中间的文字块
          .main-line-text {
            position: absolute;
            // top: -14px;
            font-size: 16px;
            color: #055FC2;
            font-weight: bold;
            background-color: #f7f8f9;
            padding: 0 10px;
            z-index: 2;

            // 箭头背景
            height: 32px;
            line-height: 32px;
            width: 160px;
            text-align: center;
            background: rgba(231, 243, 255, 1);
            clip-path: polygon(0% 0%, 90% 0%, 100% 50%, 90% 100%, 0% 100%, 10% 50%);

            &.blue-theme {
              background: rgba(231, 243, 255, 1);
              color: rgba(22, 119, 255, 1);
            }

            &.green-theme {
              background: rgba(225, 255, 251, 1);
              color: rgba(19, 168, 168, 1);
            }

            &.purple-theme {
              background: rgba(246, 235, 255, 1);
              color: rgba(146, 84, 222, 1);
            }
          }
        }
      }

      .company-icon {
        width: 16px;
        height: 16px;
        margin: 0 4px;
        object-fit: contain;
      }

      .top-bone {
        position: absolute;
        top: 20px;
        right: 200px;
        width: 3px;
        height: 260px;
        background: rgb(230, 231, 232);
        transform: skew(30deg);
        z-index: 1;

        .left-bone {
          color: #777;
          position: absolute;
          top: 0;
          left: -150px;
          width: 150px;
          height: 50px;

          // overflow: hidden;
          .left-bone-item {
            transform: skew(-30deg);
            height: 45px;
            margin-bottom: 2px;
            margin-top: 2px;
            display: flex;
            justify-content: flex-end;
            align-items: center;

            .text {
              margin-left: 4px;
              height: 25px;
              line-height: 25px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .line {
              margin-left: 7px;
              width: 40px;
              height: 2px;
              background: rgb(230, 231, 232);
            }
          }
        }

        .right-bone {
          color: #777;
          position: absolute;
          top: 0;
          right: -150px;
          width: 150px;
          height: 210px;
          overflow: hidden;

          .right-bone-item {
            transform: skew(-30deg);
            height: 39px;
            margin-bottom: 2px;
            margin-top: 2px;
            display: flex;
            justify-content: flex-start;
            align-items: center;

            .line {
              margin-right: 7px;
              width: 30px;
              height: 2px;
              background: rgb(230, 231, 232);
            }

            .text {
              max-width: 100px;
              margin-right: 4px;
              height: 25px;
              line-height: 25px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }
      }

      .top-bone1 {
        @extend .top-bone;
        right: 500px;
      }

      .top-bone2 {
        @extend .top-bone;
        right: 800px;
      }

      .bottom-bone {
        position: absolute;
        top: 280px;
        right: 360px;
        width: 3px;
        height: 260px;
        background: rgb(230, 231, 232);
        transform: skew(-30deg);
        z-index: 1;

        .left-bone {
          color: #777;
          position: absolute;
          top: 50px;
          left: -150px;
          width: 150px;
          height: 260px;

          .left-bone-item {
            transform: skew(30deg);
            height: 39px;
            margin-bottom: 2px;
            margin-top: 2px;
            display: flex;
            justify-content: flex-end;
            align-items: center;

            .text {
              margin-left: 4px;
              height: 25px;
              max-width: 130px;
              line-height: 25px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .line {
              margin-left: 7px;
              width: 40px;
              height: 2px;
              background: rgb(230, 231, 232);
            }
          }
        }

        .right-bone {
          color: #777;
          position: absolute;
          top: 50px;
          right: -150px;
          width: 150px;
          height: 260px;

          .right-bone-item {
            transform: skew(30deg);
            height: 35px;
            margin-bottom: 2px;
            margin-top: 2px;
            display: flex;
            justify-content: flex-start;
            align-items: center;

            .line {
              margin-right: 7px;
              width: 30px;
              height: 2px;
              background: rgb(230, 231, 232);
            }

            .text {
              max-width: 100px;
              margin-right: 4px;
              height: 25px;
              line-height: 25px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }
      }

      .bottom-bone1 {
        @extend .bottom-bone;
        right: 660px;
      }

      .bottom-bone2 {
        @extend .bottom-bone;
        right: 960px;
      }
    }

    .right-main-content-footer {
      margin-top: 16px;
      display: flex;
      justify-content: space-between;

      .footer-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
      }

      .footer-item {
        .footer-item-top {
          height: 28px;
          text-align: center;
          line-height: 28px;
          font-family: Microsoft YaHei;
          font-size: 16px;
          font-weight: 700;
          margin-top: 10px;
          position: relative;
          z-index: 1;
        }
        .footer-item-bottom {
          display: flex;
          justify-content: center;
          align-items: center;

          .text {
            color: rgba(206, 79, 81, 1);
            font-size: 14px;
            line-height: 14px;
            margin-left: 6px;
          }
          .icon {
            width: 16px;
            height: 16px;
            font-size: 0;

            img {
              width: 100%;
              height: 100%;
            }
          }
        }
      }

      .footer-item1 {
        color: rgba(22, 119, 255, 1);
        .footer-item-top {
          background: rgba(231, 243, 255, 1);
        }
      }
      .footer-item2 {
        color: rgba(19, 168, 168, 1);
        .footer-item-top {
          background: rgba(225, 255, 251, 1);
        }
      }
      .footer-item3 {
        color: rgba(146, 84, 222, 1);
        .footer-item-top {
          background: rgba(246, 235, 255, 1);
        }
      }
    }
  }
}
</style>