<template>
  <div class="manage-root add-goods">
    <Header />
    <breadcrumb
      :breadcrumbList="breadcrumbList"
      class="breadcrumb-box"
    ></breadcrumb>
    <div class="manage-root-contain" v-loading="tableLoading">
      <div class="common-title-box">
        <h3>
          添加兑换内容
          <span
            style="color: rgba(255, 20, 20, 1)"
            v-if="checkGoodsList.length > 0"
            >已选{{ checkGoodsList.length }}</span
          >
        </h3>
        <div class="btn-box">
          <el-button @click="$router.go(-1)" size="small">取消</el-button>
          <el-button
            type="primary"
            @click="handleChooseGoods"
            size="small"
            :loading="loading"
            ><svg-icon icon-class="Check" style="margin-right: 8px"></svg-icon
            >完成</el-button
          >
        </div>
      </div>
      <div class="filt-box">
        <div class="filt-item">
          <label>类型</label>
          <ul>
            <li
              :class="[items.value === itemType ? 'active' : '']"
              v-for="(items, indexs) in typeSelectList"
              :key="indexs"
              @click="
                itemType = items.value;
                getList(1);
              "
            >
              <i v-if="items.value === itemType" class="el-icon-success"></i>
              {{ items.label }}
            </li>
          </ul>
        </div>
        <template v-if="itemType === 'kecheng'">
          <div class="filt-item">
            <label>学段</label>
            <ul>
              <li
                :class="[
                  items.study_phase === courseForm.studyValue ? 'active' : '',
                  courseForm.categoryValue === 'ZB' ? 'not-allow' : '',
                ]"
                v-for="(items, indexs) in studyList"
                :key="indexs"
                @click="
                  handleClick('courseForm', 'studyValue', items.study_phase)
                "
              >
                <i
                  v-if="items.study_phase === courseForm.studyValue"
                  class="el-icon-success"
                ></i>
                {{ items.study_phase_name }}
              </li>
            </ul>
          </div>
          <div class="filt-item">
            <label>类别</label>
            <ul>
              <li
                :class="[
                  itemt.value === courseForm.categoryValue ? 'active' : '',
                ]"
                v-for="(itemt, indext) in categoryList"
                :key="indext"
                @click="handleClick('courseForm', 'categoryValue', itemt.value)"
              >
                <i
                  v-if="itemt.value === courseForm.categoryValue"
                  class="el-icon-success"
                ></i>
                {{ itemt.label }}
              </li>
            </ul>
          </div>
        </template>
        <template v-else-if="itemType === 'baozhi'">
          <div class="filt-item">
            <label>年份</label>
            <ul>
              <li
                :class="[itemy.value === baozhiForm.yearValue ? 'active' : '']"
                v-for="(itemy, indexy) in yearList"
                :key="indexy"
                @click="handleClick('baozhiForm', 'yearValue', itemy.value)"
              >
                <i
                  v-if="itemy.value === baozhiForm.yearValue"
                  class="el-icon-success"
                ></i>
                {{ itemy.label }}
              </li>
            </ul>
          </div>
          <div class="filt-item">
            <label>学段</label>
            <ul>
              <li
                :class="[
                  items.study_phase === baozhiForm.studyValue ? 'active' : '',
                ]"
                v-for="(items, indexs) in baozhiStudyList"
                :key="indexs"
                @click="
                  handleClick(
                    'baozhiForm',
                    'studyValue',
                    items.study_phase,
                    items.study_phase_name
                  )
                "
              >
                <i
                  v-if="items.study_phase === baozhiForm.studyValue"
                  class="el-icon-success"
                ></i>
                {{ items.study_phase_name }}
              </li>
            </ul>
          </div>
          <div class="filt-item">
            <label>类型</label>
            <ul>
              <li
                :class="[itemt.value === baozhiForm.typeValue ? 'active' : '']"
                v-for="(itemt, indext) in typeList"
                :key="indext"
                @click="handleClick('baozhiForm', 'typeValue', itemt.value)"
              >
                <i
                  v-if="itemt.value === baozhiForm.typeValue"
                  class="el-icon-success"
                ></i>
                {{ itemt.label }}
              </li>
            </ul>
          </div>
        </template>
        <template v-if="itemType === 'jingdu'">
          <div class="filt-item">
            <label>主题</label>
            <ul>
              <li
                :class="[
                  itemy.value === jingduForm.categoryValue ? 'active' : '',
                ]"
                v-for="(itemy, indexy) in themeList"
                :key="indexy"
                @click="handleClick('jingduForm', 'categoryValue', itemy.value)"
              >
                <i
                  v-if="itemy.value === baozhiForm.categoryValue"
                  class="el-icon-success"
                ></i>
                {{ itemy.label }}
              </li>
            </ul>
          </div>
          <div class="filt-item">
            <label>学段</label>
            <ul>
              <li
                :class="[
                  items.study_phase === jingduForm.studyValue ? 'active' : '',
                ]"
                v-for="(items, indexs) in jingduStudyList"
                :key="indexs"
                @click="
                  handleClick(
                    'jingduForm',
                    'studyValue',
                    items.study_phase,
                    items.study_phase_name
                  )
                "
              >
                <i
                  v-if="items.study_phase === jingduForm.studyValue"
                  class="el-icon-success"
                ></i>
                {{ items.study_phase_name }}
              </li>
            </ul>
          </div>
        </template>
        <template v-else-if="itemType === 'huakan'">
          <div class="filt-item">
            <label>年份</label>
            <ul>
              <li
                :class="[itemy.value === huakanForm.yearValue ? 'active' : '']"
                v-for="(itemy, indexy) in huakanyearList"
                :key="indexy"
                @click="handleClick('huakanForm', 'yearValue', itemy.value)"
              >
                <i
                  v-if="itemy.value === huakanForm.yearValue"
                  class="el-icon-success"
                ></i>
                {{ itemy.label }}
              </li>
            </ul>
          </div>
        </template>
        <div class="filt-item">
          <label>搜索</label>
          <el-input placeholder="搜索" v-model="searchValue" maxlength="20">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getList(1)"
            ></el-button>
          </el-input>
        </div>
      </div>
      <ul class="item-box">
        <li
          v-for="(itemC, indexC) in tableData"
          :key="indexC"
          @click="changeSelectGoods(itemC)"
        >
          <el-image
            class="image"
            :src="
              itemC.cover_image_url || itemC.iss_cover_url
                ? itemC.cover_image_url || itemC.iss_cover_url
                : itemC.goods_type === 2
                ? require('../../assets/baozhi' +
                    (Math.floor(Math.random() * 2) + 1) +
                    '.png')
                : require('../../assets/kecheng' +
                    (Math.floor(Math.random() * 3) + 1) +
                    '.png')
            "
            :fit="'cover'"
          >
          </el-image>
          <el-checkbox
            v-model="itemC.check"
            @change="changeSelectGoods(itemC)"
            >{{ itemC.name || itemC.iss_name }}</el-checkbox
          >
        </li>
      </ul>
      <div class="nodata" v-if="total_count === 0">
        <img src="../../assets/nodata.png" />
        <p>找不到文件</p>
      </div>
      <!-- <el-pagination
            background
            :current-page="currentPages"
            :page-size="page_capacitys"
            :page-sizes="[8, 16, 24, 32, 40]"
            :total="total_count"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="(val)=>handleSizeChange(val,'page_capacitys','currentPages')"
            @current-change="(val)=>handleCurrentChange(val,'currentPages')"
            v-if="total_count>0&&(courseForm.categoryValue==='ZB'||itemType==='jingdu')"
        /> -->
      <el-pagination
        background
        :current-page="currentPage"
        :page-size="page_capacity"
        :page-sizes="[9, 18, 27, 36, 45, 54]"
        :total="total_count"
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="
          (val) => handleSizeChange(val, 'page_capacity', 'currentPage')
        "
        @current-change="(val) => handleCurrentChange(val, 'currentPage')"
        v-else-if="total_count > 0"
      />
    </div>
  </div>
</template>

<script>
//这里可以导入其它文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》from ‘《组件路径》';
import Header from "../../components/Header.vue";
import Breadcrumb from "../../components/Breadcrumb.vue";
import { getLogin } from "@/api/ajax";
import { mapState } from "vuex";

export default {
  //import引入的组件需要注入到对象中才能使用
  components: { Header, Breadcrumb },
  props: {},
  data() {
    //这里存放数据
    return {
      breadcrumbList: [
        {
          icon: "barcode-line",
          url: "",
          text: "",
        },
        {
          icon: "",
          url: "",
          notLink: true,
          text: "兑换码管理",
        },
        {
          icon: "",
          url: "",
          text: "创建兑换码",
        },
        {
          icon: "",
          url: "",
          text: "添加内容",
        },
      ],
      pageLoading: false,
      tableData: [],
      tableHeight: "", // 表格高度
      total_count: 0,
      loading: false,
      tableLoading: false,
      itemType: "baozhi",
      typeSelectList: [
        {
          label: "报纸",
          value: "baozhi",
        },
        {
          label: "精读",
          value: "jingdu",
        },
        {
          label: "课程",
          value: "kecheng",
        },
        {
          label: "画刊",
          value: "huakan",
        },
      ],
      yearList: [
        {
          value: -1,
          label: "全部",
        },
      ],
      huakanyearList: [
        {
          value: null,
          label: "全部",
        },
      ],
      studyList: [
        {
          study_phase: -1,
          study_phase_name: "全部",
        },
      ],
      baozhiStudyList: [],
      categoryList: [
        {
          value: "LB",
          label: "录播",
        },
        {
          value: "ZB",
          label: "直播",
        },
      ],
      typeList: [
        {
          value: 0,
          label: "单本",
        },
        {
          value: 1,
          label: "专辑",
        },
      ],
      courseForm: {
        studyValue: -1,
        categoryValue: "LB",
      },
      baozhiForm: {
        yearValue: -1,
        studyValue: -1,
        typeValue: 0,
      },
      jingduForm: {
        studyValue: 11,
        categoryValue: "",
      },
      huakanForm: {
        yearValue: null,
        key_word: "",
      },
      searchValue: "",
      page_capacity: 18,
      currentPage: 1,
      currentPages: 1,
      page_capacitys: 8, // 每页条数
      themeList: [],
      jingduStudyList: [
        {
          study_phase: 11,
          study_phase_name: "小学",
        },
        {
          study_phase: 21,
          study_phase_name: "初一",
        },
        {
          study_phase: 22,
          study_phase_name: "初二",
        },
        {
          study_phase: 23,
          study_phase_name: "初三",
        },
      ],
      checkGoodsList: [],
      checkGoodsIdList: [],
    };
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中数据变化
  watch: {},
  //方法集合
  methods: {
    changeSelectGoods(item) {
      if (this.checkGoodsIdList.indexOf(item.goods_id) > -1) {
        this.checkGoodsIdList.splice(
          this.checkGoodsIdList.indexOf(item.goods_id),
          1
        );
        this.checkGoodsList.splice(
          this.checkGoodsIdList.indexOf(item.goods_id),
          1
        );
        item.check = false;
      } else {
        this.checkGoodsIdList.push(item.goods_id);
        this.checkGoodsList.push({
          goods_id: item.goods_id,
          goods_type: item.goods_type,
        });
        item.check = true;
      }
    },
    getList(val) {
      this.tableLoading = true;
      if (val) {
        this.pageNumber = val;
      }
      let MethodName = "/ShopServer/Manager/GoodsQuery/PageQueryCourseList";
      let data = {
        page_capacity: this.page_capacity,
        cur_page: this.currentPage,
        search_content: this.searchValue.trim(),
      };
      if (this.itemType === "baozhi") {
        MethodName = "/ShopServer/Manager/GoodsQuery/PageQueryIssueList";
        data.year_label = this.baozhiForm.yearValue;
        data.study_phase = this.baozhiForm.studyValue;
        data.comb_flag =
          this.baozhiForm.typeValue == 1 ? null : this.baozhiForm.typeValue;
        data.album_flag =
          this.baozhiForm.typeValue == 0 ? null : this.baozhiForm.typeValue;
        getLogin(MethodName, data)
          .then((res) => {
            this.tableLoading = false;
            if (res.status === 1) {
              res.issue_list.forEach((item) => {
                item.goods_type = 2;
                item.goods_id = item.id;
                item.check =
                  this.checkGoodsIdList.indexOf(item.id) > -1 ? true : false;
              });
              this.tableData = res.issue_list;
              this.total_count = res.total_count;
            }
          })
          .catch(() => {
            this.tableLoading = false;
          });
      } else if (this.itemType === "kecheng") {
        (data.course_type = this.courseForm.categoryValue),
          (data.study_phase = this.courseForm.studyValue);
        getLogin(MethodName, data)
          .then((res) => {
            this.tableLoading = false;
            if (res.status === 1) {
              res.course_list.forEach((item) => {
                item.goods_type =
                  this.courseForm.categoryValue === "ZB" ? 1 : 0;
                item.goods_id = item.id;
                item.check =
                  this.checkGoodsIdList.indexOf(item.id) > -1 ? true : false;
              });
              this.tableData = res.course_list;
              this.total_count = res.total_count;
            }
          })
          .catch(() => {
            this.tableLoading = false;
          });
      } else if (this.itemType === "jingdu") {
        MethodName = "/ShopServer/Manager/GoodsQuery/PageQueryIreadArticleList";
        data.label = this.jingduForm.categoryValue;
        data.study_phase = this.jingduForm.studyValue;
        getLogin(MethodName, data)
          .then((res) => {
            this.tableLoading = false;
            if (res.status === 1) {
              res.iread_article_list.forEach((item) => {
                item.goods_type = 3;
                item.goods_id = item.id;
                item.check =
                  this.checkGoodsIdList.indexOf(item.id) > -1 ? true : false;
              });
              this.tableData = res.iread_article_list;
              this.total_count = res.total_count;
            }
          })
          .catch(() => {
            this.tableLoading = false;
          });
      } else if (this.itemType === "huakan") {
        MethodName = "/PaperServer/Manager/PicIssueManager/PageQueryIssue";
        data.year_label = this.huakanForm.yearValue;
        data.key_word = this.searchValue.trim();

        getLogin(MethodName, data)
          .then((res) => {
            this.tableLoading = false;
            if (res.status === 1) {
              res.data.list.forEach((item) => {
                item.goods_type = 4;
                item.goods_id = item.id;
                item.check =
                  this.checkGoodsIdList.indexOf(item.id) > -1 ? true : false;
              });
              this.tableData = res.data.list;
              this.total_count = res.data.total_count;
            }
          })
          .catch(() => {
            this.tableLoading = false;
          });
      }
    },
    //计算table高度(动态设置table高度)
    getTableHeight() {
      let tableH = 320; //距离页面下方的高度
      let tableHeightDetil = window.innerHeight - tableH;
      if (tableHeightDetil <= 320) {
        this.tableHeight = 320;
      } else {
        this.tableHeight = window.innerHeight - tableH;
      }
    },
    handleSizeChange(val, type, page) {
      this[type] = val;
      this[page] = 1;
      this.getList();
    },
    handleCurrentChange(val, type) {
      this[type] = val;
      this.getList();
    },
    // 去掉前后空格
    handleTrim(form, fild) {
      this[form][fild] = this[form][fild].trim();
    },
    handleClick(form, file, value, name) {
      if (form === "courseForm" && file === "categoryValue" && value === "ZB") {
        this.courseForm.studyValue = -1;
      } else if (
        form === "courseForm" &&
        file === "categoryValue" &&
        value === "LB"
      ) {
        this.courseForm.studyValue = window.localStorage.getItem(
          "courseFormstudyValue"
        )
          ? window.localStorage.getItem("courseFormstudyValue") * 1
          : -1;
      }
      if (
        form === "courseForm" &&
        file === "studyValue" &&
        this.courseForm.categoryValue === "ZB"
      ) {
        return false;
      }
      this[form][file] = value;
      this.currentPage = 1;
      this.currentPages = 1;
      this.getList();
    },
    // 提交表单
    handleChooseGoods() {
      if (this.checkGoodsList.length === 0) {
        this.$message.warning("至少需要选择一个内容");
        return;
      }
      this.loading = true;
      let MethodName =
        "/ShopServer/Manager/DiscountCodeManager/AddGoodsToDiscountCode";
      let data = {
        discount_code_id: window.localStorage.getItem("cdKeyId")
          ? window.localStorage.getItem("cdKeyId")
          : "",
        goods_list: this.checkGoodsList,
      };
      getLogin(MethodName, data)
        .then((res) => {
          this.loading = false;
          if (res.status === 1) {
            this.$router.go(-1);
          }
        })
        .catch((res) => {
          this.loading = false;
        });
    },
    // 学段列表
    getStudyList() {
      let MethodName = "/OrgServer/DictManager/GetStudyPhaseList";
      getLogin(MethodName, {})
        .then((res) => {
          if (res.status === 1) {
            let studyList = [
              {
                study_phase: -1,
                study_phase_name: "全部",
              },
            ];
            this.studyList = studyList.concat(res.study_phase_list);
            this.baozhiStudyList = res.study_phase_list;
            this.baozhiForm.studyValue = window.localStorage.getItem(
              "baozhiFormstudyValue"
            )
              ? window.localStorage.getItem("baozhiFormstudyValue") * 1
              : res.study_phase_list[0]
              ? res.study_phase_list[0].study_phase
              : -1;
            if (this.itemType === "baozhi") {
              this.titleName = window.localStorage.getItem(
                "baozhiFormstudyValueName"
              )
                ? window.localStorage.getItem("baozhiFormstudyValueName")
                : res.study_phase_list[0]
                ? res.study_phase_list[0].study_phase_name
                : "";
            } else if (this.itemType === "jingdu") {
              this.titleName = window.localStorage.getItem(
                "jingduFormstudyValueName"
              )
                ? window.localStorage.getItem("jingduFormstudyValueName")
                : res.study_phase_list[0]
                ? res.study_phase_list[0].study_phase_name
                : "";
            } else if (this.itemType === "kecheng") {
              this.titleName = window.localStorage.getItem(
                "courseFormstudyValueName"
              )
                ? window.localStorage.getItem("courseFormstudyValueName")
                : res.study_phase_list[0]
                ? res.study_phase_list[0].study_phase_name
                : "";
            }
          }
        })
        .catch(() => {});
    },
    // 获取年份列表
    getYearList() {
      this.yearList = [
        {
          value: -1,
          label: "全部",
        },
      ];
      let yearList = [];
      let MethodName = "/ShopServer/Client/ShopHomeQuery/GetIssueYearLabelList";
      getLogin(MethodName, {})
        .then((res) => {
          if (res.status === 1) {
            res.year_label_list.forEach((nowYear) => {
              let obj = {
                value: nowYear,
                label: nowYear,
              };
              yearList.push(obj);
            });
            this.yearList = this.yearList.concat(yearList);
          }
        })
        .catch(() => {
          this.loading = false;
        });
      this.huakanyearList = [
        {
          value: null,
          label: "全部",
        },
      ];
      getLogin(MethodName, { goods_type: 4 })
        .then((res) => {
          if (res.status === 1) {
            let yearLists = [];
            res.year_label_list.forEach((nowYear) => {
              let obj = {
                value: nowYear,
                label: nowYear,
              };
              yearLists.push(obj);
            });
            this.huakanyearList = this.huakanyearList.concat(yearLists);
          }
        })
        .catch(() => {});
    },
    getLabelList() {
      this.themeList = [
        {
          value: "",
          label: "全部",
        },
      ];
      let yearList = [];
      let MethodName =
        "/ShopServer/Manager/GoodsQuery/GetIreadArticleLabelList";
      getLogin(MethodName, {})
        .then((res) => {
          if (res.status === 1) {
            res.label_list.forEach((nowYear) => {
              let obj = {
                value: nowYear,
                label: nowYear,
              };
              yearList.push(obj);
            });
            this.themeList = this.themeList.concat(yearList);
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getTableHeight();
    this.getStudyList();
    this.getYearList();
    this.getLabelList();
    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类 */
.breadcrumb-box {
  width: 1408px;
  margin: 0 auto;
  position: initial;
}
.manage-root-contain {
  width: 1408px;
  height: calc(100vh - 120px);
  overflow: auto;
  margin: 0 auto;
  border-radius: 4px;
  background: #fff;
  padding: 24px;
  display: block;
  .common-title-box {
    width: 100%;
    .el-icon-arrow-left {
      font-weight: 500;
      margin-right: 8px;
      cursor: pointer;
    }
  }
  .filt-box {
    margin: 24px 0;
  }
  .filt-item {
    display: flex;
    margin-bottom: 8px;
    label {
      width: 52px;
      font-weight: 400;
      font-size: 16px;
      line-height: 32px;
      color: #2f3742;
      flex-shrink: 0;
    }
    ul {
      list-style: none;
      display: flex;
      flex-flow: wrap;
      padding: 0;
      margin: 0;
      li {
        margin: 0 8px 16px 0;
        background: #f2f3f5;
        border-radius: 2px;
        padding: 3px 11px;
        font-weight: 500;
        font-size: 16px;
        line-height: 24px;
        color: #2f3742;
        cursor: pointer;
        border: 1px solid #f2f3f5;
        height: 32px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        &:hover {
          color: #165dff;
        }
        &.not-allow {
          cursor: not-allowed;
          background: #f2f3f5;
          color: #c1c5cd;
        }
        &.active {
          color: #165dff;
          border-color: #165dff;
          background: #ffffff;
          .el-icon-success {
            margin-right: 4px;
            font-size: 12px;
            margin-top: 2px;
          }
        }
        &.not-allow.active {
          color: #cedcfe;
          border-color: #cedcfe;
        }
      }
    }
    .el-input {
      width: 240px;
      height: 32px;
      background: #f2f3f5;
      border-radius: 2px;
    }
  }
}
.item-box {
  padding: 0 0 0 40px;
  margin: 0;
  list-style: none;
  display: flex;
  flex-flow: wrap;
  li {
    width: 120px;
    margin: 12px;
    .image {
      width: 120px;
      height: 168px;
    }
    .el-checkbox {
      width: 120px;
      display: flex;
    }
  }
}
.nodata {
  text-align: center;
  img {
    width: 329px;
  }
  p {
    color: #a8a8a8;
    font-size: 14px;
    font-weight: 400;
    line-height: 22px;
    margin: 30px 0;
  }
}
</style>
<style lang="scss">
.filt-box {
  input {
    height: 32px;
    line-height: 32px;
    background: #f2f3f5;
    border: none;
  }
  .el-input__icon {
    line-height: 32px;
    cursor: pointer;
    color: #4e5969 !important;
  }
  .el-input-group__append {
    background: #f2f3f5;
    border: none;
  }
  .el-button {
    padding: 9px 12px;
  }
}
.add-goods {
  .item-box {
    .el-checkbox {
      padding: 12px 0;
      .el-checkbox__inner {
        margin-top: 5px;
      }
      .el-checkbox__label {
        width: 100px;
        white-space: normal;
        color: #2f3742;
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
      }
    }
  }
}
</style>
