<template>
    <div class="module-property" style="padding: 16px" slot="content" :modal = "groupList">
        <div class="property-item vertical">
            <label class='block'>头部主题</label>
            <div class="property-item-content">
                <RadioGroup v-model="groupList.headerPro.theme" >
                    <Radio label="light">浅色</Radio>
                    <Radio label="dark">深色</Radio>
                    <Radio label="primary">蓝色</Radio>
                </RadioGroup>
            </div>  
        </div>

        <div class="property-item">
            <label>编辑菜单功能</label>
            <div class="property-item-content">
                <!-- <Button type="default" @click = "newGroups">新增分组</Button>
                <Button type="default" @click = "newModule(false)">新增功能</Button> -->
                <Button type="primary" @click="newModule(true)">编辑功能</Button>
            </div>
        </div>

        <!-- <div class="property-item  vertical">
            <div class="property-item-content">
                <Checkbox v-model="groupList.headerPro.titleModal">显示标题</Checkbox>
            </div>                      
        </div>

        <div class="property-item" v-if = "groupList.headerPro.titleModal">
            <label class='block'>标题</label>
            <div class="property-item-content">
                <i-input v-model = "groupList.logo.name"></i-input>
            </div>
        </div> -->

        <div class="property-item  vertical">
            <div class="property-item-content">
                <Checkbox v-model="groupList.headerPro.versionModal">显示版本信息</Checkbox>
            </div>                      
        </div>

        <div class="property-item  vertical">
            <div class="property-item-content">
                <Checkbox v-model="groupList.headerPro.userModal">显示用户信息</Checkbox>
            </div>                      
        </div>

        <Table border ref="selection" 
          :columns="columns" 
          :data="userInfos"
          @on-select-all = "onSelectAll"
          @on-select-cancel = "selectAllOrCancel"
          @on-select = "handleSelect"
          @on-selection-change = "selectAllOrCancel"
          >          
          </Table>
    </div>
</template>


<script>
import { mapMutations } from "vuex";
import addModule from "./addModule.vue";
import addGroups from "./addGroups.vue";
import homeAPI from "../../api/homeAPI";
export default {
  props: ["itemid"],
  data: () => ({
    id: "headerViewPro",
    pubObj: [
      {
        id: "",
        label: null,
        icon: "",
        linkTo: "",
        type: null,
        parents: [],
        children: [],
        multiSelect: false
      }
    ],
    columns: [
      {
        type: "selection",
        width: 60,
        align: "center"
      },
      {
        title: "账户信息",
        key: "label"
      }
    ],
    userInfos: [],
    designModel:false,
    isAdmin:false,
  }),
  computed: {
    groupList() {
      let self = this,
        id = self.id,
        headerProps = self.$store.getters.getHeaderProp;
      if (!headerProps) {
        var values = self.$store.getters.packageHeaderProp();
        self.setHeaderProp({ values: values });
      }
      return self.$store.getters.getHeaderValues;
    }
  },
  watch: {
    "groupList.headerPro.titleModal"(val, oldval) {
      this.updateTitle();
      this.saveHeaderProp();
    },
    "groupList.headerPro.versionModal"(val, oldval) {
      this.updateVersion();
      this.saveHeaderProp();
    },
    "groupList.headerPro.userModal"(val, oldval) {
      this.updateUserInfo();
      this.saveHeaderProp();
      this.$refs.selection.selectAll(val);
    }
  },
  created() {
    this.designModel = this.$store.getters.getDesignModel;
    this.isAdmin = this.$store.getters.getIsAdmin;
  },
  mounted() {
    this.initHeader();
  },
  methods: {
    ...mapMutations([
      "setHeaderProp",
      "updateTitle",
      "updateVersion",
      "updateUserInfo",
      "setHeaderPro",
    ]),
    initHeader() {
      this.updateTitle();
      this.updateVersion();
      this.updateUserInfo();
      // this.saveHeaderProp();
      this.updateUserModuleList();
    },
    newGroups() {
      let self = this;
      self.pubObj[0]["id"] = self.newGuid();
      self.$Modal.confirm({
        title: "新增分组",
        render: h => {
          return h(addGroups, {
            props: {
              pubObj: self.pubObj[0]
            }
          });
        },
        onOk(e) {
          self.groupList.menue.center.push(
            JSON.parse(JSON.stringify(self.formatPubObj()))
          );
          self.saveHeaderProp();
          self.initPubObj();
        },
        onCancel(e) {
          self.initPubObj();
        }
      });
    },
    newModule(multiSelect) {
      let self = this,
        moduleList = self.$store.getters.getModuleList;
      self.initPubObj();
      // self.pubObj[0]["id"] = self.newGuid();
      self.pubObj[0]["multiSelect"] = multiSelect;
      let curModules = self.groupList.menue.center;
      if (curModules && curModules.length > 0) {
        if (self.pubObj[0].type == null) self.pubObj[0].type = [];
        for (let index = 0; index < curModules.length; index++) {
          const type = curModules[index].type;
          if (
            curModules[index].children &&
            curModules[index].children.length > 0
          ) {
            let sltModuleChildren = moduleList.find(
              t => t.id == curModules[index].type
            ).children;
            if (
              sltModuleChildren &&
              sltModuleChildren.length == curModules[index].children.length
            ) {
              self.pubObj[0].type.push(type);
            } else {
              for (let i = 0; i < curModules[index].children.length; i++) {
                self.pubObj[0].type.push(curModules[index].children[i].id);
              }
            }
          } else {
            self.pubObj[0].type.push(type);
          }
        }
        self.pubObj[0].parents.push("nullObj");
      }
      self.initGroups();
      self.$Modal.confirm({
        title: "新增功能",
        render: h => {
          return h(addModule, {
            props: {
              pubObj: self.pubObj[0],
              groupList: self.groupList.menue.center,
              moduleList: moduleList
            }
          });
        },
        onOk(e) {
          let nodes = {
            children: self.groupList.menue.center
          };
          self.traverseTree(nodes, multiSelect);
          self.saveHeaderProp();
          self.clearGroups();
        },
        onCancel(e) {
          self.clearGroups();
        }
      });
    },
    updateUserModuleList() {
      let self = this,
        userInfo = self.groupList.menue.right.find(t => t.id == "UserInfo"),
        checked = !userInfo ? [] : userInfo.children,
        userInfosAll = self.$store.getters.getUserInfos;
      for (let index = 0; index < userInfosAll.length; index++) {
        const element = userInfosAll[index];
        self.userInfos.push({
          id: element.id,
          order: element.order,
          label: element.label,
          _checked: checked.find(t => t.id == element.id) ? true : false
        });
      }
    },
    selectAllOrCancel(selection, row) {
      let self = this,
      len = self.$store.getters.getUserInfos.length;
      if (!row) {
        let status = selection && selection.length > 0 ? true : false;
        self.groupList.headerPro.userModal = status;
      } else {
        let accountInfo = self.groupList.menue.right.find(
          t => t.id == "UserInfo"
        );
        if (!accountInfo) return;
        let _index = accountInfo.children.findIndex(t => t.id == row.id);
        if (_index > -1) accountInfo.children.splice(_index, 1);
      }
    },
    handleSelect(selection, row) {
      let self = this,
        userInfosAll = self.$store.getters.getUserInfos,
        accountInfo = self.groupList.menue.right.find(t => t.id == "UserInfo"),
        thatHeaderValue = self.$store.getters.getHeaderValues.logo;
      if (!accountInfo) {
        accountInfo = {
          id: "UserInfo",
          label: thatHeaderValue.userName,
          icon: thatHeaderValue.userHeaderImg,
          linkTo: "",
          children: []
        };
        self.groupList.menue.right.push(accountInfo);
      }
      if (accountInfo.children.findIndex(t => t.id == row.id) == -1) {
        let rowItem = userInfosAll.find(t => t.id == row.id);
        if(rowItem){
          var posIndex = accountInfo.children.findIndex(t => t.order > row.order);
          if(posIndex > -1)
            accountInfo.children.splice(posIndex, 0, rowItem);
          else 
            accountInfo.children.push(rowItem);
        }        
      }
    },
    onSelectAll(selection){
      if(!selection) return;
      let self = this, status = this.groupList.headerPro.userModal;
      if(!status) {
        self.groupList.headerPro.userModal = true;
        return;
      }
      let userInfosAll = self.$store.getters.getUserInfos,
          accountInfo = self.groupList.menue.right.find(t => t.id == "UserInfo");
      if (!accountInfo) {
        accountInfo = {
          id: "UserInfo",
          label: thatHeaderValue.userName,
          icon: thatHeaderValue.userHeaderImg,
          linkTo: "",
          children: []
        };
        self.groupList.menue.right.push(accountInfo);
      }
      selection.forEach(function(val, idx){
        let rowItem = accountInfo.children.find(t => t.id == val.id);       
        if(!rowItem){
          rowItem = userInfosAll.find(t => t.id == val.id);
          let posIndex = accountInfo.children.findIndex(t => t.order > val.order);
          if(posIndex > -1)
            accountInfo.children.splice(posIndex, 0, rowItem);
          else 
            accountInfo.children.push(rowItem);
        }
      });
      self.saveHeaderProp();
    },
    formatGroups(node, multiSelect) {
      let self = this,
        newPubObj = self.formatPubObj(multiSelect);
      if (self.pubObj[0].parents[0] != "nullObj") {
        if (multiSelect) {
          node.children = [];
          node.children.push.apply(node.children,newPubObj);
        } else {
          let curMobj = node.children.find(t => t.type == newPubObj.type);
          if (!curMobj) {
            node.children.push(newPubObj);
          } else {
            var _index = node.children.findIndex(curMobj);
            node.children.splice(_index, 1, newPubObj);
          }
        }
      } else {
        if (multiSelect) {
          self.groupList.menue.center = [];
          self.groupList.menue.center.push.apply(self.groupList.menue.center,newPubObj);
        } else {
          let curObj = self.groupList.menue.center.find(
            t => t.type == newPubObj.type
          );
          if (!curObj) {
            self.groupList.menue.center.push(newPubObj);
          } else {
            let _index = self.groupList.menue.center.indexOf(curObj);
            self.groupList.menue.center.splice(_index, 1, newPubObj);
          }
        }
      }
    },
    traverseTree(node, multiSelect) {
      let self = this;
      if (!node) {
        return;
      }
      if (
        node.id == self.pubObj[0].parents[self.pubObj[0].parents.length - 1]
      ) {
        self.formatGroups(node, multiSelect);
        return;
      }
      if (node.children && node.children.length > 0) {
        for (let i = 0; i < node.children.length; i++) {
          self.traverseTree(node.children[i], multiSelect);
        }
      }
    },
    formatPubObj(multiSelect) {
      let self = this,
        obj = self.pubObj[0],
        moduleList = self.$store.getters.getModuleList,
        arrs = obj.type,
        newPubObj = null,
        newObj = [];
      if (multiSelect) {
        for (let i = 0; i < arrs.length; i++) {
          let index = arrs[i].indexOf("-"),
            module = null;
          if (index > -1) {
            module = moduleList.find(t => t.id == arrs[i].substr(0, index));
            if (!newObj.find(t => t.type == arrs[i].substr(0, index))) {
              newObj.push({
                id: module.id, //self.newGuid(),
                icon: module.icon,
                label: module.label,
                linkTo: module.linkTo,
                allowAnonymous: module.allowAnonymous,
                children: [],
                type: arrs[i].substr(0, index)
              });
              newObj
                .find(t => t.type == arrs[i].substr(0, index))
                .children.push(module.children.find(t => t.id == arrs[i]));
            } else {
              let submodule = module.children.find(t => t.id == arrs[i]);
              newObj
                .find(t => t.type == arrs[i].substr(0, index))
                .children.push(submodule);
            }
          } else {
            module = moduleList.find(t => t.id == arrs[i]);
            // let mid = self.newGuid();
            newObj.push({
              id: module.id,
              value: module.id, //id value 为了兼容两个不同控件
              icon: module.icon,
              label: module.label,
              linkTo: module.linkTo,
              allowAnonymous: module.allowAnonymous,
              type: arrs[i],
              children: module.children ? module.children : []
            });
          }
        }
        for (let i = 0; i < newObj.length; i++) {
          if (!newObj[i].children || newObj[i].children.length == 0)
            delete newObj[i].children;
        }
        newPubObj = newObj;
      } else {
        newPubObj = {
          id: obj.id,
          value: obj.id, //id value 为了兼容两个不同控件
          icon: obj.icon,
          label: obj.label,
          linkTo: obj.type,
          children: obj.children
        };
      }
      return newPubObj;
    },
    formatMultiObj(obj) {
      if (!obj) return;
    },
    initPubObj() {
      this.pubObj = [
        {
          id: "",
          label: "",
          icon: "",
          linkTo: "",
          type: null,
          parents: ['nullObj'],
          children: [],
          multiSelect: false
        }
      ];
      this.clearGroups();
    },
    initGroups() {
      let self = this;
      if (!self.groupList.menue.center.find(t => t.id == "nullObj")) {
        let newObj = {
          id: "nullObj",
          value: "nullObj",
          icon: "",
          label: "空",
          linkTo: "",
          type: "",
          children: []
        };
        self.groupList.menue.center.push(newObj);
      }
    },
    clearGroups() {
      let self = this;
      if (self.groupList.menue.center.find(t => t.id == "nullObj")) {
        let _index = self.groupList.menue.center.indexOf(
          self.groupList.menue.center.find(t => t.id == "nullObj")
        );
        self.groupList.menue.center.splice(_index, 1);
      }
    },
    saveHeaderProp() {
      this.clearGroups();

      let self = this,
        values = self.$store.getters.packageHeaderProp();
      self.setHeaderProp({ values: values });
    },
    newGuid() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(
        c
      ) {
        var r = (Math.random() * 16) | 0,
          v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    }
  },
  destoryed() {},
  components: {
    addGroups,
    addModule
  }
};
</script>
<style >
</style>