import routerUserMenu from '@/mixins/router-user-menu'
import breadcrumbComponent from '@/components/breadcrumb.vue'
import simpleSelectTree from '@/components/simple-select-tree.vue'

import {toTree} from '@/utils/util'

export default {
  name: 'ReportAccess',
  components:{ breadcrumbComponent, simpleSelectTree},
  mixins: [routerUserMenu],
  data () {
    return {
      id: '',
      name: '',
      filterUserText: '',
      userOptions: [],
      filterReportText: '',
      reportOptions: [],

      allReports: [],

      reportIds:[],
      userIds:[],
      /* 树过滤条件 */
      filterText: '',

      /* 接口返回的树 */
      menu: [],

      /* 树组件配置 */
      defaultProps: {
        children: 'children',
        label: 'name'
      },

      /* 右侧节点信息 */
      formInfo: {
        menuName: '',
        id: '',
        pcode: '0',
        updateTime: '',
        updateUserName: ''
      },
    }
  },
  watch: {
    /* 监听树过滤条件 */
    filterText(val) {
      this.$refs.menuTree.filter(val);
    },
  },
  computed: {
    /* 报表已选 */
    selectedReport: {
      get: function(){
        let {reportIds,allReports}=this
        let newArr=allReports.filter(item=>{
          return reportIds.indexOf(item.id)>=0
        })
        return newArr
      }

    },
    /* 报表已选 */
    selectedUser: {
      get: function(){
        let {userIds,userOptions}=this
        let newArr=userOptions.filter(item=>{
          return userIds.indexOf(item.id)>=0
        })
        return newArr
      }

    },
    /* 报表选项 */
    reportOptionsFiltered: {
      get: function(){
        let {reportOptions,filterReportText}=this
        let arr=[]
        if(filterReportText){
          arr=reportOptions.filter(report=>{
            return report.name.indexOf(filterReportText)>=0
          })
        }else{
          arr=[...reportOptions]
        }
        return arr
      }
    },
    /* 用户选项 */
    userOptionsFiltered: {
      get: function(){
        let {userOptions,filterUserText}=this
        let arr=[]
        if(filterUserText){
          arr=userOptions.filter(user=>{
            return user.name.indexOf(filterUserText)>=0
          })
        }else{
          arr=[...userOptions]
        }
        return arr
      }
    },
    /* 转换数据格式 */
    treeData:{
      get: function(){
        let tree=this.menu
        // 线性数组转成树后渲染
        let defaultProps={
          id: 'menuCode',
          parent_id: 'pcode',
          label: 'menuName'
        }
        let newTree=toTree(tree,'0',defaultProps)
        let root={
          id: '0',
          children: newTree,
          name: '自助报表',
          data:{
            id: '0',
            menuCode: '0',
            menuName: '自助报表'
          }
        }
        return [root]
      }
    }
  },

  mounted () {
    this.init()
  },
  methods: {
    addTab(targetName) {
      let newTabName = ++this.tabIndex + '';
      this.editableTabs2.push({
        title: 'New Tab',
        name: newTabName,
        content: 'New Tab content'
      });
      this.editableTabsValue2 = newTabName;
    },
    removeTab(targetName) {
      let tabs = this.editableTabs2;
      let activeName = this.editableTabsValue2;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }

      this.editableTabsValue2 = activeName;
      this.editableTabs2 = tabs.filter(tab => tab.name !== targetName);
    },










    /* 保存单个操作 */
    reportRelUsers(){
      let params={
        userIds: this.userIds,
        reportId: this.id
      }
      this.$api.report.reportRelUsers(params).then(res=>{
        if(res.code=== '1'){
          this.$message.success(res.msg)
          this.goBack()
        }
      })
    },
    /* 保存批量操作 */
    reportsRelUsers(){
      let params={
        userIds: this.userIds,
        reportIds:this.reportIds
      }
      this.$api.report.reportsRelUsers(params).then(res=>{
        if(res.code=== '1'){
          this.$message.success(res.msg)
          this.goBack()
        }
      })
    },
    //  如果有id，则获取id对应的报表信息
    init(){
      // 获取url参数
      let params = this.$route.params
      if(params.hasOwnProperty('id')){
        // 如果有id，则加载组件对象
        this.id = params.id
        this.name=params.name
        this.getDetail()
      }
      this.getTree()
      this.getReports()
      this.getUsers()
    },

    // 对象
    getDetail(){
      let params = { id: this.id }
      let _this=this
      this.$api.report.listRelUser(params)
        .then(res => {
          if (res.code == 1) {
            if(res.data){
              _this.userIds=res.data.map(u=>{
                return u.id
              })
            }
          }
        })
    },

    selectReportAll(flag){
      let {reportOptionsFiltered, reportIds}=this
      if(flag){
        reportOptionsFiltered.forEach((current)=>{
          let index=reportIds.indexOf(current.id)
          if(index<0){
            reportIds.push(current.id)
          }
        })
      }else{
        reportOptionsFiltered.forEach((current)=>{
          let index=reportIds.indexOf(current.id)
          if(index>=0){
            reportIds.splice(index,1)
          }
        })
      }
    },
    selectUserAll(flag){
      let {userOptionsFiltered, userIds}=this
      if(flag){
        userOptionsFiltered.forEach((current)=>{
          let index=userIds.indexOf(current.id)
          if(index<0){
            userIds.push(current.id)
          }
        })
      }else{
        userOptionsFiltered.forEach((current)=>{
          let index=userIds.indexOf(current.id)
          if(index>=0){
            userIds.splice(index,1)
          }
        })
      }
      },
    removeItem(arr,index){
      console.log(arr)
      arr.splice(index,1)
    },
    reloadReports(data){
      let menuCode=data.data.menuCode
      if(menuCode==0){
        this.getReports()
      }else{
        this.getReports({menuCode})
      }
    },
    getReports(obj){
      let params={}
      if(obj){
        Object.assign(params,obj)
      }
      this.$api.report.listPReport(params).then(res=>{
        if(res.code==1){
          this.reportOptions=res.data
          if(!obj){
            this.allReports=res.data
          }
        }
      })
    },
    getUsers(){
      this.$api.report.listUser().then(res=>{
        if(res.code==1){
          this.userOptions=res.data
        }
      })
    },
    /* 获取整个树 */
    getTree(){
      this.$api.menu.getTree().then(res=>{
        if(res.code==1){
          this.menu=res.data
        }
      })
    },

    /* 获取单个节点 */
    getTreeNode(menuCode){
      this.$api.menu.getMenu({id:menuCode}).then(res=>{
        if(res.code==='1'){
          this.formInfo=res.data
        }
      })
    },

    /* 点击更新 */
    editTreeNode(node, data, store){
      this.getTreeNode(data.data.menuCode)
    },

    /* 点击插入 */
    addTreeNode(node, data, store){
      let newNode={
        menuName: '',
        id: '',
        pcode: data.data.menuCode,
        updateTime: '',
        updateUserName: ''
      }
      this.formInfo=newNode
    },

    /* 点击删除 */
    delTreeNode(node, data, store){
      this.$confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delAction(data.data)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 提交删除
    delAction(obj) {
      let params = {
        id: obj.menuCode
      }
      this.$api.menu.deleteMenu(params)
        .then(res => {
          if (res.code == 1) {
            this.$message.success(res.msg)
            this.getTree()
          }
        })
    },

    // 修改节点文本，自定义图标，return内是jsx语法
    renderContent(h, { node, data, store }) {
      if(node.level == 1){
        return (
          <div class='tree-node'>
            <i class={node.level == 1 ? 'el-icon-datau-genmulu' : (data.children&&data.children.length > 0 ?  'el-icon-datau-wenjianjia' : 'el-icon-datau-wenjian')}></i>
            <span>{node.label}</span>
          </div>
        )
      }
      return (
        <div class='tree-node'>
          <i class={node.level == 1 ? 'el-icon-datau-genmulu' : (data.children&&data.children.length > 0 ?  'el-icon-datau-wenjianjia' : 'el-icon-datau-wenjian')}></i>
          <span>{node.label}</span>
        </div>
      )
    },

    /* 提交新增节点 */
    add(){
      let _this = this
      // 判断组件设置是否通过验证
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          // 提交后台并在成功后回到上一页
          let params = _this.formInfo
          _this.$api.menu.addMenu(params)
            .then(res => {
              if (res.code == 1) {
                _this.$message.success(res.msg)
                _this.getTree()
              }
            })
        } else {
          return false
        }
      })
    },

    /* 提交更新节点 */
    update(){
      let _this = this
      // 判断组件设置是否通过验证
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          // 提交后台并在成功后回到上一页
          let params = _this.formInfo
          params.id=params.menuCode
          _this.$api.menu.updateMenu(params)
            .then(res => {
              if (res.code == 1) {
                _this.$message.success(res.msg)
                _this.getTree()
              }
            })
        } else {
          return false;
        }
      })
    },

    /* 树过滤 */
    filterNode(value, data) {
      console.log(data)
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
  }
}
