<template>
  <PageWrapper :class="prefixCls" v-loading="loadingRef" loading-tip="加载中...">
    <Loading
      :loading="compState.loading"
      :absolute="compState.absolute"
      :theme="compState.theme"
      :background="compState.background"
      :tip="compState.tip"
    />
    <div class="btn-box">
      <a-button type="primary" :icon="h(SendOutlined)" @click="handleSubmit" 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="
          designerData.formCurrentNode.formTitle
            ? designerData.formCurrentNode.formTitle
            : '表单信息'
        "
        v-if="formVisble"
      >
        <FormViewer
          ref="formBoxRef"
          :formConfig="formConfig"
          :flowFormData="props.flowFormData"
          :formVerison="designerData.formCurrentNode.formVerison"
          :issueId="designerData.formCurrentNode.issueId"
          v-if="formVisble"
        />
      </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-form-item>
            </a-form>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { h, ref, reactive, onBeforeMount, onMounted } from 'vue';
  import { ProcessViewer } from '@/components/ProcessViewer/index';
  import { PageWrapper } from '@/components/Page';
  import { FormViewer } from '@/components/FormViewer';
  import { SendOutlined, SaveOutlined, 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, LoadFormScheme } 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';
  import { Loading } from '/@/components/Loading';

  const { createMessage } = useMessage();
  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,
    flowFormData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    isUpdate: Boolean,
  });
  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;
    }
  }
  const compState = reactive<{
    absolute?: boolean;
    loading?: boolean;
    theme?: 'dark' | 'light';
    background?: string;
    tip?: string;
  }>({
    absolute: false,
    loading: false,
    theme: 'dark',
    background: 'rgba(111,111,111,.7)',
    tip: '加载中...',
  });
  function openLoading(absolute: boolean) {
    compState.absolute = absolute;
    compState.loading = true;
    setTimeout(() => {
      compState.loading = false;
    }, 1000);
  }
  async function getDetailInfo() {
    openLoading(false);
    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');
    designerData.isCustmerTitle = currentNode.isCustmerTitle;
    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;
  }
  function handleSubmit() {
    var processId = buildGUID();
    var querys = {
      schemeId: designerData.formCurrentNode.formVerison,
      isUpdate: props.isUpdate,
      pkey: keyValue.value,
    };
    // 有表单内容，先存表单信息
    if (formVisble.value) {
      if (!designerData.formCurrentNode.formRelationId) {
        return createMessage.error('请设置表单和流程关联字段');
      }
      formBoxRef.value
        .getForm()
        .then(async (res) => {
          console.log(res);
          if (!res) {
            createMessage.error('请检查表单必填项');
          } else {
            if (!props.isUpdate) {
              res[designerData.formCurrentNode.formRelationId] = processId;
              querys.pkeyValue = processId;
            }
            console.log(res);
            for (var item in res) {
              if (res[item] == undefined) {
                res[item] = '';
                if (item.search('_input_guid') != -1 && !props.isUpdate) {
                  res[item] = buildGUID();
                }
              } else {
                if (props.isUpdate) {
                  if (item.search('_input_guid') != -1) {
                    querys.pkeyValue = res[item];
                  }
                }
              }
            }
            console.log(res);
            querys.data = JSON.stringify(res);
            const formValue = await functionsaveForm(querys);
            if (formValue) {
              handleCreateFlow(processId, querys.pkeyValue);
            }
          }
        })
        .catch((error) => {
          console.log(error);
          activeName.value = 'form';
          return;
        });
    } else {
      handleCreateFlow(processId);
    }
  }
  async function handleCreateFlow(processId, pkeyValue) {
    let values;
    if (designerData.isCustmerTitle) {
      values = await formRef.value
        .validate()
        .then(() => {
          return true;
        })
        .catch((error: ValidateErrorEntity<FormState>) => {
          console.log('error', error);
          processVisble.value = true;
          activeName.value = 'flow';
          return false;
        });
    } else {
      values = true;
    }
    if (values) {
      var commit = {
        schemeId: designerData.formCurrentNode.formVerison,
        pkey: keyValue.value,
        pkeyValue: pkeyValue ? pkeyValue : processId,
      };
      var querys = {
        schemeCode: designerData.isDraft ? '' : props.code,
        userId: formData.userId,
        title: formData.title,
        processId: processId,
        InstanceInfo: JSON.stringify(commit),
      };
      let data;
      if (!designerData.isDraft) {
        let draft = await saveDraft(querys);
        querys.schemeCode = '';
        designerData.isDraft = true;
        if (draft) {
          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.tabList.forEach((tabElement) => {
        tabElement.schemas.forEach((element) => {
          if (element.field == designerData.formCurrentNode.formRelationId) {
            keyValue.value = element.componentProps.fieldName;
          }
        });
      });
    }
  }
  function closePreview() {
    emit('closeModel');
  }
  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>
