<template>
  <PageWrapper :class="prefixCls">
    <div class="btn-box">
      <a-button type="primary" :icon="h(SendOutlined)" @click="handleCreateFlow" 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">
      <a-tab-pane key="form" tab="表单信息">

      </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" />
          <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="delegateUsers"></a-select>
              </a-form-item>
            </a-form>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>

  </PageWrapper>

</template>

<script lang="ts" setup>
  import { h, ref, provide, reactive, onMounted, defineProps, computed, defineEmits, onBeforeMount } from 'vue';
  import ProcessViewer from '@/components/ProcessViewer/index.vue';
  import { PageWrapper } from '@/components/Page';

  import { SendOutlined, SaveOutlined, CloseCircleOutlined, ZoomInOutlined, RotateLeftOutlined, RotateRightOutlined, ClearOutlined } 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 { useRoute } from 'vue-router'
  import { useMultipleTabStore } from '@/store/modules/multipleTab';
  import { useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { buildGUID } from '@/utils/uuid';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createConfirm, createMessage } = useMessage();

  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo
  const prefixCls = 'preview-box'
  const tabStore = useMultipleTabStore();
  const router = useRouter();
  const content = ref('')
  const flowContent = ref('')
  const route = useRoute()
  const code = route.query.code
  const designerOpen = ref(false)
  const formRef = ref();
  const labelCol = { span: 7 };
  const wrapperCol = { span: 13 };

  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: []
  })
  const activeName = ref('flow')
  const modelDesigner = ref < any > ()

  const formData = reactive({
    userId: '',
    title: ''
  })
  const rules = reactive({
    title: [
      { required: true, message: '请选择流程标题', trigger: 'blur' }
    ],
    userId: [
      { required: true, message: '请选择流程发起人', trigger: 'blur' }
    ],
  })
  async function getDetailInfo() {
    let data = await getDetail({ code: 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
  }
  async function getDelegateUsers() {
    const data = await getLoadMyUserList({
      code: code
    })
    designerData.delegateUsers = data
  }
  async function handleSaveDraft() {

  }
  async function handleCreateFlow() {
    var querys = {
      schemeCode: designerData.isDraft ? '' : code,
      userId: formData.userId,
      title: formData.title,
      processId: buildGUID()
    }
    if (!designerData.isDraft) {
      await saveDraft(querys)
      querys.schemeCode = ''
      designerData.isDraft = true
    }
    const data = await create(querys)
    if (data) {
      closePreview()
      return createMessage.info('创建成功');
    } else {
      return createMessage.error('创建失败');
    }
  }

  function closePreview() {
    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;

    }
  }

  .form-box {
    width: 480px;
  }
</style>