<template>
  <PageWrapper :class="prefixCls">
    <div class="btn-box">
      <a-button type="primary" :icon="h(SendOutlined)" @click="handleSubmit" class="ml-2"
        >发起流程
      </a-button>
      <a-button type="primary" :icon="h(SaveOutlined)" @click="handleSaveDraft" class="ml-2"
        >保存草稿
      </a-button>
      <a-button
        type="primary"
        :icon="h(CloseCircleOutlined)"
        @click="closePreview"
        class="ml-2"
        danger
        >关闭
      </a-button>
    </div>
    <a-tabs v-model:activeKey="activeName" @change="changeActive">
      <a-tab-pane key="form" tab="表单信息" v-if="formVisble">
        <FormViewer ref="formBoxRef" :formConfig="formConfig" v-if="formVisble"></FormViewer>
      </a-tab-pane>
      <a-tab-pane key="flow" tab="流程信息" force-render>
        <div class="process-design" :style="'display: flex; height:' + designerData.height">
          <process-viewer :key="`designer-${code}`" :xml="flowContent" v-if="processVisble" />
          <div
            class="form-box"
            v-if="
              designerData.isCustmerTitle ||
              (designerData.delegateUsers && designerData.delegateUsers.length > 0)
            "
          >
            <a-form
              ref="formRef"
              :model="formData"
              :rules="rules"
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
            >
              <a-form-item
                ref="title"
                label="流程标题"
                name="title"
                v-if="designerData.isCustmerTitle"
              >
                <a-input v-model:value="formData.title" />
              </a-form-item>
              <a-form-item
                label="流程发起人"
                name="userId"
                v-if="designerData.delegateUsers && designerData.delegateUsers.length > 0"
              >
                <a-select
                  v-model:value="formData.userId"
                  placeholder="请选择"
                  :options="designerData.delegateUsers"
                ></a-select>
              </a-form-item>
            </a-form>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { h, ref, reactive, onBeforeMount } from 'vue';
  import { ProcessViewer } from '@/components/ProcessViewer/index';
  import { PageWrapper } from '@/components/Page';
  import { FormViewer } from '@/components/FormViewer';
  import { SendOutlined } from '@ant-design/icons-vue';
  import { SaveOutlined } from '@ant-design/icons-vue';
  import { CloseCircleOutlined } from '@ant-design/icons-vue';
  import { getDetail } from '@/api/sys/WFSchemeInfo';
  import { create, saveDraft } from '@/api/sys/WFProcess';
  import { getLoadMyUserList } from '@/api/sys/WFDelegate';
  import { functionsaveForm } from '@/api/demo/formScheme';
  import { useUserStore } from '@/store/modules/user';
  import { buildGUID } from '@/utils/uuid';
  import { IFormConfig } from '@/views/demo/form-design/typings/v-form-component';
  import { useMessage } from '@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { LoadFormScheme } from '@/api/demo/formScheme';
  const formBoxRef = ref<any>();
  const userStore = useUserStore();
  const userInfo: any = userStore.getUserInfo;
  const prefixCls = 'preview-box';
  const flowContent = ref('');
  const formRef = ref();
  const labelCol = { span: 7 };
  const wrapperCol = { span: 13 };
  const formVisble = ref(false);
  const processVisble = ref(false);
  const props = defineProps({
    code: String,
  });
  const emit = defineEmits(['closeModel']);
  const keyValue = ref('');
  // 表单数据
  const formConfig = ref<IFormConfig>({
    // 表单配置
    schemas: [],
    layout: 'horizontal',
    labelLayout: 'flex',
    labelWidth: 100,
    labelCol: {},
    wrapperCol: {},
    currentItem: {
      component: '',
      componentProps: {},
    },
    activeKey: 1,
  });
  const designerData = reactive({
    loading: false,
    xmlString: '',
    controlForm: {
      prefix: 'flowable',
    },
    height: document.documentElement.clientHeight - 230.5 + 'px;',
    midVisible: false,
    isCustmerTitle: false,
    nodeUsers: [],
    selectUsersVisible: false,

    isDraft: false,
    delegateUsers: [],
    formVerison: '',
    formCode: '',
    formCurrentNode: {},
  });
  const activeName = ref('form');
  const formData = reactive({
    userId: '',
    title: '',
  });
  const rules = reactive({
    title: [{ required: true, message: '请选择流程标题', trigger: 'blur' }],
    userId: [{ required: true, message: '请选择流程发起人', trigger: 'blur' }],
  });
  function changeActive(activeKey) {
    if (activeKey == 'flow') {
      processVisble.value = true;
    }
  }
  async function getDetailInfo() {
    let data = await getDetail({ code: props.code });
    flowContent.value = data.scheme.flowContent;
    formData.userId = userInfo.id;
    let content = JSON.parse(data.scheme.content);
    let wfData = content.wfData;
    const currentNode = wfData.find((t) => t.type == 'bpmn:StartEvent');
    if (currentNode.authFields.length > 0) {
      formVisble.value = true;
    } else {
      processVisble.value = true;
      activeName.value = 'flow';
    }
    formConfig.value = currentNode.authFields;
    designerData.formCurrentNode = currentNode;
    getFormHistory();
  }
  async function getDelegateUsers() {
    const data = await getLoadMyUserList({
      code: props.code,
    });
    designerData.delegateUsers = data;
  }
  async function handleSaveDraft() {
    var querys = {
      schemeCode: designerData.isDraft ? '' : props.code,
      userId: formData.userId,
      title: formData.title,
      processId: buildGUID(),
    };
    const data = await saveDraft(querys);
    querys.schemeCode = '';
    designerData.isDraft = true;
    if (data) {
      closePreview();
      return createMessage.success('保存草稿成功');
    } else {
      return createMessage.error('保存草稿失败');
    }
  }
  function handleSubmit() {
    var processId = buildGUID();
    var querys = {
      schemeId: designerData.formCurrentNode.formVerison,
      isUpdate: false,
      pkey: keyValue.value,
      pkeyValue: processId,
    };
    // 有表单内容，先存表单信息
    if (formVisble.value) {
      if (!designerData.formCurrentNode.formRelationId) {
        return createMessage.error('请设置表单和流程关联字段');
      }
      formBoxRef.value
        .getForm()
        .then(async (res) => {
          res[designerData.formCurrentNode.formRelationId] = processId;
          for (var item in res) {
            if (res[item] == undefined) {
              res[item] = '';
              if (item.search('_input_guid') != -1) {
                res[item] = buildGUID();
              }
            }
          }
          querys.data = JSON.stringify(res);
          const formValue = await functionsaveForm(querys);
          if (formValue) {
            handleCreateFlow(processId);
          }
        })
        .catch((error) => {
          console.log(error);
          activeName.value = 'form';
          return;
        });
    } else {
      handleCreateFlow(processId);
    }
  }
  async function handleCreateFlow(processId) {
    var querys = {
      schemeCode: designerData.isDraft ? '' : props.code,
      userId: formData.userId,
      title: formData.title,
      processId: processId,
    };
    if (!designerData.isDraft) {
      await saveDraft(querys);
      querys.schemeCode = '';
      designerData.isDraft = true;
    }
    const data = await create(querys);
    if (data) {
      closePreview();
      return createMessage.success('发起流程成功');
    } else {
      return createMessage.error('发起流程失败');
    }
  }
  async function getFormHistory() {
    const data = await LoadFormScheme({
      schemeId: designerData.formCurrentNode.formVerison,
    });
    if (data) {
      const scheme = JSON.parse(data.scheme);
      scheme.formInfo.schemas.forEach((element) => {
        if (element.field == designerData.formCurrentNode.formRelationId) {
          keyValue.value = element.componentProps.fieldName;
        }
      });
    }
  }
  function closePreview() {
    emit('closeModel');
    // if (!code) {
    //   tabStore.closeTabByKey('/dashboard/create_preview/add', router);
    // } else {
    //   // /dashboard/create_preview/add?code=测试1
    //   tabStore.closeTabByKey('/dashboard/create_preview/add?code=' + code, router);
    // }
  }
  onBeforeMount(() => {
    getDetailInfo();
    getDelegateUsers();
  });
</script>
<style lang="less" scoped>
  .preview-box {
    background-color: @component-background;

    .btn-box {
      padding: 10px;
      justify-content: flex-end;
      display: flex;
    }
  }
  ::v-deep .anticon svg {
    width: 1em !important;
    height: 1em !important;
  }
  .form-box {
    width: 480px;
  }
</style>
