<template>
  <div class="app-container" >
    <div class="left-content">
      <div style="margin-bottom: 20px;">图片目录：</div>
      <el-tree :data="cates" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
    </div>
    <div class="right-content" v-loading="tableLoading">
      <el-form :model="query" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="图片标题" prop="imageTitle">
        <el-input
          v-model="query.imageTitle"
          placeholder="请输入图片标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryTable">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQueryTable">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleUpload"
        >上传</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getTableList"></right-toolbar>
    </el-row>
    <div class="image-list">
      <ImageItem v-for="(item, index) in tableData" :key="index" :item="item" class="image-item" @goDetail="showImageViewer($event, index, item)"></ImageItem>
    </div>
    <!-- 表格页脚 -->
    <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="page.pageNum"
        :limit.sync="page.pageSize"
        @pagination="getTableList"
      />
    </div>
    
      <MyImageViewer ref="previewImage" :z-index="2000"
      :files="images" :options="{
        download: true,
        print: true,
        edit: true,
        check: true,
      }" @change="imageEditChange"></MyImageViewer>
      <!-- 添加或修改部门对话框 -->
    <el-dialog title="上传图片" :visible.sync="openLoad" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标签" prop="tagId">
              <el-select v-model="form.tagId" 
              style="width: 100%" @change="tagChange">
                <el-option v-for="item in tags" :key="item.id" :label="item.tagName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目录" prop="cataId">
              <treeselect
              v-model="form.cataId"
              :options="cates"
              :normalizer="normalizer"
              placeholder="选择目录"
              :allow-empty="true"
            />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图片标题" prop="imageTitle">
              <el-input v-model="form.imageTitle" placeholder="请输入图片标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关键词" prop="keyWords">
              <el-input v-model="form.keyWords" placeholder="请输入图片关键词" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="拍摄时间" prop="photoTime">
              <el-date-picker
                v-model="form.photoTime"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传时间" prop="uploadTime">
              <el-date-picker
                v-model="form.uploadTime"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-upload
          v-if="openLoad"
          ref="upload"
          class="avatar-uploader"
          :action="uploadFileUrl"
          :show-file-list="false"
          :on-change="handleFileChange"
          :on-success="handleFileSuccess"
          :on-error="handleFileError"
          :auto-upload="false"
          :headers="headers"
          :data="uploadData"
          :limit="1" accept=".png,.jpg,.jpeg,.gif">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-loading="uploading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ImageItem from './components/ImageItem.vue';
import tableMixin from '../../../mixins/table-mixin';
import { listCata } from "@/api/gallery/cata";
import { pageListImages } from "@/api/gallery/images";
import { getToken } from "@/utils/auth";
import { formatDateStr } from "@/utils";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listTag } from "@/api/system/tag";

export default {
  name: 'List',
  components: {
    ImageItem,
    Treeselect
  },
  mixins: [tableMixin],
  pageInfo: {
    title: '图片列表',
    exportUrl: '',
    pageListApi: pageListImages,
  },
  props: {
    isPerson: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tags: [],
      cates: [],
      defaultProps: {
        children: 'children',
        label: 'cataName'
      },
      openLoad: false,
      form: {
        imageTitle: null,
        photoTime: null,// 图片拍摄时间,
        uploadTime: formatDateStr(),
        isOpen: this.isPerson ? 0:1,
        keyWords: '日常',
        cataId: null,
      },
      rules: {
        imageTitle: [{ required: true, message: '请输入图片标题', trigger: 'blur' }],
        photoTime: [{ required: true, message: '请输入图片拍摄时间', trigger: 'change' }],
        uploadTime: [{ required: true, message: '请输入上传时间', trigger: 'change' }],
        cataId: [{ required: true, message: '请选择图片目录', trigger: 'change' }]
      },
      imageUrl: '',
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/gallery/images/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      uploading: false,
    };
  },
  computed: {
    uploadData() {
      const params = {};
      Object.keys(this.form).forEach(key => {
        if (this.form[key] !== null) {
          params[key] = this.form[key];
        }
      });
      return params;
    },
    images() {
      return this.tableData.map(item => {
        return item.file?.[0] || {};
      });
    }
  },
  created() {
    listCata().then(res => {
      const list = res.data || [];
      this.cates = list;
    });

    listTag().then(res => {
      const list = res.data || [];
      this.tags = list;
    });
    
  },
  methods: {
    MXCreated() {
      this.query.isOpen = this.isPerson ? '0':'';
},

normalizer(node) {
      return {
        id: node.id,
        label: node.cataName,
        children: node.children,
      };
    },
    tagChange(tagId) {
      const index = this.tags.findIndex(val => val.id === tagId);
      if (index > -1 && this.tags[index].saveDir) {
        this.form.cataId = this.tags[index].saveDir;
      }
    },
resetQueryTable() {
      this.$refs.multipleTable?.clearSort();
      this.tableSort = {};
      this.page = {
        ...this.MXDefaultPage()
      };

      this.query = { ...this.MXPageInfo().defaultQuery };
      this.query.isOpen = this.isPerson ? '0':'';
      this.getTableList();
    },
    imageEditChange() {
      this.getTableList();
    },
    showImageViewer(event, index, item) {
      console.log('showImageViewer');
      
      this.$refs.previewImage.open(index);

    },
    handleNodeClick(data) {
      console.log(data);
      if (this.query.cataId === data.id) {
        this.query.cataId = null; 
      } else {
        this.query.cataId = data.id;
      }
      this.getTableList();
    },
    handleUpload() {
      this.form = {
        imageTitle: null,
        photoTime: null,// 图片拍摄时间,
        uploadTime: formatDateStr(),
        isOpen: this.isPerson ? 0:1,
        keyWords: '日常',
        cataId: null,
      };
      this.imageUrl = '';
      this.openLoad = true;
    },
    cancel() {
      this.openLoad = false;
      this.uploading = false;
    },
    submitForm() {
      if (!this.imageUrl) {
        this.$message.error('请选择图片');
        return;
      }
       
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.uploading = true;
          this.$refs.upload.submit();
        }
      });
    },
    handleFileChange(file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      handleFileSuccess(res, file) {
        
        this.uploading = false;
        if (res.code === 200) {
          this.$message.success('上传成功');
          this.openLoad = false;
          this.getTableList();
        } else {
          this.$message.error(res.msg);
        }
        this.$refs.upload.clearFiles();
      },
      handleFileError() {
        this.$message.error('上传失败');
        this.uploading = false;
        this.$refs.upload.clearFiles();
      },
      beforeAvatarUpload(file) {
        const isImg = file.type.indexOf('image/') !== -1;

        if (!isImg) {
          this.$message.error('只能上传图片!');
        }
        return isImg;
      }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
}
.left-content {
  width: 300px;
  padding: 15px;
  border: #EEEEEE 1px solid;
  border-radius: 8px;
}

.right-content {
  width: 0;
  flex: 1;
  margin-left: 10px;
}
  .image-list {
    display: flex;
    flex-wrap: wrap;

    .image-item {
      width: 300px;
      margin: 0 15px 15px 0;
    }
  }

  .avatar-uploader ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader ::v-deep  .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>