<template>
  <div class="newbi-dataset-filter">
    <div class="wrapper">
      <div class="left">
        <el-tabs tab-position="left" v-model="nowName" @tab-click="onSelectItem">
          <el-tab-pane v-for="(item, i) of list" :name="item.visualdevPermName" :key="item.id" :label="item.visualdevPermName"> </el-tab-pane>
        </el-tabs>
        <div class="add-tab">
          <el-button size="small" type="success" plain icon="el-icon-plus" @click="onAddItem">添加标签组</el-button>
        </div>
      </div>
      <div class="right" v-if="nowFilter">
        <el-form size="mini" label-width="60px">
          <el-form-item label="名称">
            <el-input v-model="nowFilter.visualdevPermName"></el-input>
          </el-form-item>
          <el-form-item label="权限组">
            <auth-group-selector @change="dataPermIdChange" v-model="nowFilter.dataPermId"></auth-group-selector>
          </el-form-item>
          <el-form-item label="标签默认填充色" label-width="120px">
            <el-color-picker @change="$forceUpdate();"
              v-model="nowFilter.defaultBgColor"
              show-alpha
              :predefine="predefineColors">
            </el-color-picker>
          </el-form-item>
          <el-form-item label="标签选中填充色" label-width="120px">
            <el-color-picker  @change="$forceUpdate();"
              v-model="nowFilter.actionBgColor"
              show-alpha
              :predefine="predefineColors">
            </el-color-picker>
          </el-form-item>
          <div style="margin-bottom: 10px;display: flex;justify-content: space-between;">
            <el-button size="mini" type="primary" @click="addLabelGroup">{{ !nowFilter.id ? '新增标签组' : '更新标签组' }}</el-button>
            <el-button size="mini" @click="addLabelClick">添加标签</el-button>
          </div>
          <el-table :data="newlabelList" border style="width: 100%">
            <el-table-column label="标签名称" prop="visualdevPermName">
            </el-table-column>
            <el-table-column label="是否启用">
              <template slot-scope="scope">
                <el-switch @change="labelStatusChange($event, scope.row)" v-if="scope.row.visualdevPermName !== '全部' " :active-value="0" :inactive-value="1" v-model="scope.row.labelStatus">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="设置">
              <template slot-scope="scope">
                <el-button v-if="scope.row.visualdevPermName !== '全部' " size="mini" type="text" @click="onEditLabel(scope.row)">编辑</el-button>
                <el-button v-if="scope.row.visualdevPermName !== '全部' " size="mini" type="text" @click="onDelLabel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </div>
    <el-dialog title="新增标签" :visible.sync="dialogVisible" width="30%" append-to-body>
      <el-form :model="addForm" size="mini" ref="addForm" :rules="rulesList" label-width="80px">
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="标签发布状态" label-width="107px">
          <el-switch v-model="addForm.states" :active-value="0" :inactive-value="1">
          </el-switch>
        </el-form-item>
        <p style="padding-left: 10px">标签筛选条件</p>
        <filter-setting :active="true" :config="addForm" :dbLinkId="cubeId" :max-level="3"/>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addFormClick()">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>
<script>
import authGroupSelector from "./auth-group-selector";
import {
  addDataPermLabelGroup,
  addLabel, delLabel,
  getDataPermLabel,
  getDataPermLabelGroup,
  updateDataPermLabelGroup
} from "@/components/Dataset-filter/report";
import FilterSetting from "@/components/Dataset-filter/filterSetting.vue";
import {deepClone} from "@/utils";

export default {
  name: "tab-filter",
  components: {FilterSetting, authGroupSelector},
  props:['modelId','activeName','cubeId','formData'],
  data(){
    return {
      list: [],
      nowName: '',
      nowFilter: {},
      predefineColors: [
      '#ff4500',
      '#ff8c00',
      '#ffd700',
      '#90ee90',
      '#00ced1',
      '#1e90ff',
      '#c71585',
      'rgba(255, 69, 0, 0.68)',
      'rgb(255, 120, 0)',
      'hsv(51, 100, 98)',
      'hsva(120, 40, 94, 0.5)',
      'hsl(181, 100%, 37%)',
      'hsla(209, 100%, 56%, 0.73)',
      '#c7158577'
    ],
      dialogVisible:false,
      addForm: {
        name:'',
        states:0,
        columnList:[],
        filter:[],
        filterRelation: '',
      },
      newlabelList:[],
      rulesList:{
        name: [{ required: true, message: '请输入标签名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getInfo()
  },
  watch: {
    activeName: {
      deep: true,
      handler(val) {
        if (val && val === 'labelManage') {
          this.getInfo()
        }
      }
    }
  },
  methods:{
    getInfo(){
      getDataPermLabelGroup(this.modelId).then((res)=>{
        this.list = res.data.data
        if (!this.list.length) {
          this.list.push({
            visualdevPermName: '默认标签组',
            dataPermId: '',
            id: '',
            labelJson: '',
            labelList:[],
            labelStatus: '',
            visualdevId: this.modelId,
            defaultBgColor: '#ffffff',
            actionBgColor: '#1e90ff',
          })
        }
        this.nowName = this.list[0].visualdevPermName
        this.onSelectItem({ name: this.nowName })
      })
    },
    // 选择过滤器时
    async onSelectItem({name}) {
      let now = this.list.find((i) => i.visualdevPermName == name)
      this.nowName = now.visualdevPermName
      this.nowFilter = now
      try {
        this.nowFilter.labelJson = now.labelJson ? deepClone(JSON.parse(now.labelJson)) : {}
      }catch {
        this.nowFilter.labelJson = now.labelJson ? deepClone(now.labelJson) : {}
      }
      this.nowFilter.defaultBgColor = this.nowFilter.labelJson.defaultBgColor
      this.nowFilter.actionBgColor = this.nowFilter.labelJson.actionBgColor
      let params = {groupId: now.id}
      await getDataPermLabel(this.modelId, params).then((res) => {
        this.newlabelList = res.data.data
        this.newlabelList.unshift({visualdevPermName:'全部',labelStatus:true})
      })
    },
    // 添加过滤器时
    onAddItem() {
      let visualdevPermName = this.list.length + 1 + '-新增标签组'
      let newFilter = {
        visualdevPermName,
        dataPermId: '',
        cubeDataId: parseInt(this.cubeId),
        filterRelation: '',
        filterList: [],
        excludeColumn: []
      }
      this.list.push(newFilter)
      this.nowName = visualdevPermName
      this.nowFilter = newFilter
    },
    addLabelClick(){
      this.dialogVisible = true
      this.$nextTick(()=>{
        this.addForm = {
          visualdevPermName:'',
          labelStatus:1,
          columnList:[],
          filter:[],
          filterRelation: '',
        }
      })
    },
    updateNullNode(parent,item,filter){
      if (item?.conditions && item.conditions.length) {
        item.conditions.forEach((node, i) => this.updateNullNode(item,node,filter));
      }else {
        let filterItem = filter.find(item1=> item1.uniqId === item.uniqId)
        if (filterItem.conditions && filterItem.conditions.length){
          filterItem.conditions.forEach((z, i) =>{
            parent.conditions.push(
              {uniqId: z.uniqId, columnTitle: filterItem.columnTitle,}
            )
          });
          parent.conditions = parent.conditions.filter(item1=> item1.uniqId !== item.uniqId)
        }
      }
    },
    addFormClick(){
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.newlabelList = this.newlabelList.filter(item=> item.visualdevPermName !== '全部')
          // let browserRequest = []
          if (this.addForm.filter && this.addForm.filter.length) {
            if (!this.addForm.filterRelation) {
              let filterRow = this.addForm.filter.filter((i) => i.connectTime === "where");
              // 遍历 filterRelation 定义filterRelation下每个对象为item，如果item下conditions 存在且有长度的 遍历item的 conditions map出来 {uniqId: i.uniqId, columnTitle: item.columnTitle}
              let conditionsList = []
              filterRow.forEach((item) => {
                let filterItem = item.conditions.map((i) => ({uniqId: i.uniqId, columnTitle: item.columnTitle,}));
                conditionsList = [...conditionsList,...filterItem]
              });
              let filterRelation = {
                conditions: conditionsList,
                  relation: "AND",
              }
              this.addForm.filterRelationIntegration = JSON.stringify(filterRelation)
              this.addForm.filterRelation = JSON.stringify({
                conditions: this.addForm.filter
                  .filter((i) => i.connectTime === "where")
                  .map((i) => ({uniqId: i.uniqId, columnTitle: i.columnTitle,})),
                relation: "AND",
              })
            }else {
              let filterRelation = JSON.parse(this.addForm.filterRelation)
              if (filterRelation.conditions && filterRelation.conditions.length) {
                let cloneFilterRelation = deepClone(filterRelation)
                cloneFilterRelation.conditions.forEach((i,z)=>{
                  this.updateNullNode(cloneFilterRelation,i,this.addForm.filter)
                })
                this.addForm.filterRelationIntegration = JSON.stringify(cloneFilterRelation)
              }
            }
          }
          let params = {
            visualdevPermName:this.addForm.name,
            labelStatus: this.addForm.states,
            labelJson:JSON.stringify({filter:this.addForm.filter,filterRelationIntegration:this.addForm.filterRelationIntegration,filterRelation:this.addForm.filterRelation}),
            dataPermId:this.nowFilter.dataPermId,
            labelGroupId:this.nowFilter.id,
            id:this.addForm.id,
            labelCss:JSON.stringify(this.nowFilter.labelJson)
          }
          addLabel(this.modelId,params).then((res)=>{
            this.$message({ message: res.data.msg, type: 'success', duration: 1500 })
            this.onSelectItem({ name: this.nowName })
          })
          this.$nextTick(()=>{
            this.addForm = {
              visualdevPermName:'',
              labelStatus:false,
              columnList:[],
              filter:[],
              filterRelation: '',
            }
            this.dialogVisible = false
            this.newlabelList.unshift({visualdevPermName:'全部',labelStatus:true})
          })
        } else {
          return false;
        }
      });
    },
    onEditLabel(row){
      this.dialogVisible = true
      let dataJson = JSON.parse(row.labelJson)
      this.$nextTick(()=>{
        this.addForm = {
          name:row.visualdevPermName,
          states:row.labelStatus,
          filter:dataJson.filter,
          filterRelation: dataJson.filterRelation,
          id:row.id
        }
      })
    },
    onDelLabel(row){
      delLabel(row.id).then((res)=>{
        this.$message({ message: res.data.msg, type: 'success', duration: 1500 })
        this.onSelectItem({ name: this.nowName })
      })
    },
    addLabelGroup(){
      let params = {
        visualdevPermName:this.nowFilter.visualdevPermName,
        labelJson:JSON.stringify({defaultBgColor:this.nowFilter.defaultBgColor,actionBgColor:this.nowFilter.actionBgColor}),
        dataPermId:this.nowFilter.dataPermId,
        id:this.nowFilter.id
      }
      const formMethod = this.nowFilter.id ? updateDataPermLabelGroup : addDataPermLabelGroup
      formMethod(this.modelId,params).then((res)=>{
        this.$message({ message: res.data.msg, type: 'success', duration: 1500 })
        this.getInfo()
      })
    },
    labelStatusChange(val,row){
      let params = {
        visualdevPermName:row.visualdevPermName,
        labelStatus: val,
        labelJson:row.labelJson,
        dataPermId:row.dataPermId,
        labelGroupId:this.nowFilter.id,
        id:row.id,
        labelCss:row.labelCss
      }
      addLabel(this.modelId,params).then((res)=>{
        this.$message({ message: res.data.msg, type: 'success', duration: 1500 })
        this.onSelectItem({ name: this.nowName })
      })
    },
    dataPermIdChange(){
      this.addLabelGroup()
    },
  }
}
</script>
<style scoped lang="scss">
.newbi-dataset-filter {
  height: 100%;
  .wrapper {
    display: flex;
    height: 100%;
    .left {
      .el-tabs {
        height: 90%;
        .el-tabs__content {
          display: none;
        }
      }
      .add-tab {
        text-align: center;
        margin-right: 9px;
        padding: 13px 0;
      }
    }
    .right {
      flex: 1;
      height: 100%;
      overflow-y: auto;
      .filter-item {
        width: 300px;
        display: flex;
        height: 30px;
        line-height: 30px;
        align-items: center;
        padding: 0 10px;
        margin: 10px;
        border: 1px solid #ccc;
        .title {
          flex: 1;
          &.WEIDU {
            color: #468cff;
          }
          &.ZHIBIAO {
            color: #00c13a;
          }
        }
        .type {
          color: #777;
        }
      }
      .column {
        padding: 0 8px;
        margin: 8px 4px;
        width: 200px;
        height: 26px;
        line-height: 26px;
        font-size: 14px;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        align-items: center;
        &.WEIDU {
          border: 1px solid #468cff;
        }
        &.ZHIBIAO {
          border: 1px solid #00c13a;
        }
        .close {
          color: #f56c6c;
          cursor: pointer;
          margin-left: 5px;
        }
      }
      .el-tabs {
        margin-left: 10px;
      }
      .el-tab-pane {
        height: 93%;
        //overflow-y: auto;
      }
    }
  }
  .btns {
    margin-top: 20px;
    text-align: center;
    .el-button {
      width: 80px;
    }
  }
}
</style>
