<script setup lang="ts">
import { useRouter } from 'vue-router'
import XEClipboard from 'xe-clipboard'
import AddReferenceDialog from './AddReferenceDialog.vue'

const router = useRouter()

const props = defineProps({
  data: Object
})
const allData: any = ref({
  basicInformation: {
    top: [
      {
        label: 'Booking No.',
        content: ''
      },
      {
        label: 'HAWB/HBL No.',
        content: '',
        type: 'link'
      },
      {
        label: 'Carrier Booking No.',
        content: ''
      },
      {
        label: 'PO No.',
        content: ''
      },
      {
        label: 'Ref No.',
        content: []
      }
    ],
    bottom: [
      {
        label: 'Vessel / Airline',
        content: ''
      },
      {
        label: 'Voyage / Flight',
        content: ''
      },
      {
        label: 'Incoterm',
        content: ''
      },
      {
        label: 'Service Type',
        content: ''
      }
    ]
  },
  businessPartners: [
    {
      title: 'Shipper',
      company: '',
      address: '',
      phone: ''
    },
    {
      title: 'Consignee',
      company: '',
      address: '',
      phone: ''
    },
    {
      title: 'Origin Agent',
      company: '',
      address: '',
      phone: ''
    },
    {
      title: 'Destination Agent',
      company: '',
      address: '',
      phone: ''
    }
  ],
  packing: [
    {
      label: 'Quantity / Unit',
      content: ''
    },
    {
      label: 'G. Weight',
      content: ''
    },
    {
      label: 'Ch. Weight',
      content: ''
    },
    {
      label: 'Volume',
      content: ''
    }
  ],
  marksAndDescription: [
    {
      label: 'Marks',
      content: ''
    },
    {
      label: 'Description',
      content: ''
    }
  ]
})

const convertData = (data: any) => {
  return {
    basicInformation: {
      top: [
        {
          label: 'Booking No.',
          content: data.basicInfo['bookingNo.'] || '--'
        },
        {
          label: 'HAWB/HBL No.',
          content: data.basicInfo['HAWB/HBOL'] || '--',
          type: 'link'
        },
        {
          label: 'Carrier Booking No.',
          content: data.basicInfo['Carrier_Booking_No'] || '--'
        },
        {
          label: 'PO No.',
          content: data.basicInfo['PO_NO'] || '--'
        },
        {
          label: 'Ref No.',
          content: data.ref_no
        }
      ],
      bottom: [
        {
          label: 'Vessel / Airline',
          content: data.basicInfo['Vessel/Airline'] || '--'
        },
        {
          label: 'Voyage / Flight',
          content: data.basicInfo['Voyage/Filght'] || '--'
        },
        {
          label: 'Incoterm',
          content: data.basicInfo['Incoterm'] || '--'
        },
        {
          label: 'Service Type',
          content: data.basicInfo['Service_Type'] || '--'
        }
      ]
    },
    businessPartners: [
      {
        title: 'Shipper',
        company: data.businessPartners.shipper.company || '--',
        address: data.businessPartners.shipper.address || '--',
        phone: data.businessPartners.shipper.phone || '--'
      },
      {
        title: 'Consignee',
        company: data.businessPartners.consignee.company || '--',
        address: data.businessPartners.consignee.address || '--',
        phone: data.businessPartners.consignee.phone || '--'
      },
      {
        title: 'Origin Agent',
        company: data.businessPartners.origin.company || '--',
        address: data.businessPartners.origin.address || '--',
        phone: data.businessPartners.origin.phone || '--'
      },
      {
        title: 'Destination Agent',
        company: data.businessPartners.destination.company || '--',
        address: data.businessPartners.destination.address || '--',
        phone: data.businessPartners.destination.phone || '--'
      }
    ],
    packing: [
      {
        label: 'Quantity / Unit',
        content: data.packing['Quantity/Unit'] || '--'
      },
      {
        label: 'G. Weight',
        content: data.packing['G. Weight'] || '--'
      },
      {
        label: 'Ch. Weight',
        content: data.packing['Ch. Weight'] || '--'
      },
      {
        label: 'Volume',
        content: data.packing['Volume'] || '--'
      }
    ],
    marksAndDescription: [
      {
        label: 'Marks',
        content: data.marksAndDescription.marsk || '--'
      },
      {
        label: 'Description',
        content: data.marksAndDescription.description || '--'
      }
    ]
  }
}

// 处理Business Partners的折叠
const curShowBusinessPartnersData = ref(allData.value.businessPartners.slice(0, 2))
const businessPartnersCollapse = (isCollapse: boolean) => {
  curShowBusinessPartnersData.value = isCollapse
    ? allData.value.businessPartners
    : allData.value.businessPartners.slice(0, 2)
}

// 处理Basic Information的折叠
// 当前Basic information Top展示的数据
const curShowBasicInforTopData = ref(allData.value.basicInformation.top.slice(0, 4))
const basicInformationCollapse = (isCollapse: boolean) => {
  curShowBasicInforTopData.value = isCollapse
    ? allData.value.basicInformation.top
    : allData.value.basicInformation.top.slice(0, 4)
}

// 处理marks and description的折叠
const isDescriptionCollapse = ref(false)
const descriptionContainerRef = ref()
const descriptionTextRef = ref()
const checkTextOverflow = () => {
  const textElement = descriptionTextRef.value[1]
  const containerHeight = descriptionContainerRef.value[1].clientHeight
  const textHeight = textElement.scrollHeight
  // 检查内容高度是否超出容器的三行高度
  isDescriptionCollapse.value = textHeight > containerHeight
}
onMounted(() => {
  checkTextOverflow()
  window.addEventListener('resize', checkTextOverflow)
})
onBeforeUnmount(() => {
  window.removeEventListener('resize', checkTextOverflow)
})

watch(
  () => props.data,
  (newVal) => {
    if (newVal) {
      allData.value = convertData(newVal)
      if (curShowBusinessPartnersData.value.length === 2) {
        curShowBusinessPartnersData.value = allData.value.businessPartners.slice(0, 2)
        curShowBasicInforTopData.value = allData.value.basicInformation.top.slice(0, 4)
      }
    }
  },
  { immediate: true, deep: true }
)

// 跳转到shipment页面
const handLink = () => {
  router.push({
    path: '/tracking/detail',
    query: { a: props?.data?.__serial_no, _schemas: props?.data?._schemas }
  })
}

const handleCopy = (data: any) => {
  const sanitizedData = data.map((item: string) => {
    return item
      ? item
          .replace(/[\r\n]+/g, ' ')
          .replace(/\s+/g, ' ')
          .trim()
      : ''
  }) // 用空格替换换行符
  const copyText = sanitizedData.join('\n') // 拼接为单行文本
  if (XEClipboard.copy(copyText)) {
    ElMessage.success('Copy success')
  }
}

const addReferenceRef = ref()
// const addReference = () => {
//   addReferenceRef.value.openDialog()
// }
const isHoverRef = ref('')

defineExpose({
  businessPartnersCollapse,
  basicInformationCollapse
})
</script>

<template>
  <div class="basic-information">
    <div class="left-section">
      <div v-for="item in curShowBasicInforTopData" :key="item.label" class="data-item">
        <div class="title">
          <span>{{ item.label }}</span>
          <!-- <el-button
            style="font-size: 12px"
            v-if="item.label === 'Ref No.'"
            class="el-button-text"
            @click="addReference"
          >
            <span class="font_family icon-icon_add_b"></span>
            Add Reference
          </el-button> -->
        </div>
        <div class="content" v-if="item.label !== 'Ref No.' && item.type !== 'link'">
          {{ item.content }}
        </div>
        <div
          class="content link"
          v-else-if="item.label !== 'Ref No.' && item.type === 'link'"
          @click="handLink()"
        >
          {{ item.content }}
        </div>
        <template v-else>
          <template v-if="item.content?.length > 0">
            <div
              class="content ref-no-content"
              v-for="noItem in item.content"
              :key="noItem.label"
              @mouseenter="isHoverRef = noItem.label"
              @mouseleave="isHoverRef = ''"
            >
              <span>{{ noItem.label }}: {{ noItem.value }}</span>
            </div>
          </template>
          <template v-else>
            <div class="content">--</div>
          </template>
        </template>
      </div>

      <el-divider />
      <div v-for="item in allData.basicInformation.bottom" :key="item.label" class="data-item">
        <div class="title">{{ item.label }}</div>
        <div class="content">{{ item.content }}</div>
      </div>
    </div>
    <div class="right-section">
      <div class="business-partner">
        <div class="item" v-for="item in curShowBusinessPartnersData" :key="item.title">
          <div class="title">
            {{ item.title }}
            <el-button class="el-button--text copy-btn">
              <span
                class="font_family icon-icon_clone_b copy-icon"
                @click="handleCopy([item.company, item.address, item.phone])"
              ></span
            ></el-button>
          </div>
          <div class="content">
            <div class="info">
              <span class="font_family icon-icon_company_b"></span>
              <span style="color: var(--color-neutral-1); font-weight: 600">{{
                item.company
              }}</span>
            </div>
            <div class="info">
              <span style="margin-left: -2px" class="font_family icon-icon_location_b"></span>
              <span>{{ item.address }}</span>
            </div>
            <div class="info">
              <span class="font_family icon-icon_phone_b"></span>
              <span>{{ item.phone }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="packing">
        <div class="header">Packing</div>
        <div class="content">
          <div class="data-item" v-for="item in allData.packing" :key="item.label">
            <div class="title">{{ item.label }}</div>
            <div class="content">{{ item.content }}</div>
          </div>
        </div>
      </div>
      <div class="marks-and-description">
        <div class="header">
          <span>Marks and Description</span>
        </div>
        <div class="data-info">
          <div class="data-item" v-for="item in allData.marksAndDescription" :key="item.label">
            <div class="title">
              {{ item.label }}
              <el-button class="el-button--text copy-btn">
                <span
                  class="font_family icon-icon_clone_b copy-icon"
                  @click="handleCopy([item.content])"
                ></span>
              </el-button>
            </div>
            <div
              ref="descriptionContainerRef"
              class="content description-info"
              style="position: relative; font-weight: 400"
            >
              <span
                ref="descriptionTextRef"
                style="display: block"
                :class="{
                  'ellipsis-3-lines': item.label === 'Description' && isDescriptionCollapse
                }"
              >
                {{ item.content }}
              </span>

              <el-popover
                v-if="item.label === 'Description' && isDescriptionCollapse"
                popper-class="marks-popover description-see-all"
                placement="top-end"
                :width="700"
                title="Description"
                trigger="click"
              >
                <div class="description-info">
                  {{ allData.marksAndDescription[1].content }}
                </div>
                <template #reference>
                  <el-button class="description-see-all el-button--text">See All</el-button>
                </template>
              </el-popover>
            </div>
          </div>
        </div>
      </div>
    </div>
    <AddReferenceDialog ref="addReferenceRef"></AddReferenceDialog>
  </div>
</template>

<style lang="scss" scoped>
.basic-information {
  display: flex;
  padding-left: 16px;
  .left-section {
    display: flex;
    flex-direction: column;
    gap: 16px;
    width: 334px;
    padding: 10px 16px 16px 0;
    border-right: 1px solid var(--color-border);

    .data-item {
      &:has(.ref-no-content) {
        gap: 0px;
      }

      .link {
        color: var(--color-theme);
        cursor: pointer;
      }

      .ref-no-content {
        display: flex;
        justify-content: space-between;
        width: 100%;
        padding: 0 4px;
        line-height: 24px;

        .icon-icon_delete_b {
          font-size: 14px;
          transform: scale(1.2);
          color: var(--color-neutral-1);
          cursor: pointer;
        }
      }
    }

    :deep(.el-divider--horizontal) {
      margin: 0px;
    }
  }
  .copy-icon {
    display: inline-block;
    transform: translateY(1px);
    font-size: 12px;
  }
}

.left-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 334px;
  padding: 10px 16px 8px 0;
  border-right: 1px solid var(--color-border);

  :deep(.el-divider--horizontal) {
    margin: 0px;
  }
}

.right-section {
  flex: 1;
  padding: 10px 0px 0;
}

.business-partner {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  padding: 0 16px;

  .item {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;

    .title {
      font-size: 12px;
      color: var(--color-neutral-2);
    }

    & > .content {
      display: flex;
      flex-direction: column;
      gap: 8px;
      height: 100%;
      padding: 8px;
      background-color: var(--color-header-bg);
      border-radius: 6px;

      .info {
        display: flex;
        flex-direction: row;
        align-items: flex-start;
        gap: 4px;

        .font_family {
          margin-top: 0;
          font-size: 16px;
          color: var(--color-neutral-1);
        }

        span {
          margin-top: 2px;
          color: var(--color-neutral-2);
        }
      }
    }
  }
}

.packing,
.marks-and-description {
  margin-top: 16px;
  border-top: 1px solid var(--color-border);

  & > .header {
    height: 48px;
    padding: 0 16px;
    background-color: var(--color-header-bg);
    line-height: 48px;
    font-size: 18px;
    font-weight: 700;
  }

  .ellipsis-3-lines {
    // display: -webkit-box;
    // -webkit-box-orient: vertical;
    // -webkit-line-clamp: 3;
    // overflow: hidden;

    // /* 其他样式 */
    // line-height: 1.5em;
    // position: relative;

    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    line-clamp: 3;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;

    &:after {
      content: '...';
      position: absolute;
      bottom: 0;
      right: 0;
      padding-right: 90px;
      padding-left: 17px;
      background: linear-gradient(to right, transparent, rgb(255, 255, 250) 17px, white 40px);
    }
  }
}

.packing {
  & > .content {
    display: flex;
    padding: 16px;
    padding-bottom: 0;

    & > .data-item {
      flex: 1;
    }
  }
}

.marks-and-description {
  & > .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 48px 0 16px;
  }

  & > .data-info {
    display: flex;
    flex-direction: column;
    gap: 16px;
    padding: 16px;

    & > .data-item {
      flex: 1;
    }
  }

  .description-info {
    line-height: 21px;

    .description-see-all {
      position: absolute;
      top: 40px;
      right: 26px;
    }
  }

  .description-info.content {
    max-height: calc(1.5em * 3);
    /* 设置最大三行高度 */
    overflow: hidden;
  }
}
</style>
<style lang="scss">
.copy-btn {
  display: inline-flex;
  align-items: center;
  height: 16px !important;
  width: 16px;
  padding: 0 !important;
  color: var(--color-neutral-2);
  & > span {
    display: block;
    height: 16px;
    width: 16px;
  }
  .font_family {
    font-size: 12px !important;
    color: var(--color-neutral-1) !important;
  }
}
div.el-popper.marks-popover {
  border-radius: 12px;
  overflow: hidden;

  .el-popover__title {
    height: 48px;
    padding-left: 16px;
    background-color: var(--color-header-bg);
    line-height: 48px;
    font-size: 18px;
    font-weight: 700;
  }

  .description-info {
    padding: 0px 16px 16px;
    font-weight: 500;
  }
}
</style>
