<template>
  <div style="margin-top: 16px">
    <el-form-item label="处理用户">
      <el-input v-model="userTaskForm.assignee" clearable @change="updateElementTask('assignee')" />
    </el-form-item>
    <el-form-item label="候选用户">
      <el-input
        v-model="userTaskForm.candidateUsers"
        clearable
        @change="updateElementTask('candidateUsers')"
      />
    </el-form-item>
    <el-form-item label="候选分组">
      <el-input
        v-model="userTaskForm.candidateGroups"
        clearable
        @change="updateElementTask('candidateGroups')"
      />
    </el-form-item>
    <el-form-item label="到期时间">
      <el-input v-model="userTaskForm.dueDate" clearable @change="updateElementTask('dueDate')" />
    </el-form-item>
    <el-form-item label="跟踪时间">
      <el-input
        v-model="userTaskForm.followUpDate"
        clearable
        @change="updateElementTask('followUpDate')"
      />
    </el-form-item>
    <el-form-item label="优先级">
      <el-input v-model="userTaskForm.priority" clearable @change="updateElementTask('priority')" />
    </el-form-item>
  </div>
</template>

<script>
import { ElFormItem, ElInput } from 'element-plus'

export default {
  name: 'UserTask',
  components: {
    ElFormItem,
    ElInput
  },
  props: {
    id: String,
    type: String
  },
  data() {
    return {
      defaultTaskForm: {
        assignee: '',
        candidateUsers: [],
        candidateGroups: [],
        dueDate: '',
        followUpDate: '',
        priority: ''
      },
      userTaskForm: {}
    }
  },
  watch: {
    id: {
      immediate: true,
      handler() {
        this.bpmnElement = window.bpmnInstances.bpmnElement
        this.$nextTick(() => this.resetTaskForm())
      }
    }
  },
  methods: {
    resetTaskForm() {
      for (const key in this.defaultTaskForm) {
        let value
        if (key === 'candidateUsers' || key === 'candidateGroups') {
          value = this.bpmnElement?.businessObject[key]
            ? this.bpmnElement.businessObject[key].split(',')
            : []
        } else {
          value = this.bpmnElement?.businessObject[key] || this.defaultTaskForm[key]
        }
        this.userTaskForm[key] = value
      }
    },
    updateElementTask(key) {
      const taskAttr = Object.create(null)
      // if (key === 'candidateUsers' || key === 'candidateGroups') {
      //   taskAttr[key] =
      //     this.userTaskForm[key] && this.userTaskForm[key].length
      //       ? this.userTaskForm[key].join()
      //       : null
      // } else {
      taskAttr[key] = this.userTaskForm[key] || null
      // }
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, taskAttr)
    }
  },
  beforeUnmount() {
    this.bpmnElement = null
  }
}
</script>
