<script setup>
import { computed, getCurrentInstance, onMounted, ref, watch } from 'vue'
import $func from '@/plugins/preload'
import useWorkFlowStore from '@/store/modules/workFlow'
const props = defineProps({
  nodeConfig: {
    type: Object,
    default: () => ({}),
  },
  flowPermission: {
    type: Object,
    default: () => {},
  },
})

const emits = defineEmits(['update:flowPermission', 'update:nodeConfig'])

const workFlowStore = useWorkFlowStore()

const _uid = getCurrentInstance().uid
const bgColors = ['87, 106, 149', '255, 148, 62', '50, 150, 250']
const placeholderList = ['发起人', '审核人', '抄送人']
const defaultText = computed(() => {
  return placeholderList[props.nodeConfig.type]
})
const showText = computed(() => {
  console.log('showText')
  if (props.nodeConfig.type == 0) {
    return '发起人'
    // return $func.arrToStr(props.flowPermission) || '所有人'
  }
  if (props.nodeConfig.type == 1) {
    return $func.setApproverStr(props.nodeConfig)
  }
  return $func.copyerStr(props.nodeConfig)
})
watch(() => props.nodeConfig, (val) => {
  console.log('watch nodeConfig')
  if (props.nodeConfig.type == 1) {
    return $func.setApproverStr(props.nodeConfig)
  }
  return $func.copyerStr(props.nodeConfig)
}, {
  deep: true, // 深度监听的参数
})

const isInputList = ref([])
const isInput = ref(false)
const resetConditionNodesErr = () => {
  for (let i = 0; i < props.nodeConfig.conditionNodes.length; i++) {
    props.nodeConfig.conditionNodes[i].error = $func.conditionStr(props.nodeConfig, i) == '请设置条件' && i != props.nodeConfig.conditionNodes.length - 1
  }
}
onMounted(() => {
  if (props.nodeConfig.type == 1) {
    props.nodeConfig.error = !$func.setApproverStr(props.nodeConfig)
  }
  else if (props.nodeConfig.type == 2) {
    props.nodeConfig.error = !$func.copyerStr(props.nodeConfig)
  }
  else if (props.nodeConfig.type == 4) {
    resetConditionNodesErr()
  }
})
// 审批
watch(() => workFlowStore.approverConfig1, (val) => {
  if (val.flag && val.id === _uid) {
    emits('update:nodeConfig', val.value)
  }
})
// 发起人
watch(() => workFlowStore.flowPermission1, (val) => {
  if (val.flag && val.id === _uid) {
    emits('update:flowPermission', val.value)
  }
})
// 条件
watch(() => workFlowStore.conditionsConfig1, (val) => {
  if (val.flag && val.id === _uid) {
    emits('update:nodeConfig', val.value)
  }
})
// 抄送
watch(() => workFlowStore.copyerConfig1, (val) => {
  console.log(val.flag)
  console.log(val.id === _uid, val.id, _uid)
  if (val.flag && val.id === _uid) {
    console.log('监听抄送人')

    emits('update:nodeConfig', val.value)
  }
})
// watch([workFlowStore.flowPermission1, workFlowStore.approverConfig1, workFlowStore.copyerConfig1, workFlowStore.conditionsConfig1], ([flow, approver, copyer, condition]) => {
//   if (flow.flag && flow.id === _uid) {
//     emits('update:flowPermission', flow.value)
//   }
//   if (approver.flag && approver.id === _uid) {
//     emits('update:nodeConfig', approver.value)
//   }
//   if (copyer.flag && copyer.id === _uid) {
//     emits('update:nodeConfig', copyer.value)
//   }
//   if (condition.flag && condition.id === _uid) {
//     emits('update:nodeConfig', condition.value)
//   }
// })

const {
  setPromoter,
  setApprover,
  setCopyer,
  setCondition,
  setFlowPermission,
  setApproverConfig,
  setCopyerConfig,
  setConditionsConfig,
} = workFlowStore
const clickEvent = (index) => {
  if (index || index === 0) {
    isInputList.value[index] = true
  }
  else {
    isInput.value = true
  }
}
const blurEvent = (index) => {
  if (index || index === 0) {
    isInputList.value[index] = false
    props.nodeConfig.conditionNodes[index].nodeName = props.nodeConfig.conditionNodes[index].nodeName || '条件'
  }
  else {
    isInput.value = false
    props.nodeConfig.nodeName = props.nodeConfig.nodeName || defaultText
  }
}
// 删除节点
const delNode = () => {
  emits('update:nodeConfig', props.nodeConfig.childNode)
}
// 添加条件
const addTerm = () => {
  const len = props.nodeConfig.conditionNodes.length + 1
  props.nodeConfig.conditionNodes.push({
    nodeName: `条件${len}`,
    type: 3,
    priorityLevel: len,
    conditionList: [],
    nodeUserList: [],
    childNode: null,
  })
  resetConditionNodesErr()
  emits('update:nodeConfig', props.nodeConfig)
}
const reData = (data, addData) => {
  if (!data.childNode) {
    data.childNode = addData
  }
  else {
    reData(data.childNode, addData)
  }
}
const delTerm = (index) => {
  props.nodeConfig.conditionNodes.splice(index, 1)
  props.nodeConfig.conditionNodes.map((item, index) => {
    item.priorityLevel = index + 1
    item.nodeName = `条件${index + 1}`
  })
  resetConditionNodesErr()
  emits('update:nodeConfig', props.nodeConfig)
  if (props.nodeConfig.conditionNodes.length == 1) {
    if (props.nodeConfig.childNode) {
      if (props.nodeConfig.conditionNodes[0].childNode) {
        reData(props.nodeConfig.conditionNodes[0].childNode, props.nodeConfig.childNode)
      }
      else {
        props.nodeConfig.conditionNodes[0].childNode = props.nodeConfig.childNode
      }
    }
    emits('update:nodeConfig', props.nodeConfig.conditionNodes[0].childNode)
  }
}

const setPerson = (priorityLevel) => {
  const { type } = props.nodeConfig
  if (type == 0) { // 发起人
    // setPromoter(true)
    // setFlowPermission({
    //   value: props.flowPermission,
    //   flag: false,
    //   id: _uid,
    // })
  }
  else if (type == 1) {
    const { approverConfig1, approverDrawer } = workFlowStore
    console.log('0000000000000', approverDrawer)
    setApprover(true)
    setApproverConfig({
      value: {
        ...JSON.parse(JSON.stringify(props.nodeConfig)),
        ...{ settype: props.nodeConfig.settype ? props.nodeConfig.settype : 1 },
      },
      flag: false,
      id: _uid,
    })
  }
  else if (type == 2) {
    setCopyer(true)
    setCopyerConfig({
      value: JSON.parse(JSON.stringify(props.nodeConfig)),
      flag: false,
      id: _uid,
    })
  }
  else {
    setCondition(true)
    setConditionsConfig({
      value: JSON.parse(JSON.stringify(props.nodeConfig)),
      priorityLevel,
      flag: false,
      id: _uid,
    })
  }
}
const arrTransfer = (index, type = 1) => {
  // 向左-1,向右1
  props.nodeConfig.conditionNodes[index] = props.nodeConfig.conditionNodes.splice(
    index + type,
    1,
    props.nodeConfig.conditionNodes[index],
  )[0]
  props.nodeConfig.conditionNodes.map((item, index) => {
    item.priorityLevel = index + 1
  })
  resetConditionNodesErr()
  emits('update:nodeConfig', props.nodeConfig)
}
</script>

<template>
  <div v-if="nodeConfig.type < 3" class="node-wrap">
    <div class="node-wrap-box" :class="(nodeConfig.type === 0 ? 'start-node ' : '') + (workFlowStore.isTried && nodeConfig.error ? 'active error' : '')">
      <div class="title" :style="`background: rgb(${bgColors[nodeConfig.type]});`">
        <span v-if="nodeConfig.type === 0">{{ nodeConfig.nodeName }}</span>
        <template v-else>
          <span class="iconfont">{{ nodeConfig.type === 1 ? '' : '' }}</span>
          <input
            v-if="isInput"
            v-model="nodeConfig.nodeName"
            v-focus
            type="text"
            class="ant-input editable-title-input"
            :placeholder="defaultText"
            @blur="blurEvent()"
            @focus="$event.currentTarget.select()"
          >
          <span v-else class="editable-title" @click="clickEvent()">{{ nodeConfig.nodeName }}</span>
          <i class="anticon anticon-close close" @click="delNode" />
        </template>
      </div>
      <div class="content" @click="setPerson">
        <div class="text">
          <span v-if="!showText" class="placeholder">请选择{{ defaultText }}</span>
          {{ showText }}
        </div>
        <i v-if="props.nodeConfig.type !== 0" class="anticon anticon-right arrow" />
      </div>
      <div v-if="workFlowStore.isTried && nodeConfig.error" class="error_tip">
        <i class="anticon anticon-exclamation-circle" />
      </div>
    </div>
    <add-node v-model:childNodeP="nodeConfig.childNode" />
  </div>
  <div v-if="nodeConfig.type === 4" class="branch-wrap">
    <div class="branch-box-wrap">
      <div class="branch-box">
        <button class="add-branch" @click="addTerm">
          添加条件
        </button>
        <div v-for="(item, index) in nodeConfig.conditionNodes" :key="index" class="col-box">
          <div class="condition-node">
            <div class="condition-node-box">
              <div class="auto-judge" :class="workFlowStore.isTried && item.error ? 'error active' : ''">
                <div v-if="index !== 0" class="sort-left" @click="arrTransfer(index, -1)">
                  &lt;
                </div>
                <div class="title-wrapper">
                  <input
                    v-if="isInputList[index]"
                    v-model="item.nodeName"
                    v-focus
                    type="text"
                    class="ant-input editable-title-input"
                    @blur="blurEvent(index)"
                    @focus="$event.currentTarget.select()"
                  >
                  <span v-else class="editable-title" @click="clickEvent(index)">{{ item.nodeName }}</span>
                  <span class="priority-title" @click="setPerson(item.priorityLevel)">优先级{{ item.priorityLevel }}</span>
                  <i class="anticon anticon-close close" @click="delTerm(index)" />
                </div>
                <div v-if="index !== nodeConfig.conditionNodes.length - 1" class="sort-right" @click="arrTransfer(index)">
                  &gt;
                </div>
                <div class="content" @click="setPerson(item.priorityLevel)">
                  {{ $func.conditionStr(nodeConfig, index) }}
                </div>
                <div v-if="workFlowStore.isTried && item.error" class="error_tip">
                  <i class="anticon anticon-exclamation-circle" />
                </div>
              </div>
              <add-node v-model:childNodeP="item.childNode" />
            </div>
          </div>
          <node-wrap v-if="item.childNode" v-model:nodeConfig="item.childNode" />
          <template v-if="index === 0">
            <div class="top-left-cover-line" />
            <div class="bottom-left-cover-line" />
          </template>
          <template v-if="index === nodeConfig.conditionNodes.length - 1">
            <div class="top-right-cover-line" />
            <div class="bottom-right-cover-line" />
          </template>
        </div>
      </div>
      <add-node v-model:childNodeP="nodeConfig.childNode" />
    </div>
  </div>
  <node-wrap v-if="nodeConfig.childNode" v-model:nodeConfig="nodeConfig.childNode" />
</template>

<style>
.error_tip {
  position: absolute;
  top: 0;
  right: 0;
  transform: translate(150%, 0);
  font-size: 24px;
}

.promoter_person .el-dialog__body {
  padding: 10px 20px 14px;
}

.selected_list {
  margin-bottom: 20px;
  line-height: 30px;
}

.selected_list span {
  margin-right: 10px;
  padding: 3px 6px 3px 9px;
  line-height: 12px;
  white-space: nowrap;
  border-radius: 2px;
  border: 1px solid rgb(220 220 220 / 100%);
}

.selected_list img {
  margin-left: 5px;
  width: 7px;
  height: 7px;
  cursor: pointer;
}
</style>
