<template>
  <div class="edit-custom-wrap">
    <bread-crumb
      :curmbFirst="curmbFirst"
      :curmbSecond="curmbSecond"
      :curmbThird="curmbThird"
      :jumPathThird="jumPathThird"
    ></bread-crumb>

    <div class="add-content-new screenSet" id="screenSet">
      <div class="step-content-new">
        <el-col style="width: 530px;">
          <el-steps :active="active" simple class>
            <span class="step-num" v-bind:class="{ 'on-step': active==0 }">1</span>
            <el-step title="选择项目课程">1</el-step>
            <span class="step-num" v-bind:class="{ 'on-step': active==1 }">2</span>
            <el-step title="填写项目信息">2</el-step>
            <span class="step-num" v-bind:class="{ 'on-step': active==2 }">3</span>
            <el-step title="选择学员范围">3</el-step>
          </el-steps>
        </el-col>
        <div>
          <div v-if="!canNext" class="dis-btn">下一步</div>
          <el-button class="dis-btn-b" v-if="active != 0 && projectStatus == 1 && isPreview != 1" size="small" @click="save">暂存</el-button>
          <el-button class="dis-btn-b" v-if="active !== 2 && canNext" size="small" type="primary" @click="nextStep">下一步</el-button>
          <el-button class="dis-btn-b" v-if="active == 2" size="small" type="primary" @click="complete">完成</el-button>
        </div>
      </div>

      <!-- 模板列表
        <div v-if="active == 0" class="tpl-main">
           <template-list @checkFn="checkFn"></template-list>
      </div>-->

      <!-- 选择课程 -->
      <div v-if="active == 0" class="tpl-main">
        <SelectCourseComp></SelectCourseComp>
      </div>

      <!-- 填写项目信息-->
      <!-- <template-message -->
      <custom-baseinfo
        ref="CustomBaseinfo"
        v-if="active == 1"
        :openTemplateId="openTemplateId"
        :projectId="projectId"
        :editor="editor"
        @next="next"
        @backSelectVue="backSelectVue"
        @hideSave="hideSave"
        @setStatus4Flag="setStatus4Flag"
      />

      <!-- 设定行政范围与设定机构 -->
      <div class="three-step" v-if="active === 2">
        <el-tabs v-model="activeName" @tab-click="handleClickTabs">
          <el-tab-pane label="设定行政范围" name="first">
            <select-region ref="selectRegion" :projectId="projectId" :status4Flag="status4Flag"></select-region>
          </el-tab-pane>
          <el-tab-pane label="设定机构" name="second">
            <set-organization
              ref="setOrganization"
              :projectId="projectId"
              :status4Flag="status4Flag"
            ></set-organization>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <dialog-componet :dialogObj="dialogObj" @hide="hide"></dialog-componet>
    <dialog-componet :dialogObj="sendObj" @hide="hidefn" @confirm="confirmFn"></dialog-componet>
  </div>
</template>

<script>
import BreadCrumb from "@/components/breadcrumb.vue";
// import CustomBaseinfo from "@/components/education/template/CustomBaseinfo";
import CustomBaseinfo from "@/components/education/custom/custom-baseinfo";
import selectTemplate from "@/components/education/template/selectTemplate";
import selectRegion from "@/components/education/template/selectRegion";
import setOrganization from "@/components/education/template/setOrganization";
import SelectCourseComp from "@/components/education/custom/select-course-comp";
import dialog from "@/components/education/template/dialog";
import { openLoading, closeLoading, resizeHeight } from "@/utils/utils";
import { mapGetters, mapActions } from "vuex";

let vm = null;
export default {
  data() {
    return {
      curmbFirst: "教培项目",
      curmbSecond: "项目管理",
      jumPathThird: "item-manager",
      curmbThird: "发起项目",
      active: 0,
      formTemplate: {
        component: [],
        configure: 2,
        certificate: ""
      },
      activeName: "first",
      canNext: false,
      openTemplateId: 0, // 开放模板ID
      projectId: "", // 项目id
      status: 10, // 0正常10没有加入机构11审核中12审核失败20存在进行中项目21数量已达上限
      editor: false, // 是否为编辑状态
      dialogObj: {
        visible: false,
        title: "",
        message: "",
        tip: "",
        hideMsg: ""
      },
      statusObj: {
        status_10: {
          title: "您暂未加入机构",
          message: "请前往云鹊医APP-个人中心-我的资料-填写工作所属机构。加入机构后，可创建项目",
          tip: "",
          hideMsg: "我知道了"
        },
        status_11: {
          title: "您创建的机构正在审核中",
          message: "请前往云鹊医APP-个人中心-我的资料-填写工作所属机构。加入机构后，可创建项目",
          tip: "",
          hideMsg: "我知道了"
        },
        status_12: {
          title: "您创建的机构审核不通过",
          message: "请前往云鹊医APP-个人中心-我的资料-填写工作所属机构。加入机构后，可创建项目",
          tip: "",
          hideMsg: "我知道了"
        },
        status_20: {
          title: "该项目正在进行中",
          message: "不能重复创建,请选择其他模版或者下架正在进行中的项目",
          hideMsg: "确定"
        },
        status_21: {
          title: "自定义项目创建数量已达上限",
          message: "本年度免费创建自定义项目数已达20次，不能继续创建",
          hideMsg: "确定"
        }
      },
      sendObj: {
        // 发布
        visible: false,
        title: "确定发布吗?",
        message:
          "发布后,项目将进入审核中,待审核完成后学员可在云鹊医App上参加培训学习",
        tip: "",
        confirmMsg: "取消",
        hideMsg: "确定发布"
      },
      projectStatus: 1, //1.草稿 2.未上架 3.审核中/待审核 4.已上架 5.已下架 6.已拒绝/未上架
      status4Flag: 0, //0表示没有上过架，1表示上过架
      isPreview: 0, // 1表示是查看信息
      maxLimitCreatedCustomProjectCountInYear: 20, // 同一个用户每年能够创建的项目数
      allSubList: [],
    };
  },
  computed: {
    ...mapGetters(["searchParam", "cartList"])
  },
  watch: {
    searchParam: {
      handler(val) {
        this.getCourseList(val);
      },
      deep: true
    },
    cartList(val) {
      this.canNext = val.length > 0;
    }
  },
  components: {
    BreadCrumb,
    CustomBaseinfo,
    selectTemplate,
    selectRegion,
    setOrganization,
    dialogComponet: dialog,
    SelectCourseComp
  },
  created() {
    vm = this;
    vm.isEditorFn();
    vm.isPreviewFn();
  },
  mounted() {
    resizeHeight();
    this.getLabelList();
    this.initPageParams();
    // this.initPageParams();
  },
  methods: {
    ...mapActions([
      "setSearchParam",
      "setCartList",
      "setCourseList",
      "setAllLabelList",
      "setSubLabelList",
      "setCourseLimitCount",
    ]),

    initPageParams(labelIdList) {
      let searchParam = {
        orderBy: 2,
        dir: 1,
        grade: 0,
        pageNo: 1,
        pageSize: 10,
        labelIdList: labelIdList || []
      };
      this.setCartList([]);
      this.setCourseList([]);
      this.setAllLabelList([]);
      this.setSubLabelList([]);
      this.courseLimitCount();
      // this.getLabelList();
      // this.getCourseList(searchParam);
    },

    // 自定义项目--选择课程个数限制(-1表示不限制)
    courseLimitCount() {
      vm.GET("portal/portalCustom/courseLimitCount", {}).then(res => {
        if (res.code == "000000") {
          this.setCourseLimitCount(res.data);
        }
      });
    },

    // 获取所有标签（一级及二级）,交做相应处理
    getLabelList() {
      vm.GET("contents/diseases/labelList", {}).then(res => {
        if (res.code == "000000") {
          // 先将所有的标签添加checked字段
          let labelList = res.data;
          let allSubList = [];
          let labelIdList = [];
          labelList.forEach((item, index) => {
            item.checked = false;
            item.subList.forEach((sub, subIndex) => {
              sub.parentIndex = index;
              sub.checked = true;
              if (subIndex == 0) {
                sub.id = `subid-${index}`;  // 将二级中的“全部”id改为可以识别的
              } else {
                allSubList.push(sub);
                labelIdList.push(sub.id);
              }
            });
          });
          // 构建其子标签
          allSubList.unshift({
            name: "全部",
            checked: true,
            id: 'parentid-0'
          });
          // 添加一级的“全部”标签，并构建其子标签
          labelList.unshift({
            name: "全部",
            checked: true,
            subList: allSubList
          });
          // this.initPageParams(labelIdList);
          this.setAllLabelList(labelList);
          this.setSubLabelList(allSubList);

          let searchParam = {
            orderBy: 2,
            dir: 1,
            grade: 0,
            pageNo: 1,
            pageSize: 10,
            labelIdList: labelIdList || []
          };
          this.setSearchParam(searchParam);
        }
      });
    },

    // （根据条件）查询课程
    getCourseList(searchParam) {
      vm.GET("contents/diseases/courseListForPortal", searchParam).then(res => {
        if (res.code == "000000") {
          let courseList = res.data, cartIndex = -1;
          courseList.list.forEach(item => {
            cartIndex = vm.cartList.findIndex( current => {
              return current.courseId == item.courseId;
            })
            if(cartIndex >= 0) {
              item.checked = true;
            } else {
              item.checked = false;
            }
          });
          this.setCourseList(courseList);
        }
      });
    },

    // 判断是否为编辑状态
    isEditorFn() {
      if (vm.$route.query.projectId) {
        vm.projectId = vm.$route.query.projectId;
        vm.editor = true;
        vm.active = 1;
        vm.canNext = true;
      }
    },

    // 判断是否为预览状态
    isPreviewFn() {
      if (vm.$route.query.isPreview == 1 && vm.$route.query.projectId) {
        vm.projectId = vm.$route.query.projectId;
        vm.isPreview = vm.$route.query.isPreview;
        vm.active = 1;
        vm.canNext = true;
      }
    },

    // 按钮点击下一步
    nextStep() {
      if (vm.active == 0) {
        vm.checkSelectCustomCourse();
        // vm.checkSelectTemplate()
        return;
      }
      if (vm.active == 1) {
        // 查看时，点击下一步直接跳
        if (vm.isPreview == 1) {
          vm.active = 2;
          return;
        }
        // 调用项目信息中的下一步操作
        vm.$refs.CustomBaseinfo.nextStep();
        return;
      }
    },
    // 填写项目信息组件的下一步回调（获取项目id）
    next(id) {
      vm.projectId = id;
      vm.active = 2;
    },
    // 暂存
    save() {
      if (vm.active == 1) {
        vm.$refs.CustomBaseinfo.save(false);
      } else if (vm.active == 2) {
        vm.regionComplete();
      }
    },
    confirmFn() {
      vm.sendObj.visible = false;
    },
    // 完成
    complete() {
      // 4不弹框
      if (vm.projectStatus != 4 && vm.isPreview != 1) {
        vm.sendObj.visible = true;
      } else {
        // 查看时,点击完成直接跳到列表页
        if (vm.isPreview == 1) {
          let query = {};
          if (vm.$route.query.pageNum) {
            query = { pageNum: vm.$route.query.pageNum };
          }
          vm.$router.push({ path: "item-manager", query: query });
          return;
        }
        vm.hidefn();
      }
    },
    // 完成触发的接口
    hidefn() {
      vm.regionComplete(vm.changeStatus);
    },
    // 选择学元范围暂存
    regionComplete(fishFn) {
      let req = {
        projectId: vm.projectId,
        scopeOfAdministrative: vm.$refs.selectRegion.setScope(),
        scopeOfDepartment: 99999999,
        flag: fishFn ? 3 : 1 //0：下一步 1：暂存
      };
      openLoading(vm);
      vm.POST("portal/new/scope", req)
        .then(res => {
          closeLoading(vm);
          if (res.code == "000000" && fishFn) {
            fishFn();
          }
          if (!fishFn) {
            vm.$message({
              type: "info",
              message: res.message
            });
          }
        })
        .catch(() => {
          vm.$message({
            type: "warning",
            message: res.message
          });
        });
    },
    // 完成后更改状态
    changeStatus() {
      let req = {
        projectId: vm.projectId,
        changeStatus: 3 //待审核
      };
      vm.POST("portal/portalInfo/changeStatus", req)
        .then(res => {
          vm.sendObj.visible = false;
          if (res.code == "000000") {
            let query = {};
            if (vm.$route.query.pageNum) {
              query = { pageNum: vm.$route.query.pageNum };
            }
            console.log("vm.$router.push");
            vm.$router.push({ path: "item-manager", query: query });
          } else {
            vm.$message({
              type: "warning",
              message: res.message
            });
          }
        })
        .catch(() => {
          vm.$message({
            type: "warning",
            message: res.message
          });
        });
    },
    //切换tabs
    handleClickTabs(tab, event) {
      if (tab.name == "second") {
        vm.setRegion();
      }
    },
    // 模板列表选中
    checkFn(id) {
      vm.canNext = true;
      vm.openTemplateId = id;
    },

    //选中自定义课程后点击下一步时检测(机构和进行中的项目)
    checkSelectCustomCourse() {
      openLoading(vm);
      vm.GET(`portal/portalCustom/checkBeforeCreateCustomProject`)
        .then(res => {
          closeLoading(vm);
          if (res.code == "000000") {
            if (res.data.status == 0) {
              vm.maxLimitCreatedCustomProjectCountInYear =
                res.data.maxLimitCreatedCustomProjectCountInYear;
              vm.active = 1;
              return;
            } else {
              if(res.data.status == 21) {
                vm.statusObj.status_21.message = `本年度免费创建自定义项目数已达${res.data.maxLimitCreatedCustomProjectCountInYear}次，不能继续创建`;
              }
              vm.dialogObj = Object.assign(vm.dialogObj, vm.statusObj[`status_${res.data.status}`]);
              vm.dialogObj.visible = true;
              return;
            }
          } else {
            vm.$message.info(res.message);
          }
        })
        .catch(err => {
          closeLoading(vm);
          vm.$message.warning("请稍后重试");
        });
    },

    //选中模板后点击下一步时检测(机构和进行中的项目)
    checkSelectTemplate() {
      openLoading(vm);
      vm.GET(
        `portal/openTemplateProject/checkAfterSelectOneOpenTemplate/${vm.openTemplateId}`
      )
        .then(res => {
          closeLoading(vm);
          if (res.code == "000000") {
            if (res.data.status == 0) {
              vm.active = 1;
              return;
            } else {
              vm.dialogObj = Object.assign(
                vm.dialogObj,
                vm.statusObj[`status_${res.data.status}`]
              );
              vm.dialogObj.visible = true;
              return;
            }
          } else {
            vm.$message.info(res.message);
          }
        })
        .catch(err => {
          closeLoading(vm);
          vm.$message.warning("请稍后重试");
        });
    },
    // 隐藏弹框
    hide() {
      vm.dialogObj.visible = false;
    },
    // 获取行政范围
    setRegion() {
      vm.getOrganizationList(vm.$refs.selectRegion.getScope());
    },
    // 查询行政范围的设定机构列表
    getOrganizationList(r) {
      vm.$refs.setOrganization.init();
      vm.$refs.setOrganization.getOrganization(r);
    },
    // 返回选择模板页
    backSelectVue() {
      vm.active = 0;
    },
    // 是否隐藏暂存按钮
    hideSave(num) {
      this.projectStatus = num;
    },
    // 从子组件（项目信息）获取项目状态是否为上架
    setStatus4Flag(s) {
      vm.status4Flag = s;
    }
  }
};
</script>

<style lang="scss">

.edit-custom-wrap {
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
    background-color: #fff;
  }

  /*定义滚动条轨道 内阴影+圆角*/
  ::-webkit-scrollbar-track {
    // box-shadow: inset 0 0 3px rgba(0,0,0,0.3);
    // -webkit-box-shadow: inset 0 0 3px rgba(0,0,0,0.3);
    border-radius: 10px;
    background-color: #fff;
  }

  /*定义滑块 内阴影+圆角*/
  ::-webkit-scrollbar-thumb {
    border-radius: 6px;
    // box-shadow: inset 0 0 3px rgba(0,0,0,.3);
    // -webkit-box-shadow: inset 0 0 3px rgba(0,0,0,.3);
    background-color: #C7C8C9;
  }

  .el-step.is-simple:not(:last-of-type) .el-step__title {
    max-width: 100%;
  }
  .top-lin {
    position: fixed;
    height: 30px;
    background: #f0f2f5;
    right: 30px;
    left: 285px;
    z-index: 1001;
    top: 125px;
  }
  .step-content-new {
    min-width: 1125px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    // min-width: 1300px;
    background: #fff;
    background: #fff;
    overflow: hidden;
    height: 54px;
    // line-height: 54px;
    // padding: 15px 0 50px 0;
    padding: 0 30px;
    border-bottom: 1px solid #efefef;
    background: #fff;
    .is-text {
      display: none;
    }
    .el-steps--simple {
      background: #fff;
      padding: 13px 0;
      align-items: center;
    }
    .button-green {
      color: #ffffff;
      background: #449284;
      border-color: #bfdad5;
      border-radius: 2px;
    }
    .button-white {
      color: #606266;
      background: #ffffff;
      border-color: #ecedf1;
      border-radius: 2px;
    }
    .step-num {
      display: block;
      font-size: 12px;
      border: 1px solid #999 !important;
      border-radius: 50%;
      width: 25px;
      height: 18px;
      line-height: 16px;
      text-align: center;
      color: #999;
    }
    .el-step__title.is-wait {
      color: #999;
    }
    .el-step__title.is-process {
      color: #449284;
    }
    .is-finish {
      color: #999 !important;
    }
    .on-step {
      color: #449284;
      border: 1px solid #449284 !important;
    }
    .dis-btn {
      width: 78px;
      height: 34px;
      background: rgba(240, 242, 245, 1);
      border-radius: 3px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(144, 147, 153, 1);
      line-height: 34px;
      text-align: center;
      cursor: pointer;
    }
    .dis-btn-b {
      position: relative;
      left: 5px;
      // bottom: 10px;
    }
  }
  .add-content-new {
    background: #fff;
  }
  .three-step {
    padding-top: 64px;
    margin: 10px 0 0 20px;
    .area-p {
      margin-bottom: 15px;
      font-size: 14px;
    }
    .span_ecology {
      line-height: 45px;
      margin-left: 8px;
    }
    .dialog-p {
      text-align: center;
      span {
        color: #449284;
      }
    }
    //隐藏树展开
    .table-empty {
      img {
        width: 100px;
      }
      p {
        margin-top: -50px;
      }
    }
    .el-tree-node__expand-icon {
      display: none;
    }
    .department {
      margin-top: 20px;
      border: 1px solid #dddddd;
    }
    .el-tabs__nav-wrap::after {
      display: none;
    }
    .el-tabs__active-bar {
      display: none;
    }
    #tab-first,
    #tab-second,
    #tab-third {
      padding-right: 0px;
    }
    #tab-first::after {
      color: #c7cbd2;
      margin-left: 20px;
      content: "•";
    }
    .el-tabs__item.is-active {
      color: #fff;
    }
    .el-tag {
      margin: 0 10px 10px 0;
      border: 1.3px solid #48a8fe;
      color: #1e92fe;
      background-color: #e7f6fe;
      .el-icon-close {
        width: 13px;
        height: 13px;
        line-height: 13px;
        font-size: 12px;
        background-color: #0486fe;
        border-radius: 50%;
        color: #d4edfe;
      }
    }
    .down-button {
      margin-left: 10px;
    }
    .down-button-close {
      margin-left: 100px;
      float: left;
    }
    .dialog-success {
      p {
        text-align: center;
        .upload-text {
          color: #449284;
        }
      }
    }
    .dialog-fail {
      .fail-type {
        p {
          margin-top: 10px;
        }
        .fail-num {
          color: #db3f52;
        }
        .fail-notice {
          color: #e3e3e3;
          font-size: 13px;
        }
        .fail-link {
          text-align: center;
          color: #449284;
          cursor: pointer;
        }
      }
    }
  }
  .tpl-main {
    // padding-top: 64px;

  }
}
</style>
