<template>
  <div class="manage-root organize-manage">
    <Header />
    <div class="manage-root-contain">
      <nav-menu
        class="manage-root-contain-left"
        :activeMenuIndex="activeMenuIndex"
      ></nav-menu>
      <div class="manage-root-contain-right personnel-manage-right">
        <breadcrumb
          :breadcrumbList="breadcrumbList"
          class="breadcrumb-box"
        ></breadcrumb>
        <div class="personal-inner">
          <div class="common-title-box">
            <h3>专辑管理</h3>
            <div class="btn-box">
              <el-button type="primary" size="small" @click="handleEdit()"
                >创建专辑</el-button
              >
            </div>
          </div>
          <div class="search-box">
            <div class="search-item">
              <label>搜索</label>
              <el-input
                placeholder="输入搜索内容"
                v-model="searchInput"
                maxlength="200"
              >
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-search"
                  @click="getList(1)"
                  style="cursor: pointer"
                ></i>
              </el-input>
            </div>
            <div class="search-item">
              <label>状态</label>
              <el-select
                v-model="searchStatus"
                @change="getList(1)"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in checkStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
            <div class="search-item">
              <label>学段</label>
              <el-select
                v-model="searchStudy"
                @change="getList(1)"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in $studyTypeAll"
                  :key="item.study_phase"
                  :label="item.study_phase_name"
                  :value="item.study_phase"
                >
                </el-option>
              </el-select>
            </div>
          </div>
          <el-table
            class="search-table"
            :data="tableData"
            style="width: 100%"
            @sort-change="handleSort"
            :default-sort="dataSort"
            :max-height="tableHeight"
            key="checked-table"
            v-loading="tableLoading"
          >
            <el-table-column
              type="index"
              label="#"
              sortable
              width="56"
              :index="(pageNumber - 1) * pageSize + 1"
            >
            </el-table-column>
            <el-table-column
              prop="name"
              label="名称"
              sortable="custom"
              min-width="226"
            >
            </el-table-column>
            <el-table-column prop="study_phase" label="学段" width="72">
              <template slot-scope="scope">
                {{ formatterStudy(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column prop="goods_type" label="类型" width="72">
              <template slot-scope="scope">
                {{ typeList[scope.row.goods_type] }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="104">
              <template slot-scope="scope">
                <div class="status-box">
                  <span
                    :style="{
                      background: $checkStatusColorList[scope.row.status].bg,
                    }"
                  ></span>
                  <b
                    :style="{
                      color: $checkStatusColorList[scope.row.status].color,
                    }"
                    >{{ $checkStatusColorList[scope.row.status].text }}</b
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="creator_name"
              label="创建人"
              width="120"
              sortable="custom"
            >
            </el-table-column>
            <el-table-column
              prop="create_time"
              label="创建时间"
              width="144"
              sortable="custom"
            >
              <template slot-scope="scope">
                {{
                  scope.row.create_time
                    ? scope.row.create_time.substring(0, 16)
                    : "-"
                }}
              </template>
            </el-table-column>
            <el-table-column
              prop="last_modifier_name"
              label="最近编辑"
              min-width="96"
            >
            </el-table-column>
            <el-table-column
              prop="last_modify_time"
              label="最近编辑时间"
              width="144"
              sortable="custom"
            >
              <template slot-scope="scope">
                {{
                  scope.row.last_modify_time
                    ? scope.row.last_modify_time.substring(0, 16)
                    : "-"
                }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="180">
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="handleEdit(scope.row)"
                  type="text"
                  size="small"
                  class="primary-btn"
                >
                  编辑
                </el-button>
                <el-button
                  @click.native.prevent="handleUp(scope.row, scope.$index)"
                  type="text"
                  size="small"
                  class="red-btn"
                  v-if="scope.row.status === 2"
                >
                  下架
                </el-button>

                <el-button
                  @click.native.prevent="handleUp(scope.row, scope.$index)"
                  type="text"
                  size="small"
                  class="primary-btn"
                  v-else
                >
                  上架
                </el-button>
                <el-button
                  @click.native.prevent="handleDelete(scope.row, scope.$index)"
                  type="text"
                  size="small"
                  class="red-btn"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            @size-change="
              (val) => handleSizeChange(val, 'pageSize', 'pageNumber')
            "
            @current-change="(val) => handleCurrentChange(val, 'pageNumber')"
            :current-page="pageNumber"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, prev, pager, next, sizes, jumper"
            :total="total_count"
          >
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
//这里可以导入其它文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》from ‘《组件路径》';
import Header from "../../../components/Header.vue";
import NavMenu from "../../../components/NavMenu.vue";
import Breadcrumb from "../../../components/Breadcrumb.vue";
import { mapState } from "vuex";
import { getLogin } from "@/api/ajax";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: { Header, NavMenu, Breadcrumb },
  props: {},
  data() {
    //这里存放数据
    return {
      activeMenuIndex: "album_manage",
      breadcrumbList: [
        {
          icon: "file-list-line",
          url: "",
          text: "",
        },
        {
          icon: "",
          url: "",
          notLink: true,
          text: "内容管理",
        },
        {
          icon: "",
          url: "",
          text: "专辑管理",
        },
      ],
      searchInput: "",
      searchStudy: -1,
      searchStatus: -1,
      studyList: [
        {
          value: "",
          label: "全部",
        },
        {
          value: "0",
          label: "初一",
        },
        {
          value: "1",
          label: "初二",
        },
        {
          value: "2",
          label: "初三",
        },
        {
          value: "3",
          label: "高一",
        },
      ],
      checkStatusList: [
        {
          value: -1,
          label: "全部",
        },
        {
          value: 1,
          label: "未上架",
        },
        {
          value: 2,
          label: "已上架",
        },
      ],
      typeList: {
        0: "课程",
        2: "报纸",
        3: "精读",
        4: "画刊",
        5: "练习册",
      },
      tableData: [],
      pageSize: window.localStorage.getItem("pageSize")
        ? Number(window.localStorage.getItem("pageSize"))
        : 10,
      pageNumber: window.localStorage.getItem("pageNumber")
        ? Number(window.localStorage.getItem("pageNumber"))
        : 1,
      tableHeight: "", // 表格高度
      total_count: 0,
      dataSort: {},
      tableLoading: false,
    };
  },
  //计算属性 类似于data概念
  computed: {
    ...mapState(["$studyTypeAll", "$checkStatusColorList"]),
  },
  //监控data中数据变化
  watch: {},
  //方法集合
  methods: {
    handleSort(value) {
      let dataSort = {
        prop: value.prop,
        order: value.order,
      };
      this.dataSort = dataSort;
      this.getList();
    },
    // 处理学段
    formatterStudy(row) {
      let studyCn = "";
      let list = this.$studyTypeAll;
      if (row.study_phase) {
        for (let i = 0; i < list.length; i++) {
          if (row.study_phase === list[i].study_phase) {
            studyCn = list[i].study_phase_name;
          }
        }
      } else {
        studyCn = "未知";
      }
      return studyCn;
    },
    // 创建机构或者编辑信息
    handleEdit(row) {
      // 根据登录用户判断当前用户是不是超管 在table里加上disabled

      // 点击时记录页码和每页条数
      window.localStorage.setItem("pageSize", this.pageSize);
      window.localStorage.setItem("pageNumber", this.pageNumber);
      window.localStorage.removeItem("albumId");
      window.localStorage.removeItem("albumType");
      window.localStorage.removeItem("albumStudyPhase");
      this.$router.push({
        path: "/createAlbum",
        query: {
          id: row ? row.id : "",
          isCreate: !row ? "true" : "false",
        },
      });
    },
    // 停用 启用
    handleUp(row, index) {
      let Mname = "/ShopServer/Manager/AlbumManager/ShelveAlbum";
      let updataData = JSON.parse(JSON.stringify(row));
      let data = {
        id: row.id,
      };
      if (row.status === 2) {
        // 上架状态
        data.is_pass = "false";
        updataData.status = 1;
      } else {
        data.is_pass = "true";
        updataData.status = 2;
      }
      getLogin(Mname, data).then((res) => {
        this.$message.success("操作成功");
        this.getList();
      });
    },
    // 审核
    handleCheck(row, index) {
      let Mname = "/PaperServer/Manager/IssueManager/EditIssueStatus";
      let updataData = JSON.parse(JSON.stringify(row));
      let data = {
        id: row.id,
      };
      this.$confirm("审核", "提示", {
        confirmButtonText: "审核通过",
        cancelButtonText: "驳回",
        distinguishCancelAndClose: true,
        type: "warning",
      })
        .then(() => {
          data.iss_status = 1;
          updataData.iss_status = 1;
          getLogin(Mname, data).then((res) => {
            this.$message.success("操作成功");
            this.getList();
          });
        })
        .catch((action) => {
          if (action === "cancel") {
            data.iss_status = 3;
            updataData.iss_status = 3;
            getLogin(Mname, data).then((res) => {
              this.$message.success("操作成功");
              this.getList();
            });
          }
        });
    },
    // 删除
    handleDelete(row) {
      this.$confirm("确定删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let Mname = "/ShopServer/Manager/AlbumManager/DeleteAlbum";
          let data = {
            id: row.id,
          };
          getLogin(Mname, data).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    handleSizeChange(val, type, page) {
      this[type] = val;
      this[page] = 1;
      this.getList();
    },
    handleCurrentChange(val, type) {
      this[type] = val;
      this.getList();
    },
    //计算table高度(动态设置table高度)
    getTableHeight() {
      let tableH = 420; //距离页面下方的高度
      let tableHeightDetil = window.innerHeight - tableH;
      if (tableHeightDetil <= 300) {
        this.tableHeight = 300;
      } else {
        this.tableHeight = window.innerHeight - tableH;
      }
    },
    getList(val) {
      this.tableLoading = true;
      if (val) {
        this.pageNumber = val;
      }
      let MethodName = "/ShopServer/Manager/AlbumManager/PageQueryAlbumList";
      let order_column_list = [];
      if (this.dataSort != {}) {
        if (this.dataSort.order == "descending") {
          order_column_list.push({
            name: this.dataSort.prop,
            asc: false,
          });
        } else if (this.dataSort.order == "ascending") {
          order_column_list.push({
            name: this.dataSort.prop,
            asc: true,
          });
        } else {
          order_column_list = [
            {
              name: "update_time",
              asc: false,
            },
          ];
        }
      } else {
        order_column_list = [
          {
            name: "update_time",
            asc: false,
          },
        ];
      }
      let data = {
        search_content: this.searchInput.trim(),
        status: this.searchStatus,
        study_phase: this.searchStudy,
        page_capacity: this.pageSize,
        cur_page: this.pageNumber,
        order_bys: order_column_list,
      };
      getLogin(MethodName, data)
        .then((res) => {
          this.tableLoading = false;
          if (res.status === 1) {
            this.tableData = res.album_list;
            this.total_count = res.total_count;
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getTableHeight();
    this.getList();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    let _this = this;
    let input = document.querySelector("input");
    input.addEventListener("keyup", function (event) {
      // 判断是否按下回车键
      if (event.keyCode === 13) {
        // 回车键被按下，执行你想要的操作
        _this.getList(1);
      }
    });
  },
  //生命周期-创建之前
  beforeCreated() {},
  //生命周期-挂载之前
  beforeMount() {},
  //生命周期-更新之前
  beforUpdate() {},
  //生命周期-更新之后
  updated() {},
  //生命周期-销毁之前
  beforeDestory() {},
  //生命周期-销毁完成
  destoryed() {},
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() {},
};
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
.tabs {
  display: flex;
  padding: 16px 0 0 0;
  a {
    font-size: 14px;
    line-height: 22px;
    color: #4e5969;
    border-radius: 100px;
    padding: 5px 16px;
    margin-right: 12px;
    &:hover {
      background: #f2f3f5;
    }
    &.active {
      background: #f2f3f5;
      font-weight: 500;
      color: #165dff;
    }
  }
}
</style>
<style lang="scss">
.organize-manage {
  .el-cascader {
    width: 160px;
    height: 32px;
    line-height: 32px;
    .el-input {
      width: 100%;
      height: 32px;
    }
  }
}
</style>
