<template>
    <div class="row items-center flex-between q-mb-lg">
      <div></div>
      <el-input style="width:600px" v-model="queryObj.Title" 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="主色调">
        <template #default="scope">
          {{scope.row.ColorName?scope.row.ColorName:'不限'}}
        </template>
      </el-table-column>
      <el-table-column label="颜色名称">
        <template #default="scope">
          {{scope.row.Name}}
        </template>
      </el-table-column>
      <el-table-column label="色值">
        <template #default="scope">
            <el-tag
            :color="scope.row.Content"
            effect="dark" class="q-mr-md">
            &nbsp;
            </el-tag>
          {{scope.row.Content}}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button type="primary" :icon="Edit" size="small" @click.stop="editDelete(scope.row)">编辑</el-button>
          <el-button type="primary" :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: 373px;" 
    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="addTemplateInput q-mt-xs q-mb-lg row items-center">
            <span class="q-pr-md shrink">主色：</span>
            <el-select v-model="datas.params.Code" 
              style="width: 260px;"
              class="ml-1"
              placeholder="主颜" clearable>
                  <el-option key="" label="不限" value=""/>
                  <el-option
                      v-for="item in ColorList"
                      :key="item.Id"
                      :label="`${item.ColorName}`"
                      :value="item.Id"
                  />
            </el-select>
          </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.Name"
              placeholder="请输入颜色名称" class=""></el-input>
          </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.Content"
            placeholder="例子:#e5e3da" class=""></el-input>
            <div class="q-pl-sm">
                <el-color-picker v-model="datas.params.Content" />
                <!-- <el-tag
                :color="datas.params.ColorValue" style="width: 32px;height: 32px;"
                effect="dark">
                &nbsp;
                </el-tag> -->
            </div>
        </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 { ElMessage, ElMessageBox } 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 ConfigService from '@/services/ConfigService'
    import LineService from '@/services/LineService'
    import { DominantColour } from '@/utils/common'
  
    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({
      DictKey: 'Trip_Template_Color',
      Name: ''
    })
    const dataTableRef = ref()
    const datas = reactive({
      requestLoading: false,
      addEditVisible: false,
      params: {
        ID: 0,
        DictKey: 'Trip_Template_Color',
        Name: '',
        Content: '',
        Code: '',
      }
    })
  
    const fonts = ref<{fontFamily:string,uploadType:number,selectedFont?:string}[]>()
    const uploadingIndex = ref(-1)
  
    const ColorList = DominantColour()

    const close = () => {
        datas.params = {
          ID: 0,
          DictKey: 'Trip_Template_Color',
          Name: '',
          Content: '',
          Code: '',
        }
    }
    const ConfirmCreation = async () => {
      //添加、编辑颜色
      if(!datas.params.Name)return ElMessage({
                showClose: true,
                message: '请完善颜色名称',
                type: 'warning',
            }) 
    if(!datas.params.Content){
        ElMessage({
            showClose: true,
            message: '请完善颜色的16进制',
            type: 'warning',
        }) 
        return
    }
    if(datas.params.Content.indexOf('#')==-1){
        ElMessage({
            showClose: true,
            message: "色号需要在最前面加 # 号",
            type: 'warning',
        }) 
        return
    }
      datas.requestLoading = true
      const result = await LineService.SetTemplateConfigData(datas.params)
      if(result){
        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.params.Code = item.Code?Number(item.Code):''
        datas.addEditVisible = true
      }
    }
  
    const deleteFont = (index: Number, item: Object) => {
      ElMessageBox.confirm(
          `此操作将删除 ${item.label} 颜色，是否确定?`,
          '提示',
          {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          }
      ).then(async () => {
          try {
            dataList.value.splice(index,1)
              // let queryMsg = {
              //     TempId: item.TempId
              // }
              // deleteLoading.value = ElLoading.service({
              //     lock:true,
              //     text:'正在处理'
              // })
              // let dataRes = await ConfigService.SetDeleteTripTemplate(queryMsg)
              // if (dataRes.data.resultCode == 1) {
              //     queryObj.pageIndex = 1
              //     ElMessage({
              //         showClose: true,
              //         message: `删除${item.label}成功`,
              //         type: 'success',
              //     })
              //     await queryTemplateBySearchHandler()
              // }else {
              //     ElMessage({
              //         showClose: true,
              //         message: `删除${item.label}失败`,
              //         type: 'warning',
              //     }) 
              // }
              // deleteLoading.value.close()
              // deleteLoading.value = null
          } catch (error) {}
      }).catch(() => {})
    }
  
    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 LineService.GetTemplateConfigDataList(queryObj);
          if (pageRes.data.resultCode == 1) {
            let arrList = function(list){
              list.forEach(x=>{
                x.ColorName = ''
              })
            }
            arrList(pageRes.data.data)
            dataList.value = pageRes.data.data
            for(let i=0;i<dataList.value.length;i++){
              let Color = ColorList.filter(x=>{return x.Id==dataList.value[i].Code })
              if(Color.length>0) {
                dataList.value[i].ColorName = Color[0].ColorName
              }
            }
          }
          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>