<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" type="card">
      <a-tab-pane
        key="form"
        :tab="
          designerData.formCurrentNode.formTitle
            ? designerData.formCurrentNode.formTitle
            : '表单信息'
        "
        v-if="formVisble"
      >
        <div :class="mapConfig?.isShowMap ? 'form-container' : ''">
          <FormViewer
            ref="formBoxRef"
            :formConfig="formConfig"
            :formVerison="designerData.formCurrentNode.formVerison"
            v-if="formVisble"
          />
        </div>
        <div class="maper-container" v-if="mapConfig?.isShowMap">
          <MapboxMap
            :mapConfig="mapConfig"
            @handlerDrawComplete="handlerDrawComplete"
            @mapOnLoad="mapOnLoad"
            ref="MapboxComponent"
          />
        </div>
      </a-tab-pane>
      <a-tab-pane
        key="form"
        :tab="
          designerData.formCurrentNode.formTitle
            ? designerData.formCurrentNode.formTitle
            : '系统表单信息'
        "
        v-if="formUrlVisble"
      >
        <AsyncComponent ref="pcForm" />
      </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, defineAsyncComponent } 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';

  const MapboxMap = defineAsyncComponent(() => import('@/components/MapboxMaps/MapComponent.vue'));
  const mapConfig = ref({});
  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 formUrlVisble = ref(false);
  const processVisble = ref(false);
  const AsyncComponent = ref();
  const props = defineProps({
    code: String,
    ParentNodeId: String,
    ParentTaskId: String,
    ParentProcessId: String,
  });
  const emit = defineEmits(['closeModel']);
  const keyValue = ref('');
  const pcForm = 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');
    console.log('currentNode', currentNode);
    mapConfig.value = currentNode.mapConfig;

    console.log('mapConfig', mapConfig.value);
    designerData.isCustmerTitle = currentNode.isCustmerTitle;
    if (currentNode.authFields.length > 0) {
      // 有自定义表单时
      formVisble.value = true;
    } else if (currentNode.formUrl) {
      // 有PC系统表单时
      formUrlVisble.value = true;
      let url = '../../' + currentNode.formUrl + '.vue';
      console.log(url);
      // AsyncComponent.value = defineAsyncComponent(() => import(url));
      AsyncComponent.value = defineAsyncComponent({
        // 加载函数
        loader: () => import(url),
        // 展示加载组件前的延迟时间，默认为200ms,注：这里如果设置的时间过短，会有闪烁的效果
        delay: 200,
        // 如果提供了一个timeout时间限制，并且超时了，也会展示这里的报错组件
        // 设置加载超时时间为3000毫秒
        timeout: 3000,
        onError: function () {
          createMessage.error('无法加载系统表单，请查看流程配置是否正确!');
        },
      });
    } else {
      // 无表单时
      processVisble.value = true;
      activeName.value = 'flow';
    }

    formConfig.value = currentNode.authFields;

    console.log('formConfigConfig', formConfig.value);
    designerData.formCurrentNode = currentNode;
    getFormHistory();
  }

  async function getDelegateUsers() {
    const data = await getLoadMyUserList({
      code: props.code,
    });
    designerData.delegateUsers = data;
  }
  async function handleSaveDraft() {
    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;
    }
    console.log(values);
    if (values) {
      var processId = buildGUID();
      var commit = {
        schemeId: designerData.formCurrentNode.formVerison,
        pkey: keyValue.value,
        pkeyValue: processId,
      };
      var querys = {
        schemeCode: designerData.isDraft ? '' : props.code,
        userId: formData.userId,
        title: formData.title,
        processId: processId,
        InstanceInfo: JSON.stringify(commit),
        ParentNodeId: props.ParentNodeId,
        ParentTaskId: props.ParentTaskId,
        ParentProcessId: props.ParentProcessId,
      };
      if (props.ParentNodeId) {
        querys.isChild = 1;
      }
      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) => {
          if (!res) {
            createMessage.error('请检查表单必填项');
          } else {
            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 if (formUrlVisble.value) {
      //有系统表单，先存系统表单
      // const funName = 'handleSubmit';
      // pcForm.value[funName]();
      handleCreateFlow(processId);
    } else {
      handleCreateFlow(processId);
    }
  }
  async function handleCreateFlow(processId) {
    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: processId,
      };
      var querys = {
        schemeCode: designerData.isDraft ? '' : props.code,
        userId: formData.userId,
        title: formData.title,
        processId: processId,
        InstanceInfo: JSON.stringify(commit),
        ParentNodeId: props.ParentNodeId,
        ParentTaskId: props.ParentTaskId,
        ParentProcessId: props.ParentProcessId,
      };
      if (props.ParentNodeId) {
        querys.isChild = 1;
      }
      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.tabList.forEach((tabElement) => {
        tabElement.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;
  }

  .form-container {
    float: left;
    width: 60%;
  }
  .maper-container {
    float: left;
    width: 40%;
    padding: 20px;
    height: 100%;
  }
</style>
