<template>
  <div class="app-container">
      <a-tabs v-model:activeKey="activeName" @tabClick="handleClick" >
        <!--表单信息-->
        <a-tab-pane key="1" tab="表单信息">
            <div style="margin:5px;height: 100%;">
              <div v-show="formUrl" class="iframe-container">
                <iFrame :src="formUrl" class="responsive-iframe"></iFrame>
              </div>
              <div v-show="!formUrl">
                <inner-form ref="refInnerForm"></inner-form>
              </div>
             
              <div v-show="!formUrl">
                <inner-form ref="refInnerForm"></inner-form>
              </div>
             
              <div style="margin:10px;width:100%;text-align: center;">
                <a-space>
                  <a-button type="primary" @click="saveForm()" :loading="loading">提 交</a-button>
                  <a-button type="primary" @click="resetForm">重 置</a-button>
                </a-space>
                </div>
            </div>
        </a-tab-pane>
        <!--流程图-->
        <a-tab-pane key="2" tab="流程图">
          <bpmn-viewer :flow-data="flowData"/>
        </a-tab-pane>
      </a-tabs>
    
    <RoleSelectModal rowKey="id"  @register="registerSelRoleModal" @getSelectResult="onSelectOk" isRadioSelection :showButton="false" labelKey="roleName"/>
    <UserSelectModal rowKey="id" @register="registerSelUserModal"  @getSelectResult="onSelectOk" isRadioSelection :showButton="false" labelKey="realname"/>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { message, Modal } from 'ant-design-vue'
import BpmnViewer from '/@/components/Process/viewer/index.vue'
import { definitionStart, flowXmlAndNode } from "/@/components/Process/api/definition"
import { flowFormData } from "/@/components/Process/api/process"
import { getNextFlowNodeByStart } from "/@/components/Process/api/todo"
import { useModal } from '/@/components/Modal';
import UserSelectModal from '/@/components/Form/src/jeecg/components/modal/UserSelectModal.vue'
import RoleSelectModal  from '/@/components/Form/src/jeecg/components/modal/RoleSelectModal.vue'
import InnerForm from '/@/views/flowable/definition/InnerForm.vue'

const [registerSelUserModal, { openModal:userOpenModal }] = useModal();
const [registerSelRoleModal, { openModal:roleOpenModal }] = useModal();


interface QueryParams {
  deptId?: string
}

interface FlowData {
  [key: string]: any
}

interface FormJson {
  [key: string]: any
}

// 模型xml数据
const flowData = ref<FlowData>({})
const activeName = ref<string>('1') // 切换tab标签
// 查询参数
const queryParams = reactive<QueryParams>({
  deptId: undefined
})
const loading = ref(false)
const deployId = ref<string>("")  // 流程定义编号
const procDefId = ref<string>("")  // 流程实例编号
const taskTitle = ref<string | null>(null)
const taskOpen = ref<boolean>(false)
const checkType = ref<string>('') // 选择类型
const checkValues = ref<any>(null) // 选中任务接收人员数据
const formData = ref<any>({}) // 填写的表单数据
const multiInstanceVars = ref<string>('') // 会签节点
const formJson = ref<FormJson>({}) // 表单json

const emit = defineEmits(['register', 'success']);

const userType = ref<string>("user");

const formUrl = ref();
const refInnerForm = ref();

const handleClick = (key: string) => {
  if (key === '2') {
    flowXmlAndNode({ deployId: deployId.value }).then(res => {
      flowData.value = res
    })
  }
}

/** 流程表单数据 */
const getFlowFormData = async (deployId: string) => {
  const params = { deployId: deployId }
  flowFormData(params).then(resData => {
    nextTick(() => {
      if(resData.formUrl) {
        formUrl.value = resData.formUrl
      } else {
        formUrl.value = ""
        refInnerForm.value.iniData(resData)
        formJson.value = resData.formRules
      }
    })
  }).catch(res => {
  
  })
}


const goBack = () => {
  emit("success")
}

/** 申请流程表单数据提交 */
const saveForm = async() => {
  loading.value = true
  formData.value = refInnerForm.value.getFormData()
  await getNextFlowNodeByStart({ deploymentId: deployId.value, variables: formData.value }).then(resData => {
    const data = resData
    if (data) {
      if (data.dataType === 'dynamic') {
        if (data.type === 'assignee'||data.type === 'user') { 
          userType.value = "user"
          checkType.value = "single"
          userOpenModal()
        } else if (data.type === 'candidateUsers') { 
        } else if (data.type === 'candidateGroups'||data.type === 'role') {
          userType.value = "role"
          checkType.value = "single"
          roleOpenModal();
        } 
        taskOpen.value = true
        taskTitle.value = "选择任务接收"
      } else {
        if (procDefId.value) {
          definitionStart(procDefId.value, formData.value).then(res => {
            goBack()
          })
        }
      }
    }
    loading.value = false
  })

}


const resetForm = () => {
  refInnerForm.value.resetForm()
}

const submitTask = () => {
  if (!checkValues.value) {
    if(userType.value=="user") {
      message.error("请选择任务接收!")
    } else if(userType.value=="role") {
      message.error("请选择流程接收角色组!")
    }
    return
  }

  const formData = refInnerForm.value.getFormData()
  if (formData) {
    const submitData = {
      formJson: formJson.value,
    }
   
    Object.assign(submitData, formData)
    if (multiInstanceVars.value) {
      submitData[multiInstanceVars.value] = checkValues.value
    } else {
      submitData["approval"] = checkValues.value
      submitData["approvalType"] = userType.value
    }

    

    definitionStart(procDefId.value, submitData).then(res => {
      goBack()
    })
  }
}

const handleUserSelect = (selection: any) => {
  if (selection) {
    if (Array.isArray(selection)) {
      const selectVal = selection.map(item => item.userId)
      if (multiInstanceVars.value) {
        checkValues.value = selectVal
      } else {
        checkValues.value = selectVal.join(',')
      }
    } else {
      checkValues.value = selection.userId
    }
  }
}

const handleRoleSelect = (selection: any) => {
  if (selection) {
    if (Array.isArray(selection)) {
      const selectVal = selection.map(item => item.roleId)
      checkValues.value = selectVal.join(',')
    } else {
      checkValues.value = selection
    }
  }
}

const iniData = async (selFlower) => {
   deployId.value = selFlower?.deploymentId as string || ""
   procDefId.value = selFlower?.id as string || ""
   await getFlowFormData(deployId.value)
}


// const handleNextReceiver = (userType) => {
//   openModal(true,{
//     isUpdate: false,
//     userType:userType
//   })
// }

const onSelectOk  = async (options,values) => {
  if(!values||values.length==0) {
    return false 
  }
  checkValues.value = values[0];
  await submitTask()
}

defineExpose({
  iniData,
})
</script>

<style lang="scss" scoped>

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

.app-container {
  height: calc(100vh - 150px);
  margin: 0px;
  padding: 5px;
}

.my-label {
  background: #E1F3D8;
}


.iframe-container {
  height: calc(100vh - 200px);
  width: 100%;
}

.responsive-iframe {
  width: 100%;
  height: 100%;
  border: none;
}
</style>