<template>
  <div ref="modalContent" class="modal-content">
    <div class="modal-title">
      <div class="title-span">图片管理</div>
      <div class="close-button-div">
        <div class="close-button" @click="closeModal"></div>
      </div>
    </div>
    <div class="content-div">
      <div class="menu-div">
        <div class="menu-title">
          <div class="menu-title-icon"></div>
          <div class="menu-title-span">图片资源</div>
          <div v-if="isChange" style="font-size: 20px;cursor: pointer;" @click="openAddMenu"><PlusSquareOutlined /></div>
        </div>
        <div class="menu-list">
          <div :class="`menu-item ${selectPhotoGroup == item? 'select-menu': ''}`" v-for="(item, index) in photoGroupList" :key="index" @click="changeMenu">
            <div class="menu-item-icon"></div>
            <div class="menu-item-span">{{ item }}</div>
          </div>
          <!-- <div v-if="!addMenuOpen" class="add-menu-div" @click="openAddMenu"><PlusSquareOutlined /></div> -->
          <div v-if="addMenuOpen" class="add-menu-div" style="padding: 0px 10px;">
            <a-input v-model:value="addMenuName" style="margin-right: 7px;" />
            <a-button type="primary" style="background-color: #52c41a;margin-right: 5px;" shape="circle" :icon="h(CheckOutlined)" @click="submitMenu"></a-button>
            <a-button type="primary" style="background-color: #ff7875;" shape="circle" :icon="h(CloseOutlined)" @click="closeAddMenu"></a-button>
          </div>
        </div>
      </div>
      <div class="show-list-div">
        <div class="show-control">
          <div class="control-left">
            <a-radio-group class="show-type" v-model:value="showType">
              <a-radio-button  class="custom-radio-btn" value="item">
                  <AppstoreOutlined style="font-size: 20px;"/>
              </a-radio-button>
              <a-radio-button  class="custom-radio-btn" value="list">
                <BarsOutlined style="font-size: 20px;"/>
              </a-radio-button>
            </a-radio-group>
            <a-select
              class="select-sort"
              v-model:value="sort"
              style="width: 166px;"
              :options="selectSortOptions"/>
          </div>
          <div class="control-right">
            <a-input-search
              class="search-input"
              v-model:value="search"
              placeholder="查询图片名称"
            >
              <template #enterButton>
                <a-button 
                  type="primary"
                  :icon="h(SearchOutlined)"
                  style="height: 36px;"
                  @click="searchPhoto"
                >搜索</a-button>
              </template>
            </a-input-search>
          </div>
        </div>
        <div class="show-list" v-if="showType == `item`">
          <div class="show-item" v-for="(item,index) in paginatedData" :key="index">
            <div class="item-image-div">
              <a-image
                class="item-image"
                :src="`${apiUrl}/${item.filePath}`"
                :preview="{ getContainer: () => modalContent }"
              />
              <div class="image-size">{{ `` }}</div>
              <a-checkbox class="select-image" 
                :checked="selectPhotoList.some(obj => obj.id === item.id)"
                @change="changeSelect(selectPhotoList.some(obj => obj.id === item.id)? 1: 2,item)">
              </a-checkbox>
            </div>
            <div class="item-span">{{ item.fileName }}</div>
          </div>
        </div>
        <div class="show-list" v-else style="margin-right: 74px;border: 1px solid #D9D9D9;border-radius: 4px;">
          <div class="list-title">
            <div style="margin-left: 69px;margin-right: 339px;">素材名称</div>
            <div style="margin-right: 103px;">尺寸</div>
            <div style="margin-right: 161px;">大小</div>
            <div>更新时间</div>
          </div>
          <div class="list-content">
            <div class="list-item" v-for="(item, index) in paginatedData" :key="index">
              <a-checkbox class="list-select-image" 
                :checked="selectPhotoList.some(obj => obj.id === item.id)"
                @change="changeSelect(selectPhotoList.some(obj => obj.id === item.id)? 1: 2,item)"/>
              <a-image
                class="list-item-image"
                :src="`${apiUrl}/${item.filePath}`"
              />
              <div class="list-item-span">{{ item.fileName }}</div>
              <div class="list-item-size"></div>
              <div class="list-item-size">{{ `${(item.fileSize / 1024).toFixed(1)}kb`}}</div>
              <div class="list-item-time">{{item.createTime}}</div>
            </div>
          </div>
          
        </div>
        <div class="pagination-div">
          <a-pagination
            v-model:current="current"
            v-model:page-size="pageSize"
            show-quick-jumper
            show-size-changer
            :total="photoList.length"
            :show-total="total => `共 ${total} 条`"
            @showSizeChange="handlePageSizeChange"
          />
        </div>
      </div>
    </div>
    <div class="button-div">
      <Button v-if="isChange"  type="primary" style="margin-right: 10px;background-color: #ed6f6f;" @click="deleteImage">删除图片</Button>
      <Upload
        :multiple="true"
        :accept="'.jpg,.png,.jpeg'"
        :showUploadList="false"
        :custom-request="customRequest"
        v-if="isChange"
      >
        <Button  type="primary" :icon="h(UploadOutlined)" style="margin-right: 10px;">上传图片</Button>
      </Upload>
      <Button v-if="isChange"  type="primary" @click="addPhotoToList">添加到图片列表</Button>
      <Button v-if="!isChange"  type="primary" @click="changePhotoPath">修改</Button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, h, computed, defineProps, defineEmits } from "vue"
import { imageList, imageUpload, imageDelete, getImageGroupList } from '@/api/demo/photo'
import { useGlobSetting } from '@/hooks/setting';
import { Image, Button, Upload, Modal } from 'ant-design-vue';
import Icon from '@/components/Icon/Icon.vue';
import { UploadOutlined,AppstoreOutlined, BarsOutlined, SearchOutlined, PlusSquareOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { photoModalStore } from '@/store/modules/photoModal'
import { usePackagesStore } from '@/store/modules/packagesStore/packagesStore'
import { StorageEnum } from '@/enums/storageEnum'
import { ImageConfig } from '@/packages/components/Informations/Mores/Image/index'
import { ChatCategoryEnum, ChatCategoryEnumName } from '@/packages/components/Photos/index.d'
import { ChartFrameEnum, ConfigType, PackagesCategoryEnum } from '@/packages/index.d'
import { setLocalStorage, getLocalStorage } from '@/utils'
import { selectSortOptions } from './util'

const photoModalStateStore = photoModalStore()
const packagesStore = usePackagesStore()
const { apiUrl } = useGlobSetting();
const props = defineProps({
  readonly: {
    type: Boolean,
    required: true,
  },
})
const emits = defineEmits(['closePhotoModal','saveChangePhoto'])
const isChange = computed(() => !props.readonly)

onMounted(() => {
  // getList()
  getPhotoGroup()
})

const StoreKey = StorageEnum.GO_USER_MEDIA_PHOTOS
const photoList = ref([])
const selectPhotoList = ref([])
const photoGroupList = ref([])
const selectPhotoGroup = ref()
const showType = ref('item')
const sort = ref()
const search = ref()
const checked = ref()
const current = ref(1)
const pageSize = ref(10)
const addMenuName = ref('')
const addMenuOpen = ref(false)
const modalContent = ref()

const paginatedData = computed(() => {
  const start = (current.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return photoList.value.slice(start, end);
});

const getList = () => {
  let params = {
    GroupName: selectPhotoGroup.value,
    page: current.value,
    limit: pageSize.value,
  }
  if(search.value){
    params['key'] = search.value
  }
  imageList(params).then(res => {
    photoList.value = res
  })
}
const getPhotoGroup = () => {
  getImageGroupList().then(res => {
    console.log('res',res)
    photoGroupList.value = res
    if(res.length > 0){
      selectPhotoGroup.value = res[0]
      getList()
    }
  })
}
const closeModal = () => {
  if(isChange.value){
    photoModalStateStore.changeOpenState(false)
  }else{
    emits('closePhotoModal')
  }
  
}
const changeSelect = (type,item) => {
  switch(type){
    case 1: 
      selectPhotoList.value = selectPhotoList.value.filter(useItem => useItem.id !== item.id);
      break;
    case 2:
      selectPhotoList.value.push(item)
      break
  }
}
const customRequest = (file) => {
  const formData = new FormData()
  formData.append('files', file.file)
  imageUpload(formData,selectPhotoGroup.value).then(res => {
    console.log(res)
    getList()
  })
}
const deleteImage = () => {
  if(selectPhotoList.value.length <= 0){
    window.$message.warning('请选择要被删除的图片')
    return
  }
  Modal.confirm({
    title: '确定要删除选中的图片吗？',
    onOk: async () => {
      let resultId = selectPhotoList.value.map(item => item.id).join(',')
      imageDelete(resultId).then(res => {
        if(res){
          selectPhotoList.value = []
          window.$message.success('删除成功')
          getList()
        }
      })
    },
    onCancel() {
    },
  })
  
}
const addPhotoToList = () =>{
  if(selectPhotoList.value.length <= 0){
    window.$message.warning('请选择要添加到列表的图片')
    return
  }
  const userPhotosList: ConfigType[] = getLocalStorage(StoreKey) || []
  const addNewPhotosList: ConfigType[] = []
  selectPhotoList.value.forEach(item => {
    const newPhoto = {
      ...ImageConfig,
      category: ChatCategoryEnum.PRIVATE,
      categoryName: ChatCategoryEnumName.PRIVATE,
      package: PackagesCategoryEnum.PHOTOS,
      chartFrame: ChartFrameEnum.STATIC,
      title: item.fileName,
      image: `${apiUrl}/${item.filePath}`,
      dataset: `${apiUrl}/${item.filePath}`,
      redirectComponent: `${ImageConfig.package}/${ImageConfig.category}/${ImageConfig.key}` // 跳转组件路径规则：packageName/categoryName/componentKey
    }
    userPhotosList.unshift(newPhoto)
    addNewPhotosList.unshift(newPhoto)
  })
  setLocalStorage(StoreKey, userPhotosList)
  packagesStore.addPhotos(addNewPhotosList, 1)
  selectPhotoList.value = []
  closeModal()
}
const handlePageSizeChange = (page, size) => {
  pageSize.value = size;
  current.value = 1;
};
const searchPhoto = () => {
  current.value = 1
  getList()
}
const openAddMenu = () => {
  addMenuName.value = ''
  addMenuOpen.value = true
}
const closeAddMenu = () => {
  addMenuOpen.value = false
  addMenuName.value = ''
}
const submitMenu = () => {
  if(addMenuName.value.trim()){
    photoGroupList.value.push(addMenuName.value.trim())
    addMenuOpen.value = false
    addMenuName.value = ''
  }else{
    window.$message.warning('分组名称不能为空')
  }
}
const changeMenu = (item) => {
  selectPhotoGroup.value = item.target.textContent
  current.value = 1
  getList()
}
const changePhotoPath = () => {
  if(selectPhotoList.value.length <= 0){
    window.$message.warning('请选择要修改的图片')
    return
  }
  if(selectPhotoList.value.length > 1){
    window.$message.warning('请只选择一张需要修改的图片')
    return
  }
  emits('saveChangePhoto',`${apiUrl}/${selectPhotoList.value[0].filePath}`)
}
</script>

<style lang="scss" scoped>
.modal-content{
  height: 790px;
  .modal-title{
    height: 91px;
    font-size: 23px;
    font-weight: 500;
    // margin-bottom: 10px;
    display:flex;
    justify-content: space-between;
    border-bottom: 1px solid #E9E9E9;
    .title-span{
      display: flex;
      align-items: center;
      padding-left: 42px;
      font-family: 'PingFangSC-Medium';
      font-weight: 500;
      font-size: 30px;
      color: #1A1A1A;
      line-height: 42px;
    }
    .close-button-div{
      display: flex;
      align-items: center;
      padding-right: 39px;
      .close-button{
        width: 30px;
        height: 30px;
        transform: rotate(0deg);
        transition: 0.5s;
        cursor: pointer;
        background-image: url('/public/photomodal/photo_close_button.png');
        background-size: 100% 100%;
      }
    }
    .close-button:hover{
      transform: rotate(180deg);
    }
  }
  .content-div{
    height: 630px;
    display: flex;
    margin-bottom: 10px;
    .menu-div{
      width: 260px;
      border-right: 1px solid #E9E9E9;
      border-bottom: 1px solid #E9E9E9;
      .menu-title{
        height: 63px;
        display: flex;
        align-items: center;
        padding-left: 45px;
        .menu-title-icon{
          width: 18px;
          height: 16px;
          background-image: url('/public/photomodal/menu_title_icon.png');
          background-size: 100% 100%;
          margin-right: 8px;
        }
        .menu-title-span{
          font-family: 'PingFangSC-Regular';
          font-weight: 400;
          font-size: 18px;
          color: #333333;
          line-height: 25px;
          margin-right: 40px;
        }
      }
      .menu-list{
        height: 567px;
        overflow: auto;
        scrollbar-width: none; 
        ::-webkit-scrollbar {
          width: 0;
          height: 0;
        }
        .menu-item{
          height: 40px;
          display: flex;
          align-items: center;
          padding-left: 91px;
          cursor: pointer;
          .menu-item-icon{
            width: 18px;
            height: 14px;
            background-image: url('/public/photomodal/menu_item_icon.png');
            background-size: 100% 100%;
            margin-right: 11px;
          }
          .menu-item-span{
            font-family: 'PingFangSC-Regular';
            font-weight: 400;
            font-size: 14px;
            color: #333333;
            line-height: 20px;
          }
        }
        .menu-item:hover{
          background-color: #F4F8FF;
        }
        .select-menu{
          background-color: #F4F8FF;
        }
        .add-menu-div{
          height: 40px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 20px;
        }
      }
    }
    .show-list-div{
      flex: 1;
      padding-top: 34px;
      padding-left: 31px;
      position: relative;
      border-bottom: 1px solid #E9E9E9;
      .show-control{
        display: flex;
        justify-content: space-between;
        margin-bottom: 34px;
        .control-left{
          display: flex;
          .show-type{
            display: flex;
            margin-right: 14px;
            .custom-radio-btn {
              display: flex;
              align-items: center;
              justify-content: center;
              height: 36px;
              padding: 0 12px;
              .anticon {
                font-size: 20px;
              }
              span{
                display: flex;
              }
            }
          }
          .select-sort{
            :deep(.ant-select-selector){
              height: 36px;
              .ant-select-selection-item{
                display: flex;
                align-items: center;
              }
            }
          }
        }
        .control-right{
          padding-right: 74px;
          .search-input{
            :deep(.ant-input){
              height: 36px;
            }
          }
        }
      }
      .show-list{
        height: 440px;
        display: flex;
        flex-wrap: wrap;
        align-content: flex-start;
        overflow: auto;
        scrollbar-width: none;
        ::-webkit-scrollbar {
          width: 0;
          height: 0;
        }
        .show-item{
          width: 150px;
          margin-right: 28px;
          margin-bottom: 13px;
          .item-image-div{
            position: relative;
            border-radius: 11px;
            margin-bottom: 15px;
            background-color: rgb(24,24,28);
            :deep(.item-image){
              width: 150px;
              height: 150px;
              object-fit: contain;
              border-radius: 11px;
            }
            .image-size{
              position: absolute;
              bottom: 0px;
              left: 0px;
              width: 150px;
              height: 30px;
              background-color: rgba(22, 22, 22, 0.56);
              border-bottom-right-radius: 11px;
              border-bottom-left-radius: 11px;
              display: flex;
              align-items: center;
              justify-content: center;
              font-family:  'PingFangSC-Regular';
              font-weight: 400;
              font-size: 14px;
              color: #FFFFFF;
              line-height: 20px;
              user-select: none;
            }
            .select-image{
              position: absolute;
              top: 12px;
              right: 14px;
              :deep(.ant-checkbox-inner){
                width: 23px;
                height: 23px;
              }
            }
          }
          .item-span{
            font-family: 'PingFangSC-Regular';
            font-weight: 400;
            font-size: 16px;
            color: #040404;
            line-height: 22px;
            text-align: center;
            font-style: normal;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        .list-title{
          width: 974px;
          height: 50px;
          display: flex;
          align-items: center;
          background: #F3F3F3;
          font-family: 'PingFangSC-Medium';
          font-weight: 500;
          font-size: 18px;
          color: #504E4E;
          line-height: 25px;
          font-style: normal;
          text-transform: none;
        }
        .list-item{
          width: 974px;
          height: 110px;
          display: flex;
          align-items: center;
          padding-left: 29px;
          border-bottom: 1px solid #EFEFEF;
          .list-select-image{
            margin-right: 20px;
            :deep(.ant-checkbox-inner){
              width: 20px;
              height: 20px;
            }
          }
          :deep(.list-item-image){
            width: 70px;
            height: 70px;
            object-fit: contain;
            border-radius: 5px;
            background-color: rgb(24,24,28);
          }
          .list-item-span{
            width: 220px;
            font-family: 'PingFangSC-Regular';
            font-weight: 400;
            font-size: 16px;
            color: #040404;
            line-height: 22px;
            font-style: normal;
            margin-left: 20px;
            margin-right: 51px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .list-item-size{
            width: 138px;
            font-family: 'PingFangSC-Regular';
            font-weight: 400;
            font-size: 16px;
            color: #171717;
            line-height: 22px;
            text-align: center;
            font-style: normal;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .list-item-time{
            font-family: 'PingFangSC-Regular';
            font-weight: 400;
            font-size: 16px;
            color: #171717;
            line-height: 22px;
            text-align: center;
            font-style: normal;
            margin-left: 60px;
          }
        }
        .list-content{
          height: 388px;
          overflow: auto;
          scrollbar-width: none;
          ::-webkit-scrollbar {
            width: 0;
            height: 0;
          }
        }
      }
      .pagination-div{
        height: 80px;
        display: flex;
        align-items: center;
        justify-content: end;
        padding-right: 73px;
      }
    }
  }
  .button-div{
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 73px;
  }
}
</style>
