<template>
    <div class="row items-center flex-between q-mb-lg">
      <div class="row items-center shrink q-pr-md marketTagDown marketTagDown">
          <!-- <div class="MarketButton cursor-pointer" 
          :class="[datas.type == x.Id?'active':'']" v-for="(x,index) in datas.colorType" :key="index"
          @click="datas.type=x.Id,search()">
              {{x.Name}}
      </div> -->
        <!-- <span class="fz14 q-pr-sm shrink">&nbsp;&nbsp;列表类型:</span>
        <el-select v-model="datas.type" 
            class="ml-1 shrink TemSel"
            placeholder="类型" @change="search">
                <el-option
                    v-for="item in datas.colorType"
                    :key="item.Id"
                    :label="`${item.Name}`"
                    :value="item.Id"
                />
        </el-select> -->
      </div>
      <el-input style="max-width:500px" v-model="queryObj.Name" 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>
      <div class="row">
        <el-button type="primary" size="default" style="color: #ffff;" @click="addColour(1)">
          新增颜色
        </el-button>
        <el-button type="primary" size="default" style="color: #ffff;" @click="addColour(2)">
          新增分类
        </el-button>
        <el-button class="q-pl-md" type="primary" size="default" style="color: #ffff;" @click="BatchSetting">
          设置分类
        </el-button>
      </div>
    </div>
    <el-table v-loading="loading" ref="dataTableRef" highlight-current-row 
    v-load-more="tableScrollHandler" :data="dataList" class="tableHBEbeef5 col" height="82vh"
    @selection-change="handleSelectionChange"
    row-key="ID"
    :tree-props="{ children: 'ChildList', hasChildren: 'hasChildren' }"
    :default-expand-all="datas.defaultExpandAll"
    >
    <el-table-column type="selection" width="55"
    :selectable="selectable" :reserve-selection="true"/>
    <el-table-column label="颜色分类">
        <template #default="scope">
          <span v-html="queryObj.Name!=''&&scope.row.ColorName?(scope.row.ColorName.replaceAll(queryObj.Name,`<span class='text-waring'>${queryObj.Name}</span>`)):scope.row.ColorName"></span>
          <!-- {{scope.row.ColorName?scope.row.ColorName:''}} -->
        </template>
      </el-table-column>
      <el-table-column :label="datas.type==1?'颜色名称':'名称'">
        <template #default="scope">
          <div v-html="queryObj.Name!=''&&scope.row.Name?(scope.row.Name.replaceAll(queryObj.Name,`<span class='text-waring'>${queryObj.Name}</span>`)):scope.row.Name"></div>
          <!-- {{scope.row.Name}} -->
        </template>
      </el-table-column>
      <el-table-column label="色值">
        <template #default="scope">
            <el-tag
            :color="scope.row.ColorValue"
            effect="dark" class="q-mr-md">
            &nbsp;
            </el-tag>
            <div v-html="queryObj.Name!=''&&scope.row.ColorValue?(scope.row.ColorValue.replaceAll(queryObj.Name,`<span class='text-waring'>${queryObj.Name}</span>`)):scope.row.ColorValue"></div>
          <!-- {{scope.row.ColorValue}} -->
        </template>
      </el-table-column>
      <el-table-column label="操作" width="130">
        <template #default="scope">
          <el-button type="default" link :icon="Edit" size="small" @click="editDelete(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.Code||(!scope.row.Code&&scope.row.ChildList.length==0)" type="default" link :icon="Delete" size="small" @click="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?'编辑':'新增'}}{{datas.type==2?'分类':'颜色'}}</div>
        </template>
        <div class="addTemplateBox q-mb-lg fz14">
          <div v-if="datas.type==1" 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.Name}`"
                      :value="item.ID"
                      :disabled="setColorDisabled(item.ID)"
                  />
            </el-select>
          </div>
          <div class="addTemplateInput q-mt-xs q-mb-lg row items-center">
              <span class="q-pr-md shrink">{{datas.type==1?'':'分类'}}名称：</span>
              <el-input min="750" v-model="datas.params.Name"
              :placeholder="datas.type==1?'请输入颜色名称':'请输入分类名称'" 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 class="addTemplateInput q-mt-xs q-mb-lg row items-center">
          <span class="q-pr-md shrink">排序：</span>
          <el-input min="750" type="number" v-model="datas.params.SNO" 
            placeholder="请输入排序" clearable>
          </el-input>
        </div>
       </div>
        <div class="text-center">
          <el-button class="MarketIndexButtom MarketRec" type="primary" @click="ConfirmCreation(0)"
          :loading="requestLoading">
              确认{{datas.params.ID?'编辑':'新增'}}
          </el-button>
      </div>
    </el-dialog>
    <!-- 批量设置分类 -->
    <el-dialog v-model="datas.DominantColour" :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">设置颜色分类</div>
        </template>
        <div class="addTemplateBox q-mb-lg fz14">
          <div class="addTemplateInput q-mt-xs q-mb-lg">
            <template v-for="(x,index) in multipleSelection">
              <el-tag
                :color="x.ColorValue"
                effect="dark" class="q-mr-xs w10">
                &nbsp;
              </el-tag>
            </template>
          </div>
          <div class="addTemplateInput q-mt-xs q-mb-lg row items-center">
            <span class="q-pr-md shrink">颜色分类：</span>
            <el-select v-model="datas.paramsParent.ParentId" 
              style="width: 260px;"
              class="ml-1"
              placeholder="请选择颜色分类" clearable>
                  <el-option :key="Number(0)" label="不限" :value="Number(0)"/>
                  <el-option
                      v-for="item in ColorList"
                      :key="item.ID"
                      :label="`${item.Name}`"
                      :value="item.ID"
                      :disabled="setColorDisabled(item.ID)"
                  />
            </el-select>
          </div>
       </div>
        <div class="text-center">
          <el-button class="MarketIndexButtom MarketRec" type="primary" @click="ConfirmCreation(1)"
          :loading="requestLoading">
              确认设置
          </el-button>
      </div>
    </el-dialog>
  </template>
    
    <script lang="ts" setup>
    import { reactive, ref, inject, onMounted, watch, nextTick} 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 } 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'
  
    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 DataListAll =  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({
      defaultExpandAll: false,
      type: 1,
      colorType:[
        {Name:'颜色',Id:1},
        {Name:'颜色分类',Id:2},
      ],
      DominantColour: false,
      requestLoading: false,
      addEditVisible: false,
      params: {
        ID: 0,
        DictKey: 'Trip_Template_Color',
        Name: '',
        Content: '',
        Code: 0,
        SNO: 0,
      },
      paramsParent: {
        ParentId: 0,
        ColorList: []
      }
    })
    const queryColor = ref({
        DictKey: 'Trip_Template_Color',
        Code: '',
    })
  
    const fonts = ref<{fontFamily:string,uploadType:number,selectedFont?:string}[]>()
    const uploadingIndex = ref(-1)
  
    const ColorList = ref([])
    const multipleSelection = ref([])

    watch(() => datas.defaultExpandAll, (n,o) => {
      nextTick(() => dataTableRef.value.doLayout())
    })
    const setColorDisabled = (ID:number) => {
      if(datas.addEditVisible) {
        if(datas.params.Code==ID) return true
        else false
      }
      if(datas.DominantColour) {
        for(let i=0;i<multipleSelection.value.length;i++){
          if(multipleSelection.value[i].ID==ID) return true
          else false
        }
      }
    }
    const selectable = (row:Object, index:Number)=> {
      if (row.ChildList&&row.ChildList.length>0) {
        return false;
      } else {
        return true;
      }
    }
    const handleSelectionChange = (val: any) =>{
      multipleSelection.value = val
      datas.paramsParent.ColorList = val.length>0? val.map(x=> {return x.ID}) : 0
    }
    // 批量设置颜色分类
    const BatchSetting = () => {
      if(datas.paramsParent.ColorList.length==0)return ElMessage({
                showClose: true,
                message: '请选择需要设置的颜色',
                type: 'warning',
            }) 
      datas.DominantColour = true
      
    }
    const close = () => {
        datas.params = {
          ID: 0,
          DictKey: 'Trip_Template_Color',
          Name: '',
          Content: '',
          Code: '',
        }
        // datas.paramsParent = {
        //   ParentId: 0,
        //   ColorList: []
        // }
    }
    const ConfirmCreation = async (type:Number) => {
      if(type==1){
        await setColour()
      }else{
        await addEditColor()
      }
    }
    const toggleSelection = (rows:any) => {
        if (rows) {
          rows.forEach(row => {
            dataTableRef.value.toggleRowSelection(row);
          });
        } else {
          dataTableRef.value.clearSelection();
        }
        getColor()
    }
    const setColour = async () => {
      datas.requestLoading = true
      const result = await LineService.BatchSetColor(datas.paramsParent)
      if(result.data.resultCode==1){
        datas.DominantColour = false
        datas.requestLoading = false
        toggleSelection()
        querySearchHandler()
      }else{
          ElMessage({
              message:'颜色分类设置失败,请重试',
              type:'error'
          })
          datas.requestLoading = false
      }
    }
    const addEditColor = 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
      if(datas.type==2) datas.params.Code = ''
      const result = await ConfigService.SetTemplateConfigData(datas.params)
      if(result.data.resultCode==1){
        datas.addEditVisible = false
        datas.requestLoading = false
        toggleSelection()
        querySearchHandler()
      }else{
          ElMessage({
              message:'颜色新增失败,请重试',
              type:'error'
          })
          datas.requestLoading = false
      }
    }
    const addColour = (Id:number) => {
      datas.type = Id
      datas.addEditVisible = true
    }
    const editDelete = (item: Object,index: Number) => {
      if(index>=0){
        deleteColor(item)
      }else{
        datas.params = JSON.parse(JSON.stringify(item))
        datas.params.Code = item.Code?Number(item.Code):''
        datas.params.Content = item.ColorValue
        datas.type = item.ChildList&&item.ChildList.length>0?2:1
        if(datas.type==2||(datas.type==1&&!datas.params.Name))datas.params.Name = item.ColorName
        datas.addEditVisible = true
      }
    }
  
    const deleteColor = (item: Object) => {
      ElMessageBox.confirm(
          `此操作将删除 ${item.Content} 颜色，是否确定?`,
          '提示',
          {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          }
      ).then(async () => {
          try {
            try {
              deleteLoading.value = ElLoading.service({
                  lock:true,
                  text:'正在处理'
              })
              let dataRes = await LineService.RemoveTemplateConfigData(item.ID)
              if (dataRes.data.resultCode == 1) {
                  // queryObj.pageIndex = 1
                  ElMessage({
                      showClose: true,
                      message: `删除${item.Content}成功`,
                      type: 'success',
                  })
                  search()
              }else {
                  ElMessage({
                      showClose: true,
                      message: `删除${item.Content}失败`,
                      type: 'warning',
                  }) 
              }
          } catch (error) {}
          deleteLoading.value.close()
          deleteLoading.value = null
          } catch (error) {}
      }).catch(() => {
        deleteLoading.value.close()
        deleteLoading.value = null
      })
    }
  
    const tableScrollHandler = ()=>{
      // if(queryObj.pageCount>queryObj.pageIndex){
      //     queryObj.value.pageIndex++
      //     refreshHandler()
      // }
    }
    const search = () => {
      // queryObj.pageIndex = 1
      querySearchHandler()
    }
  
    const querySearchHandler = async () => {
      if(!queryObj.Name||queryObj.Name=='') datas.defaultExpandAll = false
      if(queryObj.Name) datas.defaultExpandAll = true
      loading.value = true
      try {
          let response = await ConfigService.GetTemplateQueryAsync(queryObj)
          if (response.data.resultCode == 1) {
            let arrList = function(list){
              list.forEach(x=>{
                x.Content = ''
              })
            }
            arrList(response.data.data.ColorList)
            DataListAll.value = response.data.data.ColorList
            dataList.value = response.data.data.ColorList
          }
          loading.value = false
      } catch (error) {
          loading.value = false
      }
  }
  const getColor = async () => {
      let response = await LineService.GetParentColor(queryColor.value)
      if (response.data.resultCode == 1) {
          ColorList.value = response.data.data;
      }
  }
  getColor()
  querySearchHandler()
    </script>
    
    <style scoped>
    .addTemplateInput span {
      width: 95px;
      text-align: right;
    }
    .addTemplateInput span.w10{
      width: 10px;
      height: 15px;
    }
    .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;
    }
    .TemSel{
      width: 120px;
    }
    .marketTagDown .el-check-tag{
        line-height: 22px;
        margin-left: 13px;
        margin-right: 0;
    }
    .marketTagDown {
        width: 409px;
    }
    .marketTagDown.marketTagDown{
        width: 309px;
    }
    .MarketButton{
        width: 90px;
        height: 36px;
        line-height: 36px;
        font-size: 14px;
        text-align: center;
        color: #9EA2B3;
        position: relative;
        margin-right: 13px;
    }
    .MarketButton.active{
        background: #F4F7FE;
        border-radius: 6px;
        -webkit-border-radius: 6px;
        -moz-border-radius: 6px;
        -ms-border-radius: 6px;
        -o-border-radius: 6px;
        color: #1C1C1C;
    }
    .MarketButton.active::after{
        content: "";
        position: absolute;
        left: 35.5px;
        bottom: 0;
        width: 19px;
        height: 4px;
        background: linear-gradient(134deg, #649DED, #570AD8);
    }
    </style>