<template>
    <div class="row items-center flex-between q-mb-lg">
      <div></div>
      <el-input style="max-width:600px" v-model="queryObj.keyWords" placeholder="请输入关键字" class="q-pr-33" clearable
      @keyup.enter="search">
        <template #append>
          <div class="Market-select-line absolute"></div>
          <div class="row items-center pointer">
              <img src="../../assets/img/home-search.png" width="21" height="21"
              @click="search"/>
          </div>
        </template>
      </el-input>
      <el-button type="primary" size="default" style="color: #ffff;" @click="addFont">
        新增字体
      </el-button>
    </div>
    <el-table v-loading="loading" ref="dataTableRef" highlight-current-row 
    v-load-more="tableScrollHandler" :data="dataList" class="tableHBEbeef5 col" height="82vh">
      <el-table-column label="字体名称" width="240">
        <template #default="scope">
          <span :style="{'font-family':scope.row.reduceName}">{{scope.row.label}}</span>
        </template>
      </el-table-column>
      <el-table-column label="font-family" width="190">
        <template #default="scope">
          {{scope.row.fontFamily}}
        </template>
      </el-table-column>
      <el-table-column label="url">
        <template #default="scope">
          {{scope.row.fontUrl}}
        </template>
      </el-table-column>
      
      <el-table-column label="裁剪URL">
        <template #default="scope">
          {{scope.row.reduceUrl}}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="130">
        <template #default="scope">
          <el-button type="default" link :icon="Edit" size="small" @click.stop="editDelete(scope.row)">编辑</el-button>
          <el-button type="default" link :icon="Delete" size="small" @click.stop="editDelete(scope.row,scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑字体 -->
    <el-dialog v-model="datas.addEditVisible" :align-center="true" :show-close="true" :close-on-press-escape="false" 
    :close-on-click-modal="false" style="width: 573px;" class="small-padding" @close="close">
        <template #header>
            <div class="text-title text-center fz16 PingFangSC">{{datas.params.id?'编辑':'新增'}}字体</div>
        </template>
        <div class="addTemplateBox q-mb-lg fz14">
          <div class="row flex-end q-mb-lg">
            <el-button type="primary" size="small" style="color: #ffff;">
              <el-upload
                ref="upload"  
                :on-change="(uploadFile:any, uploadFiles:any)=> uploadFontHandler(uploadFile, uploadFiles,datas.params.fontFamily)"
                action=""
                :limit="1"
                :auto-upload="false"
                accept=".ttf, .woff, otf"
                :show-file-list="false"
                :on-exceed="handleExceed"  
            >
                <template #trigger>
                  <span class="text-white">{{datas.params.id?'替换':'上传'}}字体</span>
                </template>
              </el-upload>
            </el-button>
          </div>
          <div class="addTemplateInput q-mt-xs q-mb-lg row items-center">
              <span class="q-pr-md shrink">名称：</span>
              <el-input min="750" v-model="datas.params.label"
              placeholder="请输入字体名称" class=""></el-input>
              <span class="q-px-md shrink">fontFamily：</span>
              <el-input min="750" v-model="datas.params.fontFamily"
              placeholder="请输入fontFamily" class=""></el-input>
          </div>
          <div class="addTemplateInput q-mt-xs q-mb-lg row items-center">
            <span class="q-pr-md shrink">URL：</span>
            <el-input min="750" type="textarea" v-model="datas.params.fontUrl"
            placeholder="请输入URL" class=""></el-input>
          </div>
          <div class="addTemplateInput q-mt-xs row items-center">
            <span class="q-pr-md shrink">裁剪URL：</span>
            <el-input min="750" type="textarea" v-model="datas.params.reduceUrl"
            placeholder="请输入裁剪字体URL" class=""></el-input>
          </div>
       </div>
        <div class="text-center">
          <el-button class="MarketIndexButtom MarketRec" type="primary" @click="ConfirmCreation"
          :loading="requestLoading">
              确认{{datas.params.id?'编辑':'新增'}}
          </el-button>
      </div>
    </el-dialog>
  </template>
    
    <script lang="ts" setup>
    import { reactive, ref, inject, onMounted, watch} from "vue";
    import { ENT_USER_THEME, VIP_USER_THEME } from "@/configs/customer";
    import { useUserStore, useFontStore } from "@/store";
    import { storeToRefs } from "pinia";
    import { USER_DEFAULT_HEADER } from '@/configs/customer'
    import { Edit,Delete } from '@element-plus/icons-vue';
    import { ElLoading, ElMessage, ElMessageBox, UploadInstance } from 'element-plus'
    import { CustomerFonts } from '@/store/font'
    import {getFonts} from '@/utils/psdParser/index'
    import FontService from '@/services/FontService'
    import AliyunUpload from '@/utils/upload/aliyun'
    import { reduceFont } from '@/utils/fonts/convertFont'
    import FileService from '@/services/FileService'
  
    const useUser = useUserStore()
    const { userInfo } = storeToRefs(useUser)
  
    const { formatFonts } = storeToRefs(useFontStore())
  
    const userTheme = useUser.getUserTheme
    
    const vipTheme = VIP_USER_THEME
    const enTheme = ENT_USER_THEME
  
    const dataList = ref([] as Array < any > );
    const RawDataList =  ref([] as Array < any > );
    const loading = ref(false as any)
    const deleteLoading = ref<any>(null)
    const queryObj = reactive({
      pageIndex: 1,
      pageCount: 0,
      keyWords: ''
    })
    const dataTableRef = ref()
    const datas = reactive({
      requestLoading: false,
      addEditVisible: false,
      params: {
        id: 0,
        fontFamily: '',
        label: '',
        fontUrl: '',
        reduceName: '',
        reduceUrl: '',
      }
    })
  
    const fonts = ref<{fontFamily:string,uploadType:number,selectedFont?:string}[]>()
    const uploadingIndex = ref(-1)
    const upload = ref<UploadInstance>()
  
    const close = () => {
      datas.params = {
        id: 0,
        fontFamily: '',
        label: '',
        fontUrl: '',
        reduceName: '',
        reduceUrl: '',
      }
    }

    const handleExceed: UploadProps['onExceed'] = (files) => {
      upload.value!.clearFiles()
      const file = files[0] as UploadRawFile
      upload.value!.handleStart(file)
      upload.value.submit()
    }

    const ConfirmCreation = async () => {
      //添加、编辑字体
      if(!datas.params.label)return ElMessage({
        message:'请输入名称',
        type:'error'
      })
      if(!datas.params.fontFamily)return ElMessage({
        message:'请输入fontFamily',
        type:'error'
      })
      if(!datas.params.fontUrl)return ElMessage({
        message:'请输入URL',
        type:'error'
      })
      if(!datas.params.reduceUrl)return ElMessage({
        message:'请输入裁剪URL',
        type:'error'
      })
      datas.requestLoading = true
      const result = await useFontStore().uploadFontAsync(datas.params)
      if(result){
        ElMessage({
            showClose: true,
            message: `操作${datas.params.label}成功`,
            type: 'success',
        })
        datas.addEditVisible = false
        datas.requestLoading = false
        querySearchHandler()
      }else{
          ElMessage({
              message:'字体上传失败,请重试',
              type:'error'
          })
          datas.requestLoading = false
      }
    }
    const addFont = () => {
      datas.addEditVisible = true
    }
    const editDelete = (item: Object,index: Number) => {
      if(index>=0){
        deleteFont(index,item)
      }else{
        datas.params = JSON.parse(JSON.stringify(item))
        datas.addEditVisible = true
      }
    }
  
    const deleteFont = (index: Number, item: Object) => {
      ElMessageBox.confirm(
          `此操作将删除 ${item.label} 字体，是否确定?`,
          '提示',
          {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          }
      ).then(async () => {
          try {
              deleteLoading.value = ElLoading.service({
                  lock:true,
                  text:'正在处理'
              })
              let dataRes = await FontService.RemoveTripFile(item.id)
              if (dataRes.data.resultCode == 1) {
                  ElMessage({
                      showClose: true,
                      message: `删除${item.label}成功`,
                      type: 'success',
                  })
                  search()
              }else {
                  ElMessage({
                      showClose: true,
                      message: `删除${item.label}失败`,
                      type: 'warning',
                  }) 
              }
          } catch (error) {}
          deleteLoading.value.close()
          deleteLoading.value = null
      }).catch(() => {
        deleteLoading.value.close()
        deleteLoading.value = null
      })
      
    }
  
    const uploadFontHandler = async (uploadFile:any, uploadFiles:any, fontName:string) => {
      const ns = uploadFile.name.toLowerCase().split('.')
      const n = ns[ns.length-1]
      const acceptFile = ['ttf','otf','woff']
      if(acceptFile.indexOf(n)==-1){
          ElMessage.error({
              message:`不支持此类文件上传，目前只支持${acceptFile.join(',')}等文件上传`
          })
          return;
      }
      uploadingIndex.value = dataList.value?.findIndex(x=>x.fontFamily==fontName)??-1
      try {
          let info:any = null
          try {
              info = await reduceFont(uploadFile?.raw)
          } catch (error) {
              ElMessage.error({message:'字体无法识别，请更换'})
              uploadingIndex.value=-1
              return
          }
  
          const flagIndex = dataList.value.findIndex(x=>x.label==info.name)
          if(flagIndex>0){
              ElMessage.error({message:`${info.name} 字体已存在，请选择使用已有字体`})
              uploadingIndex.value=-1
              return
          }
          let url = await FileService.uploadToFontServerAsync(uploadFile?.raw)
          if(url && url!=''){
            
              if(url.indexOf('"')!=-1) url = url.replaceAll('"','')
              let label=uploadFile.name.split('.')[0],reduceName='',reduceUrl=''
              try {
                  if(info.file){
                      label = info.name
                      reduceName = `${fontName}_reduce`
                      reduceUrl = await AliyunUpload.UploadAsync(info.file,"tripfont/"+info.file.name)
                  }
              } catch (error) { 
              }
              datas.params.label = label
              datas.params.fontFamily = fontName
              datas.params.fontUrl = url
              datas.params.reduceName = reduceName
              datas.params.reduceUrl = reduceUrl
              await ConfirmCreation()
          }else{
              ElMessage({
                  message:'上传失败，请重试',
                  type:'error'
              })
          }
      } catch (error) {
      }
  }
    const tableScrollHandler = ()=>{
      if(queryObj.pageCount>queryObj.pageIndex){
          queryObj.value.pageIndex++
          refreshHandler()
      }
    }
    const search = () => {
      queryObj.pageIndex = 1
      querySearchHandler()
    }
  
    const querySearchHandler = async () => {
      loading.value = true
      try {
          let pageRes = await FontService.GetManagerFontList(queryObj);
          if (pageRes.data.resultCode == 1) {
              dataList.value = pageRes.data.data
              RawDataList.value = pageRes.data.data
          }
          loading.value = false
      } catch (error) {
          loading.value = false
      }
  }
  querySearchHandler()
    </script>
    
    <style scoped>
    .addTemplateInput span {
      width: 95px;
      text-align: right;
    }
    .user-header {
      padding: 16px 24px;
      position: relative;
      font-size: 14px;
      color:#FFF;
      z-index: 1;
      width:100%;
      overflow: hidden;
    }
    
    .user-header::after {
      position: absolute;
      top: 0;
      right: -48px;
      bottom: -12px;
      z-index: -1;
      width: 100%;
      background: url('https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1713496804000_500.png') no-repeat right center / contain;
      content: "";
      transform: scale(2);
      transform-origin: right center;
    }
    .user-label{
      font-size: 12px;
      margin-bottom: 8px;
    }
    .user-card {
      width: 33%;
      min-height: 112px;
    }
    .user-card .title,
    .enter-card .title{
      font-size: 15px;
      font-weight: bold;
      color: #000;
    }
    </style>