<template>
  <div>
    <!---lxh-修改密码-->
    <div class="dig_update">
      <el-dialog
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        width="40%"
        top="5vh"
        style="overflow: hidden"
      >
        <div slot="title">
          <el-form
            :model="ruleForm"
            :rules="rules"
            :inline="true"
            ref="ruleForm"
            label-width="150px"
            class="demo-ruleForm"
          >
            <p v-if="isView" class="dig_title">新增计划</p>
            <p v-if="!isView" class="dig_title">编辑计划</p>
            <div slot=""></div>
            <div slot="footer"></div>
            <div
              style="
                height: 60vh;
                overflow-y: auto;
                padding-left: 20px;
                padding-right: 20px;
              "
              class="form_main"
            >
              <el-form-item label="计划名称" prop="planName">
                <el-input v-model="ruleForm.planName"></el-input>
              </el-form-item>
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  v-model="ruleForm.endTime"
                  type="date"
                  placeholder="选择日期"
                  @change="timeChange"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="快捷选项">
                <el-row>
                  <el-col :span="12">
                    <!-- @change="gradeChange" 
                     @remove-tag="gradeRemoveChange"
                    -->
                    <el-select
                      :collapse-tags="true"
                      multiple
                      placeholder="请选择届"
                      v-model="grade"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in gradeOption"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="12" style="text-align: right">
                    <el-select
                      :collapse-tags="true"
                      multiple
                      placeholder="请选择辅导员"
                      v-model="instructor"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in instructorOption"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="配置计划">
                <el-tree
                  :data="treeData"
                  show-checkbox
                  node-key="id"
                  default-expand-all
                  :default-checked-keys="checkedList"
                  :props="defaultProps"
                  ref="tree"
                >
                </el-tree>
              </el-form-item>
              <el-button @click="getCheckedNodes"> 获取已选 </el-button>
              <el-form-item label="任务选择" class="taskSelect">
                <el-checkbox-group v-model="checkboxGroup2" size="mini">
                  <el-checkbox
                    v-for="item in scaleList"
                    :key="item.id"
                    :label="item.flag"
                    border
                    :disabled="item.isRequired == '1'"
                    >{{ item.name }}</el-checkbox
                  >
                  <el-checkbox
                    v-for="item in taskList"
                    :key="item.id"
                    :label="item.flag"
                    border
                    :disabled="item.isRequired == '1'"
                    >{{ item.name }}</el-checkbox
                  >
                  <!-- <el-checkbox label="2" border>{{ cognitionName }}</el-checkbox> -->
                </el-checkbox-group>
              </el-form-item>
            </div>
          </el-form>
          <div class="dig_button">
            <el-button type="info" round @click="resetData()">重置</el-button>
            <el-button type="success" round @click="submitCom()">提交</el-button>
          </div>
        </div>
        <!-- <div slot="footer">
          <div class="dig_button">
            <el-button type="info" round @click="resetData()">重置</el-button>
            <el-button type="success" round @click="submitCom()">下一步</el-button>
          </div>
        </div> -->
      </el-dialog>
    </div>
  </div>
</template>
<script>
// import { oSessionStorage } from "../../utils/utils";
import { oSessionStorage } from "../utils/utils";
import md5 from "md5";
export default {
  data() {
    return {
      //编辑返回的值
      userDetailData: {},
      //组织架构名字
      groupName: "",

      disableFlag: false,
      phoneFlag: false,
      flag: 3,
      dialogVisible: false,
      //渠道列表

      ruleForm: {
        //所属组织架构
        planName: "",
        endTime: "",
      },
      isView: true,
      rules: {
        planName: [{ required: true, message: "请输入计划名称", trigger: "blur" }],
        endTime: [{ required: true, message: "请输结束时间", trigger: "blur" }],
      },
      userInfo: {},

      scaleAndCon: [],
      checkboxGroup2: ["1"],
      //查看是不是两次都调用完了
      countList: [],
      //显示用的认知任务名称
      cognitionName: "",
      id: "",
      //学生届数
      gradeOption: [],
      //辅导员列表
      instructorOption: [],

      //辅导员的原始列表
      teacherList: [],
      //树形选择班级的框
      treeData: [
        {
          id: 1,
          label: "一级 1",
        },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },
      //所选届数
      grade: [],
      instructor: [],
      ppData: [],
      checkedList: [],
      //任务可选量表数据
      scaleAndTaskList: [],
      scaleList: [],
      taskList: [],
    };
  },
  //需要监听变量
  //如果这样变量增加的是谁，减少的是谁都知道
  watch: {
    grade(newCount, oldCount) {
      //首先是判断是新增还是减少
      //如果是新增
      if (newCount.length > oldCount.length) {
        let poor = newCount.filter((a) => !oldCount.includes(a));
        //此时新增的话需要调用方法
        //此时要判断增加的是谁
        if (poor.length == 1) {
          this.gradeAdd(poor[0], "isGrade");
        }
      } else if (newCount.length < oldCount.length) {
        let poor = oldCount.filter((a) => !newCount.includes(a));
        if (poor.length == 1) {
          this.gradeDecrease(poor[0], "isGrade");
        }
      }
      //如果是减少
    },
    //判断是减少还是增多
    instructor(newCount, oldCount) {
      if (newCount.length > oldCount.length) {
        let poor = newCount.filter((a) => !oldCount.includes(a));
        //此时新增的话需要调用方法
        //此时要判断增加的是谁
        if (poor.length == 1) {
          this.gradeAdd(poor[0], "noGrade");
        }
      } else if (newCount.length < oldCount.length) {
        let poor = oldCount.filter((a) => !newCount.includes(a));
        if (poor.length == 1) {
          this.gradeDecrease(poor[0], "noGrade");
        }
      }
    },
  },
  mounted() {
    this.userInfo = JSON.parse(oSessionStorage.getItem("userInfo"));

    // this.ruleForm.type = "3";
  },
  methods: {
    //查询学生模版
    queryStudentTemp() {
      this.$http.get(`/content/findAllByTemplate?template=studentContent`, {}, (res) => {
        //  this.$toast.success({message:'成功'});
        if (res && res.code == 200) {
          //将值赋值给list
          if (res.data.length > 0) {
            this.scaleAndTaskList = res.data;
            this.scaleList = res.data.filter((item) => {
              //并且 是必须展示的
              return item.type == "0" && item.isDisplayed == "1";
            });

            this.taskList = res.data.filter((item) => {
              return item.type == "1" && item.isDisplayed == "1";
            });
            // checkboxGroup2
            let listRequest = res.data.filter((item) => {
              return item.isRequired == "1";
            });
            this.checkboxGroup2 = [];
            for (let i = 0; i < listRequest.length; i++) {
              this.checkboxGroup2.push(listRequest[i].flag);
            }
            // instructorOption
          } else {
            // this.groupData = [];
          }
          // this.channelList = res.data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    //获取辅导员
    getTeacher() {
      this.instructorOption = [];
      this.$http.get(`/user/findAllCounsellor`, {}, (res) => {
        //  this.$toast.success({message:'成功'});
        if (res && res.code == 200) {
          //将值赋值给list
          if (res.data.length > 0) {
            //
            this.teacherList = res.data;
            for (let i = 0; i < res.data.length; i++) {
              //
              let obj = {
                value: res.data[i].userNo,
                label: res.data[i].userName,
              };
              this.instructorOption.push(obj);
            }
            // instructorOption
          } else {
            // this.groupData = [];
          }
          // this.channelList = res.data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    //当选择的届减少时
    gradeDecrease(val, flag) {
      //减少的时候去查询
      // this.checkedList = [];
      let original = JSON.parse(JSON.stringify(this.checkedList));
      let gradeIds = [];
      if (flag == "isGrade") {
        for (let i = 0; i < this.ppData.length; i++) {
          if (this.ppData[i].extend == val) {
            //将此选项的ID保存下来
            gradeIds.push(this.ppData[i].id);
          }
        }
      } else {
        //
        for (let i = 0; i < this.teacherList.length; i++) {
          if (this.teacherList[i].userNo == val) {
            if (this.teacherList[i].gradeEntities.length > 0) {
              for (let j = 0; j < this.teacherList[i].gradeEntities.length; j++) {
                gradeIds.push(this.teacherList[i].gradeEntities[j].orgNo);
              }
            }
          }
        }
      }

      //求差值
      this.checkedList = original.filter((item) => !gradeIds.includes(item));
      //这些ID都需要从已选中去掉
      // this.checkedList=['000000100015']
      this.$refs.tree.setCheckedKeys(this.checkedList);
      //应该是要判断减少的是什么
    },
    //当选择的届发生改变时
    gradeAdd(val, flag) {
      //获取当前已选列表
      //届数改变以后
      //获取数行已选项，将已选ID组合
      //---------------已选 开始----------
      this.checkedList = [];
      let list = this.$refs.tree.getCheckedNodes();
      let listIds = [];
      if (list.length > 0) {
        for (let i = 0; i < list.length; i++) {
          listIds.push(list[i].id);
        }
      }
      //---------------已选 结束----------
      //---------------筛选届 开始----------
      let gradeIds = [];

      if (flag == "isGrade") {
        for (let i = 0; i < this.ppData.length; i++) {
          if (this.ppData[i].extend == val) {
            //将此选项的ID保存下来
            gradeIds.push(this.ppData[i].id);
          }
        }
      } else {
        //去遍历数组
        for (let i = 0; i < this.teacherList.length; i++) {
          if (this.teacherList[i].userNo == val) {
            if (this.teacherList[i].gradeEntities.length > 0) {
              for (let j = 0; j < this.teacherList[i].gradeEntities.length; j++) {
                gradeIds.push(this.teacherList[i].gradeEntities[j].orgNo);
              }
            }
          }
        }
      }

      //合并两个数组
      let listAll = gradeIds.concat(listIds);
      //然后去重
      let listDeWeight = listAll.filter((item, index, arr) => {
        return arr.indexOf(item) == index;
      });
      this.checkedList = listDeWeight;
      //this.checkedList
      //然后将两个数组进行合并去重

      //---------------筛选届 结束----------

      //再将届数的id合并仅已选组合
    },
    // gradeAdd(val) {
    //   //获取当前已选列表
    //   console.log(this.grade);
    //   //届数改变以后
    //   //获取数行已选项，将已选ID组合
    //   //---------------已选 开始----------
    //   this.checkedList = [];
    //   let list = this.$refs.tree.getCheckedNodes();
    //   let listIds = [];
    //   if (list.length > 0) {
    //     for (let i = 0; i < list.length; i++) {
    //       listIds.push(list[i].id);
    //     }
    //   }
    //   //---------------已选 结束----------
    //   //---------------筛选届 开始----------
    //   let gradeIds = [];
    //   if (this.grade.length > 0) {
    //     for (let i = 0; i < this.ppData.length; i++) {
    //       for (let j = 0; j < this.grade.length; j++) {
    //         if (this.ppData[i].extend == this.grade[j]) {
    //           //将此选项的ID保存下来
    //           gradeIds.push(this.ppData[i].id);
    //         }
    //       }
    //     }
    //   }
    //   //合并两个数组
    //   let listAll = gradeIds.concat(listIds);
    //   //然后去重
    //   let listDeWeight = listAll.filter((item) => {
    //     return listAll.indexOf(item);
    //   });
    //   console.log("去重listDeWeight");
    //   console.log(listDeWeight);
    //   this.checkedList = listDeWeight;
    //   //this.checkedList
    //   //然后将两个数组进行合并去重

    //   //---------------筛选届 结束----------

    //   //再将届数的id合并仅已选组合
    // },
    //通过node获取方法已选选项
    getCheckedNodes() {
      console.log(this.$refs.tree.getCheckedNodes());
      //循环得到ID 将ID放入数组
    },
    //获取组织架构方法--------------------开始-----------------------
    getChannel() {
      this.$http.get(
        `/org/findAllOrgByPOrgNo?orgNo=${this.userInfo.orgNo}`,
        {},
        (res) => {
          //  this.$toast.success({message:'成功'});
          if (res && res.code == 200) {
            //将值赋值给list
            if (res.data.length > 0) {
              let resAdd = this.addPro(res.data);
              this.ppData = JSON.parse(JSON.stringify(resAdd));
              let forRes = this.arrToTree(resAdd);
              let resultRes = this.deleteChildren(forRes);

              let levelList = this.markersFun(resultRes, 1);
              this.treeData = levelList;
            } else {
              this.groupData = [];
            }
            // this.channelList = res.data;
          } else {
            this.$message.error(res.msg);
          }
        }
      );
    },
    //z增加
    addPro(val) {
      let data = JSON.parse(JSON.stringify(val));
      for (let i = 0; i < val.length; i++) {
        data[i].id = val[i].orgNo;
        data[i].label = val[i].orgName;
      }
      return data;
    },
    //非递归方式：将平铺数据转换为树形结构数据
    arrToTree(arr) {
      let data = arr.filter((item) => {
        item.children = arr.filter((e) => {
          return item.orgNo === e.parentOrgNo;
        });
        return item.orgNo == this.userInfo.orgNo;
      });
      return data;
    },
    //去除转换树形结构数据后存在的空children
    deleteChildren(arr) {
      let childs = arr;
      for (let i = childs.length; i--; i > 0) {
        if (childs[i].children) {
          if (childs[i].children.length) {
            this.deleteChildren(childs[i].children);
          } else {
            delete childs[i].children;
          }
        }
      }
      return arr;
    },

    //标记层级
    markersFun(arr, level) {
      if (!arr || !arr.length) {
        return;
      }
      arr.forEach((item) => {
        item.level = level;
        //设置都可以编辑
        item.isEdit = true;
        //设置都可以增加
        item.isAdd = true;
        //设置都可以删除
        item.isDelete = true;
        // item.extend = true;
        item.isExtend = true;

        //当角色是超级管理员时
        if (this.userInfo.roleType == "5") {
          //则level 是三级时
          if (level == "3") {
            item.isAdd = false;
          }
        }
        //   //当角色是院管理员时
        if (this.userInfo.roleType == "4") {
          //则level 是三级时
          if (level == "2") {
            item.isAdd = false;
          }
        }

        if (item.children && item.children.length) {
          //
          this.markersFun(item.children, level + 1);
        }
      });
      return arr;
    },
    //获取当前届数
    getGradeFun() {
      this.gradeOption = [];
      //获取当前届数
      //获取当前年份
      let date = new Date();
      let currentYear = date.getFullYear();
      let preYear = currentYear - 12;
      let list = [];
      for (let i = preYear; i < currentYear + 1; i++) {
        //
        let obj = {
          value: i + "",
          label: i + "届",
        };
        list.push(obj);
      }
      this.gradeOption = list.reverse();
    },
    resetForm(val) {
      this.cancle();
    },
    timeChange(val) {
      if (val !== null) {
        //根据时间得到格式化的数据
        this.ruleForm.endTime = this.formatterTime(val);
      }
    },
    formatterTime(val) {
      let date = new Date(val);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      month = this.formatterMon(month);
      let day = date.getDate();
      day = this.formatterMon(day);
      return year + "-" + month + "-" + day;
    },
    formatterMon(val) {
      if (val < 10) {
        return "0" + val;
      } else {
        return val;
      }
    },
    open(val) {
      this.cancle();

      //打开后返回的数组

      this.dialogVisible = true;
      this.isView = val;
      //获取渠道信息
      this.getGradeFun();
      this.getChannel();
      this.getTeacher();
      this.queryStudentTemp();
      //查询以下的教师
      //查询学生模版
      //添加计划
      //查询需要选择的量表

      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    edit(val) {
      this.id = val.id;
      this.dialogVisible = true;
      this.isView = false;
      this.ruleForm.planName = val.planName;
      this.ruleForm.endTime = val.planEndTime;
      this.userDetailData = val;

      //调用查询详情的接口
    },
    //查询量表
    queryDetail() {
      //val 是查询的类型
      this.$http.get(`/plan/findPlanById?id=${this.id}`, {}, (res) => {
        if (res.code == 200) {
          let list = res.data.contentEntities;
          let listTmp = list.filter((item) => {
            return item.contentType == "1";
          });
          if (listTmp.length > 0) {
            // this.checkboxGroup2 = ["1", "2"];
          }
        }
      });
    },
    //调用查询详情的接口
    resetData() {
      this.$refs["ruleForm"].clearValidate();
      //清空表单
      this.ruleForm.planName = "";
      this.ruleForm.endTime = "";
    },
    cancle() {
      this.$refs["ruleForm"].clearValidate();
      //清空表单
      this.ruleForm.planName = "";
      this.ruleForm.endTime = "";
      this.dialogVisible = false;
    },
    disableFlagStatus() {
      setTimeout(() => {
        this.disableFlag = false;
      }, 1500);
    },
    submitCom() {
      if (this.disableFlag) {
        return;
      }
      this.disableFlag = true;
      let validSp = [];
      if (this.isView) {
        validSp = ["planName", "endTime"];
      } else {
        validSp = ["planName", "endTime"];
      }
      let aa = [];
      this.$refs["ruleForm"].validateField(validSp, (valid) => {
        if (!valid) {
          aa.push(valid);
          //判断是编辑还是新增
          if (this.isView) {
            if (aa.length == 2) {
              this.register();
            } else {
              this.disableFlagStatus();
            }
          } else {
            if (aa.length == 2) {
              this.editUserFun();
            } else {
              this.disableFlagStatus();
            }
          }

          //都校验通过后可以触发注册接口了
          //调用方法进行入参
        } else {
          this.disableFlagStatus();
        }
      });
    },
    register() {
      let that = this;
      //获取已选任务的列表
      let list = [];
      let listTmp = [];
      listTmp = this.scaleAndTaskList.filter((item) => {
        return this.checkboxGroup2.includes(item.flag);
      });
      for (let i = 0; i < listTmp.length; i++) {
        let obj = {
          contentType: listTmp[i].type,
          flag: listTmp[i].flag,
          isDisplayed: listTmp[i].isDisplayed,
          isAvailable: listTmp[i].isAvailable,
          name:listTmp[i].name
        };
        list.push(obj);
      }
      //获取已选组织架构的列表

      let listOrg = [];
      let listOrgTmp = [];
      listOrgTmp = this.ppData.filter((item) => {
        return this.checkedList.includes(item.orgNo);
      });

      for (let i = 0; i < listOrgTmp.length; i++) {
        let obj = {
          orgNo: listOrgTmp[i].orgNo,
          orgName: listOrgTmp[i].orgName,
        };
        listOrg.push(obj);
      }
      // this.ruleForm.password = md5(this.ruleForm.password);
      this.$http.post(
        `/plan/addOrUpdate`,
        {
          contentEntities: list,
          orgEntityList: listOrg,
          planName: this.ruleForm.planName,
          planEndTime: this.ruleForm.endTime,
          createUserId: this.userInfo.id,
          createUserName: this.userInfo.userName,
          planOrgNo: this.userInfo.orgNo,
          planOrgName: this.userInfo.orgName,
          planType:'0'
        },
        (res) => {
          this.disableFlagStatus();
          // this.disableFlag = false;
          if (res && res.code == 200) {
            this.dialogVisible = false;

            // this.$toast.success({ message: "成功" });
            //调用父组件的查询方法

            that.$emit("search");
            // that.$emit("configuration", res.data);
            //也调用打开人员配置的方法
          } else {
            // this.$toast.fail({ message: res.msg });
            this.$message.error(res.msg);
          }
          //清空缓存
          this.cancle();
        }
      );
    },
    editUserFun() {
      let that = this;
      let list = [];
      if (this.checkboxGroup2.length == 2) {
        //开始组装数据
        for (let i = 0; i < this.scaleAndCon.length; i++) {
          //
          if (this.scaleAndCon[i].paramType == "cognition") {
            let obj = {
              contentType: "1",
              description: this.scaleAndCon[i].paramDesc,
              flag: this.scaleAndCon[i].paramValue,
              name: this.scaleAndCon[i].paramName,
            };
            list.push(obj);
          }
          if (this.scaleAndCon[i].paramType == "scale") {
            let obj = {
              contentType: "0",
              description: this.scaleAndCon[i].paramDesc,
              flag: this.scaleAndCon[i].paramValue,
              name: this.scaleAndCon[i].paramName,
            };
            list.push(obj);
          }
        }
      } else {
        for (let i = 0; i < this.scaleAndCon.length; i++) {
          if (this.scaleAndCon[i].paramType == "scale") {
            let obj = {
              contentType: "0",
              description: this.scaleAndCon[i].paramDesc,
              flag: this.scaleAndCon[i].paramValue,
              name: this.scaleAndCon[i].paramName,
            };
            list.push(obj);
          }
        }
      }
      this.userDetailData.planEndTime = this.ruleForm.endTime;
      this.userDetailData.planName = this.ruleForm.planName;
      this.userDetailData.contentEntities = list;

      this.$http.post(
        `/plan/addOrUpdate`,
        {
          ...this.userDetailData,
        },
        (res) => {
          this.disableFlagStatus();
          if (res && res.code == 200) {
            this.dialogVisible = false;
            // this.$toast.success({ message: "成功" });
            //调用父组件的查询方法
            that.$emit("search");
            this.$message.success("修改成功");
          } else {
            // this.$toast.fail({ message: res.msg });
            this.$message.error(res.msg);
          }

          //清空缓存

          //清空缓存
        }
      );
    },
  },
};
</script>
<style lang="less" scoped>
.taskSelect /deep/ .el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin-left: 0px !important;
}

.dig_update /deep/ .el-dialog {
  border-radius: 20px !important;
}
.form_main::-webkit-scrollbar {
  width: 6px;
}
.form_main::-webkit-scrollbar-track {
  background: rgb(239, 239, 239);
  border-radius: 2px;
}
.form_main::-webkit-scrollbar-thumb {
  background: #00000049;
  border-radius: 10px;
}
.form_main::-webkit-scrollbar-thumb:hover {
  background: #444444;
}

.dig_update /deep/.el-cascader {
  position: relative;
  font-size: 14px;
  line-height: 40px;
  width: 100%;
}
// .dig_update /deep/.el-dialog {
//   box-shadow: none !important;
//   background: transparent !important;
// }
.demo-ruleForm /deep/ .el-form-item {
  margin-right: 10px;
  vertical-align: top;
  display: flex !important;
  flex-direction: column;
}
.demo-ruleForm /deep/.el-form-item__label {
  text-align: left;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.demo-ruleForm /deep/.el-input {
  width: 100% !important;
}

.demo-ruleForm /deep/.el-input__inner {
  width: 100% !important;
  background-color: #f7f7f7;
  border: 0px;
}

.dig_button {
  display: flex;
  width: 100%;
  justify-content: space-around;
}

.demo-ruleForm {
  background-color: #ffffff;
  // border-radius: 20px;
  margin-right: -10px;
  margin-top: -10px;
  // padding-right: 100px;
  // padding-left: 100px;
  border-radius: 20px;
  padding-top: 20px;
  padding-bottom: 40px;
  .dig_title {
    margin-bottom: 30px;
    text-align: center;
    font-weight: 700;
  }
}
</style>
