<script lang="ts" setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { searchMarketPreview } from '@/api/templateMarket'
import { useI18n } from '@/hooks/web/useI18n'
import { useCache } from '@/hooks/web/useCache'
import { ElMessage } from 'element-plus-secondary'
import { Base64 } from 'js-base64'
import { useEmbedded } from '@/store/modules/embedded'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useEmitt } from '@/hooks/web/useEmitt'
import type { FormInstance } from 'element-plus'
import AddTemplate from '@/viewsnew/TemplateResource/addtemplate.vue'
import AddTemplateClass from '@/viewsnew/TemplateResource/addclass.vue'
import { update } from 'lodash'
const basePath = import.meta.env.VITE_API_BASEPATH
const router = useRouter()
const { t } = useI18n()
const { wsCache } = useCache()
const keywords: any = ref("") // 输入关键字
const dataList: any = ref([])
const classList: any = ref([])
const mask = ref(-1) // 遮罩层
const activeIndex: any = ref(null)
const detailsList: any = ref([])
const loading: any = ref(false)
const embeddedStore = useEmbedded()
const appStore = useAppStoreWithOut()
const isEmbedded = computed(() => appStore.getIsDataEaseBi || appStore.getIsIframe)
const state = reactive({
  initReady: true,
  curPosition: 'branch',
  pid: null,
  treeProps: {
    value: 'label',
    label: 'label'
  },
  templateType: 'all', // 模板类型 仪表板 数据大屏
  templateSourceType: 'all', // 模板来源 模板市场 模板管理
  templateClassifyType: 'all', // 模板分类 样式模板 应用模板
  treeShow: true,
  templateClassifyOptions: [
    {
      value: 'all',
      label: t('visualization.all_type')
    },
    {
      value: 'app',
      label: t('visualization.apply_template')
    },
    {
      value: 'template',
      label: t('visualization.style_template')
    }
  ],
  templateSourceOptions: [
    {
      value: 'all',
      label: t('work_branch.all_source')
    },
    {
      value: 'market',
      label: t('visualization.template_market')
    },
    {
      value: 'manage',
      label: t('template_manage.name')
    }
  ],
  templateTypeOptions: [
    {
      value: 'all',
      label: t('work_branch.all_types')
    },
    {
      value: 'PANEL',
      label: t('work_branch.dashboard')
    },
    {
      value: 'SCREEN',
      label: t('work_branch.big_data_screen')
    }
  ],
  loading: false,
  hasResult: true,
  templateMiniWidth: 250,
  templateCurWidth: 310,
  templateSpan: '25%',
  previewVisible: false,
  templatePreviewId: '',
  marketTabs: [],
  marketActiveTab: null,
  searchText: null,
  dvCreateForm: {
    resourceName: null,
    name: null,
    pid: null,
    nodeType: 'panel',
    templateUrl: null,
    newFrom: 'new_market_template',
    templateId: null,
    panelType: 'self',
    panelStyle: {},
    panelData: '[]'
  },
  panelGroupList: [],
  curApplyTemplate: null,
  folderSelectShow: false,
  baseUrl: 'https://dataease.io/templates',
  currentMarketTemplateShowList: [],
  curTemplateShowFilter: [],
  curTemplateIndex: 0,
  curTemplate: null,
  networkStatus: true,
  rule: {
    name: [
      {
        required: true,
        message: t('visualization.template_name_tips'),
        trigger: 'blur'
      }
    ],
    pid: [
      {
        required: true,
        message: '',
        trigger: 'blur'
      }
    ]
  }
})
const templateApply = (template: any) => {

  state.curApplyTemplate = template
  state.dvCreateForm.name = template.title
  state.dvCreateForm.nodeType = template.templateType
  if (template.source === 'market') {
    state.dvCreateForm.newFrom = 'new_market_template'
    state.dvCreateForm.templateUrl = template.metas.theme_repo
    state.dvCreateForm.resourceName = template.id
  } else {
    state.dvCreateForm.newFrom = 'new_inner_template'
    state.dvCreateForm.templateId = template.id
  }
  apply()
}
const apply = () => {
  if (state.dvCreateForm.newFrom === 'new_market_template' && !state.dvCreateForm.templateUrl) {
    ElMessage.warning(t('template_manage.get_download_link_hint'))
    return false
  }
  const templateTemplate = {
    newFrom: state.dvCreateForm.newFrom,
    templateUrl: state.dvCreateForm.templateUrl,
    resourceName: state.dvCreateForm.resourceName,
    templateId: state.dvCreateForm.templateId
  }
  state.curApplyTemplate.recentUseTime = Date.now()
  state.curApplyTemplate.categoryNames.push(t('work_branch.recent'))
  const baseUrl =
    (['dataV', 'SCREEN'].includes(state.dvCreateForm.nodeType)
      ? '#/dvCanvas?opt=create&createType=template'
      : '#/dashboard?opt=create&createType=template') +
    '&templateParams=' +
    encodeURIComponent(Base64.encode(JSON.stringify(templateTemplate)))
  let newWindow = null
  if (isEmbedded.value) {
    embeddedStore.clearState()
    embeddedStore.setCreateType('template')
    embeddedStore.setTemplateParams(
      encodeURIComponent(Base64.encode(JSON.stringify(templateTemplate)))
    )
    embeddedStore.setOpt('create')

    if (state.pid) {
      embeddedStore.setPid(state.pid)
    }
    useEmitt().emitter.emit(
      'changeCurrentComponent',
      ['dataV', 'SCREEN'].includes(state.dvCreateForm.nodeType)
        ? 'VisualizationEditor'
        : 'DashboardEditor'
    )
    return
  }
  const openType = wsCache.get('open-backend') === '1' ? '_self' : '_blank'
  if (state.pid) {
    newWindow = window.open(baseUrl + `&pid=${state.pid}`, openType)
  } else {
    newWindow = window.open(baseUrl, openType)
  }
  initOpenHandler(newWindow)
}
const openHandler = ref(null)
const initOpenHandler = newWindow => {
  if (openHandler?.value) {
    const pm = {
      methodName: 'initOpenHandler',
      args: newWindow
    }
    openHandler.value.invokeMethod(pm)
  }
}
const dialogVisible = ref(false)
const classform = ref({ name: '' })
const dialogVisibles = ref(false)
const optType = ref('insert')
onMounted(() => {
  init()
})
function addClass() {
  classform.value = { name: '' }
  dialogVisible.value = true
}
function importTemplate() {
  dialogVisibles.value = true
}
function preview(item, index) {
  router.push({
    path: '/TemplatePreview',
    query: { title: classList.value[activeIndex.value].category.label, index: index }
  })
}
function design(item, index) {
  templateApply(dataList.value[index])
}
function init() {
  searchMarketPreview().then(res => {
    classList.value = res.data.contents
    if (classList.value[0]) {
      activeIndex.value = 0
      dataList.value = classList.value[activeIndex.value].contents
    }
  })
}

function classclick(index) { // 分类点击
  activeIndex.value = index
  dataList.value = classList.value[activeIndex.value].contents
}

function handleDatasetName() { // 关键字搜索
  console.log(dataList.value)
  if (keywords.value == '') {
    dataList.value = classList.value[activeIndex.value].contents
  } else {
    var arr = dataList.value
    var resarr = []
    arr.forEach((e) => {
      if (e.title.indexOf(keywords.value) != -1) {
        resarr.push(e)
      }
    })
    dataList.value = resarr
  }
}
function mouseover(index) { // 鼠标移入遮罩层
  mask.value = index
}
function mouseleave() { // 鼠标移出遮罩层
  mask.value = -1
}
function closeClassDialog() {
  dialogVisible.value = false
}
function closeTemplateDialog() {
  dialogVisibles.value = false
}
function classrefresh() {
  init()
}
function editTemplate(item) { 
  optType.value = 'template'
  console.log(item)

}
</script>
<template>
  <div class="common-layout">
    <div style="display: flex;align-items: center;">
      <el-input placeholder="请输入模板名称" class="keywordsClass" maxlength="64" v-model="keywords" @blur="handleDatasetName">
        <template #prepend>
          <img src="@/assets/newimg/u62.png" alt="">
        </template>
      </el-input>
      <div class="import-btn" @click="importTemplate">导入模板</div>
      <div class="import-btn" @click="addClass">添加分类</div>
    </div>
    <div>
      <div class="class_list_box">
        <div v-for="(item, index) in classList" :key="index"
          :class="activeIndex === index ? 'class_list_active' : 'class_list'" @click="classclick(index)">
          <div class="class_list_text">{{ item.category.label }} ({{ item.contents.length }}) </div>
        </div>
      </div>
      <div class="application_list_box">
        <div v-for="(item, index) in dataList" :key="index" class="application_list" @mouseover="mouseover(index)"
          @mouseleave="mouseleave">
          <img v-if="item.thumbnail != null && item.thumbnail != ''" :src="basePath + item.thumbnail" alt=""
            style="width: 267px;height: 155px;">
          <img v-else src="@/assets/newimg/u110.png" alt="" style="width: 267px;height: 155px;">
          <div style="display: flex;justify-content: space-between;">
            <div class="application_list_text">{{ item.title }}</div>
          </div>
          <div class="mask_box" v-if="mask == index">
            <div>
              <img src="@/assets/newimg/icon/editpro.png" @click="editTemplate(item)" style="cursor: pointer;" title="编辑模板">
              <img src="@/assets/newimg/icon/del.png" alt="" style="margin-left: 10px;cursor: pointer;" title="删除">
            </div>
            <div style="display: flex;justify-content: center;margin-top: 20px;">
              <div class="yulan" @click="preview(item, index)">预览</div>
              <div class="mokuaipeizhi" @click="design(item, index)">设计</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="添加分类" width="30%" :before-close="closeClassDialog">
      <AddTemplateClass v-if="dialogVisible" @closeClassDialog="closeClassDialog" :classrefresh="classrefresh" />
    </el-dialog>
    <el-dialog v-model="dialogVisibles" title="导入模板" width="30%" :before-close="closeTemplateDialog">
      <AddTemplate v-if="dialogVisibles" :optType="optType" :classList="classList" @init="init"
        @closeTemplateDialog="closeTemplateDialog" />
    </el-dialog>
  </div>

</template>

<style lang="less" scoped>
.common-layout {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  color: #1f2329;
  min-width: 1000px;
  overflow-x: auto;
  box-sizing: border-box;
  padding: 20px;
  padding-left: 40px;
  padding-right: 0px;
  background-color: rgb(21, 21, 21);
}

.keywordsClass {
  width: 403px;
  height: 40px;
  background: inherit;
  background-color: rgba(37, 38, 38, 1);
  box-sizing: border-box;
  border-width: 1px;
  border-style: solid;
  border-color: rgba(51, 51, 51, 1);
  border-radius: 4px;

  :deep(.ed-input__wrapper) {
    background-color: rgba(37, 38, 38, 1);
    box-sizing: border-box;
    border-width: 1px;
    border-style: solid;
    border-color: rgba(51, 51, 51, 0);
    border-radius: 4px;
    box-shadow: 0 0 0 1px transparent;
  }

  :deep(.ed-input__inner) {
    background-color: rgba(37, 38, 38, 1);
    box-sizing: border-box;
    border-width: 1px;
    border-style: solid;
    border-color: rgba(51, 51, 51, 0);
    border-radius: 4px;
    color: #fff;
  }

  :deep(.ed-input-group__prepend) {
    background-color: rgba(37, 38, 38, 1);
    border: 0;
    box-shadow: 0 0 0 1px transparent;
    padding: 0 10px;
    padding-right: 0;
  }
}

.application_list_box {
  display: flex;
  flex-wrap: wrap;
  height: calc(100vh - 200px);
  overflow: auto;
  align-content: flex-start;
}

.application_list {
  position: relative;
  margin-top: 20px;
  width: 296px;
  height: 210px;
  background: inherit;
  background-color: rgba(37, 38, 38, 1);
  box-sizing: border-box;
  padding: 10px;
  border-width: 1px;
  border-style: solid;
  border-color: rgba(51, 51, 51, 1);
  border-radius: 10px;
  margin-right: 20px;
  text-align: center;
}

.application_list_text {
  font-family: 'Arial Normal', 'Arial';
  font-weight: 400;
  font-style: normal;
  font-size: 12px;
  color: #F2F4F5;
  padding-top: 13px;
  position: relative;
  z-index: 11;
}

.mask_box {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 10px;
  box-sizing: border-box;
  padding-top: 60px;
  border: 1px solid #0089ff;
}

.mask_box_img {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;

  img {
    margin: 0 8px;
    cursor: pointer;
  }
}

.yulan {

  width: 50px;
  height: 28px;
  line-height: 28px;
  text-align: center;
  background-color: rgba(255, 255, 255, 0.3);
  border: none;
  border-radius: 4px;
  box-shadow: none;
  font-size: 14px;
  font-family: 'Arial Normal', 'Arial';
  font-weight: 400;
  font-style: normal;
  color: rgb(255, 255, 255);
  margin-right: 10px;
  cursor: pointer;
}

.mokuaipeizhi {
  width: 50px;
  height: 28px;
  line-height: 28px;
  text-align: center;
  background-color: rgba(0, 137, 255, 1);
  border: none;
  border-radius: 4px;
  box-shadow: none;
  font-size: 14px;
  font-family: 'Arial Normal', 'Arial';
  font-weight: 400;
  font-style: normal;
  color: rgb(255, 255, 255);
  cursor: pointer;
}

.import-btn {
  width: 80px;
  height: 35px;
  line-height: 35px;
  text-align: center;
  background-color: rgba(0, 137, 255, 1);
  border: none;
  border-radius: 4px;
  box-shadow: none;
  font-size: 14px;
  font-family: 'Arial Normal', 'Arial';
  font-weight: 400;
  font-style: normal;
  color: rgb(255, 255, 255);
  cursor: pointer;
  margin-left: 10px;
}

.class_list_box {
  display: flex;
  align-items: center;
  margin-top: 20px;
  margin-bottom: 10px;
  width: calc(100% - 270px);
  flex-wrap: wrap;
  gap: 15px;
}

.class_list {
  padding: 0px 20px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background-color: rgba(36, 37, 38, 1);
  border-radius: 4px;
  font-size: 14px;
  color: #C9C9C9;
  cursor: pointer;
}

.class_list_active {
  padding: 0px 20px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background-color: rgba(54, 55, 56, 1);
  border-radius: 4px;
  font-size: 14px;
  color: #F2F4F5;
  cursor: pointer;
}

.class-add {
  width: 100%;
  background-color: transparent;
  padding: 10px;
  font-size: 14px;
  cursor: pointer;
}

.class-add:hover {
  background-color: #434343;
  ;
}
</style>
<style>
.ed-message-box__headerbtn {
  top: -15px;
  right: -10px;
}

.ed-dialog {
  background-color: #212121;
}

.ed-form-item__label {
  color: #D2D2D2;
}

.ed-input__wrapper {
  background-color: #252626;
  box-sizing: border-box;
  border-width: 1px;
  border-style: solid;
  border-color: rgba(67, 67, 67, 0);
  border-radius: 4px;
  box-shadow: none;
  border: 1px solid #434343;
}

.ed-form-item.is-error .ed-input__wrapper {
  box-shadow: none;
  border: 1px solid #f54a45;
}

.ed-input__wrapper.is-focus {
  box-shadow: none;
  border: 1px solid #0089ff;
}

.ed-input__wrapper:hover {
  box-shadow: none;
  border: 1px solid #0089ff;
}

.ed-input__inner {
  color: #fff;
}

.ed-button {
  color: #ffffff;
  background-color: rgb(54, 55, 56);
  border: 1px solid #363636;
}

.ed-button:focus,
.ed-button:hover {
  color: #ffffff;
  background-color: rgb(54, 55, 56);
  border: 1px solid #363636;
}

.ed-button--primary {
  background-color: #0089ff;
  border-color: #0089ff;
}

.ed-button--primary:focus,
.ed-button--primary:hover {
  background-color: #0089ff;
  border-color: #0089ff;
}

.ed-dialog__title {
  color: #fff;
}

.ed-select__wrapper {
  border: 1px solid #434343;
  box-shadow: none !important;
  height: 32px;
  word-wrap: break-word;
  text-align: left;
  color: rgba(0, 0, 0, 0.65);
  list-style: none;
  user-select: none;
  cursor: pointer;
  line-height: 32px;
  box-sizing: border-box;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  opacity: 1;
  background-color: #252626;
}

.ed-select__popper.ed-popper {
  background: rgb(41, 41, 41) !important;
  color: #fff;
  border: 1px solid #434343;
}

.ed-select-dropdown__item.is-hovering {
  background: #434343 !important;
}

.ed-select-dropdown__item {
  color: #fff;
}

.ed-select-dropdown__footer {
  padding: 5px 0px;
  border-top: 1px solid #434343;
}

.ed-tag {
  background: #434343;
  color: #fff;
}
</style>