<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 label="拍摄时间" prop="photoTime">
        <el-date-picker
                v-model="form.photoTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
              ></el-date-picker>
      </el-form-item>
      <el-form-item label="上传人员" prop="userId">
        <el-input
          v-model="query.userId"
          placeholder="请输入上传人员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标签" prop="label">
        <el-input
          v-model="query.label"
          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-button
                type="reset"
                icon="el-icon-download"
                @click="handleExport"
              >导出
              </el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-switch
          v-model="switchType"
          active-text="方格模式"
          inactive-text="列表模式">
        </el-switch>
      </el-col>
      <!-- <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" v-if="switchType">
      <ImageItem v-for="(item, index) in tableData" :key="index" :item="item" class="image-item" @goDetail="showImageViewer($event, index)"></ImageItem>
    </div>
    <el-table
      v-else
        ref="multipleTable"
        tooltip-effect="dark"
        :data="tableData"
        class="w100p"
        border
        header-cell-class-name="duojibiaotou"
      >
        <el-table-column
          align="center"
          label="图片"
          show-overflow-tooltip
          min-width="160"
          prop="taskTitle"
        >
        <template slot-scope="scope">
          <img style="width: 160px;height: 100px;" :src="getImageUrl(scope.row)" />
          <div class="image-name">{{ imageName(scope.row) }}</div>
        </template>
        
      </el-table-column>
        <el-table-column label="图片标题" align="center" prop="imageTitle" min-width="100">
        </el-table-column>
        <el-table-column label="拍摄时间" align="center" prop="uploadTime" min-width="100">
        </el-table-column>
        
      </el-table>
    <!-- 表格页脚 -->
    <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"  @change="imageEditChange"></MyImageViewer>
      
  </div>
</template>

<script>
import ImageItem from '../list/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";

export default {
  name: 'List',
  components: {
    ImageItem
  },
  mixins: [tableMixin],
  pageInfo: {
    title: '图片列表',
    exportUrl: '',
    pageListApi: pageListImages,
  },
  props: {
    isPerson: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      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' }],
        cataId: [{ required: true, message: '请选择图片目录', trigger: 'change' }]
      },
      imageUrl: '',
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/gallery/images/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      uploading: false,
      switchType: 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;
    })
  },
  methods: {
    MXCreated() {
      this.query.isOpen = this.isPerson ? '0':'';
},
resetQueryTable() {
      this.$refs.multipleTable?.clearSort();
      this.tableSort = {};
      this.page = {
        ...this.MXDefaultPage()
      };

      this.query = { ...this.MXPageInfo().defaultQuery };
      this.query.isOpen = this.isPerson ? '0':'';
      this.getTableList();
    },
    imageName(item) {
      if (item.file?.length > 0) {
        return item.file[0].oldName || item.imageName;
      }
      return item.imageName;
    },
    getImageUrl(item) {
      let url = item.imagePath;
      if (item.file?.length > 0) {
        url = item.file[0].attachFileUrl || item.imagePath;
      }
      if (url.indexOf("http") === 0) {
          return url;
      }
      return process.env.VUE_APP_BASE_API + url;
    },
    imageEditChange() {
      this.getTableList();
    },
    showImageViewer(event, index) {
      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.$message.success('上传成功');
        this.openLoad = false;
        this.uploading = false;
        this.getTableList();
      },
      handleFileError() {
        this.$message.error('上传失败');
        this.uploading = false;
      },
      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>