<template>
  <div class="createZyCourse" v-loading="loading">
    <el-card>
      <div class="flex justify-between pr-30px">
        <div style="padding: 0 75px">
          <span class="title">自主研学</span>
          <span class="subTitle"
            >我的课程 - 我创建的 -
            <span class="pointer" @click="goBack">自主研学</span> -
            <span style="color: #000"
              >资源{{ editId == "" ? "添加" : "编辑" }}</span
            ></span
          >
        </div>
        <div class="to-back" @click="goBack">返回</div>
      </div>
    </el-card>

    <el-card>
      <div style="color: #050026; font-size: 18px; font-weight: 400">
        {{ editId == "" ? "添加" : "编辑" }}
      </div>
      <div class="formContent">
        <el-form
          :model="formline"
          ref="formline"
          :rules="rules"
          size="large"
          label-position="top"
          class="demo-ruleForm"
        >
          <el-form-item label="课程封面图" class="kcfmt" prop="zz_img">
            <file-upload-progress
              v-model:part="zz_img"
              list-type="picture-card"
              accept=".jpg,.png,.jpeg"
              :size-limit="5 * 1024"
              @compile="handleCompile"
            >
              <template #default>
                <el-icon size="38" color="#9d9ab9" v-if="formline.zz_img == ''">
                  <Picture />
                </el-icon>
                <img
                  v-else
                  :src="getFullUrl(formline.zz_img)"
                  alt=""
                  style="width: 100%; height: 100%"
                />
              </template>
              <template #tip>
                <div
                  style="
                    color: #949494;
                    font-size: 12px;
                    margin-left: 20px;
                    display: inline-block;
                    vertical-align: top;
                    line-height: 20px;
                  "
                >
                  支持格式：jpg,png,jpeg（5M以内） 建议尺寸600x320
                </div>
              </template>
            </file-upload-progress>
          </el-form-item>
          <el-form-item label="章节名称" prop="zz_name">
            <el-input v-model="formline.zz_name" />
          </el-form-item>
          <el-form-item label="上传文件" prop="zz_fj">
            <file-upload-progress
              v-model:part="formline.zz_fj"
              @compile="(data) => sourceUpload(data, 1)"
              accept=".doc,.docx,.xls,.xlsx,.pdf,.pptx,.mp3"
            >
              <template #default>
                <div
                  class="flex_center w-65px h-65px border border-dashed border-hex-E4E6E8 bg-hex-F9F9F9 text-hex-9D9AB9"
                >
                  <i-ant-design:folder-open-outlined class="text-xl" />
                </div>
                <div style="color: #949494" class="ml-30px">
                  支持格式：ppt,pptx,pdf,mp4（500M以内）
                </div>
              </template>
            </file-upload-progress>
          </el-form-item>

          <el-form-item label="上传视频" prop="zz_video">
            <file-upload-progress
              v-model:part="formline.zz_video"
              @compile="(data) => sourceUpload(data, 2)"
              :limit="10"
              accept=".mp4"
            >
              <template #default>
                <div
                  class="flex_center w-65px h-65px border border-dashed border-hex-E4E6E8 bg-hex-F9F9F9 text-hex-9D9AB9"
                >
                  <i-ant-design:folder-open-outlined class="text-xl" />
                </div>
              </template>
            </file-upload-progress>
          </el-form-item>
          <el-form-item label="是否需要审核" style="flex: 1">
            <el-radio-group v-model="formline.zz_sfxysh">
              <el-radio label="1" size="large">是</el-radio>
              <el-radio label="2" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-checkbox
              class="read"
              v-model="isRead"
              label="已阅读并同意《课程上传协议》"
              size="large"
            />
          </el-form-item>
          <el-form-item>
            <div class="btnDiv">
              <el-button type="primary" @click="submitForm('formline')"
                >提 交</el-button
              >
              <el-button @click="closeCreate()">关 闭</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElConfigProvider, ElMessage } from "element-plus";
import zhcn from "element-plus/dist/locale/zh-cn.mjs";
import user from "~/store/user";
import { dealWithDateTime } from "~/utils/common-util.js";
import { upload_file, zxxx_add, zxxx_edit, zxxx_detail } from "./api";
import { Picture, FolderOpened } from "@element-plus/icons-vue";
import { getFullUrl } from "@/utils/helper";
import MultiFileUpload from "./components/MultiFileUpload.vue";
export default {
  data() {
    return {
      loading: false,
      id: "",
      parentId: "",
      formline: {
        zz_fj: "",
        zz_video: "",
        zz_img: "",
        zz_name: "",
        zzc_id: "",
        zz_sfxysh: "",
      },
      rules: {
        zz_img: [
          { required: true, message: "请上传章节封面", trigger: "submit" },
        ],
        zz_name: [
          { required: true, message: "请输入章节名称", trigger: "blur" },
        ],
      },
      local: zhcn,
      https: window.GLOBAL_CONFIG.api,
      zz_id: "",
      wholeData: {},
      zz_img: "",
      fileList: [],
      mainFileData: ["png", "jpg", "jpeg"],
      mainFileSize: 200,
      mainTip: "",
      gradeData: [],
      subjectData: [],
      isRead: false,
      loading: true,
      scourceFile1: [],
      scourceFile2: [],
    };
  },
  components: { Picture, FolderOpened, MultiFileUpload },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    // 初始化
    initValue() {
      // 判断是新建还是编辑
      let id = this.$route.query.id;
      // 编辑
      if (id != undefined) {
        let data = {
          zz_id: this.$route.query.id,
        };
        zxxx_detail(data).then((res) => {
          if (res.code == 1) {
            this.wholeData = res.data.one_info;
            this.formline.zz_sfxysh = res.data.one_info.zz_sfxysh_option_k;
            console.log(this.wholeData, 111243);
            for (let key in this.formline) {
              this.formline[key] = res.data.one_info[key];
            }
            this.fileList = [
              {
                url: getFullUrl(this.formline.zz_img),
              },
            ];
            let m = res.data.one_info.zz_fj_json;
            if (m != "") {
              this.wholeData.fjData = JSON.parse(m);
            }
            this.scourceFile1 = [];
            this.scourceFile2 = [];
            if (this.wholeData.fjData != "") {
              this.wholeData.fjData.map((item) => {
                let suffix = item.file_url.substr(
                  item.file_url.lastIndexOf(".") + 1
                );
                if (suffix == "mp4") {
                  this.scourceFile2.push(item);
                } else {
                  this.scourceFile1.push(item);
                }
              });
            }
            console.log(
              this.wholeData.fjData,
              this.scourceFile2,
              this.scourceFile1,
              111
            );
            this.loading = false;
          }
        });
      }
      // 新建
      else {
        for (let key in this.formline) {
          this.formline[key] = "";
        }
        this.formline.zz_sfxysh = "1";
        this.loading = false;
      }
    },
    handleCompile(fileList) {
      let data = fileList[fileList.length - 1];
      this.formline.zz_img = data.response.data.url;
    },
    // 封面图
    handleMainChange(file) {
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isJPG = this.mainFileData.includes(fileType);
      const sizeLimit = file.size / 1024 < this.mainFileSize;
      if (!isJPG) {
        this.mainTip = "上传文件只能是jpg,png,jpeg格式";
      }
      if (!sizeLimit) {
        this.mainTip = "上传文件不能超过200KB";
      }
      if (isJPG && sizeLimit) {
        this.fileList = [file];
      } else {
        this.fileList = [];
      }

      if (this.fileList?.length == 0) {
        return false;
      }

      upload_file(file.raw).then((res) => {
        if (res.code == 1) {
          this.formline.zz_img = res.data.url;
          console.log(file.raw, 1123);
        } else {
          this.mainTip = "上传失败";
        }
      });
    },
    sourceUpload(data, type) {
      this["scourceFile" + type] = [];
      console.log(data, 111);
      data.map((item) => {
        let obj = {
          file_url: "",
          file_name: item.name,
          upload_user: user.user_realname,
          upload_time: dealWithDateTime(new Date()),
        };
        if (item.part_url) {
          obj.file_url = item.part_url;
        } else if (item.response && item.response.data) {
          obj.file_url = item.response.data.url;
        }
        console.log(this.wholeData, 22);
        console.log(this.wholeData.fjData, 111);
        if (this.wholeData.fjData) {
          this.wholeData.fjData.map((value) => {
            if (obj.file_url == value.file_url) {
              obj.upload_user = value.upload_user;
              obj.upload_time = value.upload_time;
              obj.file_name = value.file_name;
            }
          });
        }
        this["scourceFile" + type].push(obj);
      });

      console.log(this.wholeData.fjData, this["scourceFile" + type]);
    },
    // 提交
    submitForm(formName) {
      if (!this.isRead) {
        this.$message({
          message: "请勾选课程上传协议书。",
          type: "error",
        });
        return;
      }
      let id = this.$route.query.id;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formline.zz_img == "") {
            this.mainTip = "请上传课程封面图";
            return;
          }
          if (this.formline.zz_fj == "" && this.formline.zz_video == "") {
            this.$message({
              message: "请上传资源或视频。",
              type: "error",
            });
            return;
          }
          let arr = this.scourceFile2.concat(this.scourceFile1);
          console.log(JSON.stringify(arr, 123));

          let data = {
            zz_img: this.formline.zz_img,
            zz_name: this.formline.zz_name,
            zz_fj: this.formline.zz_fj,
            zz_video: this.formline.zz_video,
            zz_fj_json: JSON.stringify(arr),
            zzc_id: this.parentId,
            zz_sfxysh: this.formline.zz_sfxysh,
          };

          if (this.formline.zz_sfxysh == "1") {
            data.zz_shzt = "2";
          } else {
            data.zz_shzt = "1";
          }
          //   console.log(data, 123);
          if (id == undefined) {
            zxxx_add(data).then((res) => {
              if (res.code == 1) {
                this.$message({
                  message: "添加成功！",
                  type: "success",
                });
                this.goBack();
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                });
              }
            });
          } else {
            try {
              Object.assign(data, { zz_id: id });
              zxxx_edit(data).then((res) => {
                if (res.code == 1) {
                  this.$message({
                    message: "编辑成功！",
                    type: "success",
                  });
                  this.goBack();
                } else {
                  this.$message({
                    message: res.msg,
                    type: "error",
                  });
                }
              });
            } catch (error) {
              console.error(error);
            }
          }
        } else {
          return false;
        }
      });
    },
    // 关闭
    closeCreate() {
      let id = this.$route.query.id;
      if (id === undefined) {
        for (let key in this.formline) {
          this.formline[key] = "";
        }
      }
      this.$router.go(-1);
    },
  },
  created() {
    this.parentId = this.$route.query.parentId;
    this.id = this.$route.query.id || "";

    this.initValue();
  },
};
</script>

<style lang="scss" scoped>
.mask {
  border: 1px solid red;
  z-index: 4;
  width: 100%;
  height: 196px;
  // display: block;
  // position: absolute;

  // top: 0;
  // left: 0;
  background: rgba(0, 0, 0, 0.4) url("@/assets/img/zhjy/start.png") no-repeat
    center;
  cursor: pointer;
}
.to-back {
  width: 100px;
  height: 40px;
  background: rgba(0, 163, 255, 0.8);
  border-radius: 6px;
  font-size: 14px;
  font-family: PingFang SC, PingFang SC-Regular;
  font-weight: 400;
  text-align: center;
  color: #ffffff;
  line-height: 40px;
}
:deep() {
  .kcfmt {
    .el-upload--picture-card {
      width: 180px;
      height: 96px;
    }

    .el-upload-list.el-upload--picture-card,
    .el-upload-list__item {
      display: none;
    }
  }
}
.createZyCourse::v-deep {
  .el-card {
    margin-bottom: 15px;
    background: #fff;
  }

  .pointer {
    cursor: pointer;
  }

  .title {
    font-size: 18px;
    color: #050026;
  }

  .subTitle {
    font-size: 14px;
    color: #949494;
    margin-left: 45px;
  }

  .formContent {
    width: 575px;
    margin: auto;

    .el-form-item {
      &.is-required {
        .el-form-item__label {
          &::before {
            display: none;
          }

          &::after {
            content: "*";
            color: #f35421;
            margin-left: 4px;
          }
        }
      }

      .el-form-item__label {
        color: #949494;
        font-size: 14px;
        position: relative;
      }

      .el-form-item__content {
        .el-select {
          width: 100%;
        }

        .el-input {
          width: 100%;

          .el-input__wrapper {
            width: 100%;
            box-shadow: none;
            background: #f9f9f9;
            border-radius: 6px;
          }
        }

        .el-textarea {
          .el-textarea__inner {
            box-shadow: none;
            background: #f9f9f9;
            border-radius: 6px;
            // color: #d0d0d0;
          }
        }

        .el-checkbox.read {
          .el-checkbox__inner {
            border-radius: 50%;
          }
        }

        .el-input__inner {
          // color: #d0d0d0;
        }
      }
    }

    .must {
      display: flex;
      align-items: center;
      margin-bottom: 22px;

      .label {
        color: #949494;
        font-size: 14px;
        margin-right: 15px;

        &::after {
          content: "*";
          color: #f35421;
          margin-left: 4px;
        }
      }

      .uploadDiv {
        flex: 1;

        .el-upload--picture-card {
          width: 180px;
          height: 96px;
        }

        .mainUpload {
          .el-upload--picture-card {
            width: 180px;
            height: 96px;
          }

          .el-upload-list--picture-card .el-upload-list__item {
            display: none;
          }
        }

        .attachUpload {
          .el-upload-dragger {
            width: 65px;
            height: 65px;
            padding: 0;
            line-height: 65px;
            background: #f9f9f9;
          }
        }

        .tips {
          img {
            width: 90px;
            height: 48px;
            border-radius: 4px;
            margin-right: 10px;
          }
        }
      }
    }

    .showType {
      width: 100%;
      height: 40px;
      background: #f9f9f9;
      border-radius: 6px;
      display: flex;
      align-items: center;
      padding: 0 20px;

      .typeItem {
        color: #fff;
        font-size: 13px;
        padding: 3px 8px;
        border-radius: 6px;
        margin-right: 20px;
        line-height: 22px;
      }
    }

    .type {
      padding: 0 20px;
      margin-bottom: 10px;

      .flex {
        display: flex;
        align-items: baseline;

        .label {
          font-size: 13px;
          color: #333;

          &::after {
            content: "*";
            color: #f35421;
            margin-left: 4px;
          }
        }

        .valueDiv {
          margin-left: 15px;
          flex: 1;
          display: flex;
          flex-wrap: wrap;
          color: #949494;
          padding-bottom: 15px;
          font-weight: 400;
          font-size: 14px;

          .item {
            padding: 3px 5px;
            margin-right: 20px;
            margin-bottom: 5px;

            &.active {
              color: #00a3ff;
              border-radius: 6px;
              background: rgba($color: #00a3ff, $alpha: 0.1);
            }
          }
        }
      }
    }

    .btnDiv {
      text-align: center;
      width: 100%;

      .el-button {
        background: #f4f4f4;
        border: none;
        width: 160px;
        height: 50px;
        color: #41387f;
        font-family: PingFangSC, PingFangSC-Semibold;
      }

      .el-button--primary {
        background: #00a3ff;
        margin-right: 80px;
        color: #fff;
      }
    }
  }
}
</style>
