<template>
  <div class="property-panel" ref="propertyPanel">
    <el-form :inline="true" :model="form" label-width="100px" size="small">
      <el-form-item :label="`${isRoot?'流程ID':'节点ID'}`">
        <el-input v-model="form.id" disabled></el-input>
      </el-form-item>
      <el-form-item :label="`${isRoot?'流程名称':'节点名称'}`">
        <el-input v-model="form.name" @input="nameChange"></el-input>
      </el-form-item>
      <!-- <el-form-item label="节点颜色">
        <el-color-picker v-model="form.color" @active-change="colorChange"></el-color-picker>
      </el-form-item> -->
      <!-- 任务节点允许选择人员 -->
      <el-form-item label="节点人员" v-if="userTask">
        <el-select v-model="form.userType" placeholder="请选择" @change="typeChange">
          <el-option value="camunda:assignee" label="指定人员"></el-option>
          <el-option value="camunda:candidateUsers" label="候选人员"></el-option>
          <el-option value="camunda:candidateGroups" label="候选组"></el-option>
        </el-select>
      </el-form-item>
      <!-- 指定人员 -->
      <el-form-item label="指定人员" v-if="userTask && form.userType === 'camunda:assignee'">
        <el-select
          v-model="form['camunda:assignee']"
          placeholder="请选择"
          key="1"
          @change="(value) => addUser({'camunda:assignee': value})"
        >
          <el-option
            v-for="item in users"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 候选人员 -->
      <el-form-item label="候选人员" v-else-if="userTask && form.userType === 'camunda:candidateUsers'">
        <el-select
          v-model="form['camunda:candidateUsers']"
          placeholder="请选择"
          key="2"
          multiple
          @change="(value) => addUser({'camunda:candidateUsers': value.join(',') || value})"
        >
          <el-option
            v-for="item in users"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 角色/岗位 -->
      <el-form-item label="角色/岗位" v-else-if="userTask && form.userType === 'camunda:candidateGroups'">
        <el-select
          v-model="form['camunda:candidateGroups']"
          placeholder="请选择"
          multiple
          @change="(value) => addUser({'camunda:candidateGroups': value})"
        >
          <el-option
            v-for="item in roles"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 分支允许添加条件 -->
      <el-form-item label="分支条件" v-if="sequenceFlow">
        <el-select v-model="form.condition" placeholder="请选择" @change="(value) => addConditions(value)">
          <el-option
            v-for="item in conditions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {toRaw} from 'vue'
export default {
  name: "PropertyPanel",
  props: {
    modeler: {
      type: Object,
      required: true
    },
    xmlStr: {
      type: String,
    },
    users: {
      type: Array,
      required: true
    },
    roles: {
      type: Array,
      required: true
    }
  },
  computed: {
    userTask() {
      if (!this.element) {
        return;
      }
      return this.element.type === "bpmn:UserTask";
    },
    sequenceFlow() {
      if (!this.element) {
        return;
      }
      return this.element.type === "bpmn:SequenceFlow";
    }
  },
  data() {
    return {
      form: {
        id: "",
        name: "",
        color: null
      },
      rootForm: null,
      isRoot: false,
      element: {},
      condition: '',
      conditions: [
        {
          value: "approved",
          label: "通过"
        },
        {
          value: "rejected",
          label: "拒绝"
        },
      ]
    };
  },
  watch: {
    xmlStr: {
      handler: function(newVal, oldVal) {
        if (newVal && newVal !== oldVal) {
          console.log('newVal :>> ', newVal);
        }
      },
      deep: true
    }
  },
  mounted() {
    this.handleModeler();
  },
  methods: {
    getRootElements() {
      return this.modeler._definitions.rootElements[0];
kf    },
    handleModeler() {
      // 监听节点选择变化
      this.modeler.on("selection.changed", e => {
        const element = e.newSelection[0];
        this.element = element;
        if (!element) {
          this.isRoot = true;
          if(!this.rootForm){
            let rootEl = this.getRootElements()
            this.rootForm = {
              id: rootEl.id,
              name: rootEl.name,
            }
          }
          this.form = {
            id: this.rootForm.id,
            name: this.rootForm.name,
          };
          
          return;
        }
        this.isRoot = false;
        this.form = {
          ...element.businessObject,
          ...element.businessObject.$attrs
        };
        console.log('object :>> ', element);
        if(element.type === 'bpmn:SequenceFlow'){
          const conditionExpression = element.businessObject.conditionExpression;
          console.log('conditionExpression :>> ', conditionExpression);
          if (conditionExpression && conditionExpression.body) {
            if (conditionExpression.body.includes('approved')) {
              this.form.condition = 'approved';
            } else if (conditionExpression.body.includes('rejected')) {
              this.form.condition = 'rejected';  
            }
          }
        }else if(this.form.hasOwnProperty('camunda:candidateUsers')){
          this.form.userType = 'camunda:candidateUsers'
        }else if(this.form.hasOwnProperty('camunda:candidateGroups')){
          this.form.userType = 'camunda:candidateGroups'
        }else if(this.form.hasOwnProperty('camunda:assignee')){
          this.form.userType = 'camunda:assignee'
        }
        if (this.form.userType === "camunda:candidateUsers") {
          this.form["camunda:candidateUsers"] =
            this.form["camunda:candidateUsers"].split(",") || [];
        }else if(this.form.userType === "camunda:candidateGroups"){
          this.form["camunda:candidateGroups"] =
            this.form["camunda:candidateGroups"].split(",") || [];
        }
      });

      //  监听节点属性变化
      this.modeler.on("element.changed", e => {
        const { element } = e;
        if (!element) return;
        //  新增节点需要更新回属性面板
        if (element.id === this.form.id) {
          this.form.name = element.businessObject.name;
          this.form = { ...this.form };
        }
      });
    },
    // 属性面板名称，更新回流程节点
    nameChange(name) {
      if( this.isRoot ){
        this.rootForm.name = name;
        const processElement = this.modeler.get('elementRegistry').get(this.rootForm.id); // 获取根元素
        const modeling = this.modeler.get('modeling');
        modeling.updateProperties(processElement, {
          name: name
        });
      }else{
        const commandStack = this.modeler.get('commandStack');
        const elementRegistry = this.modeler.get('elementRegistry');
        const element = elementRegistry.get(this.form.id);
        if (element) {
          commandStack.execute('element.updateLabel', {
            element: element,
            newLabel: name,
            hints: {} // 根据实际需求提供额外参数
          });
        } else {
          console.error('Element not found in elementRegistry:', this.element.id);
        }

      }
     
    },
    // 属性面板颜色，更新回流程节点
    colorChange(color) {
      const modeling = this.modeler.get("modeling");
      modeling.setColor(this.element, {
        fill: null,
        stroke: color
      });
      modeling.updateProperties(this.element, { color: color });
    },
    // 任务节点配置人员
    addUser(properties) {
      this.updateProperties(properties);
    },
    addConditions (value) {
      const modeling = this.modeler.get("modeling");
      const elementRegistry = this.modeler.get('elementRegistry');
      const element = elementRegistry.get(this.form.id);
      // 确保该元素是顺序流
      if (element.type === 'bpmn:SequenceFlow') {
        try {
          // 使用 bpmnFactory 创建 conditionExpression
          const bpmnFactory = this.modeler.get('bpmnFactory');
          const conditionExpression = bpmnFactory.create('bpmn:FormalExpression', {
            id: 'Condition_' + Math.random().toString(36).substr(2),
            body: `\${approvalResult == '${value}'}`, // 表达式内容
            language: 'JUEL'
          });

          // 设置条件表达式
          modeling.updateProperties(element, {
            conditionExpression: conditionExpression
          });

          console.log("Condition expression set successfully.");
        } catch (error) {
          console.error("Error setting condition expression:", error);
        }
      } else {
        console.error('The provided element is not a Sequence Flow.');
      }
    },
    // 切换人员类型
    typeChange() {
      const types = ["camunda:assignee", "camunda:candidateUsers", "camunda:candidateGroups"];
      types.forEach(type => {
        delete this.element.businessObject.$attrs[type];
        delete this.form[type];
      });
    },
    // 在这里我们封装一个通用的更新节点属性的方法
    updateProperties(properties) {
      const modeling = this.modeler.get("modeling");
      modeling.updateProperties(toRaw(this.element), properties);
    }
  }
};
</script>

<style lang="scss" scoped>
.property-panel {
  position: absolute;
  right: 0px;
  top: 0px;
  border-left: 1px solid #cccccc;
  padding: 20px 0;
  width: 300px;
  height: 100%;
}
</style>
