<template>
  <w-dialog
    ref="dialogRef"
    :title="$t('re.workflow.dialog.title')"
    width="600px"
    :can-maximize="false"
    :buttons="[
      {
        label: $t('submit'),
        noCaps: true,
        click: () => {
          submit();
        },
      },
    ]"
  >
    <div class="p-3 text-red-500">{{ $t('re.workflow.dialog.tip') }}</div>
    <w-form
      ref="formRef"
      :cols-num="1"
      :fields="[{ name: 'treatment', label: $t('re.workflow.dialog.entity.treatment'), type: 'w-textarea', rows: 5, requiredIf: true }]"
      class="p-2"
    ></w-form>
    <w-select-assignee-dialog ref="selectAssigneeDialogRef" @assignee-selected="assigneeSelected"></w-select-assignee-dialog>
  </w-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { axios, Environment, NotifyManager } from 'platform-core';

const props = defineProps({
  opener: { type: Object, default: undefined },
  foreignKey: { type: String, default: '' },
  foreignValue: { type: String, default: '' },
});

const emit = defineEmits<{
  (e: 'afterStarted', evt: Event): void;
}>();

const dialogRef = ref();
const formRef = ref();
const selectAssigneeDialogRef = ref();
const resourceIdRef = ref();
const resourceCodeRef = ref('');
const resourceVersionRef = ref('');
const resourceTargetStatusRef = ref('');

const submit = (assignee) => {
  const data = formRef.value.getData();
  const variables = { targetStatus: resourceTargetStatusRef.value };
  const transientVariables = { task_treatment: data.treatment };
  if (assignee) {
    transientVariables.assignee = assignee;
  }
  axios
    .post(
      Environment.apiContextPath('/api/re/resource/workflow/startProcessInstance/' + resourceIdRef.value),
      {
        bussinessKey: resourceCodeRef.value + ':' + resourceVersionRef.value,
        variables: variables,
        transientVariables: transientVariables,
        autoCompleteFirstTask: true,
      },
      { loading: true },
    )
    .then((response) => {
      if (response.data.code === 0) {
        // 操作成功
        NotifyManager.success();
        close();
        emit('afterStarted');
      } else if (response.data.code === 1) {
        // 需要选择处理人
        selectAssigneeDialogRef.value.open(response.data);
      }
    });
};

const assigneeSelected = (assignee) => {
  submit(assignee);
};

const open = (id, code, version, status) => {
  resourceIdRef.value = id;
  resourceCodeRef.value = code;
  resourceVersionRef.value = version;
  resourceTargetStatusRef.value = status;
  dialogRef.value.show();
};

const close = () => {
  dialogRef.value.hide();
};

defineExpose({
  open,
  close,
});
</script>
