<template>
  <div class="app-container">
    <!-- <div class="app-container-search main-bgcolor main-radius">
    </div> -->
    <div class="app-container-list main-bgcolor main-radius shopping">
      <div
        style="
          font-size: 20px;
          font-weight: 600;
          padding-bottom: 16px;
          border-bottom: 1px solid #e3e6eb;
        "
      >
        素材管理
      </div>
      <div class="content-container">
        <div class="group-container">
          <div style="float: right; padding-bottom: 10px">
            <el-button type="primary" size="small" @click="handleCreateGroup()">
              添加分组
            </el-button>
          </div>
          <div>
            <el-input
              v-model="queryGroupParams.groupName"
              placeholder="请输入分组名称"
              @keyup.enter.native="handleSearchGroup()"
            ></el-input>
          </div>
          <div
            style="text-align: center; margin-top: 10px; font-weight: bold"
            v-loading="groupLoading"
          >
            <template v-if="groupList.length > 0">
              <div
                v-for="item in groupList"
                :key="item.id"
                style="display: flex"
                :class="selectedGroupId == item.id ? 'active-group' : ''"
              >
                <div
                  class="group-item-title"
                  @click="handleSelectGroup(item.id)"
                >
                  {{ item.groupName }}
                </div>

                <div style="width: 23px; float: right" v-if="item.id != 0">
                  <el-dropdown
                    @command="handleCommand($event, item.id)"
                    style="height: 16px; width: 30px"
                  >
                    <i
                      class="el-icon-more"
                      style="color: #409eff; cursor: pointer"
                    ></i>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="edit" style="color: #409eff">
                        编辑
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="del"
                        style="color: rgb(247, 68, 68)"
                      >
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </div>
            </template>
            <template v-else>
              <div style="margin-top: 50%; font-size: 16px; color: #409eff">
                暂无分组
              </div>
            </template>
          </div>
        </div>
        <div class="list-container">
          <div style="display: flex">
            <div style="width: 20%">
              <el-button
                type="primary"
                size="small"
                @click="handleCreateMaterial()"
              >
                上传图片
              </el-button>
            </div>
            <div style="width: 80%; display: flex; justify-content: flex-end">
              <el-switch
                v-model="selectAllFlag"
                active-text="全选"
                style="margin-top: 5px"
                @change="handleSelectAll"
              >
              </el-switch>
              <el-button
                type="danger"
                style="margin-left: 20px"
                size="small"
                @click="handleDeleteBatch()"
              >
                删除素材
              </el-button>
              <el-button
                style="margin-left: 20px"
                type="primary"
                size="small"
                @click="handleMoveGroupBatch()"
              >
                移动分组
              </el-button>
            </div>
          </div>
          <div v-loading="loading" class="material-list">
            <template v-if="list.length > 0">
              <div style="display: flex; flex-wrap: wrap">
                <div
                  v-for="item in list"
                  :key="item.id"
                  style="
                    margin-top: 10px;
                    margin-right: 15px;
                    border-radius: 5px;
                    border: #e3e6eb 1px solid;
                  "
                >
                  <div style="display: flex">
                    <el-dropdown
                      @command="handleCommandItem($event, item.id)"
                      style="
                        position: absolute;
                        z-index: 200;
                        margin-left: 128px;
                        margin-top: 3px;
                        height: 7px;
                        width: 24px;
                      "
                    >
                      <i
                        class="el-icon-more"
                        style="cursor: pointer; position: absolute"
                      ></i>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="move" style="color: #409eff">
                          移动
                        </el-dropdown-item>
                        <el-dropdown-item
                          command="rename"
                          style="color: #409eff"
                        >
                          重命名
                        </el-dropdown-item>
                        <el-dropdown-item
                          command="del"
                          style="color: rgb(247, 68, 68)"
                        >
                          删除
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                    <el-image
                      style="width: 150px; height: 120px"
                      :src="item.materialUrl"
                      fit="scale-down"
                      :preview-src-list="[item.materialUrl]"
                    ></el-image>
                  </div>
                  <div
                    style="
                      text-align: center;
                      font-size: 12px;
                      border-top: #e3e6eb 1px solid;
                      width: 150px;
                      display: flex;
                    "
                  >
                    <div style="width: 30px; height: 20px; margin-top: 2px">
                      <input
                        type="checkbox"
                        @change="handleSelectItem(item.id)"
                        :checked="ids.includes(item.id)"
                      />
                    </div>
                    <div
                      class="hiddenText"
                      style="width: 120px"
                      :title="item.materialName"
                    >
                      {{ item.materialName }}
                    </div>
                  </div>
                </div>
              </div>
            </template>
            <template v-else>
              <div>
                <el-empty description="暂无数据"></el-empty>
              </div>
            </template>
          </div>

          <!-- 分页组件 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNo"
            :limit.sync="queryParams.pageSize"
            @pagination="handleSearch"
          />
        </div>
      </div>

      <!-- 分组弹窗 -->
      <el-dialog
        class="add-dialog"
        :title="groupDialog.title"
        :visible.sync="groupDialog.open"
        width="500px"
      >
        <el-form
          :model="groupForm"
          :rules="groupRules"
          label-width="100px"
          ref="groupForm"
        >
          <el-form-item label="分组名称：" prop="groupName">
            <el-input
              v-model="groupForm.groupName"
              aria-placeholder="请输入分组名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="groupSubmitForm">确 定</el-button>
          <el-button @click="groupCancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 素材弹窗 -->
      <el-dialog
        class="add-dialog"
        :title="dialog.title"
        :visible.sync="dialog.open"
        width="800px"
        v-if="dialog.open"
        @close="cancel"
      >
        <el-form
          :model="form"
          :rules="rules"
          label-width="150px"
          ref="form"
          label-position="top"
          style="padding: 0 20px"
        >
          <template v-if="dialog.title === '上传图片'">
            <el-form-item label="上传分组：" prop="groupId">
              <el-select
                v-model="form.groupId"
                aria-placeholder="请选择分组"
                style="width: 350px"
              >
                <template v-for="item in groupList">
                  <el-option
                    :key="item.id"
                    :label="item.groupName"
                    :value="item.id"
                    v-if="item.id != 0"
                  />
                </template>
              </el-select>
            </el-form-item>
            <el-form-item
              label="上传图片(最多上传10张，上传图片名称不能超过64个字符)"
              prop="materialUrlList"
            >
              <imageUpload2
                v-model="form.materialUrlList"
                :limit="10"
                :fileSize="10"
                :fileType="['png', 'jpg', 'jpeg', 'gif', 'svg']"
              />
            </el-form-item>
          </template>
          <template v-if="dialog.title === '重命名'">
            <el-form-item label="素材名称：" prop="materialName">
              <el-input
                v-model="form.materialName"
                aria-placeholder="请输入素材名称"
              ></el-input>
            </el-form-item>
          </template>
          <template
            v-if="
              dialog.title === '移动分组' || dialog.title === '批量移动分组'
            "
          >
            <el-form-item label="移动分组至：" prop="groupId">
              <el-select
                v-model="form.groupId"
                aria-placeholder="请选择分组"
                style="width: 350px"
              >
                <template v-for="item in groupList">
                  <el-option
                    :key="item.id"
                    :label="item.groupName"
                    :value="item.id"
                    v-if="item.id != 0"
                  />
                </template>
              </el-select>
            </el-form-item>
          </template>
        </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>
    </div>
  </div>
</template>

<script>
import ImageUpload2 from "@/components/ImageUpload2";

import {
  getMaterialManagementPage,
  getMaterialManagement,
  createMaterialManagement,
  updateMaterialManagement,
  updateMaterialManagementGroupBatch,
  deleteMaterialManagement,
  deleteMaterialManagementBatch,
  getMaterialGroupList,
  getMaterialGroup,
  createMaterialGroup,
  updateMaterialGroup,
  deleteMaterialGroup,
} from "@/api/configure/materialManagement";

export default {
  name: "materialManagement",
  components: {
    ImageUpload2,
  },
  data() {
    return {
      // 全选状态
      selectAllFlag: false,
      // 遮罩层
      loading: true,
      groupLoading: true,
      // 列表
      list: [],
      // 分组列表
      groupList: [],
      // 弹出层
      dialog: {
        open: false,
        title: "",
      },
      groupDialog: {
        open: false,
        title: "",
      },
      queryParams: {
        pageNo: 1,
        pageSize: 10,
      },
      queryGroupParams: {
        groupName: null,
      },
      total: 0,
      // 表单参数
      form: {},
      groupForm: {},
      // 表单校验
      rules: {
        materialName: [
          { required: true, message: "请输入素材名称", trigger: "blur" },
          {
            min: 1,
            max: 64,
            message: "长度在 1 到 64 个字符",
            trigger: "blur",
          },
        ],
        groupId: [{ required: true, message: "请选择分组", trigger: "blur" }],
        materialUrlList: [
          { required: true, message: "请上传图片", trigger: "blur" },
        ],
      },
      groupRules: {
        groupName: [
          { required: true, message: "请输入分组名称", trigger: "blur" },
          {
            min: 1,
            max: 12,
            message: "长度在 1 到 12 个字符",
            trigger: "blur",
          },
        ],
      },
      ids: [],
      selectedGroupId: 0,
    };
  },
  created() {
    this.handleSearchGroup();
    this.handleSearch();
  },
  methods: {
    // 全选
    handleSelectAll() {
      if (this.selectAllFlag) {
        this.ids = this.list.map((item) => item.id);
      } else {
        this.ids = [];
      }
    },
    // 选择素材
    handleSelectItem(id) {
      if (this.ids.includes(id)) {
        this.ids = this.ids.filter((item) => item != id);
      } else {
        this.ids.push(id);
      }
      // console.log(this.ids);
    },

    // 获取素材列表
    handleSearch() {
      this.loading = true;
      this.ids = [];
      this.selectAllFlag = false;
      getMaterialManagementPage(this.queryParams).then((res) => {
        this.list = res.data.list;
        this.total = res.data.total;
        this.loading = false;
      });
    },

    // 获取分组列表
    handleSearchGroup() {
      this.groupLoading = true;
      getMaterialGroupList(this.queryGroupParams).then((res) => {
        if (res.data.length > 0 && !this.queryGroupParams.groupName) {
          this.groupList = [{ groupName: "全部", id: 0 }, ...res.data];
        } else {
          this.groupList = res.data;
        }
        this.groupLoading = false;
      });
    },

    // 选择分组
    handleSelectGroup(groupId) {
      this.loading = true;
      this.selectedGroupId = groupId;
      this.ids = [];
      this.selectAllFlag = false;
      this.queryParams = {
        pageNo: 1,
        pageSize: 10,
        groupId: groupId == 0 ? null : groupId,
      };
      getMaterialManagementPage(this.queryParams).then((res) => {
        this.list = res.data.list;
        this.total = res.data.total;
        this.loading = false;
      });
    },

    // 添加分组
    handleCreateGroup() {
      this.groupForm = {};
      this.groupDialog = {
        open: true,
        title: "添加分组",
      };
    },

    // 添加素材
    handleCreateMaterial() {
      this.form = {
        groupId: this.selectedGroupId == 0 ? null : this.selectedGroupId,
      };
      this.dialog = {
        open: true,
        title: "上传图片",
      };
    },

    // 编辑分组
    handleUpdateGroup(id) {
      this.groupForm = {};

      getMaterialGroup(id).then((res) => {
        this.groupForm = res.data;
        this.groupDialog = {
          open: true,
          title: "编辑分组",
        };
      });
    },

    // 重命名素材
    handleUpdateMaterialName(id) {
      this.form = {};
      getMaterialManagement(id).then((res) => {
        this.form = {
          id: res.data.id,
          materialName: res.data.materialName,
        };
        this.dialog = {
          open: true,
          title: "重命名",
        };
      });
    },

    // 删除分组
    handleDeleteGroup(id) {
      this.$confirm("此操作将永久删除该分组, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteMaterialGroup(id).then((res) => {
            this.$message.success("删除分组成功");
            this.handleSearchGroup();
          });
        })
        .catch(() => {});
    },

    // 删除素材
    handleDeleteMaterial(id) {
      this.$confirm("此操作将永久删除该素材, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteMaterialManagement(id).then((res) => {
            this.$message.success("删除素材成功");
            this.handleSearch();
          });
        })
        .catch(() => {});
    },

    // 移动分组
    handleMoveGroup(id) {
      this.form = {};
      getMaterialManagement(id).then((res) => {
        this.form = {
          id: res.data.id,
          groupId: res.data.groupId,
        };
        this.dialog = {
          open: true,
          title: "移动分组",
        };
      });
    },

    // 批量移动分组
    handleMoveGroupBatch() {
      if (this.ids.length == 0) {
        this.$message.error("请选择要移动的素材");
        return;
      }
      this.form = {};
      this.dialog = {
        open: true,
        title: "批量移动分组",
      };
    },

    // 分组下拉菜单 command
    handleCommand(command, id) {
      switch (command) {
        case "edit":
          this.handleUpdateGroup(id);
          break;
        case "del":
          this.handleDeleteGroup(id);
          break;
        default:
          break;
      }
    },

    // 素材下拉菜单 command
    handleCommandItem(command, id) {
      switch (command) {
        case "move":
          this.handleMoveGroup(id);
          break;
        case "rename":
          this.handleUpdateMaterialName(id);
          break;
        case "del":
          this.handleDeleteMaterial(id);
          break;
        default:
          break;
      }
    },

    // 提交分组表单
    groupSubmitForm() {
      this.$refs["groupForm"].validate((valid) => {
        if (valid) {
          if (this.groupForm.id != null) {
            updateMaterialGroup(this.groupForm).then((res) => {
              this.$message.success("编辑分组成功");
              this.groupDialog.open = false;
              this.handleSearchGroup();
            });
          } else {
            createMaterialGroup(this.groupForm).then((res) => {
              this.$message.success("添加分组成功");
              this.groupDialog.open = false;
              this.handleSearchGroup();
            });
          }
        } else {
          return;
        }
      });
    },

    // 关闭分组弹窗
    groupCancel() {
      this.groupDialog.open = false;
    },

    //提交素材表单
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.dialog.title === "上传图片") {
            var data = this.form.materialUrlList.map((item) => ({
              groupId: this.form.groupId,
              materialUrl: item.url,
              materialName: item.name,
            }));
            createMaterialManagement(data).then((res) => {
              this.$message.success("上传图片成功");
              this.dialog.open = false;
              this.handleSearch();
            });
          } else if (this.dialog.title === "重命名") {
            updateMaterialManagement(this.form).then((res) => {
              this.$message.success("重命名成功");
              this.dialog.open = false;
              this.handleSearch();
            });
          } else if (this.dialog.title === "移动分组") {
            updateMaterialManagement(this.form).then((res) => {
              this.$message.success("分组移动成功");
              this.dialog.open = false;
              this.handleSearch();
            });
          } else if (this.dialog.title === "批量移动分组") {
            this.handleUpdateGroupBatch();
          }
        } else {
          return;
        }
      });
    },

    // 关闭素材弹窗
    cancel() {
      this.form = {};
      this.dialog.open = false;
    },

    //批量移动分组
    handleUpdateGroupBatch() {
      if (this.ids.length == 0) {
        this.$message.error("请选择要移动的素材");
        return;
      }
      updateMaterialManagementGroupBatch({
        ids: this.ids,
        groupId: this.form.groupId,
      }).then((res) => {
        this.$message.success("分组移动成功");
        this.dialog.open = false;
        this.handleSearch();
      });
    },

    //批量删除素材
    handleDeleteBatch() {
      if (this.ids.length == 0) {
        this.$message.error("请选择要删除的素材");
        return;
      }
      this.$confirm("此操作将永久删除选中的素材, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteMaterialManagementBatch({
            ids: this.ids,
          }).then((res) => {
            this.$message.success("删除成功");
            this.handleSearch();
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.hiddenText {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
.content-container {
  display: flex;
  padding-top: 15px;
  .group-container {
    width: 20%;
    border-right: 1px solid #e3e6eb;
    padding: 0 10px;
    .active-group {
      background-color: #ecf5ff;
      color: #409eff;
    }
    .group-item-title {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow: ellipsis;
      width: calc(100% - 23px);
      cursor: pointer;
    }
  }
  .list-container {
    width: 80%;
    padding: 0 30px;

    .material-list {
      // height: calc(100vh - 300px);
      min-height: 300px;
    }
  }
}
</style>
