<template>
  <div class="view-box">
    <el-empty v-if="!dataList?.length" style="padding-top: 15%;" description="暂无数据" :image-size="100" />
    <div v-if="dataList.length" class="main-content-main">
      <div class="main-mask"
        @wheel.prevent="handleWheel"
        @mousedown="handleMouseDown"
        @mouseup="handleMouseUp"
        @mouseleave="handleMouseUp"
        @mousemove="handleMouseMove"
      ></div>
      <div class="fishbone-container"  :style="{ transform: `translate(${translateX}px, ${translateY}px) scale(${scale})`, transformOrigin: 'center center' }">
        <!-- 主轴上的标签 -->
        <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="groupIndex"
          class="top-bone" :style="{ left: groupIndex * 400 + 510 + 'px', height: (causeGroup.causes?.length) * 22 + 100 + 'px' }">
          <div class="left-bone">
            <div class="left-bone-item" v-for="item in getLeftItems(causeGroup.causes)" :key="item.id">
              <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 in getRightItems(causeGroup.causes)" :key="item.id">
              <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="groupIndex"
          class="bottom-bone" :style="{ left: groupIndex * 400 + 310 + 'px', height: (causeGroup.causes?.length) * 22 + 100 + 'px' }">
          <div class="left-bone">
            <div class="left-bone-item" v-for="item in getRightItems(causeGroup.causes)" :key="item.id">
              <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 in getLeftItems(causeGroup.causes)" :key="item.id">
              <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>
    <div v-if="dataList.length" class="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>
</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 scale = ref(1)
const minScale = 0.1
const maxScale = 10
const handleWheel = (e) => {
  if (e.deltaY < 0) {
    // 放大：不超过最大值
    scale.value = Math.min(scale.value + 0.1, maxScale)
  } else {
    // 缩小：不低于最小值
    scale.value = Math.max(scale.value - 0.1, minScale)
  }
}
// 移动功能处理
const translateX = ref(0)     // X轴位移
const translateY = ref(0)     // Y轴位移
let isDragging = false
let startX = 0
let startY = 0
const handleMouseMove = (e) => {
  if (!isDragging) return
  translateX.value = e.clientX - startX
  translateY.value = e.clientY - startY
}
const handleMouseDown = (e) => {
  // 排除右键/中键，只响应左键（e.button=0为左键）
  if (e.button !== 0) return
  isDragging = true
  startX = e.clientX - translateX.value
  startY = e.clientY - translateY.value
}
const handleMouseUp = () => {
  isDragging = false
}

// 实体清单-深度挖掘-产业链中国企业实体信息查询
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 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%;
  display: flex;
  flex-direction: column;

  .main-content-main {
    position: relative;
    height: 20px;
    flex: auto;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    .main-mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 3;
    }

    .fishbone-container {
      position: relative;

      .main-line {
        height: 3px;
        background: rgb(230, 231, 232);
        display: flex;
        justify-content: space-between;
        align-items: center;

        // 添加中间的文字块
        .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;
      bottom: 0px;
      width: 3px;
      background: rgb(230, 231, 232);
      transform-origin: bottom center;
      transform: skew(30deg);
      z-index: 1;

      .left-bone {
        color: #777;
        position: absolute;
        top: -20px;
        right: 0;
        width: 180px;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: flex-end;

        .left-bone-item {
          transform: skew(-30deg);
          height: 40px;
          margin: 4px 0;
          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: -44px;
        left: 0;
        width: 180px;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: flex-end;

        .right-bone-item {
          transform: skew(-30deg);
          height: 40px;
          margin: 4px 0;
          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-bone {
      position: absolute;
      top: 0px;
      width: 3px;
      background: rgb(230, 231, 232);
      transform-origin: top center;
      transform: skew(-30deg);
      z-index: 1;

      .left-bone {
        color: #777;
        position: absolute;
        bottom: -44px;
        right: 0;
        width: 180px;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;

        .left-bone-item {
          transform: skew(30deg);
          height: 40px;
          margin: 4px 0;
          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;
        bottom: -20px;
        left: 0;
        width: 180px;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;

        .right-bone-item {
          transform: skew(30deg);
          height: 40px;
          margin: 4px 0;
          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;
          }
        }
      }
    }
  }

  .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>