<template>
  <common-drawer :mask="true" :mask-closable="true" :width="900" :visible="true" @close="close">
    <template #title>
      <template v-if="titleEdit">
        <a-input
          v-focus
          type="text"
          v-model:value="title"
          @blur="editTitle"
          @keydown.enter="editTitle"
          autofocus="autofocus"
          ref="titleInputRef"
        />
      </template>
      <template v-if="!titleEdit">
        <span style="cursor: pointer" @click="titleClick">{{ title }}</span>
        <span style="padding-left: 5px; cursor: pointer" @click="titleClick"><edit-outlined /></span>
      </template>
    </template>

    <template #footer>
      <a-button type="primary" @click="save" class="border-radius">确定</a-button>
    </template>
    <div v-if="formData?.bpmnConfig && nodeData.type == 248">
      <span class="flow-drawer-sub-title"> 基础数据</span>
    </div>
    <a-form
      ref="formRef"
      labelAlign="right"
      style="margin-top: 10px"
      v-if="formData && formData?.bpmnConfig && nodeData.type == 248"
      :model="formData.bpmnConfig"
      :label-col="{ span: 3 }"
      :wrapper-col="{ span: 16 }"
      autocomplete="off"
    >
      <a-form-item name="bpmnNodeId" label="bpmn节点id">
        <a-input v-model:value="formData.bpmnConfig.bpmnNodeId" placeholder="请输入bpmn节点id" />
      </a-form-item>
      <a-form-item name="remark" label="注释">
        <a-textarea v-model:value="formData.bpmnConfig.remark" placeholder="请输入" :rows="8" />
      </a-form-item>
    </a-form>
    <div>
      <span class="flow-drawer-sub-title"> 表达式</span>
    </div>
    <div class="flow-condition-box" v-if="formData">
      <div class="flow-condition-list">
        <a-space>
          <!-- 属性 -->
          <FlowBranchSelect
            v-model="condition.attribute"
            style="width: 150px"
            placeholder="插入属性"
            size="default"
            :conditionSelectList="conditionSelectList"
            @change="handleChange($event, condition)"
          />
          <!-- 运算符 -->
          <FlowSimpleSelect
            v-model="condition.operator"
            :datas="operatorTypes"
            placeholder="选择运算符"
            labelName="label"
            size="default"
            style="width: 150px"
            valueName="code"
            @change="value => valueChange(value, 'operator')"
          />
          <!-- 比较(操作)符 -->
          <FlowSimpleSelect
            v-model="condition.compare"
            :datas="optTypes"
            size="default"
            placeholder="选择比较符"
            labelName="label"
            style="width: 150px"
            valueName="code"
            @change="value => valueChange(value, 'compare')"
          />
          <!-- 选择业务值 -->
          <FlowSimpleSelect
            v-model="condition.business"
            :datas="businessList"
            size="default"
            placeholder="选择业务值"
            labelName="label"
            style="width: 150px"
            valueName="code"
            @change="commonFocus"
          />
          <a-button class="border-radius green" @click="valueChange('&&')">并且</a-button>
          <a-button class="border-radius green" @click="valueChange('||')">或者</a-button>
        </a-space>
      </div>
      <a-textarea
        v-model:value="formData.nodeCondition.expressionString"
        id="textareaId"
        ref="expressionStringRef"
        placeholder="请输入"
        :rows="12"
        @blur="expressionStringClick"
      />
      <div style="margin-top: 10px">
        提示：<br />
        1. 如果参与比对的表达式值为业务id，则必须用单引号括起来，例如：'部门id'<br />
        2. 如果参与比对的表达式值为日期格式，并且也使用单引号括起来，日期格式为：'yyyy-MM-dd HH:mm:ss'，例如：'2023-11-15 16:46:55'<br />
      </div>
      <!-- 错误信息 -->
      <div style="margin-top: 10px; color: red; margin-bottom: 10px">{{ errorMessage }}</div>
    </div>

    <!-- 选择组件 -->
    <Selection
      v-model:visible="visibleFlowPick"
      v-if="visibleFlowPick"
      :data="selectedData"
      :showTab="showTab"
      :changeHeight="true"
      @done="closeFlowPick"
    ></Selection>
  </common-drawer>
</template>

<script setup name="ConditionGatewayEventPanel">
import { onMounted, inject, ref, nextTick } from 'vue';
import { FlowDesignApi } from '../../../../mid/workflow/design/api/FlowDesignApi';
import loadApproverData from './data/load-approver-data';
import loadNodeData from '../../../utils/utils';
import FlowSimpleSelect from './common/FlowSimpleSelect.vue';
import FlowBranchSelect from './common/FlowBranchSelect.vue';

const emits = defineEmits(['close']);
// 数据
const { optTypes, operatorTypes, businessList } = loadApproverData();
// 公共方法
const { getNodeData, setNodeData, node } = loadNodeData();

const definitionId = inject('definitionId');

// 节点数据
const nodeData = ref({});

// 条件官网数据
const condition = ref({
  attribute: null,
  compare: null,
  operator: null,
  business: null
});

// 选择弹框是否显示
const visibleFlowPick = ref(false);
// 总的数据
const selectedData = ref({});
// 显示的tab栏
const showTab = ref(['user']);
// 基础类型
const baseType = ref('');
// 标题
const title = ref('');
// 标题输入框dom
const titleInputRef = ref(null);
// 是否编辑标题
const titleEdit = ref(false);

// 文本光标位置
const selectionStart = ref(0);
// 条件选择列表
const conditionSelectList = ref([]);

// ref
const expressionStringRef = ref();

// 错误信息
const errorMessage = ref('');

// 当前节点的数据
const currentNodeData = ref(getNodeData());

// 条件数据
const formData = ref(null);

/**
 * 修改标题
 */
const editTitle = () => {
  let getGraphNodeData = getNodeData();
  getGraphNodeData.data.nodeName = title.value;

  setNodeData(getGraphNodeData);

  // 关闭标题编辑框
  titleEdit.value = false;
};

// 标题点击
const titleClick = () => {
  titleEdit.value = true;
};

onMounted(() => {
  getSeletList();
  nodeData.value = JSON.parse(node.value.data);

  // 设置弹窗标题
  title.value = nodeData.value.data.nodeName;

  if (JSON.stringify(currentNodeData.value?.data?.nodeData) != '{}') {
    formData.value = Object.assign({}, currentNodeData.value.data.nodeData);
    selectionStart.value = formData.value.nodeCondition.expressionString.length ?? 0;
  }
});

// 获取可选择列表
const getSeletList = () => {
  FlowDesignApi.getConditionSelectList({ definitionId: definitionId.value }).then(res => {
    if (res.data) {
      conditionSelectList.value = res.data;
    }
  });
};

// 属性选择
const handleChange = (e, value) => {
  nextTick(() => {
    let text = formData.value.nodeCondition.expressionString ? ' #' + e + ' ' : '#' + e + ' ';
    setExpressionStringValue(text);
    condition.value.attribute = null;
  });
};

// 值改变
const valueChange = (value, valueName = '') => {
  nextTick(() => {
    let text = '';
    if (value == 'contain') {
      text = '.' + value + '()';
      setExpressionStringValue(text, true);
    } else {
      text = formData.value.nodeCondition.expressionString ? ' ' + value + ' ' : value + ' ';
      setExpressionStringValue(text);
    }
    if (valueName) {
      condition.value[valueName] = null;
    }
  });
};

// 设置插入的值
const setExpressionStringValue = (text, flag = false) => {
  if (flag) {
    if (formData.value.nodeCondition.expressionString.slice(0, selectionStart.value).replace(/(^\s*)|(\s*$)/g, '')) {
      selectionStart.value--;
    }
    formData.value.nodeCondition.expressionString =
      formData.value.nodeCondition.expressionString.slice(0, selectionStart.value).replace(/(^\s*)|(\s*$)/g, '') +
      text +
      formData.value.nodeCondition.expressionString.slice(selectionStart.value);
    selectionStart.value += 9;
  } else {
    formData.value.nodeCondition.expressionString =
      formData.value.nodeCondition.expressionString.slice(0, selectionStart.value) +
      text +
      formData.value.nodeCondition.expressionString.slice(selectionStart.value);
    selectionStart.value += text.length ?? 0;
  }
  setTextareaFocus();
};

// 设置文本选中
const setTextareaFocus = () => {
  expressionStringRef.value.focus();
  const textareaId = document.getElementById('textareaId');
  setTimeout(() => {
    textareaId.setSelectionRange(selectionStart.value, selectionStart.value);
  }, 10);
};

// 点击显示选择弹框
const commonFocus = type => {
  nextTick(() => {
    baseType.value = type;
    showTab.value = [type];
    if (type == 'user') {
      setValue('selectUserList');
    } else if (type == 'dept') {
      // 部门
      setValue('selectOrgList');
    } else if (type == 'role') {
      // 角色
      setValue('selectRoleList');
    } else if (type == 'position') {
      // 岗位
      setValue('selectPositionList');
    }
    condition.value.business = null;
    visibleFlowPick.value = true;
  });
};

// 关闭流程选择弹框
const closeFlowPick = value => {
  if (baseType.value == 'user') {
    setSaveData(value, 'selectUserList');
  } else if (baseType.value == 'dept') {
    setSaveData(value, 'selectOrgList');
  } else if (baseType.value == 'role') {
    setSaveData(value, 'selectRoleList');
  } else if (baseType.value == 'position') {
    setSaveData(value, 'selectPositionList');
  }
};
// 设置保存的值
const setSaveData = (value, listName) => {
  if (value[listName] && value[listName].length > 0) {
    let text = formData.value.nodeCondition.expressionString
      ? " '" + value[listName][0].bizId + "' "
      : "'" + value[listName][0].bizId + "' ";
    setExpressionStringValue(text);
  }
};

// 设置选中的值
const setValue = listName => {
  selectedData.value[listName] = [];
};

/**
 * 关闭
 */
const close = () => {
  emits('close', false);
};

// 获取文本光标位置
const expressionStringClick = e => {
  selectionStart.value = e.srcElement.selectionStart;
};

// 点击保存
const save = () => {
  FlowDesignApi.validateExpression({ expressionString: formData.value.nodeCondition.expressionString })
    .then(res => {
      if (res.success) {
        let saveData = getNodeData();
        saveData.data.nodeData = formData.value;
        setNodeData(saveData);
        close();
      } else {
        errorMessage.value = res.message;
      }
    })
    .catch(e => {
      errorMessage.value = e.message;
    });
};
</script>

<style scoped lang="less">
// 条件
.flow-condition-box {
  height: 95%;
  overflow-y: auto;
  margin-top: 10px;
  .flow-condition-group {
    padding-bottom: 10px;

    .flow-condition-item {
      border-radius: 3px;
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-pack: start;
      -ms-flex-pack: start;
      justify-content: flex-start;
      padding: 10px 0px 5px;

      .flow-condition-option {
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -ms-flex-pack: distribute;
        justify-content: space-around;
        width: 100%;
      }

      .flow-condition-value {
        width: 74%;
        color: #c0c4cc;
        font-size: 13px;
        height: 40px;
        line-height: 40px;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        border-radius: 5px;
      }

      .flow-condition-del {
        width: 38px;
        height: 38px;
        background-color: #fff;
        border-radius: 3px;
        border: 1px solid #dee0e3;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-align: center;
        -ms-flex-align: center;
        align-items: center;
        -webkit-box-pack: center;
        -ms-flex-pack: center;
        justify-content: center;
        color: #a3a8af;
        font-size: 16px;
        cursor: pointer;
        -webkit-box-flex: 0;
        -ms-flex: 0 0 auto;
        flex: 0 0 auto;

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

  .flow-condition-group-connector {
    margin-top: 15px;
    color: rgb(142, 142, 142);
    font-size: 14px;
  }

  .flow-condition-add {
    width: 100px;
    height: 34px;
    background-color: #fff;
    border-radius: 3px;
    border: 1px solid #dee0e3;
    color: #8e8e8e;
    text-align: center;
    font-size: 13px;
    cursor: pointer;
    line-height: 34px;
    margin-top: 15px;
    margin-right: 13px;

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

.flow-condition-list {
  display: flex;
  width: 100%;
  margin-bottom: 15px;
}
:deep(.ant-drawer-body) {
  padding: 15px;
}
.flow-drawer-sub-title {
  border-left: 3px solid var(--primary-color);
  padding-left: 6px;
  font-weight: 700;
}
:deep(.ant-select-selection-placeholder) {
  color: black;
}
:deep(.ant-select-selector:hover) {
  .ant-select-selection-placeholder {
    color: var(--primary-color);
  }
}
:deep(.ant-select-selector) {
  border-radius: 5px !important;
}
</style>
