import auditTreeService from './audit-tree-service'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'

// 判断是否已经选择
function isChecked(selectedKeys, eventKey) {
  return selectedKeys.indexOf(eventKey) === -1
}

const iamAuditTreeMixins = {
  created() {
    // 判断单选多选
    if (!this.single) {
      this.checkedKeys = {
        checked: [],
        halfChecked: [],
      }
    }
    // 如果有默认展开节点，则赋值
    if (this.defaultExpandedKeys) {
      this.defaultTreeExpandedKeys = [...this.defaultExpandedKeys]
    }
    // 如果有传根节点名称，则赋值
    if (this.topNodeText) {
      this.defaultTopNodeText = this.topNodeText
    }
    // 如果有传根节点ID，则赋值
    if (this.topNodeId) {
      this.defaultTopNodeId = this.topNodeId
    }
    // 如果有传默认选中节点，则赋值
    if (this.selectedKeys.length > 0) {
      this.defaultSelectedKeys = [...this.selectedKeys]
    }

    // this.userRoles =
  },
  methods: {
    // 初始化部门下拉 分级授权获取部门下拉列表  维护权限
    initDeptList(formId) {
      auditTreeService.getManagedHierarchyOrg(formId).then((res) => {
        res.data.editNodes.forEach((item) => {
          this.depOptions.push({
            label: item.text,
            value: item.id,
            text: item.text,
            edit: true,
          })
        })
        if (this.managerType !== 'manager') {
          // 取编辑和查看节点并集
          res.data.viewNodes.forEach((item, index) => {
            const node = this.depOptions.find((nodeinfo) => {
              return nodeinfo.value === item.id
            })
            if (!node) {
              this.depOptions.push({
                label: item.text,
                value: item.id,
                text: item.text,
                edit: false,
              })
            }
          })
        }

        // 部门下拉框列表值赋值

        if (this.depOptions.length > 0) {
          let userInfo = getUserInfo()
          const params = {
            orgId: userInfo.deptId,
          }
          axios({
            url: 'api/xcoa-mobile/v1/iamorg/getCurrentUserGroup',
            method: 'get',
          }).then((res) => {
            userInfo = res.data
            params.orgId = res.data.id
            axios({
              url: 'api/xcoa-mobile/v1/iamorg/findIamOrgId',
              method: 'post',
              params,
            }).then((res) => {
              const obj = this.depOptions.find((i) => i.value === res.data)
              if (obj) {
                this.depvalue = obj.value
                this.defaultTopNodeId = obj.value
                this.defaultTopNodeText = obj.text + this.topNodeText
                this.defaultTreeExpandedKeys = [obj.value]
                this.defaultSelectedKeys = [obj.value]
                this.edit = obj.edit
                this.initTreeData(obj.value)
                this.emitTreeSelect(obj.value, {
                  selectedNodes: [
                    {
                      data: {
                        props: {
                          id: obj.value,
                          text: obj.text + this.topNodeText,
                          edit: obj.edit,
                        },
                      },
                    },
                  ],
                })
              } else {
                this.depvalue = this.depOptions[0].value
                // 加载默认值
                this.defaultTopNodeId = this.depOptions[0].value
                this.defaultTopNodeText = this.depOptions[0].text + this.topNodeText
                this.defaultTreeExpandedKeys = [this.depOptions[0].value]
                this.defaultSelectedKeys = [this.depOptions[0].value]
                this.edit = this.depOptions[0].edit
                this.initTreeData(this.depOptions[0].value)
                this.emitTreeSelect(this.depOptions[0].value, {
                  selectedNodes: [
                    {
                      data: {
                        props: {
                          id: this.depOptions[0].value,
                          text: this.depOptions[0].text + this.topNodeText,
                          edit: this.depOptions[0].edit,
                        },
                      },
                    },
                  ],
                })
              }
            })
          })
        } else {
          this.defaultTopNodeId = null
          this.defaultTopNodeText = null
          this.defaultTreeExpandedKeys = []
          this.defaultSelectedKeys = []
          this.emitTreeSelect(9999999, {
            selectedNodes: [],
          })
          this.spinning = false
          this.empty = true
        }
      })
    },
    /**
     * 显示分类负责人
     */
    showUser(item) {
      this.$emit('showUser', item)
    },
    // 判断当前树需要展示的节点信息
    bindTree(nodeinfo) {
      const checklist = this.checkedKeys.checked
      if (nodeinfo.children) {
        this.bindTree(nodeinfo.children)
        const hiddenItem = nodeinfo.children.find((item, index) => {
          return item.hidden !== true
        })
        // 判断当前进节点是否隐藏
        if (!hiddenItem && checklist.indexOf(nodeinfo.id) === -1) {
          nodeinfo.hidden = true
        }
        // 如果显示但是没有在选择列表，则不可选中
        if (!nodeinfo.hidden && checklist.indexOf(nodeinfo.id) === -1) {
          nodeinfo.disabled = true
        }
      } else {
        nodeinfo.forEach((node, nodeindex) => {
          if (node.children) {
            // 判断子节点是否有选中的节点
            this.bindTree(node.children)
            const hiddenItem = node.children.find((item, index) => {
              return item.hidden !== true
            })
            // 判断当前进节点是否隐藏
            if (!hiddenItem && checklist.indexOf(node.id) === -1) {
              node.hidden = true
            }
            // 如果显示但是没有在选择列表，则不可选中
            if (!node.hidden && checklist.indexOf(node.id) === -1) {
              node.disabled = true
            }
          } else {
            if (checklist.indexOf(node.id) === -1) {
              node.hidden = true
            }
            // 如果显示但是没有在选择列表，则不可选中
            if (!node.hidden && checklist.indexOf(node.id) === -1) {
              node.disabled = true
            }
          }
        })
      }
    },
    /***
     * 选中复选框时的事件
     */
    treeCheck(allKeys, echecked) {
      // echecked.checkedNodes 选中的所有节点信息为数组   .data.props 获取详细信息
      // echecked.node.dataRef  当前选中的节点信息
      if (this.single) {
        this.checkedKeys.checked = []
        this.checkedKeys.checked = [echecked.node.dataRef.id]
      }

      this.$emit('checkedKeys', echecked.node.dataRef, echecked.checkedNodes)
    },
    getTree(node) {
      const removeIndex = []
      node.children.forEach((item, index) => {
        if (item.hidden === true) {
          removeIndex.push(index)
        } else {
          if (item.children) {
            this.getTree(item)
          }
        }
      })
      // 删除元素
      removeIndex.forEach((oneindex, index) => {
        node.children.splice(oneindex - index, 1)
      })
    },

    // 点击树
    treeSelect(selectedKeys, info) {
      // 点击树不会取消选中
      if (info.selectedNodes.length === 0) {
        info.selectedNodes = [
          {
            data: {
              props: info.node.dataRef,
            },
          },
        ]
        info.selectedNodes[0].data.props.props.id = info.node.dataRef.id
        info.selectedNodes[0].data.props.props.edit = info.node.dataRef.edit
      }
      // 点击树不会取消选中
      this.defaultSelectedKeys = [info.node.dataRef.id]
      if (this.single) {
        this.checkedKeys = []
        this.checkedKeys = [info.node.dataRef.id]
      } else {
        if (isChecked(this.checkedKeys.checked, info.node.dataRef.id)) {
          this.checkedKeys.checked.push(info.node.dataRef.id)
        } else {
          this.checkedKeys.checked.splice(this.checkedKeys.checked.indexOf(info.node.dataRef.id), 1)
        }
        this.checkedKeys.checked = [...new Set(this.checkedKeys.checked)]
      }
      this.emitTreeSelect(info.node.dataRef.id, info)
    },
    // 筛选树
    onSearchChange(e) {
      const value = e.target.value

      const expandedKeys = this.dataList
        .map((item) => {
          if (item.title.indexOf(value) > -1) {
            return this.getParentKey(item.key, this.treeData)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)

      expandedKeys.unshift('0') // 顶结点永远展开

      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      })
    },

    getParentKey(key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some((item) => item.id === key)) {
            parentKey = node.id
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children)
          }
        }
      }
      return parentKey
    },

    transformData(data, nodeEdit) {
      return data.map((d) => {
        let isEdit
        const { children, ...rest } = d
        rest.edit = this.edit
        // 如果需要检查节点属性，且此节点不存在属性，则添加，否则直接赋值
        if (this.checkNodeEdit && !this.userRoles) {
          const nodeinfo = this.depOptions.find((item) => {
            return item.value === rest.id
          })
          if (nodeEdit === undefined) {
            if (nodeinfo) {
              rest.edit = nodeinfo.edit
              isEdit = nodeinfo.edit
            } else {
              rest.edit = false
            }
          } else {
            rest.edit = nodeEdit
            isEdit = nodeEdit
            if (nodeinfo) {
              rest.edit = nodeinfo.edit
              isEdit = nodeinfo.edit
            }
          }
          // 如果不是根节点且没有编辑权限，则设置不可点击
          if (isEdit === undefined && rest.props.isroot !== true) {
            rest.disabled = true
          }
        }
        return {
          ...rest,
          children: children && this.transformData(children),
          scopedSlots: { title: 'title' },
        }
      })
    },

    // 处理搜索用的dataList
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        const key = node.id
        const title = node.text
        const props = node.props
        // 用来判断此几点是否已经配置了用户，需要后台返回标识位进行判断
        if (props.showuser) {
          data[i].scopedSlots.icon = 'hasuser'
        }
        this.dataList.push({ key, id: key, title: title, props })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },

    onExpand(expandedKeys) {
      // 用户点击展开时，取消自动展开效果
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    // 小箭头点击事件
    foldClick() {
      this.fold = !this.fold
      if (this.fold) {
        this.icontype = 'right'
      } else {
        this.icontype = 'left'
      }
    },
    // 组织下拉框change时触发
    changedep(value, option) {
      this.key++
      if (!value) {
        this.defaultTreeExpandedKeys = ['0']
        this.defaultSelectedKeys = ['0']
        this.defaultTopNodeId = '0'
        this.defaultTopNodeText = this.topNodeText
      } else {
        this.defaultTreeExpandedKeys = [value]
        this.defaultSelectedKeys = [value]
        this.defaultTopNodeId = value
        this.defaultTopNodeText = option.data.props.text + this.topNodeText
        this.edit = option.data.props.edit
      }
      this.initTreeData(value)
      this.$emit('depChanged', value, option)
      this.emitTreeSelect(value, {
        selectedNodes: [
          {
            data: {
              props: {
                id: value,
                text: option.data.props.text + this.topNodeText,
                edit: option.data.props.edit,
              },
            },
          },
        ],
      })
    },
    // 刷新树方法
    refreshTree() {
      this.key++
    },
    // 发布点击事件
    emitTreeSelect(value, info) {
      this.$emit('treeSelect', value, info)
    },
  },
}

export default iamAuditTreeMixins
