<template>
  <div class="layout-no-flex">
    <el-toolbar>
      <el-button @click="goBack" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save"  priv="BrowsePrivGroupManage.Add" @click="saveConditionClickHandler"><span><i class="fa fa-save"></i>保存</span></el-button>
    </el-toolbar>
    <div>
      <div class="detail-panel">
        <el-form :model="currentPrivData" ref="privdataForm" :rules="metadataRules" label-width="120px">
          <el-form-item label="名称:" prop="name">
            <el-input style="width:320px" v-model="currentPrivData.name"></el-input>
          </el-form-item>
          <el-form-item label="别名:">
            <el-input style="width:320px" v-model="currentPrivData.code" :disabled="true"></el-input>
          </el-form-item>
          筛选条件1：
          <privGroup-demo class="priv-group" :condition="conditions.condition[0][0]" :memberGroups="memberGroups"
                          :memberTypes="memberTypes" :columnTypes="conditionColumnTypes"
                          :operatorTypes1="operatorColumnTypes1" :operatorTypes2="operatorColumnTypes2"
                          :memberLevelTypes="memberLevel" @changeCondition="val => handleChangeCondition(0, val)"/>
          <el-form-item>
            <el-select class="setPadding2" placeholder="" v-model="andOrColumnTypes.operator[0].default">
              <el-option v-for="type in andOrColumnTypes.data" :key="type.key" :label="type.value"
                          :value="type.key">
              </el-option>
            </el-select>
          </el-form-item>
          <privGroup-demo class="priv-group" :condition="conditions.condition[0][1]" :memberGroups="memberGroups"
                          :memberTypes="memberTypes" :columnTypes="conditionColumnTypes"
                          :operatorTypes1="operatorColumnTypes1" :operatorTypes2="operatorColumnTypes2"
                          :memberLevelTypes="memberLevel" @changeCondition="val => handleChangeCondition(1, val)"/>
          <el-form-item>
            <el-select class="setPadding2" placeholder="" v-model="andOrColumnTypes.operator[1].default">
              <el-option v-for="type in andOrColumnTypes.data" :key="type.key" :label="type.value"
                          :value="type.key">
              </el-option>
            </el-select>
          </el-form-item>
          <privGroup-demo class="priv-group" :condition="conditions.condition[0][2]" :memberGroups="memberGroups"
                          :memberTypes="memberTypes" :operatorTypes1="operatorColumnTypes1"
                          :columnTypes="conditionColumnTypes" :operatorTypes2="operatorColumnTypes2"
                          :memberLevelTypes="memberLevel" @changeCondition="val => handleChangeCondition(2, val)"/>
          <el-radio-group v-model="andOrColumnTypes.operator[2].default">
            <el-radio class="radio" label="and">并且</el-radio>
            <el-radio class="radio" label="or">或者</el-radio>
          </el-radio-group>
          <br/>筛选条件2：
          <privGroup-demo class="priv-group" :condition="conditions.condition[0][3]" :memberGroups="memberGroups"
                          :memberTypes="memberTypes" :columnTypes="conditionColumnTypes"
                          :operatorTypes1="operatorColumnTypes1" :operatorTypes2="operatorColumnTypes2"
                          :memberLevelTypes="memberLevel" @changeCondition="val => handleChangeCondition(3, val)"/>
          <el-form-item>
            <el-select class="setPadding2" placeholder="" v-model="andOrColumnTypes.operator[3].default">
              <el-option v-for="type in andOrColumnTypes.data" :key="type.key" :label="type.value"
                          :value="type.key">
              </el-option>
            </el-select>
          </el-form-item>
          <privGroup-demo class="priv-group" :condition="conditions.condition[0][4]" :memberGroups="memberGroups"
                          :memberTypes="memberTypes" :columnTypes="conditionColumnTypes"
                          :operatorTypes1="operatorColumnTypes1" :operatorTypes2="operatorColumnTypes2"
                          :memberLevelTypes="memberLevel" @changeCondition="val => handleChangeCondition(4, val)"/>
          <el-form-item>
            <el-select class="setPadding2" placeholder="" v-model="andOrColumnTypes.operator[4].default">
              <el-option v-for="type in andOrColumnTypes.data" :key="type.key" :label="type.value"
                          :value="type.key">
              </el-option>
            </el-select>
          </el-form-item>
          <privGroup-demo class="priv-group" :condition="conditions.condition[0][5]" :memberGroups="memberGroups"
                          :memberTypes="memberTypes" :columnTypes="conditionColumnTypes"
                          :operatorTypes1="operatorColumnTypes1" :operatorTypes2="operatorColumnTypes2"
                          :memberLevelTypes="memberLevel" @changeCondition="val => handleChangeCondition(5, val)"/>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import privGroupDemo from './components/BrowsePrivGroup.vue'
import util from '@src/common/util.js'

export default {
  components: {
    'privGroup-demo': privGroupDemo
  },
  props: {
    ID: {
      type: [String, Number],
      default: 0
    }
  },
  data() {
    return {
      data: {},
      currentPrivData: {},
      conditionColumnTypes: [], // 权限详情-权限操作对象
      operatorColumnTypes1: [], // 权限详情-权限范围1
      operatorColumnTypes2: [], // 权限详情-权限范围2
      memberLevel: [], // 权限详情-权限操作对象-会员等级
      memberTypes: [],
      memberGroups: [],
      andOrColumnTypes: {
        data: [],
        operator: [{ default: 'and' }, { default: 'and' }, { default: 'and' }, { default: 'and' }, { default: 'and' }]
      }, // 权限详情-连接筛选条件
      metadataRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }, { max: 50, message: '名称不能超过50个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入别名', trigger: 'blur' },
          { max: 50, message: '别名不能超过50个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (/^\w+$/.test(value) === false) {
                callback(new Error('只能是数字和字母组成'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      conditions: {
        condition: [
          [
            { column: '', operator: '', value: [], type: '' },
            { column: '', operator: '', value: [], type: '' },
            { column: '', operator: '', value: [], type: '' },
            { column: '', operator: '', value: [], type: '' },
            { column: '', operator: '', value: [], type: '' },
            { column: '', operator: '', value: [], type: '' }
          ],
          []
        ],
        items: {}
      } // 浏览权限详情模板
    }
  },
  async mounted() {
    await Promise.all([this.getGroupOperator(), this.getConditionColumns()])
    this.loadData()
  },
  methods: {
    goBack() {
      this.$router.push(`/plugins/browsepriv`)
    },
    async loadData() {
      let res = await axios.get(`/ui/browsepriv/${this.ID}`)
      if (res.data.status === 1) {
        this.currentPrivData = res.data.data.conditions ? res.data.data
          : Object.assign(res.data.data, {conditions: this.getConditions()})
      } else {
        this.currentPrivData = {}
      }

      this.andOrColumnTypes.operator = [{ default: 'and' }, { default: 'and' }, { default: 'and' }, { default: 'and' }, { default: 'and' }]
      await this.initAllCondition()
      if (this.currentPrivData.conditions) {
        let conditionLength = this.currentPrivData.conditions.condition[0].length
        if (conditionLength) {
          let conditions = this.conditions.condition[0]
          let andOrColumnTypes = this.andOrColumnTypes
          let i = conditionLength - 1 // 上半部分个数
          let j = 0 // 下半部分个数
          let b = 0 // 定义上半部分conditions下标
          let c = 0 // 定义上半部分andOrColumnTypes下标
          let d = 0 // 定义下半部分conditions下标
          let f = 0 // 定义下半部分andOrColumnTypes下标
          let isnext = false // 是否有下半部分
          this.currentPrivData.conditions.condition[0].forEach(function(rosw, index) {
            if (rosw.type === 'group' && rosw.operator === ')' && index < conditionLength - 1 && !isnext) {
              i = index // 取上半部分
              j = conditionLength - i - 1 // 下半部分
              isnext = true
            }
          }, this)
          for (let a = 1; a < i; a++) {
            // 遍历上部分
            let rosw = this.currentPrivData.conditions.condition[0][a]
            if (rosw.type !== 'columngroup') {
              conditions[b] = Object.assign({}, rosw)
              conditions[b].value = rosw.value.split(',')
              b++
            } else {
              andOrColumnTypes.operator[c].default = rosw.operator
              c++
            }
          }
          if (isnext) {
            i = i + 1
            j = j - 1
            andOrColumnTypes.operator[2].default = this.currentPrivData.conditions.condition[0][i] ? this.currentPrivData.conditions.condition[0][i].operator : 'and' // 获取第三个operator
          }
          for (let a = 1; a < j; a++) {
            // 遍历下部分
            let rosw = this.currentPrivData.conditions.condition[0][a + i]
            if (rosw.type === 'column') {
              // 给conditions赋值要加上3 第一部分已经有三个了
              conditions[d + 3] = Object.assign({}, rosw)
              conditions[d + 3].value = rosw.value.split(',')
              d++
            } else if (rosw.type === 'columngroup') {
              andOrColumnTypes.operator[f + 3].default = rosw.operator // 给operator赋值，要加上3
              f++
            }
          }
          conditions.splice(0, 0) // 强制触发数组更新检测
        }
      }
    },
    handleChangeCondition(index, value) {
      this.conditions.condition = [
        [...this.conditions.condition[0].slice(0, index), value, ...this.conditions.condition[0].slice(index + 1)],
        ...this.conditions.condition.slice(1)
      ]
    },
    getConditions() {
      // 定义数组接收数据完整的信息
      let myarray = {
        condition: [[], []],
        items: {}
      }
      let groupstart = true
      let colmumngroup = false
      let groupend = false
      var groupstarandend = false
      let start = { column: '', operator: '(', value: '', type: 'group' }
      let end = { column: '', operator: ')', value: '', type: 'group' }
      let b = this.andOrColumnTypes
      // 遍历页面的权限详情
      this.conditions.condition[0].forEach(function(row, index) {
        // 将权限中完整的数据已经索引放入数组myarray中\
        if (row.column && row.operator && row.value) {
          row.type = 'column'
          if (index < 3) {
            // 第一个分组条件处理
            // 增加条件分组开始
            if (groupstart) {
              myarray.condition[0].push(start)
              groupstart = false
              groupend = true
              groupstarandend = true
            }
            // 增加两个条件之间的关系
            if (colmumngroup && index !== 0) {
              let colmumnsgroup = b.operator[index - 1].default
              myarray.condition[0].push({
                column: '',
                operator: colmumnsgroup,
                value: '',
                type: 'columngroup'
              })
            }
          } else {
            // 第二个分组处理
            if (groupstarandend) {
              myarray.condition[0].push(end)
              colmumngroup = false
              let group = b.operator[2].default
              myarray.condition[0].push({
                column: '',
                operator: group,
                value: '',
                type: 'group'
              })
              myarray.condition[0].push(start)
              groupend = true
              groupstarandend = false
            }
            if (colmumngroup && index !== 0 && index !== 3) {
              let colmumnsgroup = b.operator[index - 1].default
              myarray.condition[0].push({
                column: '',
                operator: colmumnsgroup,
                value: '',
                type: 'columngroup'
              })
            }
          }
          // row.value = row.value
          myarray.condition[0].push(Object.assign(row, {value: row.value + ''}))
          colmumngroup = true
        }
      })
      if (groupend) {
        myarray.condition[0].push(end)
      }
      return myarray
    },
    // 保存权限详情
    async saveConditionClickHandler() {
      try {
        await util.validateForm(this.$refs.privdataForm)
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      this.currentPrivData.conditions = JSON.stringify(this.getConditions())
      // 执行保存方法
      let res = await axios.put(`/ui/browsepriv/${this.currentPrivData.ID}`, this.currentPrivData)
      util.showResponseMessage(res.data)
    },
    // 获取 第一下拉选项
    async getConditionColumns() {
      let dataCondition = await axios.get('/ui/browsepriv/conditioncolumns')

      this.conditionColumnTypes = dataCondition.data.data

      return this.conditionColumnTypes
    },
    async getGroupOperator() {
      let res = await axios.get('/ui/blocklist/groupoperator')
      this.andOrColumnTypes.data = res.data.data

      return this.andOrColumnTypes
    },
    async initAllCondition() {
      // 初始化条件
      this.operatorColumnTypes1 = []// 权限详情-权限范围1
      this.operatorColumnTypes2 = []// 权限详情-权限范围2
      this.memberLevel = []// 权限详情-权限操作对象-会员等级
      this.memberTypes = []
      this.memberGroups = []
      let dataOne = await axios.get(`/ui/browsepriv/0`, {})
      let data = dataOne.data
      let allcondition = data.data.allCondition
      for (let item in allcondition.MemberGroup_operator) {
        let obj = {
          key: item,
          value: allcondition.MemberGroup_operator[item]
        }
        this.operatorColumnTypes1.push(obj)
      }
      for (let item in allcondition.DefaultMemberScore_operator) {
        let obj = {
          key: item,
          value: allcondition.DefaultMemberScore_operator[item]
        }
        this.operatorColumnTypes2.push(obj)
      }
      for (let item in allcondition.DefaultMemberLevel_value) {
        let obj = {
          key: item,
          value: allcondition.DefaultMemberLevel_value[item]
        }
        this.memberLevel.push(obj)
      }
      for (let item in allcondition.MemberType_value) {
        let obj = { key: item, value: allcondition.MemberType_value[item] }
        this.memberTypes.push(obj)
      }
      for (let item in allcondition.MemberGroup_value) {
        let obj = { key: item, value: allcondition.MemberGroup_value[item] }
        this.memberGroups.push(obj)
      }
    }
  }
}
</script>

<style scoped>
.padding-top-bottom .search-bar {
  padding-bottom: 5px;
}

.info-form-wrap {
  padding: 10px 0;
  width: 480px;
  margin: 0 auto;
}

.info-form-wrap .el-form-item {
  margin-bottom: 0;
}

.setPadding2 {
  width: 120px;
}

.priv-group {
  width: 520px;
}
</style>
