<template>
  <div v-loading="loading">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="公告标题" prop="title">
        <el-input v-model="ruleForm.title" type="textarea" autosize placeholder="请输入公告标题"/>
      </el-form-item>
      <el-form-item label="公告信息" prop="content">
        <el-input v-model="ruleForm.content" type="textarea" autosize placeholder="请输入公告内容"/>
      </el-form-item>
      <el-form-item label="用户角色" prop="parentids">
        <el-tree
          ref="tree"
          :data="treelists"
          :default-expand-all="defaultExpandAll"
          show-checkbox
          check-strictly
          node-key="id"
          highlight-current
          @node-click="treeNodeClick"
        />
        <!--  -->
      </el-form-item>
      <el-form-item>
        <!-- <el-button type="primary" @click="setCheckedNodes">点击</el-button> -->
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getTreeList, getBlack, addBlack, editBlack } from '@/api/notice/manage'
import { validateTel } from '@/utils/validate'
import { filterContent } from '@/utils'
export default {
  name: 'AddOrEditManege',
  props: {
    rowid: {
      type: String,
      default: ''
    },
    layerid: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      ruleForm: {
        id: '',
        title: '',
        content: ''
      },
      rules: {
      },
      treelists: [], // 分类树列表
      treelistIscheck: [],
      resourceCheckedKey: [],
      defaultExpandAll: false,
      // 自定义菜单下拉数据的key值
      props: {
        id: 'id',
        name: 'name'
      },
      loading: false
    }
  },
  created() {
    if (this.rowid) {
      this.ruleForm.id = this.rowid
      this.getDetail(this.rowid)
      // this.setCheckedNodes()
      this.getTreeLists(this.rowid)// 分类指标
      this.TimeoutExe()
    } else {
      this.getTreeLists()// 分类指标
    }
  },
  methods: {
    // 分类树
    getTreeLists(rid) {
      return new Promise(resolve => {
        getTreeList(rid).then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.treelists = this.buildTree(response.data)
            this.treelistIscheck = this.buildTreeIceck(response.data)
          }
        })
        resolve()
      })
    },
    submitForm() {
      const noticeTree = this.$refs.tree.getCheckedNodes()
      const rolecodes = []
      const usercodes = []
      if (noticeTree) {
        let j = -1
        for (const i in noticeTree) {
          j++
          if (noticeTree[i].parentid) {
            usercodes.push(noticeTree[i].code)
          } else {
            rolecodes.push(noticeTree[i].code)
          }
        }
      }
      console.log(usercodes)
      console.log(rolecodes)
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading = true
          const datas = {
            id: this.ruleForm.id,
            title: filterContent.delHtmlTag(this.ruleForm.title),
            content: filterContent.delHtmlTag(this.ruleForm.content),
            rolecodes: rolecodes.length ? rolecodes.join(',') : '',
            usercodes: usercodes.length ? usercodes.join(',') : ''
          }
          // 添加
          if (!this.rowid) {
            addBlack(datas).then(response => {
              this.loading = false
              if (response.state.toLowerCase() === 'success') {
                debugger
                this.$parent.$layer.close(this.layerid)
                this.$parent.getList() // 重新加载父级数据
                this.$message.success('恭喜你，添加成功!')
              }
            }).catch(() => {
              this.loading = false
            })
            return
          }
          // 编辑
          editBlack(datas).then(response => {
            this.loading = false
            if (response.state.toLowerCase() === 'success') {
              this.$parent.$layer.close(this.layerid)
              this.$parent.getList() // 重新加载父级数据
              this.$message.success('恭喜你，编辑成功!')
            }
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.$message.error('请输入有效的必填项信息!')
          return false
        }
      })
    },
    // 获取详情
    getDetail(rid) {
      getBlack(rid).then(response => {
        if (response.state.toLowerCase() === 'success') {
          const res = response.data
          this.ruleForm.title = res.title
          this.ruleForm.content = res.content
          this.ruleForm.id = res.id
        }
      })
    },
    buildTreeIceck(listIcheck) {
      const tempIcheck = []
      const treeIcheck = []
      for (const j in listIcheck) {
        if (listIcheck[j].ischeck) {
          tempIcheck[listIcheck[j].id] = listIcheck[j]
        }
      }
      for (const i in tempIcheck) {
        if (tempIcheck[i].parentid) {
          if (!tempIcheck[tempIcheck[i].parentid].children) {
            tempIcheck[tempIcheck[i].parentid].children = []
          }
          tempIcheck[tempIcheck[i].parentid].children[tempIcheck[i].id] = tempIcheck[i]
        } else if (tempIcheck[i].ischeck) {
          treeIcheck[tempIcheck[i].id] = tempIcheck[i]
        }
      }
      return this.filterTreeidDatas(treeIcheck)
    },
    buildTree(list) {
      const temp = {}
      const tree = {}
      for (const j in list) {
        temp[list[j].id] = list[j]
      }
      for (const i in temp) {
        if (temp[i].parentid) {
          if (!temp[temp[i].parentid].children) {
            temp[temp[i].parentid].children = []
          }
          temp[temp[i].parentid].children[temp[i].id] = temp[i]
        } else {
          tree[temp[i].id] = temp[i]
        }
      }
      return this.filterTreeDatas(tree)
    },
    // 处理数据格式取id
    filterTreeidDatas(treeDatas) {
      const accessedRouters = []
      let j = -1
      console.log(treeDatas)
      for (const i in treeDatas) {
        j++
        accessedRouters.push({
          id: treeDatas[i].id,
          label: treeDatas[i].name,
          code: treeDatas[i].code,
          ischeck: treeDatas[i].ischeck,
          parentid: treeDatas[i].parentid,
          children: []
        })
        if (treeDatas[i].children.length > 0) {
          for (const n in treeDatas[i].children) {
            if (treeDatas[i].children[n].ischeck) {
              accessedRouters.push({
                id: treeDatas[i].children[n].id,
                label: treeDatas[i].children[n].name,
                code: treeDatas[i].children[n].code,
                ischeck: treeDatas[i].children[n].ischeck,
                parentid: treeDatas[i].children[n].parentid,
                children: []
              })
            }
          }
        }
      }
      return accessedRouters
    },
    // 处理数据格式
    filterTreeDatas(treeDatas) {
      const accessedRouters = []
      let j = -1
      for (const i in treeDatas) {
        j++
        accessedRouters.push({
          id: treeDatas[i].id,
          label: treeDatas[i].name,
          code: treeDatas[i].code,
          ischeck: treeDatas[i].ischeck,
          parentid: treeDatas[i].parentid,
          children: []
        })
        if (treeDatas[i].children) {
          accessedRouters[j].children = this.filterTreeDatas(
            treeDatas[i].children
          )
        }
      }
      return accessedRouters
    },
    TimeoutExe() {
      setTimeout(() => {
        // console.log(this.treelistIscheck)
        this.$refs.tree.setCheckedNodes(this.treelistIscheck)
      }, 1000)
    },
    getCheckedNodes() {
      // console.log(this.$refs.tree.getCheckedNodes())
    },
    treeNodeClick(data) {
      // this.treeclickId = data.id
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
	.date_picker{
		width: 100%;
	}
	div.date_picker input.el-range-input{
		width: 46%;
	}
</style>
