<template>
  <div class="secret-container">
    <div class="search-form">
      <AdvanceSearch v-model="newFormData" class="px-20">
        <template #operation><div></div></template>
      </AdvanceSearch>
      <div class="jyh-form-operation">
        <d-button @click="getReleaseList" class="mr-2" variant="solid">搜索</d-button>
        <d-button variant="solid" color="secondary">清空</d-button>
      </div>
      <div class="left-btn">
        <d-button v-if="isLogin" class="output-btn" icon="icon-share" variant="text">导出</d-button>
        <span v-if="isLogin" style="height: 14px" class="split"></span>
        <TableSetting :columns="columns" :show-column-list="showColumnList" @update:show-column-list="updateShowColumnList"/>
      </div>
    </div>
    <div class="mt-3 px-20">
      <d-table :key="tableKey" class="jyh-table" v-if="tableData.length" :striped="false" :data="tableData" table-layout="auto">
        <!-- 索引列 -->
        <d-column type="index" width="40"></d-column>

        <!-- 动态渲染列 -->
        <template v-for="column in columns" :key="column.key">
          <d-column
            v-if="column.visible"
            :field="column.key"
            :header="column.label"
            :filterable="column.filterable"
            :filter-list="column.filterList"
            :sortable="column.sortable"
            @filter-change="handleFilterChange"
          >
            <!-- 自定义列内容 -->
            <template #default="scope">
              <template v-if="column.key === 'versionName'">
                <a>{{ scope.row.versionName }}</a>
              </template>
              <template v-else-if="column.key === 'version'">
                <a @click="gotoDetail(scope.row)">{{ scope.row.version }}</a>
              </template>
              <template v-else-if="column.key === 'releaseDate'">
                <span>{{ formatTime(scope.row.releaseDate, 'YYYY-MM-DD') }}</span>
              </template>
              <template v-else-if="column.key === 'softwareVersion'">
                <a @click="gotoDetail(scope.row)">{{ scope.row.softwareVersion }}</a>
              </template>
              <template v-else-if="column.key === 'smStatus'">
                <a>{{ scope.row.smStatus }}</a>
              </template>
              <template v-else-if="column.key === 'industryCategory'">
                <d-tag type="success">{{ scope.row.industryCategory }}</d-tag>
              </template>
              <template v-else-if="column.key === 'programmingLanguage'">
                <d-tag type="success">{{ scope.row.programmingLanguage }}</d-tag>
              </template>
              <template v-else-if="column.key === 'contributorCountries'">
                <div style="cursor: pointer" @click="openCountryModal(column)">
                  <span class="mr-2">美国 3.57%</span>
                  <d-tag color="gray">+3</d-tag>
                </div>
              </template>
              <template v-else-if="column.key === 'contributorOrganizations'">
                <div style="cursor: pointer" @click="openOrgModal(column)">
                  <span class="mr-2">microsoft 3.57%</span>
                  <d-tag color="gray">+3</d-tag>
                </div>
              </template>
              <template v-else-if="column.key === 'sourceDownloadUrl'">
                <a>{{ scope.row.sourceDownloadUrl }}</a>
              </template>
              <template v-else>
                {{ scope.row[column.key] }}
              </template>
            </template>
          </d-column>
        </template>
      </d-table>

<!--      <DataPanel v-else skeleton :card="false" :empty="true">-->
<!--      </DataPanel>-->
      <NoData v-else :small="false"></NoData>
    </div>

    <div class="mt-20 mb-20 flex justify-end">
      <d-pagination size="md" :page-size-options="[10, 20, 50]" :total="pager.total"
                    v-model:pageSize="pager.pageSize" v-model:pageIndex="pager.pageIndex" :max-items="5"
                    :can-change-page-size="true" :can-view-total="true" total-item-text="总计" @page-index-change="changeIndex()"
                    @page-size-change="changeSize()" />
    </div>

    <!-- 删除组件 -->
    <GModal v-model="deletevModels" ref="deleteModal" title="删除?" @confirm="confirmDelete" showWarnIcon
            confirmColor="danger">
      <span class="inline-block text-G900 text-sm font-normal leading-[20px] break-all">你确认删除此项：{{ item.cla_name }}
        ？</span>
    </GModal>

    <!-- 引入子组件 -->
    <CountryModal ref="countryModalRef" />

    <!-- 引入子组件 -->
    <OrgModal ref="orgModalRef" />
  </div>
</template>

<script setup lang="ts">
import AdvanceSearch from '@/components/AdvanceSearch/index.vue'
import SettingTitle from '@/components/Setting/SettingTitle/index.vue';
import SettingText from '@/components/Setting/SettingText/index.vue';
import { ref,reactive, onMounted } from 'vue';
import { getGroupClaList, setGroupClaStatus, deleteGroupCla } from '@/api/cla';
import { useRouter, useRoute } from 'vue-router';
import { GModal } from '@/components/Setting/index';
import TableSetting from '@/components/TableSetting/index.vue';
import { reqCatch } from '@/utils/catch';
import { getOrgInfo } from '@/views/Org/hooks/orgInfo';
import { Message } from 'vue-devui';
import { storeToRefs } from 'pinia';
import CountryModal from './CountryModal.vue'
import OrgModal from './OrgModal.vue'
import { useAccountStore } from '@/stores/user';
const { formatTime } = useTimeFormat();
import { releasePage } from '@/api/jyh';
import { useTimeFormat } from '@/utils/hooks/useTimeFormat';
const { namespace } = getOrgInfo();
const userInfo = useAccountStore();
const { isLogin } = storeToRefs(userInfo);

// 定义 tableKey，用于强制刷新表格
const tableKey = ref(0);
const countryVisible = ref(false);
const orgVisible = ref(false);
const tableData = ref([]);
const formData = ref({ title: '',type: '', useType: '',formData:'',select: '',time1:null,name:'',versionCode:'',pulishTime:'' });
const typeOptions = reactive(['主软件', '依赖软件']);
const riskOptions = reactive(['低', '中', '高']);
const useTypeOptions = reactive(['软件', '文档', '文档+软件']);
const isUseOptions = reactive(['是', '否']);
const newFormData = ref({
  licenseName: '',
  searchType: 'software',
  searchWord: '',
  softwareVersion: '',
  dependentSoftware: '',
  programmingLanguage: '',
  dateRange: ['', '']
})

const pager = ref({
  total: 10,
  pageIndex: 1,
  pageSize: 10
});

// 删除弹窗
const item = ref('');
const deleteModal = ref();
const deletevModels = ref(false);
const openDelete = (row: any) => {
  item.value = row;
  deleteModal.value.showFlag = true;
  deletevModels.value = true;
};

// 定义 columns 数据
const columns = ref([
  { key: 'softwareName', label: '软件名称', visible: true, filterable: true, sortable: false },
  { key: 'softwareVersion', label: '软件版本', visible: true, filterable: true, sortable: false },
  { key: 'securityScore', label: '软件评分', visible: true, filterable: false, sortable: true },
  { key: 'licenseCount', label: 'License数量', visible: true, filterable: false, sortable: false },
  { key: 'industryCategory', label: '行业类型', visible: true, filterable: true, sortable: false },
  { key: 'primaryLanguage', label: '编程语言', visible: true, filterable: true, sortable: false },
  { key: 'codeLines', label: '代码量', visible: true, filterable: false, sortable: false },
  { key: 'sourceDownloadUrl', label: '源码包下载地址', visible: true, filterable: false, sortable: false },
  { key: 'releaseDate', label: '版本发布时间', visible: false, filterable: true, sortable: true },
  { key: 'dependencyCount', label: '依赖软件数', visible: false, filterable: false, sortable: false },
  { key: 'productComponentUsage', label: '产品成分使用量', visible: false, filterable: false, sortable: false },
  { key: 'vulnerabilityCount', label: '漏洞数量', visible: false, filterable: false, sortable: false },
  { key: 'communityName', label: '开发商', visible: false, filterable: true, sortable: false },
  { key: 'contributorCountries', label: '贡献者国家/地区分布', visible: false, filterable: false, sortable: false },
  { key: 'contributorOrganizations', label: '贡献者组织/公司分布', visible: false, filterable: false, sortable: false },
  { key: 'communityHash', label: '社区hash值', visible: false, filterable: false, sortable: false },
  { key: 'copyright', label: 'CopyRight', visible: false, filterable: false, sortable: false },
  { key: 'externalVulnerabilitySource', label: '外部漏洞源的软件名称', visible: false, filterable: true, sortable: false },
  { key: 'versionDescription', label: '版本描述', visible: false, filterable: false, sortable: false },
  { key: 'compatibilityRisk', label: '兼容性风险描述', visible: false, filterable: false, sortable: false },
  { key: 'eolDate', label: '社区EOL时间', visible: false, filterable: true, sortable: true },
]);

// 定义 showColumnList 状态
const showColumnList = ref(false);
// 获取子组件的引用
const countryModalRef = ref(null);
const orgModalRef = ref(null);

// 打开模态框的方法
const openCountryModal = () => {
  if (countryModalRef.value) {
    countryModalRef.value.openModal(); // 调用子组件的方法
  }
};
// 打开模态框的方法
const openOrgModal = () => {
  if (orgModalRef.value) {
    orgModalRef.value.openModal(); // 调用子组件的方法
  }
};
// 更新 showColumnList 的方法
const updateShowColumnList = (newValue) => {
  showColumnList.value = newValue;
  tableKey.value++; // 更新 tableKey，强制刷新表格
};
// 更新 showColumnList 的方法
const openCountryChart = (row) => {
  // selectRow.value = row;
  countryVisible.value = true;
};
// 更新 showColumnList 的方法
const openOrgChart = (row) => {
  // selectRow.value = row;
  orgVisible.value = true;
};

const router = useRouter();
const route = useRoute();
// 跳转
const gotoDetail = (row) => {
  // 后续请换成params，暂时params传参没传过去
  router.push({
    path: 'repoDetail/' + row.id
  });
};
// 分页
const changeIndex = () => {
  // getGroupClaListData();
};

const changeSize = () => {
  pager.value.pageIndex = 1;
  // getGroupClaListData();
};

const repoFun = (arr: any) => {
  return arr ? (arr.length > 3 ? arr.slice(0, 3) : arr) : [];
};

// 编辑
const editRow = (row: any) => {
  // 后续请换成params，暂时params传参没传过去
  router.push({
    path: 'cla/edit/' + row.object_id,
    query: { cla: row.cla, pageType: 'edit' }
  });
};

// 确认删除
const confirmDelete = async (e: any) => {
  // const res = await reqCatch(deleteGroupCla, { group_id: namespace.value, cla_id: item.value.object_id });
  // if (!res.error) {
  //   getGroupClaListData();
  // }
};

// 去成员页
const goMember = (row: any) => {
  // 后续请换成params，暂时params传参没传过去,注意路由有个:claID
  router.push({
    path: 'cla/claId/member',
    query: { claId: row.object_id, claName: row.cla_name, group_path: namespace.value, pageType: 'edit' }
  });
};
const getGroupClaListData = async () => {
  // const params = {
  //   group_id: namespace.value,
  //   page: pager.value.pageIndex,
  //   per_page: pager.value.pageSize
  // };
  // const res = await reqCatch(getGroupClaList, params);
  // if (!res.error) {
  //   tableData.value = res?.data?.data?.content;
  //   pager.value.total = res.data.data.total;
  // }
};
getGroupClaListData();

const setClaStatus = async (row: any) => {
  // const params = {
  //   group_id: namespace.value,
  //   cla_id: row.object_id,
  //   status: row.status
  // };
  // const res = await reqCatch(setGroupClaStatus, params);
  // if (!res.error) {
  //   Message.success('操作成功!');
  //   getGroupClaListData();
  // }
};

const signCla = (row: any) => {
  router.push('/cla/' + row.object_id);
};

const getReleaseList = async() => {
  const { data, error } = await releasePage({
    ...newFormData.value,
    releaseDateStart: newFormData.value.dateRange&&newFormData.value.dateRange.length>0?newFormData.value.dateRange[0]:'',
    releaseDateEnd: newFormData.value.dateRange&&newFormData.value.dateRange.length>0?newFormData.value.dateRange[1]:'',
    current: pager.value.pageIndex,size: pager.value.pageSize  });
  if (!error && data) {
    tableData.value = data.data.records;
    pager.value.total = data.data.total;
  }
};

onMounted(async() => {
  getReleaseList();
});

onMounted(() => {
  const query: any = route.query;
  newFormData.value = {
    ...query
  };
});
</script>

<style scoped lang="scss">
@import 'devui-theme/styles-var/devui-var.scss';

.secret-container {
  position: relative;
  min-height: 600px;

  .secret-op {
    position: absolute;
    right: 0;
    top: 0;
  }

}

.error {
  color: $devui-contrast;
}

:deep(.devui-table__row td) {
  padding-top: 16px;
  padding-bottom: 16px;
}

:deep(.devui-tag .devui-tag--default) {
  background-color: #fff;
  border-radius: 12px;
  padding: 4px 8px;
  font-size: 12px;
  line-height: 16px;
  margin-right: 8px;
  border: 1px solid #E3E3EE;
}

.one-line {
  word-break: break-all;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.title {
  font-size: 14px;
  font-weight: 400;
  color: #9a9b9c;
  line-height: 20px;
}

.cur-title {
  font-size: 14px;
  font-weight: 500;
  color: #2d2d2e;
  line-height: 20px;
}

.search-form {
  position: relative;
  border-radius: 8px 0px 8px 8px;
  //background: #F2F5FC;

  .left-btn {
    position: absolute;
    right: 28px;
    bottom: 4px;
  }

  .output-btn {
    color: #191919;
    font-family: HarmonyOS Sans SC;
    font-weight: regular;
    font-size: 14px;
    line-height: 22px;
    letter-spacing: 0px;
    text-align: left;
  }

  .jyh-form-operation {
    margin-left: 20px !important;
  }
}

.secret-breadcrumb {
  padding: 7px 20px 12px;
  background: #ffffff;
}
</style>
