<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="家族" prop="familyId">
        <!-- <el-select
          v-model="queryParams.familyId"
          placeholder="请选择家族"
          clearable
          size="small"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select> -->
        <el-tag v-if="family"
          ><span>{{ family.fullName }}</span></el-tag
        >
      </el-form-item>
      <el-form-item label="相簿" prop="albumId">
        <!-- <el-select
          v-model="queryParams.albumId"
          placeholder="请选择相簿"
          clearable
          size="small"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select> -->
        <el-tag v-if="album" type="danger"
          ><span>{{ album.title }}</span></el-tag
        >
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="cyan"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:familyPhoto:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-plus"
          size="mini"
          @click="batchUploadHandle"
          v-hasPermi="['system:familyPhoto:upload']"
          >批量上传</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:familyPhoto:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:familyPhoto:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:familyPhoto:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="photoList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="ID" align="center" prop="id" v-if="false" />
      <el-table-column label="家族" align="center" prop="familyId" />
      <el-table-column label="相簿" align="center" prop="albumId" /> -->
      <el-table-column label="url" align="center" prop="url">
        <template slot-scope="scope">
          <el-image
            class="lsw_square"
            :fit="'contain'"
            style="max-width: 80px; border-radius: 20%"
            :src="baseUrl + scope.row.url"
            :preview-src-list="[baseUrl + scope.row.url]"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" />

      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="状态"
        align="center"
        prop="status"
        :formatter="statusFormat"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:familyPhoto:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:familyPhoto:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改家族相簿照片对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="家族" prop="familyId">
          <el-select v-model="form.familyId" placeholder="请选择家族">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="相簿" prop="albumId">
          <el-select v-model="form.albumId" placeholder="请选择相簿">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item> -->

        <el-form-item label="图片" prop="url">
          <!-- <el-input v-model="form.url" placeholder="请输入url" /> -->
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="requestUpload"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.url" :src="baseUrl + form.url" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 批量上传对话框 -->
    <el-dialog
      title="批量上传图片"
      :visible.sync="openBatch"
      width="800px"
      append-to-body
    >
      <el-upload
        action="#"
        list-type="picture-card"
        :multiple="true"
        ref="batchUploadRef"
        :auto-upload="false"
      >
        <i slot="default" class="el-icon-plus"></i>
        <div slot="file" slot-scope="{ file }">
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <span
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
            >
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchUpload">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPhoto,
  getPhoto,
  delPhoto,
  addPhoto,
  updatePhoto,
  exportPhoto,
  batchUpload
} from "@/api/system/family/photo";
import { uploadFile } from "@/api/common/common";
import { listAlbum, getAlbum } from "@/api/system/family/album";
export default {
  name: "Photo",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 家族相簿照片表格数据
      photoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        familyId: null,
        albumId: null,
        title: null,
        url: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        familyId: [
          { required: true, message: "家族不能为空", trigger: "change" }
        ],
        albumId: [
          { required: true, message: "相簿不能为空", trigger: "change" }
        ],
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        url: [{ required: true, message: "url不能为空", trigger: "blur" }]
      },
      familyId: undefined,
      family: undefined,
      albumId: undefined,
      album: undefined,
      baseUrl: undefined,
      openBatch: false
    };
  },
  activated() {
    this.init();
  },
  mounted() {
    this.baseUrl = process.env.VUE_APP_BASE_API;
    this.init();
    this.getDicts("sys_show_hide").then(response => {
      this.statusOptions = response.data;
    });
    //this.getFamilyOptions();
  },
  methods: {
    init() {
      this.familyId = this.$route.query.fid;

      this.albumId = this.$route.query.albid;
      if (this.familyId) {
        this.queryParams.familyId = this.familyId;
      }
      if (this.albumId) {
        this.queryParams.albumId = this.albumId;
        this.getAlbumById(this.albumId);
      }
      this.getList();
    },

    /**获取单个家族信息 */
    // getFamilyById(_familyId) {
    //   getFamily(_familyId).then((res) => {
    //     this.family = res.data;
    //   });
    // },

    //获取家族列表
    // getFamilyOptions() {
    //   var _params = {
    //     pageNum: 1,
    //     pageSize: 10000000,
    //   };
    //   listFamily(_params).then((res) => {
    //     if (res.code == 200) {
    //       this.familyOptions = res.rows;
    //     }
    //   });
    // },
    /**获取单个相册信息 */
    getAlbumById(_albumId) {
      getAlbum(_albumId).then(res => {
        this.album = res.data;
        this.family = this.album.family;
      });
    },

    /** 查询家族相簿照片列表 */
    getList() {
      this.loading = true;
      listPhoto(this.queryParams).then(response => {
        this.photoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openBatch = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        familyId: null,
        albumId: null,
        title: null,
        url: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        status: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加家族相簿照片";
      this.form.familyId = this.familyId;
      this.form.albumId = this.albumId;
      this.form.status = "0";
      this.form.delFlag = 0;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPhoto(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改家族相簿照片";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePhoto(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addPhoto(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除家族相簿照片编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delPhoto(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有家族相簿照片数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportPhoto(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        })
        .catch(function() {});
    },
    //自定义上传
    requestUpload(data) {
      console.log(data);
      let formData = new FormData();
      let _title = data.file.name;
      _title = _title.substring(0, _title.lastIndexOf("."));

      this.form.title = _title;
      formData.append("file", data.file);
      formData.append(
        "modName",
        "family/" + this.family.code + "/" + this.albumId
      );
      uploadFile(formData).then(response => {
        if (response.code === 200) {
          this.form.url = response.fileName;
        }
      });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type.indexOf("image/") == -1;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (isJPG) {
        this.$message.error("只能上传图片");
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
      }
      return !isJPG && isLt2M;
    },
    batchUploadHandle() {
      this.openBatch = true;
    },
    handleRemove(file) {
      let refs = this.$refs.batchUploadRef;
      refs.uploadFiles.forEach((item, index) => {
        if (item.uid == file.uid) {
          refs.uploadFiles.splice(index, 1);
        }
      });
    },
    //批量上传图片
    submitBatchUpload() {
      let uploading = this.$loading({
        lock: true,
        text: "正在上传中……",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });



      let refs = this.$refs.batchUploadRef;

      let formData = new FormData();

      refs.uploadFiles.forEach((item, index) => {
        formData.append("files", item.raw);
      });
      formData.append("albumId",this.albumId);
      formData.append(
        "modName",
        "family/" + this.family.code + "/" + this.albumId
      );
      batchUpload(formData).then(response => {
        if (response.code === 200) {

          this.cancel();
          this.handleQuery();
        }
        uploading.close();
      });
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin: 10px;
}
.avatar-uploader .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>
