<template>
  <div style="overflow: auto; width: 100%">
    <TreeChart
      :json="treeData"
      :class="{ landscape: isVertical }"
      :isDetail="isDetail"
      @add="addStock"
      @delete="deleteStock"
    />
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="500px"
      :before-close="closeDig"
    >
      <!-- 当符合条件时需要暂时属于哪一届 -->
      <div class="tips">
        <el-form :model="ruleForm" ref="ruleForm" :rules="rules" class="demo-ruleForm">
          <el-form-item
            label="所属年级"
            prop="grade"
            class="imput_com"
            v-show="isShowGrade"
          >
            <el-select
              v-model="ruleForm.grade"
              clearable
              placeholder="请选择所属年级"
              style="width: 100%"
            >
              <el-option
                v-for="item in gradeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="组织架构名称" prop="orgName" class="imput_com">
            <el-input
              placeholder="输入组织架构名称"
              :maxlength="32"
              v-model="ruleForm.orgName"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="tip-left">
          <el-button type="info" @click="closeDig">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </div>
      </span>
    </el-dialog>

    <!-- 删除提示弹框 -->
    <el-dialog title="提示" :visible.sync="dialogVisible2" width="30%">
      <div class="tips">
        <p style="text-align: left">确定删除该组织信息?</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="tip-left">
          <el-button type="info" @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="confimdelete">确定</el-button>
        </div>
      </span>
    </el-dialog>
    <!-- <div class="changeDirection" @click="changeDir">切换方向</div> -->
  </div>
</template>

<script>
import TreeChart from "@/components/TreeData";
import { Loading } from "element-ui";
import { oSessionStorage } from "../../../utils/utils";

export default {
  name: "tree",
  components: {
    TreeChart,
  },
  data() {
    return {
      group: "",
      ppData: [],
      groupData: [],

      // treeData: {
      //   //公司名称
      //   orgName: "大米科技公司",
      //   proportionShares: "100",
      //   //公司层级
      //   level: 2,
      //   //公司编号
      //   orgNo: 1,
      // },
      treeData: {
        //公司名称
        orgName: "大米科技公司",
        proportionShares: "100",
        //公司层级
        level: 2,
        //公司编号
        orgNo: 1,
      },
      isVertical: false, // 是否是竖方向,只给最外层的添加
      isDetail: false, // 是否是详情,不可编辑操作
      dialogVisible: false, // 添加股东弹框
      dialogVisible2: false, // 删除提示弹框
      //当前取到的对象
      currentSelectObj: {},
      //输入表单的对象
      ruleForm: {
        orgName: "",
        grade: "",
      },
      rules: {
        orgName: [{ required: true, message: "请输入组织名称", trigger: "blur" }],
        grade: [{ required: true, message: "请选择年级", trigger: "change" }],
      },
      shareholderTypeOptions: [
        {
          labelEn: "Individual",
          labelZh: "个人",
          value: 1,
        },
        {
          labelEn: "Company",
          labelZh: "公司",
          value: 2,
        },
        {
          labelEn: "Other",
          labelZh: "其他",
          value: 3,
        },
      ], // 股东类型
      lastId: 11, // 最后一级id
      currentTreeData: {},
      userInfo: {},
      gradeOption: [],
      isShowGrade: false,
    };
  },
  mounted() {
    this.userInfo = JSON.parse(oSessionStorage.getItem("userInfo"));
    this.getChannel();
    this.getGradeFun();
  },
  methods: {
    //新增修改框关闭后的回调
    closeDig(){
      //重置数据
      this.$refs['ruleForm'].resetFields();
      this.dialogVisible=false;
    },
    //获取当前届数
    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();
    },
    changeDir() {
      //改变方向
      this.isVertical = !this.isVertical;
    },
    //获取组织架构方法--------------------开始-----------------------
    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);
              console.log("forRes");
              console.log(forRes);
              // console.log('格式化的结构')
              // console.log(forRes)
              let resultRes = this.deleteChildren(forRes);

              let levelList = this.markersFun(resultRes, 1);
              console.log("格式化的结构且去掉children");

              // console.log(JSON.stringify(levelList));
              this.treeData = levelList[0];
              console.log(levelList[0]);
            } 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].value = 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;
    },
    //获取组织架构方法--------------------结束-----------------------

    // 新增编辑股东,val: 0 新增, 1 编辑
    addStock(data) {
      this.isShowGrade = false;
      //判断是新增还是编辑
      //当等于0时是新增
      //当等于1时是修改
      if (data.val == "1") {
        //管理员编辑
        if (this.userInfo.roleType == "5" && data.data.level == "3") {
          this.isShowGrade = true;
        }
        //院管理员编辑
        if (this.userInfo.roleType == "4" && data.data.level == "2") {
          this.isShowGrade = true;
        }
      }

      if (data.val == "0") {
        //管理员新增  是否显示届数
        if (this.userInfo.roleType == "5" && data.data.level == "2") {
          this.isShowGrade = true;
        }
        //院管理员新增 是否显示届数
        if (this.userInfo.roleType == "4" && data.data.level == "1") {
          this.isShowGrade = true;
        }
      }
      //当是管理员登录时
      // if(this.userInfo.roleType=='5'&&data.data.level=='3'){

      // }

      // this.isShowGrade = true;
      //判断是修改还是
      console.log(data);
      this.currentSelectObj = data.data;
      // console.log(this.currentSelectObj);
      if (data.val) {
        this.ruleForm.orgName = data.data.orgName;
        this.ruleForm.grade = data.data.extend;
        // 不使用=赋值,内存相同,改变后,treeData数据也会改变
        // this.ruleForm = data.data;
        // this.ruleForm = Object.assign(this.ruleForm, data.data);
        // this.ruleForm.type = data.data.level;
      } else {
        this.ruleForm.orgName = "";
        this.ruleForm.grade = "";
      }
      this.isEdit = data.val;
      // 使用=赋值,编辑时改变currentTreeData, 源数据treeData也会改变
      this.currentTreeData = data.data;

      this.dialogVisible = true;
    },
    // 删除
    deleteStock(data) {
      this.currentSelectObj = data;
      console.log(this.currentSelectObj);

      this.dialogVisible2 = true;
    },
    // 确定删除
    confimdelete() {
      // 前端删除 遍历原数据,删除匹配id数据
      this.$http.get(`/org/deleteOrgById?id=${this.currentSelectObj.id}`, {}, (res) => {
        //  this.$toast.success({message:'成功'});
        if (res && res.code == 200) {
          //将值赋值给list
          //调用查询全部的
          this.getChannel();
          this.$message.success(res.msg);
          // this.channelList = res.data;
        } else {
          this.$message.error(res.msg);
        }
      });
      this.dialogVisible2 = false;
    },

    // 保存添加股东
    confirm() {
      // let loading = Loading.service();
      //判断是否输入值了
      // if (this.ruleForm.orgName != "" && this.ruleForm.orgName != null) {
      //   this.sendData();
      // } else {
      //   this.$message.warning("请输入组织架构名称");
      // }

      //当届数显示时--需要校验届数字段

      //
      let validSp = [];
      let aa = [];
      if (this.isShowGrade) {
        validSp = ["orgName", "grade"];
      } else {
        validSp = ["orgName"];
      }
      this.$refs["ruleForm"].validateField(validSp, (valid) => {
        if (!valid) {
          aa.push(valid);
          if (this.isShowGrade) {
            if (aa.length == 2) {
              this.sendData();
            }
          } else {
            if (aa.length == 1) {
              this.sendData();
            }
          }
        } else {
          // console.log("error submit!!");
          // return false;
        }
      });
    },

    // 发送添加股东数据
    sendData() {
      // let loading = Loading.service();

      if (this.isEdit) {
        // 编辑
        // data.id = this.treeData.id;
        //将参数调用接口
        this.currentSelectObj.orgName = this.ruleForm.orgName;
        this.currentSelectObj.extend = this.ruleForm.grade;
        this.$http.post(`/org/addOrUpdateOrg`, this.currentSelectObj, (res) => {
          //  this.$toast.success({message:'成功'});
          if (res && res.code == 200) {
            //将值赋值给list
            //调用查询全部的
            this.getChannel();
            this.$message.success(res.msg);
            this.dialogVisible = false;
            // this.channelList = res.data;
          } else {
            this.$message.error(res.msg);
            // this.dialogVisible = false;
          }
        });

        // this.clearDialog();
        // loading.close();
      } else {
        let data = {
          parentOrgNo: this.currentSelectObj.orgNo,
          orgName: this.ruleForm.orgName,
          extend: this.ruleForm.grade,
        };
        //将参数调用接口
        this.$http.post(`/org/addOrUpdateOrg`, data, (res) => {
          //  this.$toast.success({message:'成功'});
          if (res && res.code == 200) {
            //将值赋值给list
            //调用查询全部的
            this.getChannel();
            this.$message.success(res.msg);
            this.dialogVisible = false;
            // this.channelList = res.data;
          } else {
            this.$message.error(res.msg);
          }
        });
        //新增后接着查询就行了

        // 添加
        // 前端添加数据,需要自己生成子级id,可以传数据的时候把最后一级id传过来,进行累加
        // data.id = this.lastId++;
        // data.partnerCode = this.currentTreeData.id;
        // data.extend = true;
        // const render = (formData) => {
        //   formData.some((item) => {
        //     if (item.id === this.currentTreeData.id) {
        //       if (item.children) {
        //         item.children.push(data);
        //       } else {
        //         this.$set(item, "children", [data]);
        //       }
        //       return;
        //     } else if (item.children) {
        //       render(item.children);
        //     }
        //   });
        // };
        // let arr = [this.treeData];
        // render(arr);
        // this.treeData = arr[0];

        // this.clearDialog();
        // loading.close();
      }
    },
  },
};
</script>
<style scoped>
.imput_com >>> .el-input__inner {
  width: 400px !important;
}
.imput_com >>> .el-input {
  width: 400px !important;
}
</style>
<style lang="less" scoped>
.changeDirection {
  position: fixed;
  right: 50px;
  bottom: 80px;
  margin: auto;
  background-color: #48d68e;
  padding: 10px;
  color: #ffffff;
  cursor: pointer;
}
</style>
