<template>
  <div class="history_page">
    <div class="page_content">
      <div class="page_content_body">
        <div class="history_page_body">
          <TableSearchBar
            ref="tableSearchBar"
            :button-list="presetList"
            :placeholder="t('batchGeneration.Search')"
            @search="searchHistoryList"
          />
          <div class="history_table_content" ref="historyTable">
            <a-config-provider :locale="tableLocale">
              <a-table
                row-class-name="history_table_row"
                :columns="columns"
                :customRow="customTableRow"
                :data-source="collectionList"
                @change="changePage"
                :pagination="{
                  current: currentPage,
                  pageSize: pageSize,
                  total: total,
                  bordered: false,
                  showQuickJumper: true,
                  showSizeChanger: false,
                  size: 'small'
                }"
              >
                <template #bodyCell="{ column, text, record, index }">
                  <div class="operate_list" v-if="column?.Operations">
                    <div
                      class="operate_item"
                      :class="{
                        operate_item_hidden: !(
                          record.process === 'SERIES_DESIGN' ||
                          record.process === 'SINGLE_DESIGN'
                        )
                      }"
                      @click="turnToDetail(record)"
                    >
                      {{ $t('HistoryPage.Detail') }}
                    </div>
                    <div
                      class="operate_item"
                      :class="{
                        operate_item_hidden: !(
                          record.process === 'SERIES_DESIGN' ||
                          record.process === 'SINGLE_DESIGN'
                        )
                      }"
                      @click="renameCollection(record, index)"
                    >
                      {{ $t('HistoryPage.Edit') }}
                    </div>
                    <div class="operate_item" @click="retrieveHome(record)">
                      {{ $t('HistoryPage.Retrieve') }}
                    </div>
                    <div class="operate_item" @click="deleteGroup(record, index)">
                      {{ $t('HistoryPage.Delete') }}
                    </div>
                  </div>
                </template>
              </a-table>
            </a-config-provider>
          </div>
        </div>
      </div>
    </div>
    <HistoryDetail
      ref="historyDetail"
      :groupDetails="groupDetails"
      :collectionName="collectionName"
    ></HistoryDetail>
    <!-- <setLabel ref="setLabel"></setLabel> -->
    <!-- <RobotAssist></RobotAssist> -->
    <!-- <searchLabel ref="searchLabel" isHistory></searchLabel> -->
    <projectSetting ref="projectSetting" @getHistory="handleConfirmEdit"></projectSetting>
    <div class="history_loading" v-show="isShowMark">
      <a-spin size="large" />
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, createVNode, computed, nextTick, provide } from 'vue'
// import HeaderComponent from "@/component/HomePage/Header.vue";
import HistoryDetail from '@/component/Detail/historyDetail/index.vue'
import { Https } from '@/tool/https'
import { formatTime } from '@/tool/util'
import { Modal, message } from 'ant-design-vue'
// import RobotAssist from "@/component/HomePage/RobotAssist.vue";
import { ExclamationCircleOutlined, SearchOutlined } from '@ant-design/icons-vue'
import { ElCascader } from 'element-plus'
import { useI18n } from 'vue-i18n'
import enUS from 'ant-design-vue/es/locale/en_US'
import zhCN from 'ant-design-vue/es/locale/zh_CN'
import { ConfigProvider } from 'ant-design-vue'
import TableSearchBar from '@/component/common/TableSearchBar.vue'
// import setLabel from '@/component/LibraryPage/setLabel.vue'
// import searchLabel from '@/component/LibraryPage/searchLabel.vue'
import projectSetting from '@/component/home/newProject/setting.vue'
import { useStore } from 'vuex'
import router from '@/router'
import MyEvent from '@/tool/myEvents'

export default defineComponent({
  components: {
    // HeaderComponent,
    HistoryDetail,
    // RobotAssist,
    // setLabel,
    ElCascader,
    // searchLabel,
    SearchOutlined,
    ConfigProvider,
    TableSearchBar,
    projectSetting
  },
  setup() {
    const store = useStore()
    let rangePickerValue: any = ref([])
    const projectSetting: any = ref(null)
    let renameData: any = ref({}) //修改名字选中的数据
    let isShowMark: any = ref(false)
    const tableSearchBar: any = ref(null)

    const currentProjectPath = computed(() => {
      return store.state.Workspace.projectPath
    })

    // 根据store中的语言设置返回对应的ant-design-vue语言包
    const tableLocale = computed(() => {
      const language = store.state.UserHabit?.userDetail?.language
      return language === 'ENGLISH' ? enUS : zhCN
    })
    const columns: any = computed(() => {
      return [
        {
          title: useI18n().t('HistoryPage.CollectionsName'),
          align: 'left',
          ellipsis: true,
          width: 150,
          dataIndex: 'name',
          key: 'collectionName'
        },
        {
          title: useI18n().t('HistoryPage.UptateTime'),
          align: 'center',
          ellipsis: true,
          width: 150,
          dataIndex: 'updateDate',
          key: 'updateTime',
          customRender: (record: any) => {
            let time = formatTime(record.text / 1000, 'YYYY-MM-DD hh:mm:ss')
            return time
          }
        },
        {
          title: useI18n().t('HistoryPage.source'),
          align: 'center',
          ellipsis: true,
          width: 150,
          dataIndex: 'original',
          key: 'original',
          customRender: (record: any) => {
            let str = ''
            if (record.text == 1) {
              str = useI18n().t('newScaleImage.Original')
            } else {
              str = `@${record.record.userLikeGroupVO.originalAccountName}/${record.record.userLikeGroupVO.originalPortfolioName}`
            }
            // let time = formatTime(record.text / 1000, 'YYYY-MM-DD hh:mm:ss')
            return str
          }
        },
        {
          title: useI18n().t('HistoryPage.SketchCounts'),
          align: 'center',
          ellipsis: true,
          width: 120,
          dataIndex: 'sketchCount',
          key: 'sketchCounts'
        },
        {
          title: useI18n().t('HistoryPage.Operations'),
          key: 'operation',
          align: 'center',
          fixed: 'right',
          width: 180,
          // slots:{customRender:'action'}
          Operations: true
        }
      ]
    })
    let collectionList: any = ref([])
    let { t } = useI18n()
    const options: any = ref([])
    let value = ref({
      labelValue: [],
      editLabelValue: []
    })
    let props = {
      multiple: true,
      checkStrictly: true,
      emitPath: true,
      children: 'childList',
      value: 'id',
      label: 'classificationName'
    }
    let intersection = ref(1)
    let selectCode = ref('History')
    let type: any = {
      selectCode: selectCode,
      designType: ''
    }
    provide('type', type)
    return {
      store,
      rangePickerValue,
      columns,
      collectionList,
      renameData,
      t,
      options,
      value,
      props,
      intersection,
      selectCode,
      isShowMark,
      enUS,
      zhCN,
      tableLocale,
      projectSetting,
      tableSearchBar,
      currentProjectPath
    }
  },
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      presetList: [
        { label: this.t('Header.All'), value: '' },
        { label: this.t('newProjectg.series'), value: 'SERIES_DESIGN' },
        { label: this.t('newProjectg.single'), value: 'SINGLE_DESIGN' },
        { label: this.t('Header.Product'), value: 'TO_PRODUCT_IMAGE' },
        { label: this.t('Header.POSE_TRANSFER'), value: 'POSE_TRANSFER' }
      ],
      searchParam: {
        text: '',
        type: '',
        current: 1,
        pageSize: 10,
        total: 0
      },
      historyTableHeight: 0,
      newCollectionName: '',
      groupDetails: {}, //每个collection的详情
      collectionName: '', //选中的名字
      searchCollectionName: '',
      resizeObserver: null, // ResizeObserver 实例
      resizeTimeout: null, // 防抖定时器
      scrolled: true
    }
  },
  async mounted() {
    MyEvent.add('remChange', this.setPageSize)
    this.setPageSize()
    await this.getHistoryList()
    this.$nextTick(() => {
      this.calcScrollHeight()
      this.setupResizeObserver()
    })
    this.getClass()
  },
  beforeUnmount() {
    MyEvent.remove('remChange', this.setPageSize)
    if (this.resizeObserver) {
      this.resizeObserver.disconnect()
      this.resizeObserver = null
    }
  },
  methods: {
    setPageSize(rem) {
      const historyTable = this.$refs.historyTable
      const height = historyTable.offsetHeight
	  const itemHeight = historyTable.getElementsByClassName("ant-table-thead")[0]?.offsetHeight || 54;
      const size = Math.trunc((height - 60 - itemHeight) / itemHeight)
      this.pageSize = Math.max(1, size)
      if (rem) {
        this.currentPage = 1
        this.getHistoryList()
      }
    },
    getClass() {
      let data = {
        classificationIdList: [],
        classificationName: '',
        createTime: '',
        deleteConfirm: '',
        id: '',
        libraryId: '',
        parentId: '',
        type: this.selectCode,
        updateTime: '',
        userId: ''
      }

      Https.axiosPost(Https.httpUrls.queryClassification, data)
        .then((rv: any) => {
          this.options = rv
          rv.forEach((rvItem: any, rvIndex: number) => {
            this.options[rvIndex].value = rvItem.id
            this.options[rvIndex].label = rvItem.classificationName
            rvItem.childList.forEach((childItem: any, index: number) => {
              this.options[rvIndex].childList[index].value = childItem.id
              this.options[rvIndex].childList[index].label = childItem.classificationName
            })
          })
        })
        .catch(res => {})
    },
    turnToDetail(record: any) {
      this.groupDetails = record.groupDetails

      let historyDetail: any = this.$refs.historyDetail
      this.collectionName = record.name
      historyDetail.changeDetailShow(record)
    },

    //改变页码
    changePage(e: any) {
      this.currentPage = e.current
      this.pageSize = e.pageSize
      this.getHistoryList()
    },

    //查询列表
    searchHistoryList(value: any) {
      // console.log('value', value)
      this.currentPage = 1
      const process =
        value.currentPreset === ''
          ? []
          : value.currentPreset === 'TO_PRODUCT_IMAGE'
          ? ['TO_PRODUCT_IMAGE', 'RELIGHT']
          : [value.currentPreset]
      this.getHistoryList({
        process,
        projectName: value.searchText
      })
    },

    async getHistoryList(param: object = {}) {
      this.isShowMark = true
      let startDate: any = this.rangePickerValue
        ? new Date(this.rangePickerValue[0]).getTime()
        : ''
      let endDate: any = this.rangePickerValue
        ? new Date(this.rangePickerValue[1]).getTime()
        : ''

      let labelArr: any = []
      this.value.labelValue.forEach((item: any) => {
        labelArr.push(item[item.length - 1])
      })
      let data = {
        classificationIdList: labelArr,
        page: this.currentPage,
        size: this.pageSize,
        collectionName: this.searchCollectionName,
        startDate: startDate,
        endDate: endDate,
        intersection: this.intersection,
        ...param
      }

      await Https.axiosPost(Https.httpUrls.historyProject, data)
        .then(
          // Https.axiosPost( Https.httpUrls.queryUserGroup, data).then(
          (rv: any) => {
            if (this.currentPage > 1 && rv.content.length == 0) {
              this.currentPage = 1
              this.getHistoryList()
            } else {
              this.collectionList = rv.content.map(el => {
                const object = {
                  ...el,
                  sketchCount: el.userLikeGroupVO?.sketchCount,
                  groupDetails: el.userLikeGroupVO?.groupDetails
                }
                return object
              })
              this.total = rv.total
            }
            this.isShowMark = false

            // 数据加载完成后重新计算滚动高度
            this.$nextTick(() => {
              this.calcScrollHeight()
            })
          }
        )
        .catch(res => {
          this.isShowMark = false
        })
    },

    //删除分组
    deleteGroup(record: any, index: number) {
      console.log('record', record)

      let deleteGroupFun = (id: any, index: number) => {
        // let data = {
        //   userGroupId: id
        // }
        Https.axiosPost(
          Https.httpUrls.projectDetail,
          {},
          { params: { projectId: id } }
        ).then((rv: any) => {
          message.success(this.t('HistoryPage.jsContent1'))
          this.collectionList.splice(index, 1)
          this.getHistoryList()
          
          // 对比 currentProjectPath 中携带的参数 id
          const currentPath = this.currentProjectPath
          if (currentPath) {
            // 从路径中提取 id，路径格式为 /home/history/6784
            const pathMatch = currentPath.match(/\/history\/(\d+)/)
            if (pathMatch && pathMatch[1]) {
              const currentPathId = pathMatch[1]
              // 对比删除的 id 和当前路径中的 id
              if (String(id) === String(currentPathId)) {
                // 如果匹配，执行清理操作
                this.store.commit('createProjectPath', '')
                this.store.state.Workspace.cachedRoutes = []
              }
            }
          }
        })
      }
      Modal.confirm({
        title: this.t('HistoryPage.jsContent2'),
        icon: createVNode(ExclamationCircleOutlined),
        okText: 'Yes',
        cancelText: 'No',
        centered: true,
        mask: false,
        onOk() {
          deleteGroupFun(record.id, index)
        }
      })
    },

    //修改名字
    renameCollection(record: any, index: number) {
      // let searchLabel: any = this.$refs.searchLabel
      // searchLabel.init(record, index)
      this.$refs.projectSetting.init(record, 'edit')
    },
    handleConfirmEdit({ data }) {
      //   router.push(`/home?history=${data.id}`)
	//   if(data.id)
	if(data.id === this.store.state.Workspace.probjects.id){
		this.store.commit('createProjectPath','')
	}
    //   this.getHistoryList()
    },
    retrieveHome(record: any) {
      // let num = true
      // if (record.original == 0) {
      //   num = false
      // }
      // this.$router.push({ name: 'homePage', params: { id: record.id, type: 'History' } })
      // this.store.commit('setChooseIsDesign', num)
      // router.push(`/home/tools?tools=toProduct&id=${childItem.id}`)
	  
      this.store.state.Workspace.cachedRoutes = [];
	  this.store.commit('setProjectPath','')
      if (record.process == 'SERIES_DESIGN' || record.process == 'SINGLE_DESIGN') {
        this.$router.push(`/home/history/${record?.id}`)
        // this.$router.push(`/home?history=${record?.id}`)
      } else {
        let processList = {
          toProduct: 'TO_PRODUCT_IMAGE',
          relight: 'RELIGHT',
          poseTransfer: 'POSE_TRANSFER',
          deReconstruction: 'DE_RECONSTRUCTION',
          patternMaking3D: 'THREE_D_PLATE_MAKING',
          canvasUpload: 'CANVAS'
        }
        let process = ''
        for (const key in processList) {
          if (processList[key] == record.process) {
            process = key
            break
          }
        }
        this.$router.push(`/home/tools?tools=${process}&id=${record.id}`)
      }
    },
    removeLabel() {
      let setLabel: any = this.$refs.setLabel
      let cascader: any = this.$refs.cascader
      cascader.togglePopperVisible()
      let event = new Event('click', { bubbles: true, cancelable: true })
      document.dispatchEvent(event)
      setLabel.init('add', this.options)
    },
    dropdownVisibleChange() {
      let element: any = this.$refs.cascader
      nextTick().then(() => {
        let cascader = document.getElementsByClassName('libraryPageCascader')[0]
        let cascaderChild = cascader
        let element: any = this.$refs.cascader
        if (cascader.children.length > 3) {
        } else {
          let button1: any = document.createElement('span')
          button1.classList.add('started_btn', 'cascader_btn1')
          let button2: any = document.createElement('span')
          button2.classList.add('started_btn', 'cascader_btn2')
          let divMax: any = document.createElement('div')
          divMax.classList.add('cascader_btn_max')
          button1.textContent = 'Edit'
          // button2.textContent = '删除'
          button1.addEventListener('click', this.removeLabel, false)
          divMax.appendChild(button1)
          // divMax.appendChild(button2)
          cascaderChild?.insertAdjacentElement('afterbegin', divMax)

          // cascader.addEventListener('click',this.cascaderClick)
        }
      })
      let el = element.contentRef?.getElementsByClassName(
        'el-cascader-menu__empty-text'
      )?.[0]
      if (el) {
        el.innerHTML = this.t('LibraryPage.NoLabel')
      }
    },
    setupResizeObserver() {
      // 清理之前的观察器
      if (this.resizeObserver) {
        this.resizeObserver.disconnect()
      }

      // 创建ResizeObserver来监听容器尺寸变化
      this.resizeObserver = new ResizeObserver(entries => {
        // 使用防抖来避免频繁调用
        clearTimeout(this.resizeTimeout)
        this.resizeTimeout = setTimeout(() => {
          this.calcScrollHeight()
        }, 100)
      })

      // 观察history_page容器
      const historyPage = document.querySelector('.history_page')
      if (historyPage) {
        this.resizeObserver.observe(historyPage)
      }

      // 观察表格容器
      const table = document.querySelector('.ant-table-wrapper')
      if (table) {
        this.resizeObserver.observe(table)
      }
    },
    calcScrollHeight() {
      // 表格可滚动距离=页面总高度-表格上方高度-表头高度-分页器高度
      const historyPage = document.querySelector('.history_page')
      const historyPageTop = historyPage?.offsetTop
      const historyPageHeight = historyPage?.clientHeight

      const table = document.querySelector('.ant-table-wrapper')
      const tableTop = table?.offsetTop
      const tableHeight = historyPageHeight - tableTop - 64

      const tableHead = document.querySelector('.ant-table-thead')
      const tableHeadHeight = tableHead?.clientHeight

      // 计算表格内容区域的最大高度
      const maxTableBodyHeight = tableHeight - tableHeadHeight

      // 获取表格内容区域
      const tableBody = document.querySelector('.ant-table-tbody')
      if (tableBody) {
        // 计算所有行的高度
        const rows = tableBody.querySelectorAll('.ant-table-row')
        let totalContentHeight = 0

        rows.forEach(row => {
          totalContentHeight += row.offsetHeight
        })

        if (totalContentHeight <= maxTableBodyHeight) {
          this.scrolled = 'inherit'
        } else {
          this.scrolled = 'scroll'
        }
        this.historyTableHeight = maxTableBodyHeight + 'px'
      } else {
        // 如果表格内容还没渲染，先设置一个默认值
        this.historyTableHeight = maxTableBodyHeight + 'px'
      }
    },
    customTableRow(record: any) {
      return {
        onDblclick: () => {
          this.retrieveHome(record)
        }
      }
    }
  }
})
</script>
<style lang="less" scoped>
.flex {
  display: flex;
}
.flex-1 {
  flex: 1;
}
.flex-justify-between {
  justify-content: space-between;
}
.flex-align-center {
  align-items: center;
}
.history_page {
  width: 100%;
  height: 100%;
  padding: 0 6rem;
  overflow: hidden;
  background-color: #F9FAFA;
  // min-width: 1440px;
  position: relative;
  .history_loading {
    position: absolute;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.4);
    left: 0;
    top: 0;
    z-index: 99999;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    flex-direction: column;
  }
  .page_content {
    position: relative;
    .el-cascader .el-input .icon-arrow-down {
      font-size: 2.4rem;
    }
    .page_content_body {
      position: absolute;
      width: 100%;
      height: 100%;
      box-sizing: border-box;

      .history_page_body {
        width: 100%;
        height: 100%;
        padding: 3rem 0 0;
        box-sizing: border-box;
        flex-direction: column;
        display: flex;
        flex-direction: column;

        .history_table_content {
          margin-top: 2.6rem;
          width: 100%;
          background: #F9FAFA;
          flex: 1;
          overflow: hidden;
          //   height: calc(100% - 4rem);
          // padding-bottom: 3rem;

          :deep(.ant-table-wrapper) {
            height: 100%;
            .ant-spin-nested-loading {
              &,
              .ant-spin-container {
                height: 100%;
                .ant-table {
                  flex: 1;
                  // .ant-table-container,
                  // .ant-table-content,
                  // table {
                  //   height: 100%;
                  // }
                }
              }
            }
          }

          :deep(.ant-spin-container) {
            display: flex;
            flex-direction: column;
            .ant-table {
              background: transparent;
              // flex: 1;
            }
          }

          .ant-table-body {
            overflow-y: auto !important;
            -ms-overflow-style: none;
            overflow: -moz-scrollbars-none;

            &::-webkit-scrollbar {
              width: 0 !important;
            }
          }
          // :deep(.ant-table-content) {
          //   max-height: v-bind(historyTableHeight);
          //   overflow-y: v-bind(scrolled);
          // }

          :deep(.ant-table-thead > tr > th) {
            // background: #ffffff;
            background: transparent;
          }
          :deep(.ant-table-tbody > tr:hover) {
            background: #ededed;
          }
          :deep(.ant-table-tbody > tr > td) {
            border: none;
            background: transparent;
          }
          .ant-table-pagination-right {
            justify-content: center;
          }
          :deep(.ant-pagination-prev),
          :deep(.ant-pagination-next),
          :deep(.ant-pagination-jump-prev),
          :deep(.ant-pagination-jump-next),
          :deep(.ant-pagination-item) {
            width: 4rem;
            height: 4rem;
            min-width: 4rem;
            line-height: 4rem;
            margin-right: 0.8rem;
          }
          :deep(.ant-pagination-options-quick-jumper) {
            height: 4rem;
            line-height: 4rem;
            margin-left: 0.8rem;
            font-size: 1.6rem;
            > input {
              width: 7rem;
              height: 4rem;
              font-size: 1.6rem;
            }
          }
          .ant-table-pagination-right {
            padding-right: 3.5rem;
          }

          :deep(.ant-table-placeholder) {
            &,
            .ant-table-cell {
              background-color: #F9FAFA;
            }
          }

          :deep(.ant-pagination-item) {
            background: none;
            border: none;
            a {
              color: rgba(0, 0, 0, 0.3);
            }
            &-active a {
              color: #000;
            }
            a:hover {
              color: #000;
            }
          }

          .operate_list {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 1rem;

            .operate_item {
              // font-size: 1.4rem;
              font-family: Roboto;
              font-weight: 400;
              color: #007ee5;
              cursor: pointer;

              &.operate_item_hidden {
                visibility: hidden;
                pointer-events: none;
              }
            }
          }
        }
      }
    }
  }
}

.rename_modal_component {
  .collection_rename_content {
    padding: 2rem 9.2rem 3rem;

    .rename_form_content {
      .rename_form_input {
        width: 100%;
        height: 4.6rem;
        margin-top: 1rem;
        border: 0.1rem solid #b4bed7;
        padding-left: 2.1rem;
        line-height: 4.6rem;
        font-size: 1.8rem;
        box-sizing: border-box;

        &::placeholder {
          color: #a5b0c2;
        }
      }
    }

    .rename_submit_button {
      height: 4.8rem;
      line-height: 4.8rem;
      background: #343579;
      font-size: 2.4rem;
      font-weight: 500;
      color: #ffffff;
      width: 16rem;
      text-align: center;
      cursor: pointer;
      margin: 4.5rem auto 0;
    }
  }
}
</style>
