<template>
  <div class="main">
    <p class="common-title">基础信息</p>
    <el-divider></el-divider>
    <el-form ref="baseForm" :model="baseForm" :rules="baseFormRules" label-position="top">
      <el-row class="baseForm">
        <el-col :span="6">
          <el-form-item label="新建客群名称" prop="groupName">
            <el-input v-model="baseForm.groupName" placeholder="新建客群名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="关联客群" prop="groupId">
            <el-select v-model="baseForm.groupId" placeholder="请选已有分群" allow-create clearable filterable
              @change="handleGroupName">
              <el-option v-for="item in groupNameList" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="分群类型" prop="custType">
            <el-select v-model="baseForm.custType" placeholder="请选分群名称" allow-create clearable filterable>
              <el-option v-for="item in fqtypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="描述" prop="description">
            <el-input v-model="baseForm.description" placeholder="请输入分群描述，应用场景" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <p class="common-title">分群规则</p>
    <el-divider></el-divider>
    <div class="ruleBox" v-for="(item, index) in ruleConditionsList" :key="index">
      <div class="ruleBox_left">
        <div v-if="index == 0">满足条件</div>
      </div>
      <div class="ruleBox_line_box">
        <div class="ruleBox_line_left">
          <span v-if="index > 0" @click="handleRelation(item)" class="relation">{{ item.relation }}</span>
        </div>
        <div class="ruleBox_line"></div>
      </div>
      <div class="ruleBox_right">
        <div class="ruleBtnBox" v-if="index == ruleConditionsList.length - 1">
          <el-button round v-for="(el, i) in typeList" :key="i" @click="handleAddRule(el, item)"
            :disabled="ruleConditionsList.length > 3">{{ el }}</el-button>
        </div>
        <div class="ruleTitle" v-if="ruleConditionsList.length == 1">请选择任意条件开始创建一个分群</div>
        <div class="ruleSelectBox" v-if="index != ruleConditionsList.length - 1">
          <div class="ruleSelect_top">
            <div class="ruleSelect_left">-</div>
            <div class="ruleSelect_right">{{ item.selectTitle }}</div>
            <div class="ruleSelect_right_icon"><i class="el-icon-close" @click="handleDeleteRule(index)"></i></div>
          </div>
          <div class="ruleSelect_main">
            <div class="line_box" v-if="item.ruleList.length > 1">
              <div class="ruleSelect_main_left"></div>
              <div class="line_text" @click="handleRelationItem(item)">{{ item.relationItem }}</div>
              <div class="ruleSelect_main_left"></div>
            </div>

            <div class="ruleSelect_main_right">
              <el-row class="ruleSelect_main_right_item" v-for="(v, vi) in item.ruleList" :key="vi">
                <el-col :span="5">
                  <el-select filterable v-model="v.leftValue" @change="handleChange(vi, index, item.selectTitle)"
                    @focus="handleFocusLeft(v.leftValue, vi, index, item.selectTitle)">
                    <el-option v-for="item in rowLeftList" :key="item.value" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="5">
                  <el-select filterable v-model="v.expression" @focus="handleFocusExpress(item.selectTitle)">
                    <el-option v-for="item in expressionList" :key="item.value" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="4">
                  <el-select filterable v-model="v.rightValue" v-if="v.isShow == 'select'"
                    @focus="handleFocusRight(v.leftValue)">
                    <el-option v-for="item in rowRightList" :key="item.value" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                  <el-input :span="4" filterable v-model="v.rightValue" v-if="v.isShow == 'input'"></el-input>
                </el-col>
                <el-col :span="3" class="addIcon">
                  <!-- <i class="el-icon-plus ruleIcon" @click="handleAddRules(index)"
                    v-if="vi == item.ruleList.length - 1 && item.ruleList.length < 3"></i>
                  <i class="el-icon-close ruleIcon" @click="handleDeleteRules(index, vi)"
                    v-if="item.ruleList.length > 1"></i> -->
                    <el-button type="text" 
                        icon="el-icon-remove-outline"
                        @click="handleDeleteRules(index, vi)"
                        class="gray-color" v-if="item.ruleList.length > 1"></el-button>
                    <el-button type="text" 
                        icon="el-icon-circle-plus-outline" 
                        class="gray-color" 
                        @click="handleAddRules(index)"
                        v-if="vi == item.ruleList.length - 1 && item.ruleList.length < 3"
                        ></el-button>
                </el-col>
              </el-row>
            </div>

          </div>
        </div>
      </div>
    </div>
    <p class="common-title">更新方式</p>
    <el-divider></el-divider>
    <el-radio-group v-model="updateType">
      <el-radio :label="0">自动更新</el-radio>
      <el-radio :label="1">手动更新</el-radio>
    </el-radio-group>
    <div class="updateType_box" v-if="updateType == '0'">
      <div style="margin-right: 15px;">每</div>
      <div>
        <!-- <el-time-picker v-model="updateTypeRelateTime"></el-time-picker> -->
        <el-select filterable v-model="updateTypeRelateTime">
          <el-option v-for="item in dateList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </div>
      <div style="margin-left: 15px;">自动更新</div>
    </div>
    <el-divider></el-divider>
    <div class="footer">
      <el-button type="primary" @click="handleCommit">创建</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
    <el-dialog title="考核指标" :visible.sync="groupNameVisible" width="300px" append-to-body :close-on-click-modal="false"
      :show-close='false'>
      <el-input type="textarea" v-model="diaGroupName"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleGroupNameCommit">确定</el-button>
        <el-button @click="handleGroupNameCancle">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { tabDetail, listTab, createGroupByRule } from "@/api/system/createRuler.js";
import { getGroupList } from '@/api/task/taskList.js'
import { Message } from "element-ui";
export default {
  data() {
    return {
      groupNameVisible: false,
      diaGroupName: '',
      baseForm: {
        groupId: '',
        groupName: '',
        custType: '',
        description: ''
      },
      groupNameList: [

      ],
      fqtypeList: [
        { label: '个人', value: '0' },
        { label: '商户', value: '1' },
        { label: '企业', value: '2' },
      ],
      baseFormRules: {
        groupName: [{ required: true, message: "新建客群名称不能为空", trigger: 'blur' }],
        custType: [{ required: true, message: "请选择类型", trigger: 'change' }]
      },
      ruleConditionsList: [{ selectTitle: '属性指标', relation: '且', num: 0, relationItem: '且', itemNum: 0, ruleList: [{ leftValue: '', expression: '', rightValue: '' }] }],
      typeList: ['属性指标', '统计指标'],
      rowLeftList: [

      ],
      expressionList: [

        { label: '=', value: '3' },
        { label: '!=', value: '6' },
      ],
      rowRightList: [

      ],
      updateType: '',
      updateTypeRelateTime: '',

      tabType: '',
      tabName: '',
      dateList: [
        { label: '天', value: '1' },
        { label: '周', value: '2' },
        { label: '月', value: '3' },
        { label: '年', value: '4' },
      ]
    }
  },
  created() {
    this.initGroupList()
  },
  methods: {
    // 取消返回列表页
    handleClose(){
      this.$router.push({ path: '/grid/create/segmentation' })
    },
    handleFocusLeft(val, vi, index, title) {
      if (title == '属性指标') {
        const params = {
          custType: this.baseForm.custType,
          tabThresholdType: '3',

        }
        listTab(params).then(res => {
          console.log(res, 'ssssssssss')
          this.rowLeftList = res.data.map(item => {
            return {
              label: item.tabName,
              value: item.tabId,
              id: item.id
            }
          })
        })
      } else if (title == '统计指标') {
        const params = {
          custType: this.baseForm.custType,
          tabThresholdType: '1',

        }
        listTab(params).then(res => {
          this.rowLeftList = res.data.map(item => {
            return {
              label: item.tabName,
              value: item.tabId,
              id: item.id
            }
          })
        })
      }
    },
    handleFocusExpress(title) {
      if (title == '属性指标') {
        this.expressionList = [
          { label: '=', value: '3' },
          { label: '!=', value: '6' },
        ]
      } else if (title == '统计指标') {
        this.expressionList = [
          { label: '>', value: '1' },
          { label: '>=', value: '2' },
          { label: '=', value: '3' },
          { label: '<=', value: '4' },
          { label: '<', value: '5' },
          { label: '!=', value: '6' },
        ]
      }
    },
    handleFocusRight(val) {
      let arr = this.rowLeftList.filter(item => item.value == val)
      let id = arr ? arr[0].id : ''
      tabDetail(id).then(res => {
        if (res.code == 200) {
          this.rowRightList = res.data.tabEnums.map(item => {
            return {
              label: item.tabName,
              value: item.tabName,
            }
          })
        }

      })
    },
    handleChange(vi, index, title) {
      if (title == '属性指标') {
        this.ruleConditionsList[index].ruleList[vi].isShow = 'select'
      } else if (title == '统计指标') {
        this.ruleConditionsList[index].ruleList[vi].isShow = 'input'
      }
    },

    initGroupList() {
      const params = {
        groupType: '1'
      }
      getGroupList(params).then(res => {
        this.groupNameList = res.map(item => {
          return {
            label: item.groupName,
            value: item.groupId,
            custType: item.custType
          }
        })
      })
    },
    handleGroupName(val) {
      let arr = this.groupNameList.filter(item => item.value == val)
      this.baseForm.custType = arr[0].custType
    },
    handleGroupNameCommit() {
      this.baseForm.groupName = this.diaGroupName
      this.groupNameVisible = false
    },
    handleGroupNameCancle() {
      this.baseForm.groupName = ''
      this.diaGroupName = ''
      this.groupNameVisible = false
    },
    handleAddRule(el, item) {
      if (el == '属性指标') {
        this.ruleConditionsList.push({ selectTitle: el, relation: '且', num: 0, relationItem: '或', itemNum: 0, ruleList: [{ leftValue: '', expression: '', rightValue: '', isShow: '' }] })
      } else if (el == '统计指标') {
        this.ruleConditionsList.push({ selectTitle: el, relation: '且', num: 0, relationItem: '或', itemNum: 0, ruleList: [{ leftValue: '', expression: '', rightValue: '', isShow: '' }] })
      }
      item.selectTitle = el
    },
    handleDeleteRule(index) {
      this.ruleConditionsList.splice(index, 1)
    },
    handleRelation(item) {
      item.num++
      if (item.num % 2 === 0) {
        this.$set(item, 'relation', '且')
      } else {
        this.$set(item, 'relation', '或')
      }
    },
    handleRelationItem(item) {
      item.itemNum++
      if (item.itemNum % 2 === 0) {
        this.$set(item, 'relationItem', '且')
      } else {
        this.$set(item, 'relationItem', '或')
      }
    },
    handleAddRules(index) {
      this.ruleConditionsList[index].ruleList.push({ leftValue: '', expression: '', rightValue: '' })
    },
    handleDeleteRules(index, vi) {
      this.ruleConditionsList[index].ruleList.splice(vi, 1)
    },
    initPotRelation(arr) {
      let strList = []

      let data = arr.map(item => { return item.ruleList })
      let relationList = arr.map(item => {
        if (item.relation == '且') {
          return 'and'
        } else {
          return 'or'
        }
      })
      let relationItemList = arr.map(item => {
        if (item.relationItem == '且') {
          return 'and'
        } else {
          return 'or'
        }
      })
      data.pop()
      for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < data[i].length; j++) {
          strList.push(data[i][j].leftValue)

        }
      }
      relationList.shift()
      relationItemList.pop()
      console.log(relationList, 'relationList')
      console.log(relationItemList, 'relationItemList')
      let one1 = []
      let one2 = []
      let one3 = []

      if (data[0] && data[0].length > 0) {
        one1 = strList.slice(0, data[0].length);
      }
      if ((data[0] && data[0].length > 0) && (data[1] && data[1].length > 0)) {
        one2 = strList.slice(data[0].length, data[0].length + data[1].length);
      }
      if ((data[0] && data[0].length > 0) && (data[1] && data[1].length > 0) && (data[2] && data[2].length > 0)) {
        one3 = strList.slice(data[0].length + data[1].length, data[0].length + data[1].length + data[2].length);
      }

      let str1 = ''
      let str2 = ''
      let str3 = ''
      for (let i = 0; i < one1.length; i++) {
        str1 += `[${one1[i]}]` + relationItemList[0]
      }
      if (one2.length > 0) {
        for (let i = 0; i < one2.length; i++) {
          str2 += `[${one2[i]}]` + relationItemList[1]
        }
      }
      if (one3.length > 0) {
        for (let i = 0; i < one3.length; i++) {
          str3 += `[${one3[i]}]` + relationItemList[2]
        }
      }
      let strOne = []
      let strTwo = []
      let strTree = []
      if (str1[str1.length - 1] == 'd') {

        strOne = str1.slice(0, -3)
      } else {
        strOne = str1.slice(0, -2)
      }
      if (str2[str2.length - 1] == 'd') {

        strTwo = str2.slice(0, -3)
      } else {
        strTwo = str2.slice(0, -2)
      }
      if (str3[str3.length - 1] == 'd') {

        strTree = str3.slice(0, -3)
      } else {
        strTree = str3.slice(0, -2)
      }
      if (strOne.length > 0 && strTwo.length == 0) {
        return `(${strOne})`
      }
      if (strOne.length > 0 && strTwo.length > 0 && strTree.length == 0) {
        return `(${strOne})${relationList[0]}(${strTwo})`
      }
      if (strOne.length > 0 && strTwo.length > 0 && strTree.length > 0) {
        return `(${strOne})${relationList[0]}(${strTwo})${relationList[1]}(${strTree})`
      }


    },
    handleCommit() {
      this.$refs.baseForm.validate((valid) => {
        if (valid) {
          let arr = this.ruleConditionsList.map(item => {
            return {
              ruleList: item.ruleList,
              relation: item.relation,
              relationItem: item.relationItem,
            }
          })
          
          console.log(arr, 'arr')
          let arr1=arr.map(item=>{return item.ruleList})
          let list = (arr1.flat()).filter((el) => el.leftValue != '')
          let list1 = list.map(item => {
            return {
              potId: item.leftValue,
              tabThresholdType: '3',
              enumVal: item.rightValue,
              isUnEquals:item.expression == '6'?'1':'0'
            }
          })
          console.log(list1, 'list1')
          let str = this.initPotRelation(arr)
          const tabPotAddDTO = {
            potDetails: list1,
            potRelation: str,
            tabName: ''
          }
          const params = {
            groupName: this.baseForm.groupName,
            relateGroupId: this.baseForm.groupId,
            custType: this.baseForm.custType,
            description: this.baseForm.description,
            updateType: this.updateType,
            updateTypeRelateTime: this.updateTypeRelateTime,
            tabPotAddDTO: tabPotAddDTO
          }
          console.log(params, 'params')
          if(params.tabPotAddDTO.potDetails.length<1){
            Message.warning('请至少选择一个指标')
          }else{
            createGroupByRule(params).then(res => {
            if (res.code == 200) {
              Message.success('创建成功')
              this.$router.push({ path: '/grid/create/segmentation' })
            }
          })
          }
        
          
        } else { return false }
      })

    },
  },
}
</script>
<style lang="scss" scoped>
.main {
  background-color: #ffffff;
  overflow: hidden;
  box-shadow: 0 3px 8px 0 #00000017;
  border-radius: 16px 16px 0 0;
  padding: 10px 15px;
}

.common-title {
  position: relative;
  color: #222222;
  line-height: 16px;
  font-weight: 600;
  font-size: 16px;
  padding-left: 10px;
  margin-top: 10px;

  &::before {
    position: absolute;
    top: 50%;
    transform: translatey(-50%);
    left: 0;
    content: '';
    width: 3px;
    background-color: #4886f8;
    height: 16px;
    border-radius: 2px;
  }
}

.baseForm {
  ::v-deep .el-select {
    width: 300px;
  }

  ::v-deep .el-input {
    width: 300px;
  }
}

.ruleBox {
  display: flex;
  margin-top: 15px;
}

.ruleBox_left {
  padding-top: 10px;
  width: 80px;
  text-align: right;
}

.ruleBox_line_box {
  display: flex;
}

.ruleBox_line {
  width: 3px;
  margin-left: 20px;
  background-color: #ccc;
}

.ruleBox_line_left {
  width: 16px;
  color: rgb(64, 149, 229);
}

.relation {
  cursor: pointer;

}

.ruleBox_right {
  padding-left: 30px;
  width: 100%;
  padding-bottom: 30px;
}

.ruleSelect_top:hover .ruleSelect_right_icon {
  display: block;
}

.ruleSelect_right_icon {
  margin-left: 15px;
  cursor: pointer;
  display: none;
}

.ruleTitle {
  margin-top: 20px;
  font-size: 14px;
  color: #ccc;
}

.ruleSelect_top {
  display: flex;
  padding-left: 10px;
  align-items: center;
}

.ruleSelect_left {
  width: 15px;
  height: 15px;
  text-align: center;
  line-height: 13px;
  background-color: rgb(64, 149, 229);
  color: #fff;
}

.ruleSelect_right {
  margin-left: 15px;
}

.ruleSelect_main {
  margin-top: 15px;
  display: flex;
}

.line_box {
  display: flex;
  width: 15px;
  flex-direction: column;
}

.line_text {

  margin: 5px 0 5px 6px;
  color: rgb(64, 149, 229);
  cursor: pointer;
  width: 22px;
  height: 22px;
  text-align: center;
  line-height: 21px;
  border: 1px solid #ccc;
  border-radius: 50%;
}

.ruleSelect_main_left {
  width: 3px;
  margin-left: 15px;
  height: 100%;
  background-color: #ccc;
}

.ruleSelect_main_right {
  width: 100%;
  margin-left: 23px;
}

.addIcon {
   line-height: 40px;
    margin-left: 15px;
     ::v-deep .el-icon-circle-plus-outline {
      color: #4886f8;
      font-size: 20px;
    }

    ::v-deep .el-icon-remove-outline {
      font-size: 20px;
    }

    ::v-deep .gray-color {
      color: #999999;
    }
}

.ruleSelect_main_right_item:hover .addIcon {
  display: block;
}

::v-deep .el-date-editor {
  width: 120px;
}

.ruleSelect_main_right_item {
  height: 40px;
  margin-top: 10px;
}

.ruleIcon {
  font-size: 16px;
  cursor: pointer;
}

.updateType_box {
  display: flex;
  margin-top: 30px;
  align-items: center;

  ::v-deep .el-select {
    width: 100px;
    margin: 0 10px;
  }
}

.footer {
  margin-bottom: 30px;
  text-align: center;
}
</style>