<template>
  <div :class="{'node': true, 'node-error-state': showError}">
    <div :class="{'node-body': true, 'error': showError}">
      <div class="node-body-left" @click="emit('leftMove')" v-if="level > 1 && designState">
        <el-icon>
          <ArrowLeftBold/>
        </el-icon>
      </div>
      <div class="node-body-main" @click="emit('selected')">
        <div class="node-body-main-header">
          <ellipsis class="title" hover-tip :content="config.name ? config.name : ('条件' + level)"/>
          <span class="level">优先级{{ level }}</span>
          <span class="option" v-if="designState">
            <el-tooltip effect="dark" content="复制条件" placement="top">
              <el-icon @click.stop="emit('copy')" :size="20">
                <CopyDocument/>
              </el-icon>
            </el-tooltip>
            <el-icon @click.stop="emit('delNode')" :size="20">
                <CloseBold/>
              </el-icon>
          </span>
        </div>
        <div class="node-body-main-content">
          <span class="placeholder" v-if="(content || '').trim() === ''">{{ placeholder }}</span>
          <ellipsis hoverTip :row="4" :content="content" v-else/>
        </div>
      </div>
      <div class="node-body-right" @click="emit('rightMove')" v-if="level < size && designState">
        <el-icon>
          <ArrowRightBold/>
        </el-icon>
      </div>
      <div class="node-error" v-if="showError">
        <el-tooltip effect="dark" :content="errorInfo" placement="top-start">
          <el-icon>
            <Warning/>
          </el-icon>
        </el-tooltip>
      </div>
    </div>
    <div class="node-footer">
      <div class="btn">
        <insert-button v-if="designState" @insertNode="type => emit('insertNode', type)"></insert-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import InsertButton from '../common/InsertButton.vue'
import Ellipsis from '../common/Ellipsis.vue'
import {ValueType} from '@/views/workflow/form/ComponentsConfigExport.js'
import {ArrowRightBold, ArrowLeftBold, CopyDocument, CloseBold, Warning} from '@element-plus/icons-vue'
import {defineProps, defineEmits, defineExpose} from "vue";

const emit = defineEmits()

const props = defineProps({
  config: {
    type: Object,
    default: () => {
      return {}
    }
  },
  //索引位置
  level: {
    type: Number,
    default: 1
  },
  //条件数
  size: {
    type: Number,
    default: 0
  },
  mode: {
    type: String,
    default: 'design'
  }
})

const groupNames = ref(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']);
const placeholder = ref('请设置条件');
const errorInfo = ref('');
const showError = ref(false);
const content = computed(() => {
  const groups = props.config.props.groups
  let confitions = []
  groups.forEach(group => {
    let subConditions = []
    group.conditions.forEach(subCondition => {
      let subConditionStr = ''
      switch (subCondition.valueType) {
        case ValueType.dept:
        case ValueType.user:
          subConditionStr = `${subCondition.title}属于[${String(subCondition.value.map(u => u.name)).replaceAll(',', '. ')}]之一`
          break;
        case ValueType.number:
        case ValueType.string:
          subConditionStr = getOrdinaryConditionContent(subCondition)
          break;
        case ValueType.company:
          subConditionStr = `${subCondition.title}${subCondition.compare}${subCondition.value[1]?subCondition.value[1]:""}`
          break;
      }
      subConditions.push(subConditionStr)
    })
    //根据子条件关系构建描述
    let subConditionsStr = String(subConditions)
        .replaceAll(',', subConditions.length > 1 ?
            (group.groupType === 'AND' ? ') 且 (' : ') 或 (') :
            (group.groupType === 'AND' ? ' 且 ' : ' 或 '))
    confitions.push(subConditions.length > 1 ? `(${subConditionsStr})` : subConditionsStr)
  })
//构建最终描述
  return String(confitions).replaceAll(',', (props.config.props.groupsType === 'AND' ? ' 且 ' : ' 或 '))
})

const designState = computed(() => {
  return props.mode === 'design'
})


const getDefault = (val, df) => {
  return val && val !== '' ? val : df;
}


const getOrdinaryConditionContent = (subCondition) => {
  switch (subCondition.compare) {
    case 'IN':
      return `${subCondition.title}为[${String(subCondition.value).replaceAll(',', '、')}]中之一`
    case 'B':
      return `${subCondition.value[0]} < ${subCondition.title} < ${subCondition.value[1]}`
    case 'AB':
      return `${subCondition.value[0]} ≤ ${subCondition.title} < ${subCondition.value[1]}`
    case 'BA':
      return `${subCondition.value[0]} < ${subCondition.title} ≤ ${subCondition.value[1]}`
    case 'ABA':
      return `${subCondition.value[0]} ≤ ${subCondition.title} ≤ ${subCondition.value[1]}`
    case '<=':
      return `${subCondition.title} ≤ ${getDefault(subCondition.value[0], ' ?')}`
    case '>=':
      return `${subCondition.title} ≥ ${getDefault(subCondition.value[0], ' ?')}`
    default:
      return `${subCondition.title}${subCondition.compare}${getDefault(subCondition.value[0], ' ?')}`
  }
}

//校验数据配置的合法性
const validate = (err) => {
  const defineProps = props.config.props
  if (defineProps.groups.length <= 0) {
    showError.value = true
    errorInfo.value = '请设置分支条件'
    err.push(`${defineProps.config.name} 未设置条件`)
  } else {
    for (let i = 0; i < defineProps.groups.length; i++) {
      if (defineProps.groups[i].cids.length === 0) {
        showError.value = true
        errorInfo.value = `请设置条件组${groupNames.value[i]}内的条件`
        err.push(`条件 ${props.config.name} 条件组${groupNames.value[i]}内未设置条件`)
        break
      } else {
        let conditions = defineProps.groups[i].conditions
        for (let ci = 0; ci < conditions.length; ci++) {
          let subc = conditions[ci]
          showError.value = subc.value.length === 0;
          if (showError.value) {
            errorInfo.value = `请完善条件组${groupNames.value[i]}内的${subc.title}条件`
            err.push(`条件 ${props.config.name} 条件组${groupNames.value[i]}内${subc.title}条件未完善`)
            return false
          }
        }
      }
    }
  }
  return !showError.value
}

defineExpose({
  validate
})
</script>

<style lang="scss" scoped>
.node {
  padding: 30px 55px 0;
  //width: 220px;
  width: 320px;

  .node-body {
    cursor: pointer;
    min-height: 80px;
    max-height: 120px;
    position: relative;
    border-radius: 5px;
    background-color: white;
    box-shadow: 0px 0px 5px 0px #d8d8d8;

    &:hover {
      .node-body-left, .node-body-right {
        i {
          display: block !important;
        }
      }

      .node-body-main {
        .level {
          display: none !important;
        }

        .option {
          display: inline-block !important;
        }
      }

      box-shadow: 0px 0px 3px 0px;
    }

    .node-body-left, .node-body-right {
      display: flex;
      align-items: center;
      position: absolute;
      height: 100%;

      i {
        display: none;
      }

      &:hover {
        background-color: #ececec;
      }
    }

    .node-body-left {
      color: #888888;
      left: 0;
    }

    .node-body-right {
      color: #888888;
      right: 0;
      top: 0;
    }

    .node-body-main {
      //position: absolute;
      width: 188px;
      margin-left: 17px;
      display: inline-block;

      .node-body-main-header {
        padding: 10px 0 5px;
        position: relative;
        font-size: 14px;
        display: flex;
        align-items: center;

        .title {
          width: 125px;
          color: #2E7CF0;
          height: auto;
          display: flex;
          align-items: center;
          .name {
            height: auto;
          }
        }
        .level {
          position: absolute;
          right: 15px;
          color: #888888;
        }

        .option {
          position: absolute;
          right: 10px;
          display: none;
          font-size: medium;

          i {
            color: #888888;
            padding: 0 3px;
          }
        }
      }

      .node-body-main-content {
        padding: 6px;
        color: #656363;
        font-size: 14px;

        i {
          position: absolute;
          top: 55%;
          right: 10px;
          font-size: medium;
        }

        .placeholder {
          color: #8c8c8c;
        }
      }
    }
  }
}
</style>
