<template>
  <div>
    <Card>
      <Tree :data="treedata" :render="renderContent" class="ptree"></Tree>
    </Card>
  </div>
</template>
  <script>
import { getApp, saveAuths, findAuthsByRoles } from "@/api/meta";
import Checks from "@/view/components/tables/forms/childs/checkgroups.vue";
import config from "@/config";
export default {
  name: "roleauth_page",
  data() {
    return {
      roleid: -1, //
      rolecode: "",
      roleauths: null,
      treedata: [],
      buttonProps: {
        type: "default",
        size: "small"
      }
    };
  },
  components: {
    Checks
  },
  computed: {
    authdic() {
      let dic = {};
      this.roleauths.forEach(item => {
        dic[item.bizcode] = item.authstrs.split(",");
      });
      return dic;
    }
  },
  mounted() {
    this.roleid = this.$route.query.roleid;
    this.rolecode = this.$route.query.rolecode;
    //获取当前应用的资源清单
    this.initTree();
  },

  methods: {
    initTree() {
      getApp().then(res => {
        let rtn = res.data;
        if (rtn.status == 0) {
          console.log(rtn.data.functionJSON);
          let tmptreedata = JSON.parse(rtn.data.functionJSON);
          this.treedata = tmptreedata; //
          //按照当前角色，去获取当前应用的功能权限，对返回的数据进行处理
          //赋予权限数据
          findAuthsByRoles([this.roleid]).then(res=>{
            let rtn=res.data
            if(rtn.status==0){
                 this.roleauths=rtn.data
                 this.setAuthData(this.treedata);
            }else{
                 console.log("fetch auths fails.....")
            }
          })
         
       
        }
      });
    },
    setAuthData(datas) {
      datas.forEach(td => {
        if (td.children) {
          this.setAuthData(td.children);
        } else {
          if(td.sels){
                 console.log(this.authdic)
             td.sels = this.authdic[td.name];
          }
        }
      });
    },
    makeauths(datas, auths) {
      datas.forEach(item => {
        if (item.children) {
          this.makeauths(item.children, auths);
        } else {
          if (item.sels) {
            let oneauth = {
              role_id: this.roleid,
              rolecode: this.rolecode,
              bizcode: item.name,
              codepath: item.codepath,
              authstrs: item.sels.join(",")
            };
            auths.push(oneauth);
          }
        }
      });
    },
    saveAuths() {
      let auths = [];
      this.makeauths(this.treedata, auths);
      saveAuths(auths).then(res => {
        let rtn = res.data;
        if (rtn.status == 0) {
          this.roleauths = rtn.data;
          this.$Message.success("当前操作成功完成")
        } else {
          this.$Message.success("当前操作未完成，请稍后重试或联系管理员")
        }
      });
    },
    refreshFunc() {},
    renderContent(h, { root, node, data }) {
      // console.log(node)
      const parentKey = root.find(el => el === node).parent;
      console.log(parentKey);
      return h(
        "span",
        {
          style: {
            display: "inline-block",
            width: "100%",
            cursor: "pointer"
          },
          on: {
            click: $event => {
              $("span", ".ptree").removeClass("spansel");
              $($event.target).addClass("spansel");
            }
          }
        },
        [
          h("span", [
            h("Icon", {
              props: {
                type: !data.auths ? "ios-folder-outline" : "ios-paper-outline"
              },
              style: {
                marginRight: "8px"
              }
            }),
            h("span", data.title)
          ]),
          h(
            "span",
            {
              style: {
                display: "inline-block",
                float: "right",
                marginRight: "100px"
              }
            },
            [
              data.auths
                ? h(
                    "Checkbox",
                    {
                      on: {
                        "on-change": b => {
                          if (b) {
                            data.sels = data.auths;
                          } else {
                            data.sels = [];
                          }
                        }
                      },
                      style: {
                        display: "inline-block",
                        float: "left",
                        marginRight: "10px",
                        marginTop: "3px"
                      }
                    },
                    [h("span", ["all"])]
                  )
                : data.name == "root"
                ? h("span", [
                    h(
                      "Button",
                      {
                        props: {
                          type: "text"
                        },
                        on: {
                          click: () => {
                            this.saveAuths();
                          }
                        }
                      },
                      ["保存"]
                    ),
                    h(
                      "Button",
                      {
                        props: {
                          type: "text"
                        },
                        on: {
                          click: () => {
                            this.refreshFunc();
                          }
                        }
                      },
                      ["刷新"]
                    )
                  ])
                : "",
              data.auths
                ? h(
                    "CheckboxGroup",
                    {
                      props: {
                        value: data.sels
                      },
                      on: {
                        "on-change": v => {
                          data.sels = v;
                          console.log(v);
                        }
                      }
                    },
                    [
                      data.auths.map(function(it) {
                        return h(
                          "Checkbox",
                          {
                            props: {
                              label: it
                            }
                          },
                          [h("span", [it])]
                        );
                      })
                    ]
                  )
                : ""
            ]
          )
        ]
      );
    }
  }
};
</script>
  <style>
.ptree span:hover {
  background-color: lightgray;
}
.spansel {
  background-color: lightgray;
}
</style>
