<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">
          新增颜色{{datas.type==2?'分类':''}}
        </el-button>
        <el-button v-if="datas.type==1" 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">
    <el-table-column type="selection" width="55" v-if="datas.type==1"/>
    <el-table-column v-if="datas.type==1" label="颜色分类">
        <template #default="scope">
          {{scope.row.ColorName?scope.row.ColorName:'不限'}}
        </template>
      </el-table-column>
      <el-table-column :label="datas.type==1?'颜色名称':'名称'">
        <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="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: 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 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="Number(0)" label="不限" :value="Number(0)"/>
                  <el-option
                      v-for="item in ColorList"
                      :key="item.ID"
                      :label="`${item.Name}`"
                      :value="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.Content"
                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"
                  />
            </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" />
            </div>
         </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} 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'
    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({
      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([]) //DominantColour()
    const multipleSelection = ref([])

    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 setColour = async () => {
      datas.requestLoading = true
      const result = await LineService.BatchSetColor(datas.paramsParent)
      if(result.data.resultCode==1){
        datas.DominantColour = false
        datas.requestLoading = false
        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
        querySearchHandler()
      }else{
          ElMessage({
              message:'颜色新增失败,请重试',
              type:'error'
          })
          datas.requestLoading = false
      }
    }
    const addColour = () => {
      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.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 () => {
      loading.value = true
      try {
          let pageRes = await LineService.GetTemplateConfigDataList(queryObj);
          // if(datas.type==1) pageRes = await LineService.GetTemplateConfigDataList(queryObj);
          // else pageRes = await LineService.GetParentColor(queryColor.value);
          if (pageRes.data.resultCode == 1) {
            let arrList = function(list){
              list.forEach(x=>{
                x.ColorName = ''
              })
            }
            arrList(pageRes.data.data)
            if(datas.type==1) {
              dataList.value = pageRes.data.data.filter(x=>{
                return x.Code
              })
            }
            else {
              dataList.value = pageRes.data.data.filter(x=>{
                return !x.Code
              })
              // dataList.value = pageRes.data.data
              // ColorList.value = pageRes.data.data
            }
            for(let i=0;i<dataList.value.length;i++){
              let Color = ColorList.value.filter(x=>{
                if(datas.type==1) return x.ID==Number(dataList.value[i].Code)
                else return x.ID==Number(dataList.value[i].ID)
              })
              if(Color.length>0) {
                dataList.value[i].ColorName = Color[0].Name
              }
            }
          }
          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>