<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"
    >
      <div class="tips">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
          <el-form-item label="组织名称" prop="orgName">
            <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="dialogVisible = false">取消</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";

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

      treeData: {
        //公司名称
        orgName: "大米科技公司",
        proportionShares: "100",
        //公司层级
        level: 2,
        //公司编号
        orgNo: 1,
      },
      isVertical: false, // 是否是竖方向,只给最外层的添加
      isDetail: false, // 是否是详情,不可编辑操作
      dialogVisible: false, // 添加股东弹框
      dialogVisible2: false, // 删除提示弹框
      //当前取到的对象
      currentSelectObj: {},
      //输入表单的对象
      ruleForm: {
        orgName: "",
      },
      rules: {
        orgName: [{ required: true, message: "请输入组织名称", trigger: "blur" }],
      },
      shareholderTypeOptions: [
        {
          labelEn: "Individual",
          labelZh: "个人",
          value: 1,
        },
        {
          labelEn: "Company",
          labelZh: "公司",
          value: 2,
        },
        {
          labelEn: "Other",
          labelZh: "其他",
          value: 3,
        },
      ], // 股东类型
      lastId: 11, // 最后一级id
      currentTreeData: {},
    };
  },
  mounted() {
    this.getChannel();
  },
  methods: {
    changeDir(){
      //改变方向
      this.isVertical = !this.isVertical
    },
    //获取组织架构方法--------------------开始-----------------------
    getChannel() {
      this.$http.get(`/org/findAllOrgByPOrgNo`, {}, (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('格式化的结构')
            // 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.parentOrgNo;
      });
      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;
        if (item.children && item.children.length) {
          //
          this.markersFun(item.children, level + 1);
        }
      });
      return arr;
    },
    //获取组织架构方法--------------------结束-----------------------

    // 新增编辑股东,val: 0 新增, 1 编辑
    addStock(data) {
      console.log(data);
      this.currentSelectObj = data.data;
      // console.log(this.currentSelectObj);
      if (data.val) {
        // 不使用=赋值,内存相同,改变后,treeData数据也会改变
        // this.ruleForm = data.data;
        // this.ruleForm = Object.assign(this.ruleForm, data.data);
        // this.ruleForm.type = data.data.level;
      }
      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();
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.sendData();
        } else {
          // loading.close();
        }
      });
    },

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

      if (this.isEdit) {
        // 编辑
        // data.id = this.treeData.id;
        //将参数调用接口
        this.currentSelectObj.orgName = this.ruleForm.orgName;
        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,
        };
        //将参数调用接口
        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 lang="less" scoped>
.changeDirection{
  position: fixed;
  right: 50px;
  bottom: 80px;
  margin: auto;
  background-color: #48D68E;
  padding: 10px;
  color: #ffffff;
  cursor: pointer;
}
</style>
