<template>
  <div class="admin-department">
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="queryParams.name" size="small" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="" size="small" @click="getList">查询</el-button>
        <el-button type="primary" size="small" @click="handleAdd(0)">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="tableData"
        border
        @expand-change="getNode"
        header-row-class-name="custom-table-header"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column type="selection" width="60" align="center"></el-table-column>
      <el-table-column prop="name" label="数据权限名称" align="" show-overflow-tooltip></el-table-column>
      <el-table-column prop="tenant" label="条件" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-dropdown split-button type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
            <el-dropdown-menu slot="dropdown" class="text-align_center">
              <el-dropdown-item class="color-red" @click.native="handleDelete(scope.row)" divided>删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
       <div class="pagination">
      <el-pagination :current-page.sync="queryParams.current" :page-size="queryParams.size" :total="total" @current-change="handleCurrentChange" layout="total, prev, pager, next, jumper" background></el-pagination>
    </div>
    <el-dialog :title="title" :visible.sync="visible" width="800px" :before-close="close">
      <el-form v-if="visible" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" label-position="left">
           <!-- <el-form-item label="所属租户" prop="tenant">
              <el-tooltip
                  class="item"
                  effect="dark"
                  :disabled="!userinfo.tenantName"
                  :content="userinfo.tenantName"
                  placement="top-start"
                >
                <el-input v-model="userinfo.tenantName" placeholder="请输入所属租户" :readonly="true" ></el-input>
                </el-tooltip>
            </el-form-item> -->
           <el-form-item label="所属功能" prop="function">
            <el-input v-model="ruleForm.function" size="small" :readonly="true" placeholder="请输入所属功能"></el-input>
        </el-form-item>
        <el-form-item label="数据权限名称" prop="function">
            <el-input v-model="ruleForm.name" size="small" placeholder="请输入数据权限名称"></el-input>
        </el-form-item>
        <el-form-item label="数据权限">
             <template>

              <div class="add"><el-button type="primary" @click="addList()">添加</el-button> </div>
                  <div style="border:1px solid #C0C0C0;border-radius:4px;overflow:auto;min-height:200px;padding: 10px 20px">
                    <!-- <el-row :gutter="24" v-for="(item,i) in dataList" :key="i" class="listItem">
                      <el-col :span="3" :class="item.logicOpr ? 'normal' : 'hidden'" style="background: rgba(0,0,0,0)"><span><el-input  v-model="item.logicOpr"></el-input></span></el-col>
                      <el-col :span="7"><el-input v-model="item.field"></el-input></el-col>
                      <el-col :span="3"><el-input v-model="item.opr"></el-input></el-col>
                      <el-col :span="7"><el-input v-model="item.value"></el-input></el-col>
                      <el-col :span="4">
                      <el-button><i class="el-icon-delete"></i> </el-button>
                      </el-col>
                    </el-row> -->

                    <el-row :gutter="24" v-for="(item,i) in list" :key="i" class="listItem">
                      <el-col :span="4" style="padding:0">
                        <span>
                          <span v-if="i==0" style="opacity: 0;"> 内容 </span>
                          <el-select v-else v-model="item.logicOpr">
                              <el-option
                          v-for="item in dictionaries.LOGIC_OPERATOR"
                          :key="item.dictChildValue"
                          :label="item.dictChildLabel"
                          :value="item.dictChildValue">
                        </el-option>
                          </el-select>
                        </span>
                      </el-col>

                      <el-col :span="7">
                        <el-select v-model="item.field">
                            <el-option
                          v-for="item in dictionaries.dataDict"
                          :key="item.dataSourceField"
                          :label="item.dataSourceName"
                          :value="item.dataSourceField">
                        </el-option>
                        </el-select>
                      </el-col>
                      <el-col :span="3" style="padding:0">
                        <el-select v-model="item.opr">
                            <el-option
                          v-for="item in dictionaries.OPERATOR"
                          :key="item.dictChildValue"
                          :label="item.dictChildLabel"
                          :value="item.dictChildValue">
                        </el-option>
                        </el-select>
                      </el-col>
                      <el-col :span="7">
                        <el-select v-model="item.value"
                          filterable
                          allow-create
                          default-first-option
                          placeholder="请选择">
                             <el-option
                             :value="userinfo.tenantName"
                             >
                               <el-tooltip class="item" effect="dark" :content="userinfo.tenantName" placement="top">
                                 <span style="float: left;width:100px;white-space:nowrap;overflow:hidden;text-overflow: ellipsis;">{{userinfo.tenantName}}</span>
                                </el-tooltip> 
                                <span style="float: right; color: #8492a6; font-size: 13px;margin-left:30px">租户</span>
                              </el-option>
                        </el-select>
                      </el-col>
                      <el-col :span="3">
                      <el-button @click="deleteList(i)"><i class="el-icon-delete"></i> </el-button>
                      </el-col>
                    </el-row>
                  </div>
                </template>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" placeholder="请输入备注" type="textarea" maxlength="100" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import TreeItem from './components/TreeItem'
export default {
  components: {
    Treeselect,
    TreeItem
  },
  data() {
    return {
      options:[{label:'你好',value:1},{label:'你好1',value:2},{label:'你好2',value:3}],   
      visible: false,
      loading: false,
      btnLoading: false,
      total: 0,
      tableData: [],
      title: '',
      show:false,
      disabled:false,
      lastName:'',
      functionLis: [],
      multipleSelection: [],
      queryParams: {
        size: 10,
        current: 1,
        name: ''
      },
      data:[],
      ruleForm: {},
      roleList:[],
      rules: {
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' },],
        parentId: [{ required: true, message: '请选择所属部门', trigger: 'change' },],
      },
      list:[],
      
      dataList:
        {
          "nodeType": "logic",
          "logicOpr": "or",
          "left":{
              "nodeType": "logic",
              "logicOpr": "and",
              "left": {
              "nodeType": "exp",
                "field": "POSITION_DESCRIPTION",
                "opr": "=",
                "value": "'总经理1'"
              },
              "right": {
                "nodeType": "exp",
                "field": "POSITION_DESCRIPTION",
                "opr": "=",
                "value": "'总经理2'"
              }
            },
          "right": {
            "nodeType": "exp",
            "field": "POSITION_DESCRIPTION",
            "opr": "=",
            "value": "'总经理3'"
          }

      }
    }
  },
  created(){
   
  },
 
  mounted() {
    this.getList()
    this.getFunctionList()
    // this.ListToTree()
  },
  computed: {
    dictionaries() {
      console.log(this.$store.state.admin.dictionaries)
      return this.$store.state.admin.dictionaries
    },
    userinfo() {
      return this.$store.state.admin.userinfo
    }
  },
  methods: {
    addList() {
      this.list.push({})
    },
    deleteList(i) {
      this.list.splice(i, 1)
    },
    ListToTree(){
      console.log(this.dataList)
      var a =[]
      if(this.list.length==1){
        a = this.list[0]
         a.nodeType='logic'
      }else{
        a[0]=this.list[0]
          a[0].nodeType='exp'
        for(var i =1;i<this.list.length;i++){
          this.list[i].nodeType='exp'
          a[i]={}
          a[i].left=a[i-1]
          a[i].nodeType='logic'
          a[i].right=this.list[i]
          a[i].logicOpr = this.list[i].logicOpr
          // delete  a[i].right.logicOpr
          // delete  a[i].left.logicOpr
          
        }
      }
      console.log(a)
      this.ruleForm.rule = JSON.stringify(a[a.length-1])
      // this.TreeToList(a[a.length-1])
    },
    TreeToList(data){
       var root = data
    var a=[]
     const result = [];
    function l(root){
      const stack = [];
      let last = null;
      let current = root;
      while (current || stack.length > 0) {
        while (current) {
          stack.push(current);
          current = current.left;
        }
        current = stack[stack.length - 1];
        if (!current.right || current.right == last) {
          current = stack.pop();
          result.push(current);
          last = current;
          current = null;
        } else {
          current = current.right;
        }
      }
      // console.log(result)
      return result;

    }
    l(root)
          // console.log(result)
          var i=0
          var c=0
          function s(i){
          if(i<result.length){
            
            if(i==0){
              a.push(result[i])
              i+=1
              c+=1
            }
            if(i%2==1){
              a.push(result[i])
              // console.log(a[c])
              a[c]['logicOpr'] = result[i+1].logicOpr
              i+=2
               c+=1
            }
            
            s(i)
        }
      }
      s(i)
      console.log(a)
      this.list= a
    },
    getNode(node){
      console.log(node)
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
      }
    },
    handleAdd(updepartmentId,row) {
      // console.log(row)
      this.title = '新增数据权限'
      this.visible = true
      this.ruleForm={}
    },
    handleEdit(row) {
      this.title = '编辑数据权限'
      this.visible = true
      this.TreeToList(JSON.parse(row.rule))
      this.ruleForm = { ...row }
    },
    close() {
      this.visible = false
    },
     handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },
    getList() {
      this.loading = true
      this.$api.getDataList(this.queryParams).then(response => {
        
        this.tableData = response.data
        this.total=response.pageColumn.total
        this.loading = false
      }).catch(error => {
        this.loading = false
      })
    },
    getFunctionList() {
      this.$api.getFunctionList().then(response => {
        this.functionList = response.data
      })
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true
          this.ListToTree()
          if (this.ruleForm.id) {
            this.$api.editData(this.ruleForm).then(response => {
              this.$message.success('编辑成功')
              this.btnLoading = false
              this.getList()
              this.close()
            }).catch(error => {
              this.btnLoading = false
            })
          } else {
            this.ruleForm.tenant=this.userinfo.tenantId
            console.log(this.ruleForm)
            this.$api.addData(this.ruleForm).then(response => {
              this.$message.success('新增成功')
              this.btnLoading = false
              this.getList()
              this.close()
            }).catch(error => {
              this.btnLoading = false
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleDelete(row) {
      this.$confirm('确认删除本条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.$api.deleteData({ id: row.id }).then(response => {
          this.$message.success('删除成功')
          this.loading = false
          this.getList()
        }).catch(error => {
          this.loading = false
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.admin-department {

}
.add {
  display: flex;
  justify-content: right;
  margin-bottom: 10px;
}
.listItem {
  margin: 10px 0;
}
.normal {

}
.hidden {
 opacity: 0;
}
</style>