<template>
  <div class="container courselist">
    <Header />
    <!-- <Nav navValue="教材列表" /> -->
    <div class="content">
      <div class="inner">
        <div class="btn-box">
          <span @click="handleAdd">
            <img src="../assets/common/icon-add.png" />新建教材
          </span>
          <!-- <el-button @click="handleAdd" size="small" type="primary"
            ><img src="../assets/common/icon-add.png">新建教材</el-button
                    >-->
          <!-- <el-input
                        @keyup.enter.native="handleSearch"
                        placeholder="请输入内容"
                        prefix-icon="el-icon-search"
                        v-model="searchInput"
                    ></el-input>-->
        </div>
        <el-form
          ref="form"
          :inline="true"
          :model="form"
          class="search-form"
          style="margin-left: 10px"
        >
          <el-form-item>
            <el-form-item
              class="label-input"
              label="名称"
              style="margin-right: 30px"
            >
              <el-input v-model="form.name" />
            </el-form-item>
            <!-- <el-form-item class="label-input" label="作者">
                            <el-input v-model="form.author"></el-input>
                        </el-form-item>-->
            <el-form-item label="所属机构" style="margin-right: 30px">
              <el-select
                ref="select"
                v-model="form.agency"
                placeholder="请选择机构"
                @change="onSubmit"
              >
                <el-option
                  v-for="(statusItem, index) in myOrgList"
                  :key="'myOrgList' + index"
                  :label="statusItem.org_name"
                  :value="statusItem.org_id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="发布状态">
              <el-select
                v-model="form.publish_status"
                placeholder="请选择状态"
                @change="onSubmit"
              >
                <el-option
                  v-for="statusItem in statusList"
                  :key="statusItem.value"
                  :label="statusItem.label"
                  :value="statusItem.value"
                />
              </el-select>
            </el-form-item>
            <el-button size="medium" type="primary" @click="onSubmit"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
        <div class="table-box">
          <el-table
            v-loading="tableloading"
            :data="tableData"
            style="width: 100%"
          >
            <el-table-column
              class="table-firstC"
              label="名称"
              prop="name"
              width="150"
            />
            <el-table-column label="英文名" prop="name_english" width="150" />
            <el-table-column label="作者" prop="author" width="100" />
            <el-table-column label="版本" prop="edition" width="100" />
            <el-table-column label="出版社" prop="publisher" width="150" />
            <el-table-column
              label="出版编号"
              prop="publish_number"
              width="100"
            />
            <el-table-column label="所属机构" prop="org_name" width="150" />
            <el-table-column
              :formatter="handleStatus"
              label="发布状态"
              prop="publish_status"
              width="100"
            />
            <el-table-column
              :formatter="handleScope"
              label="发布范围"
              prop="publish_scope"
              width="100"
            />
            <el-table-column fixed="right" label="操作" prop width="300">
              <template slot-scope="scope">
                <el-button type="text" @click="handleClick(scope.row)"
                  >编辑</el-button
                >
                <el-button type="text" @click="handleView(scope.row)"
                  >预览</el-button
                >
                <el-button
                  type="text"
                  @click="handleUp(scope.row, scope.$index)"
                  >{{
                    scope.row.publish_status === 0 ? "上架" : "下架"
                  }}</el-button
                >
                <el-button
                  type="text"
                  @click="handleEdit(scope.row, scope.$index)"
                  >教材信息</el-button
                >
                <el-button type="text" @click="handleDiscount(scope.row)"
                  >优惠码</el-button
                >
                <el-button type="text" @click="handleDel(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-pagination
          :current-page="currentPage"
          :page-size="10"
          :page-sizes="[1, 10, 20, 30, 40, 50]"
          :total="courseTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      :before-close="handleClose"
      :title="titleEdit"
      :visible.sync="dialogFlag"
      :close-on-click-modal="false"
    >
      <el-form ref="formDialog" :model="formDialog" :rules="courseListRules">
        <el-form-item
          class="label-input"
          label="名称"
          label-width="90px"
          prop="name"
        >
          <el-input v-model="formDialog.name" autocomplete="off" name="name" />
        </el-form-item>
        <el-form-item
          class="label-input"
          label="英文名"
          label-width="90px"
          prop="name_english"
        >
          <el-input
            v-model="formDialog.name_english"
            autocomplete="off"
            name="name_english"
          />
        </el-form-item>
        <el-form-item label="教材类型" label-width="90px" prop="type_id">
          <!-- -->
          <el-select
            ref="typeSelects"
            v-model="formDialog.type_id"
            name="bookType"
            placeholder="请选择教材类型"
          >
            <el-option
              v-for="(item, index) in typeList"
              :key="'type' + index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          class="label-input"
          label="作者"
          label-width="90px"
          prop="author"
        >
          <el-input
            v-model="formDialog.author"
            autocomplete="off"
            name="author"
          />
        </el-form-item>
        <el-form-item
          class="label-input"
          label="版本"
          label-width="90px"
          prop="edition"
        >
          <el-input
            v-model="formDialog.edition"
            autocomplete="off"
            name="edition"
          />
        </el-form-item>
        <el-form-item
          class="label-input"
          label="出版社"
          label-width="90px"
          prop="publisher"
        >
          <el-input
            v-model="formDialog.publisher"
            autocomplete="off"
            name="publisher"
          />
        </el-form-item>
        <el-form-item
          class="label-input"
          label="出版编号"
          label-width="90px"
          prop="publish_number"
        >
          <el-input
            v-model="formDialog.publish_number"
            autocomplete="off"
            name="publish_number"
          />
        </el-form-item>
        <el-form-item
          class="label-input"
          label="丛书编号"
          label-width="90px"
          prop="series_code"
        >
          <el-input
            autocomplete="off"
            name="series_code"
            v-model="formDialog.series_code"
          ></el-input>
        </el-form-item>
        <el-form-item
          class="label-input"
          label="价格"
          label-width="90px"
          prop="price"
        >
          <el-input
            v-model="formDialog.price"
            autocomplete="off"
            name="price"
            type="number"
            @blur="blurPrice"
            @input="inputPrice"
          />
        </el-form-item>
        <el-form-item label="所属机构" label-width="90px" prop="org_id">
          <!-- -->
          <el-select
            ref="selects"
            v-model="formDialog.org_id"
            name="agency"
            placeholder="请选择机构"
            @change="changeAgency"
          >
            <el-option
              v-for="(statusItem, index) in diaMyOrgList"
              :key="'diaMyOrgList' + index"
              :label="statusItem.org_name"
              :value="statusItem.org_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="教材描述" label-width="90px" prop="description">
          <el-input v-model="formDialog.description" type="textarea" />
        </el-form-item>
        <!-- <el-form-item label="发布状态" label-width="90px">
                    <el-radio label="0" v-model="formDialog.publish_status">下架</el-radio>
                    <el-radio label="1" v-model="formDialog.publish_status">上架</el-radio>
                </el-form-item>-->
        <el-form-item label="发布范围" label-width="90px" prop="publish_scope">
          <el-radio v-model="formDialog.publish_scope" :label="0"
            >机构内用户可见</el-radio
          >
          <el-radio v-model="formDialog.publish_scope" :label="1"
            >所有用户可见</el-radio
          >
        </el-form-item>
        <el-form-item label="主题颜色" label-width="90px" prop="theme_color">
          <el-radio v-model="formDialog.theme_color" label="red">红色</el-radio>
          <el-radio v-model="formDialog.theme_color" label="green"
            >绿色</el-radio
          >
          <el-radio v-model="formDialog.theme_color" label="brown"
            >棕色</el-radio
          >
        </el-form-item>
        <el-form-item label="教材图片" label-width="90px" prop="fileList">
          <el-upload
            :action="url"
            :file-list="fileList"
            :limit="1"
            :on-exceed="handleExceed"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            accept=".jpg, .jpeg, .png"
            class="upload-demo"
            list-type="picture"
            multiple
            style="width: 500px"
          >
            <el-button size="mini" type="success">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFlag = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="submitCourse"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Header from "@/components/Header";
import { validNull, validPrice } from "@/utils/validate";
// import Nav from "@/components/inputModules/common/Nav";
import { getContent, getContentFile } from "@/api/ajax";
import Cookies from "js-cookie";
import { getToken } from "@/utils/auth";

export default {
  name: "Courselist",
  components: {
    // Nav,
    Header,
  },
  data() {
    const validateNull = (rule, value, callback) => {
      if (!validNull(value)) {
        callback(new Error("请输入相应内容"));
      } else {
        callback();
      }
    };
    const validatePrice = (rule, value, callback) => {
      if (!validPrice(value)) {
        callback(new Error("请输入价格"));
      } else {
        callback();
      }
    };
    return {
      tableData: [], // 数据内容
      currentPage: 1, // 当前页码
      page_capacity: 10, // 每页条数
      courseTotal: 0, // 数据总条数
      searchInput: "", // 搜索内容
      form: {
        author: "",
        status: "",
        agency: "",
        name: "",
        name_english: "",
        edition: "",
        publisher: "",
        publish_number: "",
        series_code: "",
        publish_status: -1,
      },
      dialogFlag: false, // 新建教材弹出层
      agency: "",
      formDialog: {
        name: "",
        name_english: "",
        edition: "",
        description: "",
        author: "",
        price: null,
        org_id: "",
        org_name: "",
        publish_scope: 0,
        publish_number: "",
        series_code: "",
        picture_id: "",
        id: "",
        publisher: "",
        theme_color: "",
        type_id: "",
      },
      agencyList: [
        {
          id: "",
          name: "请选择",
        },
      ],
      agencyLists: [
        {
          id: "",
          name: "请选择",
        },
      ],
      publishStatus: {
        0: "下架",
        1: "上架",
      },
      publishScope: {
        0: "机构内用户",
        1: "所有用户",
      },
      fileList: [], // 上传图片数组
      pageIndex: 1,
      courseListRules: {
        // 填写规则
        name: [{ required: true, trigger: "blur", validator: validateNull }],
        author: [{ required: true, trigger: "blur", validator: validateNull }],
        edition: [{ required: true, trigger: "blur", validator: validateNull }],
        publisher: [
          { required: true, trigger: "blur", validator: validateNull },
        ],
        publish_number: [
          { required: true, trigger: "blur", validator: validateNull },
        ],
        org_id: [{ required: true, message: "请选择机构", trigger: "change" }],
        type_id: [
          { required: true, message: "请选择教材类型", trigger: "change" },
        ],
        price: [{ required: true, validator: validatePrice }],
      },
      loading: false,
      titleEdit: "新建教材",
      rowIndex: 0, // 记录编辑教材的index
      tableloading: true,
      selectLoading: false,
      noMore: false,
      statusList: [
        {
          label: "全部",
          value: -1,
        },
        {
          label: "上架",
          value: 1,
        },
        {
          label: "下架",
          value: 0,
        },
      ],
      myOrgList: [
        {
          org_id: "",
          org_name: "全部",
        },
      ],
      diaMyOrgList: [],
      typeList: [],
    };
  },
  computed: {
    url() {
      let userInfor = getToken();
      let SessionID = "";
      let UserCode = "";
      let UserType = "";
      if (userInfor) {
        let user = JSON.parse(getToken());
        UserCode = user.user_code;
        UserType = user.user_type;
        SessionID = user.session_id;
      }
      return (
        process.env.VUE_APP_BASE_API +
        "/GCLSFileServer/WebFileUpload?UserCode=" +
        UserCode +
        "&UserType=" +
        UserType +
        "&SessionID=" +
        SessionID +
        "&SecurityLevel=Mid"
      );
    },
  },
  mounted() {
    this.getList();
    this.getTypeList();
    this.getMyOrgList();
    this.getMyOrgListAgree();
    // this.createOptions(1);
    // this.$refs.select.$refs.scrollbar.$refs.wrap.addEventListener(
    //   "scroll",
    //   this.selectScroll
    // );
  },
  methods: {
    createOptions(len, start = 0) {
      // this.getAgencList();
    },
    selectScroll() {
      let e = this.$refs.select.$refs.scrollbar.$refs.wrap;
      if (this.noMore) return;
      let loadMore = e.scrollHeight - e.scrollTop <= e.clientHeight;
      if (loadMore) {
        this.loadMore();
      }
    },
    loadMore() {
      if (this.selectLoading) return;
      this.selectLoading = true;
      this.getAgencList();
    },
    // 切换每页条数
    handleSizeChange(val) {
      this.currentPage = 1;
      this.page_capacity = val;
      this.getList();
    },
    // 切换页码
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },
    // 回车搜索
    handleSearch() {
      console.log(this.searchInput);
    },
    // 点击查询按钮
    onSubmit() {
      this.currentPage = 1;
      this.getList();
    },
    handleClick(row) {
      sessionStorage.setItem("Bookdetail", JSON.stringify(row));
      this.$router.push("/adultInput?bookId=" + row.id);
    },
    // 预览
    handleView(row) {
      sessionStorage.setItem("Bookdetail", JSON.stringify(row));
      this.$router.push("/courseview?bookId=" + row.id);
    },
    // 优惠码
    handleDiscount(row) {
      this.$router.push("/discountCodeList?bookId=" + row.id);
    },
    // 新建教材
    handleAdd() {
      this.titleEdit = "新建教材";
      this.formDialog = {
        name: "",
        name_english: "",
        edition: "",
        description: "",
        author: "",
        price: null,
        org_id: "",
        org_name: "",
        publish_scope: 0,
        publish_number: "",
        series_code: "",
        picture_id: "",
        id: "",
        publisher: "",
        theme_color: "",
        type_id: "",
      };
      this.agency = "";
      this.fileList = [];
      this.dialogFlag = true;
    },
    // 新建教材提交
    submitCourse() {
      const _this = this;
      _this.$refs.formDialog.validate((valid) => {
        _this.formDialog.name = _this.formDialog.name.trim();
        _this.formDialog.author = _this.formDialog.author.trim();
        if (_this.formDialog.description !== "") {
          _this.formDialog.description = _this.formDialog.description.trim();
        }
        if (valid) {
          // if (
          //   (!this.formDialog.price && this.formDialog.price != 0)
          // ) {
          //   this.$message(
          //     {
          //       type: "warning",
          //       message: "请填写价格!",
          //     },
          //     2000
          //   );
          //   return false;
          // }
          // if (this.formDialog.org_id == "") {
          //   this.$message(
          //     {
          //       type: "warning",
          //       message: "请选择所属机构!",
          //     },
          //     2000
          //   );
          //   return false;
          // }
          _this.loading = true;
          let MethodName;
          if (_this.formDialog.id) {
            MethodName = "book-book_manager-UpdateBook";
          } else {
            MethodName = "book-book_manager-AddBook";
          }
          this.formDialog.publish_status = 1;
          let data = JSON.parse(JSON.stringify(_this.formDialog));
          getContent(MethodName, data)
            .then((res) => {
              this.$message.success("操作成功");
              if (_this.formDialog.id) {
                this.$set(_this.tableData, this.rowIndex, data);
              } else {
                _this.currentPage = 1;
                _this.getList();
                _this.resetForm("formDialog");
              }
              _this.dialogFlag = false;
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          this.loading = false;
          return false;
        }
      });
    },
    // 查询数据列表
    getList() {
      let MethodName = "book-book_manager-PageQueryBookList";
      let data = {
        name: this.form.name,
        page_capacity: this.page_capacity,
        cur_page: this.currentPage,
        org_id: this.form.agency,
        order_column: "create_time:desc",
        publish_status: this.form.publish_status,
        is_control_publish_scope: "false",
      };
      getContent(MethodName, data).then((res) => {
        let _this = this;
        _this.tableData = res.book_list;
        _this.courseTotal = res.total_count;
        _this.tableloading = false;
      });
    },
    // 机构列表
    getAgencList() {
      let MethodName = "org_manager-PageQueryOrgList";
      let data = {
        name: "",
        page_capacity: 50,
        cur_page: this.pageIndex,
      };
      let dataList = [];
      getContentFile(MethodName, data)
        .then((res) => {
          dataList = res.org_list;
          if (this.pageIndex === res.total_page) {
            // 获取到最后的值时，不再监听滚动条的动作，移除滚动事件
            this.$refs.select.$refs.scrollbar.$refs.wrap.removeEventListener(
              "scroll",
              this.selectScroll()
            );
            this.noMore = true;
          }
          this.pageIndex++;
          this.agencyList = this.agencyList.concat(dataList);
          this.agencyLists = this.agencyList;
        })
        .finally(() => (this.selectLoading = false));
    },
    // 得到我的机构列表-org_manager-GetMyOrgList
    getMyOrgList() {
      let MethodName = "org_manager-GetMyOrgList";
      let data = {
        audited_status: 1,
      };
      getContentFile(MethodName, data).then((res) => {
        if (res && res.org_list.length > 0) {
          this.myOrgList = this.myOrgList.concat(res.org_list);
          this.diaMyOrgList = res.org_list;
        }
      });
    },
    // 得到我的机构列表-org_manager-GetMyOrgList--审核通过的
    getMyOrgListAgree() {
      let MethodName = "org_manager-GetMyOrgList";
      let data = {
        audited_status: 1,
      };
      console.log("MethodName");
      getContentFile(MethodName, data).then((res) => {
        if (res && res.org_list.length > 0) {
          this.diaMyOrgList = res.org_list;
        }
      });
    },
    // 教材类型列表
    getTypeList() {
      let MethodName = "dict_manager-GetBookTypeList";
      let data = {};
      getContentFile(MethodName, data).then((res) => {
        this.typeList = res.type_list;
        console.log(this.typeList);
      });
    },
    // 处理发布状态
    handleStatus(row) {
      if (row) {
        return this.publishStatus[row.publish_status];
      }
    },
    // 处理发布范围
    handleScope(row) {
      if (row) {
        return this.publishScope[row.publish_scope];
      }
    },
    // 选择机构
    changeAgency(row) {
      for (let i = 0; i < this.diaMyOrgList.length; i++) {
        let item = this.diaMyOrgList[i];
        if (item.org_id === row) {
          this.formDialog.org_name = item.org_name;
          break;
        }
      }
    },
    // 处理教材价格 最多两位小数
    inputPrice(e) {
      e = e.match(/^\d*(\.?\d{0,2})/g)[0] || "";
      this.formDialog.price = e;
    },
    // 处理教材价格 失去焦点保留两位小数
    blurPrice() {
      if (this.formDialog.price) {
        this.formDialog.price = Number(this.formDialog.price).toFixed(2);
      }
    },
    handleSuccess(response, file, fileList) {
      if (response.status == 1) {
        this.$message.success("上传成功");
        this.formDialog.picture_id = response.file_info_list[0].file_id;
      } else {
        this.fileList = [];
        this.$message.warning(response.msg);
      }
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.formDialog.picture_id = "";
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    // 清空表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.formDialog.price = null;
      this.agency = "";
      this.fileList = [];
      this.formDialog.description = "";
    },
    // 编辑书籍信息
    handleEdit(row, index) {
      this.$nextTick(() => {
        if (this.$refs["formDialog"] !== undefined) {
          this.$refs["formDialog"].resetFields();
        }
      });
      this.rowIndex = index;
      this.titleEdit = "编辑教材";
      this.fileList = [];
      let MethodName = "book-book_manager-GetBook";
      let data = {
        id: row.id,
      };
      getContent(MethodName, data)
        .then((res) => {
          this.formDialog = {
            id: res.id,
            name: res.name,
            description: res.description,
            author: res.author,
            price: res.price.toFixed(2),
            org_id: res.org_id,
            org_name: res.org_name,
            publish_scope: res.publish_scope,
            picture_id: res.picture_id,
            name_english: res.name_english,
            publish_number: res.publish_number,
            series_code: res.series_code,
            publisher: res.publisher,
            theme_color: res.theme_color,
            edition: res.edition,
            type_id: res.type_id,
          };
          sessionStorage.setItem("Bookdetail", JSON.stringify(this.formDialog));
          if (res.picture_url) {
            let obj = {
              name: "",
              url: res.picture_url,
            };
            this.fileList.push(obj);
          }
          this.agency = res.org_id;
        })
        .catch(() => {
          this.loading = false;
        });
      this.dialogFlag = true;
      // 循环select 有没有选中数据 没有插入
    },
    // 删除书籍
    handleDel(row) {
      this.$confirm("确定要删除此书籍吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let MethodName = "book-book_manager-DeleteBook";
          let data = {
            id: row.id,
          };
          getContent(MethodName, data)
            .then((res) => {
              this.currentPage = 1;
              this.getList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    // 上架
    handleUp(row, index) {
      let Mname = "book-book_manager-SetPublishStatusForBook";
      let updataData = JSON.parse(JSON.stringify(row));
      let data = {
        book_id: row.id,
      };
      if (row.publish_status == 0) {
        // 下架状态
        data.publish_status = 1;
        updataData.publish_status = 1;
      } else if (row.publish_status == 1) {
        data.publish_status = 0;
        updataData.publish_status = 0;
      }
      getContent(Mname, data).then((res) => {
        this.$message.success("操作成功");
        this.$set(this.tableData, index, updataData);
      });
    },

    // 关闭弹窗
    handleClose(done) {
      this.loading = false;
      this.formDialog.price = null;
      this.agency = "";
      this.fileList = [];
      this.formDialog.description = "";
      done();
    },
  },
};
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  background: #f5f5f5;
  .content {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    max-width: 1200px;
    margin: 0 auto;
    height: auto;
    .inner {
      width: 100%;
      margin: 0 auto;
      box-sizing: border-box;
      padding: 20px 0;
      position: relative;
      .btn-box {
        font-size: 0;
        position: absolute;
        right: 0;
        top: 40px;
        span {
          height: 36px;
          line-height: 36px;
          padding: 0 15px;
          display: flex;
          justify-content: center;
          align-items: center;
          background: #ff9900;
          border-radius: 4px;
          font-size: 14px;
          color: #ffffff;
          cursor: pointer;
          &:hover {
            opacity: 0.8;
          }
        }
        img {
          width: 20px;
          margin-right: 4px;
        }
      }
      .search-form {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;
        font-size: 0;
        margin-top: 20px;
        .el-cascader .el-input .el-input__inner {
          width: 240px;
        }
      }
    }
  }
  .el-dialog__body {
    padding-right: 20px;
  }
  .table-box {
    background: #fff;
    padding: 10px 32px 0 32px;
    border-radius: 4px;
  }
}
</style>
<style lang="scss">
.el-table th.is-leaf {
  border-color: #d5d5d5;
}
.el-table td {
  padding: 0.05rem 0;
}
.el-dialog {
  font-size: 0;
}
</style>
