<template>
  <div v-if="type == 'image'">
    <ul v-for="(item,index) in value" :key="index" class="el-upload-list el-upload-list--picture-card">
      <li tabindex="0" class="el-upload-list__item is-ready" :style="'width: '+width+'px;height: '+height+'px'">
        <div>
          <img :src="item" alt="" class="el-upload-list__item-thumbnail">
          <span class="el-upload-list__item-actions">
            <span v-if="index != 0" class="el-upload-list__item-preview" @click="moveMaterial(index,'up')">
              <i class="el-icon-back" />
            </span>
            <span class="el-upload-list__item-preview" @click="zoomMaterial(index)">
              <i class="el-icon-view" />
            </span>
            <span class="el-upload-list__item-delete" @click="deleteMaterial(index)">
              <i class="el-icon-delete" />
            </span>
            <span v-if="index != value.length-1" class="el-upload-list__item-preview" @click="moveMaterial(index,'down')">
              <i class="el-icon-right" />
            </span>
          </span>
        </div>
      </li>
    </ul>
    <div v-if="num > value.length" tabindex="0" class="el-upload el-upload--picture-card" :style="'width: '+width+'px;height: '+height+'px;'+'line-height:'+height+'px;'" @click="toSeleteMaterial">
      <i class="el-icon-plus" />
    </div>
    <!-- 查看 -->
    <el-dialog
      append-to-body
      :visible.sync="dialogVisible"
      width="35%"
    >
      <img :src="url" alt="" style="width: 100%">
    </el-dialog>
    <!-- 素材列表 -->
    <el-dialog
    @close="clos"
      title="图片素材库"
      append-to-body
      :visible.sync="listDialogVisible"
      width="70%"

    >
      <el-container style="height: 600px;">
        <el-aside width="unset">
          <div style="margin-bottom: 10px">
            <el-button
              class="el-icon-plus"
              size="small"
              @click="materialgroupAdd()"
            >
              添加分组
            </el-button>
          </div>
          <div class="group-list">
            <div class="group-item" v-for="(group) in materialGroupList">
                <el-button  @click="selectGroup(group)" type="primary" plain >{{group.name}}</el-button>
            </div>
          </div>
        </el-aside>
        <el-main>
          <el-card>
            <div slot="header">
              <el-row>
                <el-col :span="12">
                  <span>{{ materialGroup.name }}</span>
                  <span v-if="materialGroup.groupId >0">
                    <el-button size="small" type="text" class="el-icon-edit" style="margin-left: 10px;" @click="materialgroupEdit(materialGroup)">重命名</el-button>
                    <el-button size="small" type="text" class="el-icon-delete" style="margin-left: 10px;color: red" @click="materialgroupDelete(materialGroup)">删除</el-button>
                  </span>
                </el-col>
                <el-col :span="12" style="text-align: right;">
                  <el-upload
                    :action="uploadUrl"
                    :file-list="[]"
                    :on-progress="handleProgress"
                    :before-upload="beforeUpload"
                    :on-success="handleSuccess"
                    :data="{type: 1}"
                    multiple
                  >
                    <el-button size="small" type="primary">批量上传</el-button>
                  </el-upload>
                </el-col>
              </el-row>
            </div>
            <div v-loading="tableLoading">
              <el-alert
                v-if="tableData.length <= 0"
                title="暂无数据"
                type="info"
                :closable="false"
                center
                show-icon
              />
              <el-row :gutter="5">
                <el-checkbox-group v-model="urls" :max="num - value.length">
                  <el-col v-for="(item,index) in tableData" :key="index" :span="4">
                    <el-card :body-style="{ padding: '5px' }">
                      <el-image
                        style="width: 100%;height: 100px"
                        :src="item.url"
                        fit="contain"
                        :preview-src-list="[item.url]"
                        :z-index="9999"
                      />
                      <div>
                        <el-checkbox class="material-name" :label="item.url">
                          选择
                        </el-checkbox>
                        <el-row>
                          <el-col :span="24" class="col-do">
                            <el-button type="text" size="medium" @click="materialDel(item)">删除</el-button>
                          </el-col>
                        </el-row>

                      </div>
                    </el-card>
                  </el-col>
                </el-checkbox-group>
              </el-row>
               <pagination
                  v-show="total>0"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getMaterialList"
                />

            </div>
          </el-card>
        </el-main>
      </el-container>
      <span slot="footer" class="dialog-footer">
        <el-button @click="listDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial, exportMaterial } from "@/api/store/material";
import { getAllMaterialGroup,listMaterialGroup, getMaterialGroup, delMaterialGroup, addMaterialGroup, updateMaterialGroup, exportMaterialGroup } from "@/api/store/materialGroup";
import { Loading } from 'element-ui';
export default {
  name: 'ImageSelect',
  props: {
    // 素材数据
    value: {
      type: Array,
      default() {
        return []
      }
    },
    // 素材类型
    type: {
      type: String
    },
    // 素材限制数量，默认5个
    num: {
      type: Number,
      default() {
        return 5
      }
    },
    // 宽度
    width: {
      type: Number,
      default() {
        return 150
      }
    },
    // 宽度
    height: {
      type: Number,
      default() {
        return 150
      }
    }
  },
  data() {
    return {
      finalQuality:1,
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      dialogVisible: false,
      url: '',
      listDialogVisible: false,
      materialGroupList: [],
      materialGroupLoading: false,
      materialGroup:{},
      tableData: [],
      resultNumber: 0,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        groupId: null,
        name: null,
        url: null,
        isDel: null,
        createUserId: null,
      },
      tableLoading: false,
      urls: []
    }
  },
  mounted(){
    this.getAllMaterialGroup();
  },
  methods: {
    clos(){
      this.urls=[];
    },
    selectGroup(item){
      this.materialGroup=item;
      this.queryParams.groupId=item.groupId;
      this.getMaterialList();
    },
    materialgroupAdd() {
      const that = this
      this.$prompt('请输入分组名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        addMaterialGroup({
          name: value
        }).then(function() {
          that.materialGroup={};
          that.getAllMaterialGroup()
        })
      }).catch(() => {

      })
    },
    materialgroupDelete(materialgroupObj) {
      const that = this
      this.$confirm('是否确认删除该分组？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        delMaterialGroup(materialgroupObj.groupId)
          .then(function() {
            that.materialGroup={};
            that.getAllMaterialGroup()
          })
      })
    },
    materialgroupEdit(materialgroupObj) {
      const that = this
      this.$prompt('请输入分组名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: materialgroupObj.name
      }).then(({ value }) => {
        updateMaterialGroup({
          groupId: materialgroupObj.groupId,
          name: value
        }).then(function() {
          that.materialGroup={};
          that.getAllMaterialGroup()
        })
      }).catch(() => {

      })
    },
    getAllMaterialGroup() {
      this.materialGroupLoading = true;
      getAllMaterialGroup({}).then(response => {
        this.materialGroupList = response.data
        console.log(this.materialGroupList)
        this.materialGroupLoading = false;
      });
    },
    getMaterialList() {
      this.tableLoading = true;
      listMaterial(this.queryParams).then(response => {
        this.tableData = response.rows;
        this.total = response.total;
        this.tableLoading = false;
      });
    },
    moveMaterial(index, type) {
      if (type == 'up') {
        const tempOption = this.value[index - 1]
        this.$set(this.value, index - 1, this.value[index])
        this.$set(this.value, index, tempOption)
      }
      if (type == 'down') {
        const tempOption = this.value[index + 1]
        this.$set(this.value, index + 1, this.value[index])
        this.$set(this.value, index, tempOption)
      }
    },
    zoomMaterial(index) {
      this.dialogVisible = true
      this.url = this.value[index]
    },
    deleteMaterial(index) {
      const that = this
      this.$confirm('是否确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        that.value.splice(index, 1)
        that.urls = []
      })
    },
    toSeleteMaterial() {
      this.listDialogVisible = true
      this.getAllMaterialGroup()
      this.getMaterialList();
    },
    materialDel(item) {
      const that = this
      this.$confirm('是否确认删除该素材？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        delMaterial(item.materialId)
          .then(function() {
            that.queryParams.pageNum=0;
            that.getMaterialList();
          })
      })
    },
    handleProgress(event, file, fileList) {
    },
    handleSuccess(response, file, fileList) {
      const that = this
      addMaterial({
        type: '1',
        groupId: this.queryParams.groupId,
        name: file.name,
        url: response.url
      }).then(() => {
        this.resultNumber++
        if (fileList.length === this.resultNumber) {
          that.getMaterialList()
          this.resultNumber = 0
        }
      })
    },
    beforeUpload(file) {
      const isPic =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'image/jpg'
      // const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPic) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG、GIF 格式!')
        return false
      }
      return new Promise((resolve, reject) => {
        if (file.size / 1024 / 1024 > 3) {
          this.$message.error('上传的图片不能超过3MB');
          reject();
          return;
        }
        if (file.size / 1024 / 1024 > 1) {
          const loadingInstance = Loading.service({ text: '图片内存过大正在压缩图片...' });
          // 文件大于1MB时进行压缩
          this.compressImage(file).then((compressedFile) => {
            loadingInstance.close();
            if (compressedFile.size / 1024 > 500) {
              this.$message.error('图片压缩后仍大于500KB');
              reject();
            } else {
              // this.$message.success(`图片压缩成功，最终质量为: ${this.finalQuality.toFixed(2)}`);
              console.log(`图片压缩成功，最终质量为: ${this.finalQuality.toFixed(2)}`);
              console.log(`最终内存大小为: ${(compressedFile.size/1024).toFixed(2)}KB`);
              resolve(compressedFile);
            }
          }).catch((err) => {
            loadingInstance.close();
            console.error(err);
            reject();
          });
        } else {
          resolve(file);
        }
        // this.loading = this.$loading({
        //   lock: true,
        //   text: "上传中",
        //   background: "rgba(0, 0, 0, 0.7)",
        // });
      });
    },
    compressImage(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (event) => {
          const img = new Image();
          img.src = event.target.result;
          img.onload = () => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const width = img.width;
            const height = img.height;
            canvas.width = width;
            canvas.height = height;
            ctx.drawImage(img, 0, 0, width, height);

            let quality = 1; // 初始压缩质量
            let dataURL = canvas.toDataURL('image/jpeg', quality);
            
            // 逐步压缩，直到图片大小小于500KB并且压缩质量不再降低
            while (dataURL.length / 1024 > 500 && quality > 0.1) {
              quality -= 0.01;
              dataURL = canvas.toDataURL('image/jpeg', quality);
            }
            this.finalQuality = quality; // 存储最终的压缩质量
            
            if (dataURL.length / 1024 > 500) {
              reject(new Error('压缩后图片仍然大于500KB'));
              return;
            }

            const arr = dataURL.split(',');
            const mime = arr[0].match(/:(.*?);/)[1];
            const bstr = atob(arr[1]);
            let n = bstr.length;
            const u8arr = new Uint8Array(n);
            while (n--) {
              u8arr[n] = bstr.charCodeAt(n);
            }
            const compressedFile = new Blob([u8arr], { type: mime });
            compressedFile.name = file.name;
            resolve(compressedFile);
          };
          img.onerror = (error) => {
            reject(error);
          };
        };
        reader.onerror = (error) => {
          reject(error);
        };
      });
    },
    submit() {

      this.urls.forEach(item => {
        this.$set(this.value, this.value.length, item)
      })
      this.listDialogVisible = false
      this.urls = []
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  ::v-deep .el-icon-circle-close{
    color: red;
  }
  .material-name{
    padding: 8px 0px;
  }
  .col-do{
    text-align: center;
  }
  .button-do{
    padding: unset!important;
    font-size: 12px;
  }
  .group-list{
    display: flex;
    flex-direction:column;
    align-items: flex-start;
  }
  .group-item{
    margin: 5px;
  }
</style>
