<template>
  <div class="scroll">
    <div class="middle">
      <div class="filter">
        <div class="condition">
          <span>相册分类 :</span>
          <el-select
            clearable
            v-model="searchInput.categoryId"
            placeholder="请选择相册分类"
          >
            <el-option
              v-for="i in categoryData"
              :key="i.id"
              :label="i.name"
              :value="i.id"
            />
          </el-select>
        </div>
        <div class="condition">
          <span>上传人 :</span>
          <el-input
            clearable
            v-model.trim="searchInput.userName"
            class="w-50 m-2"
            placeholder="请输入上传人"
            style="width: 180px"
          />
        </div>
        <div class="condition">
          <span>上传时间 :</span>
          <el-date-picker
            v-model="searchInput.createTime"
            unlink-panels
            type="datetimerange"
            range-separator="-"
            start-placeholder="起始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择日期"
          />
        </div>
        <el-button
          style="margin-left: 20px"
          color="rgba(38, 151, 255, 1)"
          type="primary"
          class="search"
          @click="searchBtn"
          ><span>查询</span></el-button
        >
        <el-button @click="resetBtn" plain color="rgba(43, 153, 255, 1)"
          >重置</el-button
        >
      </div>
      <!-- 按钮列表 -->
      <div class="gongneng">
        <el-button
          type="primary"
          style="margin-left: 0"
          color="rgba(38, 151, 255, 1)"
          @click="addlist"
          >上传照片</el-button
        >
      </div>
    </div>
    <div class="footer" v-loading="loading">
      <el-table
        :row-class-name="tableRowClassName"
        :data="tableData.list"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        :header-cell-style="{
          background: 'rgba(240, 243, 247, 1)',
          height: '50px',
          border: 0,
        }"
      >
        <!-- <el-table-column type="selection" align="center" width="55" /> -->
        <el-table-column type="index" align="center" label="序号" width="80" />
        <el-table-column align="left" prop="school" label="照片">
          <template #default="{ row }">
            <div class="img-preview-list" v-if="row.images">
              <div
                class="img-item"
                style="width: 60px; height: 60px; margin: 10px 0"
              >
                <img
                  :src="row.images[0]"
                  alt="图片预览"
                  class="preview-img"
                  @click="handlePreview(row.images, 0)"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          width="140"
          align="center"
          prop="categoryName"
          label="相册分类"
        >
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="remark"
          label="照片描述"
        />
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="orgName"
          label="所属组织"
        />
        <el-table-column align="center" prop="userName" label="上传人" />
        <el-table-column align="center" prop="phone" label="联系方式" />
        <el-table-column align="center" prop="createTime" label="上传时间" />
        <el-table-column align="center" label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button type="primary" @click="updateS(row)" link
              >编辑</el-button
            >
            <el-button type="danger" @click="deleteS(row)" link>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div class="pageSize">
        <span></span>
        <el-pagination
          background
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]"
          layout="total,sizes, prev, pager, next, jumper, slot"
          :total="total"
          @size-change="handleSizeChange"
          @update:current-page="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <!-- 添加账号弹窗 -->
  <el-dialog
    class="addStaff"
    v-model="addDialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :title="dialongTitle"
    align-center
    width="640"
    :before-close="cancelAdd"
    destroy-on-close
    draggable
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      :size="formSize"
      label-position="right"
      status-icon
    >
      <el-form-item label="相册分类 :" prop="categoryId">
        <el-select
          clearable
          v-model="ruleForm.categoryId"
          placeholder="请选择相册分类"
        >
          <el-option
            v-for="i in categoryData"
            :key="i.id"
            :label="i.name"
            :value="`${i.id}-${i.name}`"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="照片描述 :" prop="remark">
        <el-input
          v-model.trim="ruleForm.remark"
          placeholder="请输入照片描述"
          clearable
          :autosize="{ minRows: 4 }"
          type="textarea"
        />
      </el-form-item>
      <el-form-item label="照片 :" prop="images">
        <div class="img-preview-list">
          <div
            class="img-item"
            v-for="(url, index) in ruleForm.images"
            :key="index"
          >
            <img
              :src="url"
              alt="图片预览"
              class="preview-img"
              @click="handlePreview(ruleForm.images, index)"
            />
            <span class="delete-btn" @click="handleDelete(index)">
              <el-icon><Delete /></el-icon>
            </span>
          </div>
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            class="upload-btn"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
            <span class="upload-txt">点击上传图片</span>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item class="options">
        <el-button @click="cancelAdd">取消</el-button>
        <el-button
          color="rgba(0, 97, 255, 1)"
          class="queding"
          type="primary"
          @click="submitAdd(ruleFormRef)"
        >
          确定
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import {
  ref,
  watch,
  reactive,
  nextTick,
  onBeforeMount,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { genFileId, ElMessage, ElMessageBox } from "element-plus";
import { dayjs } from "element-plus";
import lodash from "lodash";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import { storeToRefs } from "pinia";
import { useCounterStore } from "@/stores/index";
import { api as viewerApi } from "v-viewer";

import {
  getQueryImagePage,
  queryCategoryImages,
  insertWebImage,
  updateImage,
  deleteImageById,
} from "@/api/alumni-album";
import { uploadFile } from "@/api/uploadFile";

const router = useRouter();
const store = useCounterStore();

// 为避免解构时失去响应性
const { name, age, isCollapse, realAge, collegeRole } = storeToRefs(store);

const handleDelete = (index) => {
  ruleForm.images.splice(index, 1);
};

const handlePreview = (images, index) => {
  // 核心：复制数组，把点击的图片移到第一位
  const newImages = [...images]; // 拷贝原数组，避免修改原数据
  const currentImg = newImages.splice(index, 1)[0]; // 取出当前点击的图片
  newImages.unshift(currentImg); // 放到数组开头

  // 传给预览器，此时插件显示的第一张就是点击的图片
  viewerApi({
    images: newImages,
    zIndex: 3000,
  });
};

// 上传前的校验
const beforeUpload = (file) => {
  // 校验文件类型
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    ElMessage.error("只能上传图片格式文件");
    return false;
  }
  // 校验文件大小（2MB）
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过2MB");
    return false;
  }
  return true;
};

// 文件选择变化时触发
const handleFileChange = async (file, newFileList) => {
  console.log(file);
  let formData = new FormData();
  formData.append("file", file.raw);
  let res = await uploadFile(formData);
  // console.log(res.data.fileUrl);
  if (res.code == 200) {
    ruleForm.images.push(res.data.fileUrl); // 赋值给响应式fileList，页面自动刷新
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};

// 表格数据
const loading = ref(false);
const tableData = reactive({
  list: [{}],
});
const categoryData = ref(); // 相册分类

const dialongTitle = ref("新增账号"); // 弹窗标题

const searchInput = reactive({
  categoryId: null,
  userName: null,
  createTime: null,
}); // 搜索按钮数据

const currentPage = ref(1); // 当前页
const pageSize = ref(10);
const total = ref(0); // 当前总数
const selectIds = ref([]); // 勾选的全部数据

const addDialogVisible = ref(false); // 控制添加账号弹窗
const showPreview = ref(false);

// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  categoryId: "", //相册分类
  // categoryName: "",
  images: [],
  remark: "",
  id: "",
});
// 表单验证
const rules = reactive({
  categoryId: [
    { required: true, message: "校区名称不能为空", trigger: "blur" },
  ],
  images: [{ required: true, message: "楼栋名称不能为空", trigger: "blur" }],
});

// 获取账户列表
const getList = async () => {
  loading.value = true;
  let params = {
    currentPage: currentPage.value, // 当前页
    pageCount: pageSize.value, // 一页数据条数
    categoryId: searchInput.categoryId,
    userName: searchInput.userName,
  };
  if (searchInput.createTime) {
    params.startTime = searchInput.createTime[0];
    params.endTime = searchInput.createTime[1];
  }
  let res = await getQueryImagePage(params);
  console.log(res);
  if (res.code == 200) {
    tableData.list = res.data.list;
    total.value = res.data.totalCount;
    loading.value = false;
  } else {
    loading.value = false;
  }
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  currentPage.value = 1;
  getList();
}, 300);
const resetBtn = lodash.debounce(async () => {
  searchInput.categoryId = "";
  searchInput.userName = "";
  searchInput.createTime = null;
  currentPage.value = 1;
  getList();
}, 300);

// 添加账号
const addlist = () => {
  dialongTitle.value = "上传照片";
  addDialogVisible.value = true;
  ruleForm.categoryId = null;
  ruleForm.images = [];
  ruleForm.remark = null;
};
// 添加账号
const updateS = (row) => {
  console.log(row);
  dialongTitle.value = "编辑相片";
  addDialogVisible.value = true;
  ruleForm.categoryId = `${row.categoryId}-${row.categoryName}`;
  ruleForm.images = row.images;
  ruleForm.remark = row.remark;
  ruleForm.id = row.id;
};
const deleteS = async (row) => {
  ElMessageBox.confirm("是否删除此数据?", "提示!!!", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let params = {
        id: row.id,
      };
      let res = await deleteImageById(params);
      if (res.code == 200) {
        getList();
        ElMessage({
          type: "success",
          showClose: true,
          message: res.message,
          center: true,
        });
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.message,
          center: true,
        });
      }
    })
    .catch(() => {
      loading.value = false;
    });
};

// 确认添加员工
const submitAdd = lodash.debounce(async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let data = {
        categoryId: ruleForm.categoryId.split("-")[0],
        categoryName: ruleForm.categoryId.split("-")[1],
        images: ruleForm.images,
        remark: ruleForm.remark,
      };
      let res = "";
      if (dialongTitle.value == "上传照片") {
        res = await insertWebImage(data);
      } else {
        data.id = ruleForm.id;
        res = await updateImage(data);
      }
      if (res.code == 200) {
        addDialogVisible.value = false;
        ElMessage({
          type: "success",
          showClose: true,
          message: res.message,
          center: true,
        });
        getList();
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.message,
          center: true,
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
}, 1000);

const cancelAdd = () => {
  addDialogVisible.value = false;
  getList()
};

// 多选框功能
const handleSelectionChange = (val) => {
  // console.log(val);
  selectIds.value = val.map((i) => i.id);
  console.log(selectIds.value);
};

// 表格斑马纹颜色修改
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return "even";
  } else if (rowIndex % 2 !== 0) {
    return "odd";
  }
  return "";
};
// 每页显示条数
const handleSizeChange = (value) => {
  console.log(value, "每页显示条数");
  pageSize.value = value;
  getList();
};
// 分页
const handleCurrentChange = (value) => {
  // console.log(value);
  currentPage.value = value;
  getList();
};

const categoryList = async () => {
  let res = await queryCategoryImages();
  console.log(res, "相册分类下拉列表数据");
  if (res.code == 200) {
    categoryData.value = res.data;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};

onBeforeMount(() => {
  getList();
  categoryList();
});
onUnmounted(() => {
  // document.removeEventListener("keyup", Enters);
});
</script>

<style scoped lang="scss">
.scroll {
  width: calc(100% - 60px);
  height: calc(100% - 61px);
  margin: 0 auto;
  display: flex;
  flex-direction: column;

  .middle {
    width: calc(100%);
    color: #000;
    .filter {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      .search {
        margin-left: 0 !important;
        color: #fff;
      }
      .condition {
        display: flex;
        align-items: center;
        margin: 10px 30px 10px 0;
        :deep(.el-input .el-input__inner) {
          font-size: 14px;
        }
        .el-select {
          width: 220px;
        }
        span {
          margin: 0 10px 0 0;
        }
      }
    }
    .gongneng {
      margin: 10px 0;
      .el-button {
        color: #fff;
        margin-right: 15px;
      }
    }
  }
  .footer {
    width: calc(100%);
    flex: 1;
    margin: 0 auto;
    overflow: auto;

    .el-table--fit {
      height: calc(100% - 60px);
      :deep(.el-table__header-wrapper) {
        background-color: #000;
        font-size: 15px;
        color: #000;
        .cell {
          color: #000;
        }
      }
      :deep(.el-table__row) {
        height: 50px;
        font-size: 15px;
        color: #000;
      }
      :deep(.el-table__row td) {
        padding: 0;
        border: 0;
      }

      .el-button--primary {
        margin-left: 5px;
      }
      :deep(.el-table__body .even) {
        background-color: #fff;
      }
      :deep(.el-table__body .odd) {
        background-color: rgba(240, 243, 247, 1);
      }
    }

    .pageSize {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 0 30px;
      height: 60px;

      span {
        color: #000;
      }

      .el-pagination {
        // width: 1600px;
        :deep(.el-pagination__total) {
          color: #000;
        }

        :deep(.el-pagination__goto) {
          color: #000;
        }

        :deep(.el-pagination__classifier) {
          color: #000;
        }

        :deep(.el-input__wrapper) {
          border: 1px solid rgba(0, 0, 0, 1);
          border-radius: 5px;
          box-shadow: none;
        }

        :deep(.el-pager li) {
          margin: 0 5px;
          border: 1px solid rgba(0, 0, 0, 1);
          border-radius: 5px;
          background-color: transparent;
        }

        :deep(.el-pager li.is-active) {
          // background-color: rgba(0, 97, 255, 0.8);
          border: 1px solid rgba(0, 97, 255, 1);
          color: rgba(0, 97, 255, 1);
        }

        :deep(.btn-prev) {
          margin-right: 5px;
          border: 1px solid rgba(0, 0, 0, 1);
          border-radius: 5px;
          background-color: transparent;
        }

        :deep(.btn-next) {
          margin-left: 5px;
          border: 1px solid rgba(0, 0, 0, 1);
          border-radius: 5px;
          background-color: transparent;
        }
      }
    }
  }
}

// 添加员工弹窗样式
.addStaff {
  .el-dialog__body {
    padding: 20px 20px 10px 20px;
  }
}
</style>
