<template>
  <div id="commodityManageMentEdit">
    <el-form
      label-position="right"
      label-width="135px"
      :model="listData"
      :rules="rules"
      ref="listData"
    >
      <h5>商品信息</h5>
      <div class="boxBorderStyle">
        <h5 class="segmentationStyle">基本信息</h5>
        <product-information
          ref="productInformation"
          :listData="listData"
          :submitStatusInfo="submitStatusInfo"
          @activeExternalLinkStatus="activeExternalLinkStatus"
        />
        <h5 class="segmentationStyle">商品价格和有效期</h5>
        <price-period ref="pricePeriod" :listData="listData" />
        <div
          v-if="
            (listData.goodsType === 1 || listData.goodsType === 6) &&
            listData.businessId
          "
        >
          <h5 class="segmentationStyle">课程内容</h5>
          <course-content
            ref="courseContent"
            :listData="listData"
            :submitStatusInfo="submitStatusInfo"
          />
        </div>
        <div v-if="listData.goodsType === 2 && listData.businessId">
          <h5 class="segmentationStyle">题卷内容</h5>
          <bank-content ref="bankContent" :listData="listData" />
        </div>
        <div
          v-if="
            (listData.goodsType === 3 || listData.goodsType === 4) &&
            listData.businessId
          "
        >
          <h5 class="segmentationStyle">
            {{
              listData.goodsType === 3
                ? "关联商品和补考次数"
                : listData.goodsType === 4
                ? "关联商品和前培次数"
                : ""
            }}
          </h5>
          <make-up-exam ref="makeUpExam" :listData="listData" />
        </div>
        <!-- 学习次数及服务时间 -->
        <configure-content-parameters
          v-if="listData.businessId && listData.goodsType"
          ref="configureContentParameters"
          :listData="listData"
          :rules="rules"
        />
        <!-- end -->
        <div
          v-if="
            listData.businessId &&
            (listData.goodsType === 1 || listData.goodsType === 6)
          "
        >
          <h5 class="segmentationStyle">关联证书</h5>
          <issue-acertificate ref="issueAcertificate" :listData="listData" />
        </div>
      </div>
      <h5>商品包装介绍</h5>
      <div class="boxBorderStyle">
        <introduction ref="introduction" :listData="listData" />
      </div>
      <div style="text-align: center; margin-top: 20px">
        <el-button @click="backPage" size="mini">取消</el-button>
        <el-button
          type="primary"
          @click="submitForm('listData')"
          size="mini"
          :loading="disabledBtn"
          >保存</el-button
        >
        <el-button
          type="primary"
          @click="
            listData.goodsStatus === 0
              ? submitForm('listData', 1)
              : submitForm('listData', 0)
          "
          size="mini"
          :loading="disabledBtn"
          >{{
            listData.goodsStatus === 0
              ? "上架"
              : listData.goodsStatus === 1
              ? "下架"
              : "未知"
          }}</el-button
        >
      </div>
    </el-form>
  </div>
</template>

<script>
import productInformation from "./productInformation.vue";
import pricePeriod from "./pricePeriod.vue";
import courseContent from "./courseContent/index.vue";
import bankContent from "./bankContent/index.vue";
import makeUpExam from "./makeUpExam/index.vue";
import configureContentParameters from "./configureContentParameters.vue";
import issueAcertificate from "./issueAcertificate.vue";
import introduction from "./introduction.vue";
export default {
  name: "CommodityManageMentEdit",
  components: {
    productInformation,
    pricePeriod,
    courseContent,
    bankContent,
    configureContentParameters,
    issueAcertificate,
    introduction,
    makeUpExam,
  },
  data() {
    var validatorClassHours = (rule, value, callback) => {
      console.log(123);
      var reg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
      if (!reg.test(value)) {
        return callback(new Error("请规范输入学时"));
      } else {
        callback();
      }
    };
    var validatorCheckPhone = (rule, value, callback) => {
      if (rule.required) {
        if (!value) {
          return callback(new Error(rule.message));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    var validatorstandPrice = (rule, value, callback) => {
      var reg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
      if (!reg.test(value)) {
        return callback(new Error("请输入不超过两位小数点的价格数值"));
      } else {
        this.$refs["listData"].validateField("lowestPrice");
        callback();
      }
    };
    var validatorlowestPrice = (rule, value, callback) => {
      var reg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
      if (!reg.test(value)) {
        return callback(new Error("请输入不超过两位小数点的价格数值"));
      } else if (
        this.listData.standPrice &&
        parseFloat(value) > parseFloat(this.listData.standPrice)
      ) {
        return callback(new Error("价格不得高于商品标准价格"));
      } else {
        callback();
      }
    };
    var checkPwd = (rule, value, callback) => {
      var reg = /^[1-9]\d*$/;
      if (value) {
        if (!reg.test(value)) {
          return callback(new Error("请输入正整数"));
        } else if (value < this.copyNums) {
          return callback(new Error(`不能小于${this.copyNums}次`));
        } else {
          callback();
        }
      } else {
        if (this.copyNums >= 0) {
          return callback(new Error(`不能小于${this.copyNums}次`));
        } else {
          callback();
        }
      }
    };
    var checkExamPwd = (rule, value, callback) => {
      var reg = /^[0-9]\d*$/;
      if (value || value === 0) {
        if (!reg.test(value)) {
          return callback(new Error("请输入自然数"));
        } else if (rule.field === "examNumber" && value < this.copyExamNumber) {
          return callback(new Error(`不能小于${this.copyExamNumber}次`));
        } else if (rule.field === "doNumber" && value < this.copyDoNumber) {
          return callback(new Error(`不能小于${this.copyDoNumber}次`));
        } else {
          callback();
        }
      } else {
        if (rule.field === "examNumber" && this.copyExamNumber >= 0) {
          return callback(new Error(`不能小于${this.copyExamNumber}次`));
        } else if (rule.field === "doNumber" && this.copyDoNumber >= 0) {
          return callback(new Error(`不能小于${this.copyDoNumber}次`));
        } else {
          callback();
        }
      }
    };
    var checkinteger = (rule, value, callback) => {
      var reg = /^([1-9][0-9]*){1,3}$/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入非零正整数"));
      }
    };
    var checkGoodsTime = (rule, value, callback) => {
      if (this.listData.timeArrays && this.listData.timeArrays.length) {
        if (
          this.listData.timeArrays[0] < this.listData.studyTimeArrays[0] ||
          this.listData.timeArrays[1] > this.listData.studyTimeArrays[1]
        ) {
          return callback(
            new Error("商品有效期范围必须包含在学习服务期范围内，请重新调整")
          );
        }
        return callback();
      } else {
        callback();
      }
    };
    return {
      listData: {
        coverUrl: "oss/images/avatar/20211013/1634097664410_1397766697",
        goodsType: "",
        certificateTypeId: "",
        commitPeriodStatus:0
      },
      rules: {
        year: [
          {
            required: false,
            message: "请选择年份",
            trigger: "change",
          },
        ],
        supplyId: [
          {
            required: false,
            message: "请选择供应商",
            trigger: "change",
            validator: validatorCheckPhone,
          },
        ],
        goodsType: [
          {
            type: "number",
            required: true,
            message: "请选择商品类型",
            trigger: "change",
          },
        ],
        goodsName: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        externalLink: [
          {
            required: false,
            message: "请输入外链地址",
            trigger: "blur",
          },
        ],
        educationTypeId: [
          {
            type: "number",
            required: true,
            message: "请选择教育类型",
            trigger: "change",
          },
        ],
        businessId: [
          {
            type: "number",
            required: true,
            message: "请选择业务层次",
            trigger: "change",
          },
        ],
        schoolId: [
          {
            required: false,
            message: "请选择院校",
            trigger: "change",
            validator: validatorCheckPhone,
          },
        ],
        majorId: [
          {
            required: false,
            message: "请选择专业",
            trigger: "change",
            validator: validatorCheckPhone,
          },
        ],
        subjectIds: [
          {
            type: "array",
            required: true,
            message: "请选择科目",
            trigger: "change",
          },
        ],
        classHours: [
          {
            required: false,
            message: "请输入学时",
            trigger: "blur",
            validator: validatorCheckPhone,
          },
        ],
        coverUrl: [
          {
            required: true,
            message: "请选择封面",
            trigger: ["blur", "change"],
          },
        ],
        timeArrays: [
          {
            type: "array",
            required: true,
            message: "请选择有效期",
            trigger: ["blur", "change"],
          },
        ],
        status: [
          {
            type: "number",
            required: true,
            message: "请选择状态",
            trigger: "change",
          },
        ],
        standPrice: [
          {
            required: true,
            message: "请输入标准价格",
            trigger: "blur",
            type: "number",
          },
          { validator: validatorstandPrice, trigger: "blur" },
        ],
        lowestPrice: [
          {
            required: true,
            message: "请输入最低价格",
            trigger: "blur",
            type: "number",
          },
          { validator: validatorlowestPrice, trigger: "blur" },
        ],
        standPriceJson: [
          {
            type: "array",
            required: false,
            message: "请添加商品标准价格明细",
            trigger: ["blur", "change"],
          },
        ],
        courseList: [
          {
            required: false,
            message: "请选择课程",
            trigger: "change",
          },
        ],
        makeGoodsId: [
          {
            required: true,
            message: "请选择关联商品",
            trigger: "blur",
          },
        ],
        examNumber: [
          {
            type: "number",
            required: false,
            message: "请输入次数",
            trigger: "blur",
          },
          { validator: checkExamPwd, trigger: "blur" },
        ],
        doNumber: [
          {
            type: "number",
            required: false,
            message: "请输入次数",
            trigger: "blur",
          },
          { validator: checkExamPwd, trigger: "blur" },
        ],

        studyCount: [
          {
            type: "number",
            required: false,
            message: "请输入次数",
            trigger: "blur",
          },
          { validator: checkPwd, trigger: "blur" },
        ],
        serviceTimeType: [
          {
            type: "number",
            required: false,
            message: "请选择学习服务期类型",
            trigger: "change",
          },
        ],
        serviceTimeNum: [
          {
            required: false,
            message: "请输入非零正整数",
            trigger: "blur",
          },
          {
            validator: checkinteger,
            trigger: "blur",
          },
        ],
        studyTimeArrays: [
          {
            required: true,
            message: "请选择学习服务具体时间段",
            trigger: ["blur", "change"],
          },
          {
            validator: checkGoodsTime,
            trigger: ["blur", "change"],
          },
        ],
        certificateTypeId: [
          {
            required: false,
            message: "请选择证书类型",
            validator: validatorCheckPhone,
            trigger: "change",
          },
        ],
        certificateId: [
          {
            validator: validatorCheckPhone,
            required: false,
            message: "请选择证书名称",
            trigger: "change",
          },
        ],
        certificateTpId: [
          {
            validator: validatorCheckPhone,
            required: false,
            message: "请选择证书模板",
            trigger: "change",
          },
        ],
        introduce: [
          {
            required: false,
            message: "请输入商品简介",
            trigger: "blur",
          },
        ],
        suitableObject: [
          {
            required: false,
            message: "请输入适用对象",
            trigger: "blur",
          },
        ],
        buyNote: [
          {
            required: false,
            message: "请输入学员须知",
            trigger: "blur",
          },
        ],
        pcDetailHtml: [
          {
            required: false,
            message: "请输入PC端商品详情",
            trigger: ["blur", "change"],
          },
        ],
        mobileDetailHtml: [
          {
            required: false,
            message: "请输入手机端商品详情",
            trigger: ["blur", "change"],
          },
        ],
      },
      disabledBtn: false,
      goodsId: "",
      submitStatusInfo: false,
      examConfigList: [],
      auditionList: [],
    };
  },
  created() {
    this.$modal.loading("正在导入数据，请稍后...");
    this.goodsId = this.$route.query.id;
  },
  mounted() {
    this.$bus.$on("clearValidateFunc", () => {
      this.$nextTick(() => {
        this.$refs.listData.clearValidate();
      });
    });
    this.$bus.$on("validateMakeId", () => {
      this.$nextTick(() => {
        if (this.$refs["listData"]) {
          this.$refs["listData"].validateField("makeGoodsId");
        }
      });
    });
    this.$bus.$on("validateCoverUrl", () => {
      this.$nextTick(() => {
        if (this.$refs["listData"]) {
          this.$refs["listData"].validateField("coverUrl");
        }
      });
    });
    this.$bus.$on("initTimeVal", () => {
      this.$refs["listData"].clearValidate("serviceTimeNum");
      this.$refs["listData"].clearValidate("studyTimeArrays");
    });
    this.$bus.$on("againValidate", () => {
      this.$nextTick(() => {
        if (this.$refs["listData"]) {
          this.$refs["listData"].validateField("studyTimeArrays");
        }
      });
    });
    this.$bus.$on("getCheckRequired", (id) => {
      this.getCheckRequired(id);
    });
    this.$bus.$on("getCheckQuitRequired", (id) => {
      this.getCheckQuitRequired(id);
    });
    this.$bus.$on("checkStandPriceJson", () => {
      this.$refs["listData"].validateField("standPriceJson");
    });
    //修改商品初始逻辑
    this.getInit();
  },
  methods: {
    //判断是否必填外链
    activeExternalLinkStatus(e) {
      if (e) {
        this.rules.externalLink[0].required = true;
      } else {
        this.rules.externalLink[0].required = false;
      }
      this.$nextTick(() => {
        this.$refs["listData"].validateField("externalLink");
      });
    },
    /**
     * 动态字段模板
     */
    getCheckRequired(id) {
      this.$api.obtainbusiness(id).then((res) => {
        let arr = JSON.parse(res.data.goodsFieldJson);
        for (let i = 0; i < arr.length; i++) {
          for (let k in this.rules) {
            if (k === arr[i].fieldKey) {
              this.$set(
                this.rules[k][0],
                "required",
                arr[i].require == 1 ? true : false
              );
              this.$set(
                this.rules[k][0],
                "status",
                arr[i].status == 1 ? true : false
              );
              //删除type避免出现element隐藏bug
              // if (arr[i].require == 0) {
              //   if (this.rules[k][0].type) {
              //     this.rules[k][0]["types"] = this.rules[k][0]["type"];
              //     delete this.rules[k][0]["type"];
              //   }
              // } else {
              //   if (this.rules[k][0].types) {
              //     this.rules[k][0]["type"] = this.rules[k][0]["types"];
              //     delete this.rules[k][0]["types"];
              //   }
              // }
              break;
            }
          }
        }
        this.$nextTick(() => {
          this.$refs["listData"].clearValidate("subjectIds");
        });
      });
    },
    /**
     * 动态字段模板-商品类型非视频
     */
    getCheckQuitRequired(id) {
      let arr = this.$methodsTools.getTypeRules(this.listData.goodsType);
      for (let i = 0; i < arr.length; i++) {
        for (let k in this.rules) {
          if (k === arr[i].fieldKey) {
            this.$set(
              this.rules[k][0],
              "required",
              arr[i].require == 1 ? true : false
            );
            this.$set(
              this.rules[k][0],
              "status",
              arr[i].status == 1 ? true : false
            );
            //删除type避免出现element隐藏bug
            // if (arr[i].require == 0) {
            //   if (this.rules[k][0].type) {
            //     this.rules[k][0]["types"] = this.rules[k][0]["type"];
            //     delete this.rules[k][0]["type"];
            //   }
            // } else {
            //   if (this.rules[k][0].types) {
            //     this.rules[k][0]["type"] = this.rules[k][0]["types"];
            //     delete this.rules[k][0]["types"];
            //   }
            // }
            break;
          }
        }
      }
    },
    /**
     *获取项目类型Id
     */
    getProjectId(busId) {
      return new Promise((resolve, reject) => {
        for (
          let i = 0;
          i < this.$refs.productInformation.newCourTypeOptions.length;
          i++
        ) {
          if (
            busId === this.$refs.productInformation.newCourTypeOptions[i].id
          ) {
            resolve(
              this.$refs.productInformation.newCourTypeOptions[i].projectId
            );
            break;
          }
        }
      });
    },
    /**
     * 初始化参数获取
     */
    getInit() {
      this.checkSubmitInfo();
      this.search();
    },
    /**
     * 商品详细数据
     */
    search() {
      this.$api.obtainGoods(this.goodsId).then((res) => {
        var auditionList;
        var examConfigList;
        this.activeExternalLinkStatus(res.data.externalLinkStatus);
        //年份转字符串-防止报错
        if (res.data.year) {
          res.data.year = res.data.year.toString();
        } else {
          res.data.year = "";
        }
        //科目转数值
        if (res.data.subjectIds) {
          res.data.subjectIds = res.data.subjectIds.split(",").map(Number);
        } else {
          res.data.subjectIds = [];
        }
        //商品标准价格明细表转换
        if (res.data.standPriceJson) {
          res.data.standPriceJson = JSON.parse(res.data.standPriceJson);
        } else {
          res.data.standPriceJson = [];
        }
        //商品有效期转换
        res.data.timeArrays = [
          this.$methodsTools.time10to13(res.data.validityStartTime, 2),
          this.$methodsTools.time10to13(res.data.validityEndTime, 2),
        ];
        //拷贝初始学习次数-考试次数-刷题机会
        this.copyNums = res.data.studyCount;
        this.copyExamNumber = res.data.examNumber || 0;
        this.copyDoNumber = res.data.doNumber || 0;
        //试听转换
        if (
          res.data.goodsAuditionConfig &&
          (res.data.goodsType == 1 || res.data.goodsType == 6)
        ) {
          var goodsAuditionConfig = JSON.parse(res.data.goodsAuditionConfig);
          auditionList = goodsAuditionConfig.map((item) => {
            return {
              TypeId: "3-" + item.sectionId,
              menuId: item.sectionId,
              courseId: item.courseId,
              auditionMinute: this.$methodsTools.secondToDate(
                item.auditionMinute,
                false
              ),
              type: 3,
            };
          });
        }
        //试做转换
        if (res.data.goodsExamConfig && res.data.goodsType == 2) {
          var goodsExamConfig = JSON.parse(res.data.goodsExamConfig);
          examConfigList = goodsExamConfig.map((item) => {
            var ast = {};
            if (item.moduleExamId && item.chapterExamId && item.examId) {
              ast.TypeId =
                "3-" +
                item.moduleExamId +
                "-" +
                item.chapterExamId +
                "-" +
                item.examId;
              ast.moduleExamId = item.moduleExamId;
              ast.chapterExamId = item.chapterExamId;
            }
            if (!item.moduleExamId && item.chapterExamId && item.examId) {
              ast.TypeId = "3-" + item.chapterExamId + "-" + item.examId;
              ast.chapterExamId = item.chapterExamId;
            }
            if (!item.moduleExamId && !item.chapterExamId && item.examId) {
              ast.TypeId = "3-" + item.examId;
            }
            ast.examId = item.examId;
            ast.num = item.num;
            return ast;
          });
        }
        //拷贝补考/前培ID 解决无法选中当前ID问题
        if (res.data.goodsType == 3 || res.data.goodsType == 4) {
          res.data.copyMakeGoodsId = res.data.makeGoodsId;
        }
        //学习服务期转换
        if (
          (res.data.goodsType === 1 ||
            res.data.goodsType === 2 ||
            res.data.goodsType === 6) &&
          res.data.serviceTimeType === 4
        ) {
          res.data.studyTimeArrays = [
            this.$methodsTools.time10to13(res.data.studyStartTime, 2),
            this.$methodsTools.time10to13(res.data.studyEndTime, 2),
          ];
        }
        //播放和拍照设置转换
        if (res.data.goodsType == 1 || res.data.goodsType == 6) {
          if (res.data.goodsPlayConfig) {
            res.data.playConfig = JSON.parse(res.data.goodsPlayConfig);
          }
          if (res.data.goodsPhotographConfig) {
            res.data.photographConfig = JSON.parse(
              res.data.goodsPhotographConfig
            );
          }
          if (res.data.goodsPhotoExamConfig) {
            res.data.goodsPhotographExamConfig = JSON.parse(
              res.data.goodsPhotoExamConfig
            );
          }
        }
        this.listData = res.data;
        //课程内容转换
        if (res.data.goodsType === 1 || res.data.goodsType === 6) {
          this.$nextTick(() => {
            //试听传输
            this.$refs.courseContent.getBybusCourseAudition(auditionList);
            //课程内容传输
            this.$refs.courseContent.getBybusCoursetableData(this.goodsId);
          });
        }
        //题库内容转换
        if (res.data.goodsType === 2) {
          this.$nextTick(() => {
            //试做传输
            this.$refs.bankContent.getBybusBankexam(examConfigList);
            //题库内容传输
            this.$refs.bankContent.getBybusBanktableData(this.goodsId);
          });
        }
        this.$modal.closeLoading();
      });
    },
    /**
     * 查看当前商品有无学员进入学习
     */
    checkSubmitInfo() {
      this.$api.gradecheckGoodsChange({ goodsId: this.goodsId }).then((res) => {
        if (res.data > 0) {
          this.submitStatusInfo = true;
        }
      });
    },
    /**
     * 校验表单
     */
    submitForm(formName, int) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitApi(int);
        } else {
          return false;
        }
      });
    },
    async submitApi(int) {
      this.disabledBtn = true;
      let data = JSON.parse(JSON.stringify(this.listData));
      //--------------------------通用处理START----------------------------
      //商品有效期时间格式转换
      data.validityStartTime = this.$methodsTools.time10to13(
        data.timeArrays[0],
        1
      );
      data.validityEndTime = this.$methodsTools.time10to13(
        data.timeArrays[1],
        1
      );
      if (data.serviceTimeType === 4) {
        data.studyStartTime = this.$methodsTools.time10to13(
          data.studyTimeArrays[0],
          1
        );
        data.studyEndTime = this.$methodsTools.time10to13(
          data.studyTimeArrays[1],
          1
        );
      }
      //商品标准价格明细表
      data.standPriceJson = JSON.stringify(data.standPriceJson);
      //商品是否上架
      if (int >= 0) {
        data.goodsStatus = int;
      }
      data.subjectIds = data.subjectIds.toString();
      data.projectId = await this.getProjectId(data.businessId);
      //--------------------------通用处理END------------------------------
      if (this.listData.goodsType === 1 || this.listData.goodsType === 6) {
        //视频商品参数转换
        await this.goodsVideoFunc(data);
        this.$api
          .editGoods(data)
          .then((res) => {
            this.$message.success("修改成功");
            setTimeout(() => {
              this.$store
                .dispatch("tagsView/exitView", this.$route)
                .then((res) => {
                  this.$router.push({
                    path: "CommodityManageMent",
                  });
                });
            }, 300);
          })
          .catch(() => {
            this.disabledBtn = false;
          });
      }
      if (this.listData.goodsType === 2) {
        //视频商品参数转换
        await this.goodsBankFunc(data);
        this.$api
          .editGoodsbank(data)
          .then((res) => {
            this.$message.success("修改成功");
            setTimeout(() => {
              this.$store
                .dispatch("tagsView/exitView", this.$route)
                .then((res) => {
                  this.$router.push({
                    path: "CommodityManageMent",
                  });
                });
            }, 300);
          })
          .catch(() => {
            this.disabledBtn = false;
          });
      }
      if (this.listData.goodsType === 3) {
        this.$api
          .editGoodsmake(data)
          .then((res) => {
            this.$message.success("修改成功");
            setTimeout(() => {
              this.$store
                .dispatch("tagsView/exitView", this.$route)
                .then((res) => {
                  this.$router.push({
                    path: "CommodityManageMent",
                  });
                });
            }, 300);
          })
          .catch(() => {
            this.disabledBtn = false;
          });
      }
      if (this.listData.goodsType === 4) {
        this.$api
          .editGoodsfront(data)
          .then((res) => {
            this.$message.success("修改成功");
            setTimeout(() => {
              this.$store
                .dispatch("tagsView/exitView", this.$route)
                .then((res) => {
                  this.$router.push({
                    path: "CommodityManageMent",
                  });
                });
            }, 300);
          })
          .catch(() => {
            this.disabledBtn = false;
          });
      }
    },
    /**
     * 视频商品参数转换
     */
    goodsVideoFunc(data) {
      return new Promise((resolve, reject) => {
        //查看该业务层次下课程是否必填
        if (this.rules["courseList"][0].required) {
          if (this.$refs.courseContent.tableData.length <= 0) {
            this.$message.error("请添加课程内容");
            return;
          }
        }
        //查看该业务层次下富文本是否必填
        if (this.rules["pcDetailHtml"][0].required) {
          if (!this.listData.pcDetailHtml) {
            this.$message.error("请编辑PC端商品详情");
            return;
          }
        }
        if (this.rules["mobileDetailHtml"][0].required) {
          if (!this.listData.mobileDetailHtml) {
            this.$message.error("请编辑手机端商品详情");
            return;
          }
        }
        //课程排序问题检查
        for (let i = 0; i < this.$refs.courseContent.tableData.length; i++) {
          if (
            !this.$refs.courseContent.tableData[i].sort &&
            this.$refs.courseContent.tableData[i].sort !== 0
          ) {
            this.$message.warning(`课程内容第${i + 1}条请输入排序`);
            this.disabledBtn = false;
            return;
          }
        }
        let arr = this.$refs.courseContent.tableData.map((items) => {
          return items.sort;
        });
        if (new Set(arr).size != arr.length) {
          this.$message.warning("排序不允许有重复值");
          this.disabledBtn = false;
          return;
        }
        //试听数据格式转换
        data.auditionList = this.$refs.courseContent.auditionList.map(
          (item) => {
            return {
              auditionMinute: this.$methodsTools.secondFormDate(
                item.auditionMinute
              ),
              courseId: item.courseId,
              sectionId: item.menuId,
            };
          }
        );
        //课程数据格式转换
        if (this.$refs.courseContent.tableData.length > 0) {
          if (this.$refs.courseContent.tableData[0].type) {
            data.menuList = this.$refs.courseContent.tableData.map((item) => {
              item.sort = Number(item.sort);
              return item;
            });
            data.courseList = [];
          } else {
            data.courseList = this.$refs.courseContent.tableData.map((item) => {
              return {
                courseId: item.courseId,
                sort: Number(item.sort),
              };
            });
            data.menuList = [];
          }
        } else {
          data.courseList = [];
          data.menuList = [];
        }
        this.$api
          .obtainCourseSgoodsId(this.listData.goodsId)
          .then((res) => {
            if (res.rows.length === 1 && res.rows[0].courseShow === 0) {
              data.courseId = res.rows[0].courseId;
            }
          })
          .finally(() => {
            resolve();
          });
      });
    },
    /**
     * 题库商品参数转换
     */
    goodsBankFunc(data) {
      return new Promise((resolve, reject) => {
        //题卷排序问题检查
        for (let i = 0; i < this.$refs.bankContent.tableData.length; i++) {
          if (
            !this.$refs.bankContent.tableData[i].sort &&
            this.$refs.bankContent.tableData[i].sort !== 0
          ) {
            this.$message.warning(`题卷内容第${i + 1}条请输入排序`);
            this.disabledBtn = false;
            return;
          }
        }
        let arr = this.$refs.bankContent.tableData.map((items) => {
          return items.sort;
        });
        if (new Set(arr).size != arr.length) {
          this.$message.warning("排序不允许有重复值");
          this.disabledBtn = false;
          return;
        }
        //试做数据格式转换
        data.examConfigList = this.$refs.bankContent.examConfigList.map(
          (item) => {
            return {
              num: item.num,
              chapterExamId: item.chapterExamId,
              examId: item.examId,
              moduleExamId: item.moduleExamId,
            };
          }
        );
        //题卷数据格式转换
        data.bankList = this.$refs.bankContent.tableData.map((item) => {
          if (item.type === 1) {
            return {
              majorId: item.moduleExamId,
              sort: Number(item.sort),
              type: item.type,
            };
          }
          if (item.type === 2) {
            return {
              majorId: item.chapterExamId,
              sort: Number(item.sort),
              type: item.type,
            };
          }
          if (item.type === 3) {
            return {
              majorId: item.examId,
              sort: Number(item.sort),
              type: item.type,
            };
          }
        });
        resolve();
      });
    },
    backPage() {
      this.$store.dispatch("tagsView/delView", this.$route).then((res) => {
        this.$router.push({
          path: "CommodityManageMent",
        });
      });
    },
  },
  /**
   * 销毁公交
   */
  beforeDestroy() {
    console.log(2);
    this.$bus.$off("clearValidateFuncAdd");
    this.$bus.$off("validateMakeId");
    this.$bus.$off("validateCoverUrl");
    this.$bus.$off("initTimeVal");
    this.$bus.$off("againValidate");
    this.$bus.$off("getCheckRequired");
    this.$bus.$off("getCheckQuitRequired");
    this.$bus.$off("checkStandPriceJson");
  },
};
</script>

<style lang="less" scoped>
.boxBorderStyle {
  margin: 10px 0px;
  border: 1px solid #a4a4a4;
  border-top: 2px solid rgb(179, 204, 255);
  padding: 20px 40px;
}
.segmentationStyle {
  border-bottom: 1px dashed #a4a4a4;
  color: #a4a4a4;
  padding: 4px 0px;
  margin-bottom: 20px;
}

/deep/.el-button {
  border-radius: 8px;
}
/deep/.el-dialog {
  border-radius: 8px;
  .el-dialog__header {
    padding: 0;
    .hearders {
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0px 18px 0px 20px;
      border-bottom: 1px solid #e2e2e2;
      .leftTitle {
        font-size: 14px;
        font-weight: bold;
        color: #2f4378;
      }
      .rightBoxs {
        display: flex;
        align-items: center;
        img {
          width: 14px;
          height: 14px;
          margin-left: 13px;
          cursor: pointer;
        }
      }
    }
  }
  .el-dialog__footer {
    padding: 0;
    .dialog-footer {
      padding: 0px 40px;
      height: 70px;
      border-top: 1px solid #e2e2e2;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}
.imgBox {
  width: 100%;
  // height: 210px;
  border: 1px solid #e2e2e2;
  border-radius: 8px;
  padding: 8px 8px 3px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .imgLabel {
    flex: 1;
    width: 100%;
    border: 1px dotted #e2e2e2;
    color: #999;
    font-size: 14px;
    cursor: pointer;
    border-radius: 8px;
    .msPhoto {
      display: flex;
      justify-content: center;
      align-items: center;
      max-width: 100%;
      max-height: 270px;
      img {
        max-width: 100%;
        max-height: 270px;
      }
    }
    .imgbbx {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      i {
        font-weight: bold;
        margin: 14px 0;
        font-size: 24px;
      }
    }
  }
  p {
    margin: 5px 0px;
  }
}
</style>
