<template>
  <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" append-to-body :visible.sync="dialogVisible" title="选择图片"
    width="80%">
    <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="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-form-item>
        </el-form>
        <el-table ref="multipleTable" tooltip-effect="dark" :data="tableData" height="500px" class="w100p" border
          header-cell-class-name="duojibiaotou" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column align="center" label="图片" show-overflow-tooltip 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>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
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: 'ImageChooseDialog',
  components: {
  },
  mixins: [tableMixin],
  pageInfo: {
    title: '图片列表',
    exportUrl: '',
    pageListApi: pageListImages,
  },
  props: {
    isPerson: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      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,
      selections: [],
    };
  },
  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: {
    open() {
      this.dialogVisible = true;

    },
    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();
    },
    handleSelectionChange(val) {
      this.selections = val || [];
    },
    confirm() {
      if (this.selections.length === 0) {
        this.$message.error('请选择图片');
        return;
      }

      this.$emit('confirm', this.selections);
      this.dialogVisible = false;
      // 清除选项
      this.$refs.multipleTable.clearSelection();
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  padding: 0;
  margin: 0;
}

.left-content {
  width: 200px;
  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;
  }
}
</style>.