<!-- 表单预览 - 抽屉方式 -->
<template>
	<el-drawer
		v-model="visible"
    :loading="loading"
		:title="showTitle"
		:before-close="handleClose"
		:modal="false"
		:size="showWidth"
		:wrapper-closable="false"
		class="detailDrawer"
	>
		<div>
			<v-form-render
				ref="vFormRef"
				:dynamic-creation="true"
				:form-json="dataForm.formJson"
				:form-data="dataForm.formData"
				:option-data="dataForm.optionData"
				:disabled-mode="dataForm.isLook == 1"
				@appendButtonClick="testOnAppendButtonClick"
			></v-form-render>
      <Flow
          v-show="dataForm.flowId && dataForm.flowId!=''"
          ref="flow"
          :custom-event="false"
          @go-flow-agree="flowAgree"
          @complete="showForm(dataForm)"
          @flowRegOwner="flowRegOwner"
          :flow-id="dataForm.flowId"
          :flow-status="dataForm.flowStatus"
      />
		</div>
		<template #footer v-if="dataForm.btnList.length && dataForm.isLook == 0">
			<el-button v-for="(item, index) in dataForm.btnList" v-auth="getBtnAuth(item)" v-show="dataForm.isLook == 0"  :loading="loading" v-prevent-reclick type="primary" @click="btnFormBefore(item,0)"
				>{{ item.btnLabel }}
			</el-button>
      <!-- <el-button v-show="dataForm.isLook == 0 && dataForm.showFlowBtn" v-prevent-reclick type="primary" @click="showSubmitFlow"
      >保存并提交
      </el-button> -->
		</template>
    <fw-flow-user-table ref="fwFlowUserTable" @submit="submitFlow" />
		<report-dev-review-dialog ref="reportDialogRef" @close="closeReportDialog" @confirmAddRow="reportDialogAddData"></report-dev-review-dialog>
	</el-drawer>
</template>
<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue'
import {
  btnServerUrl,
  defaultBtnServer, getFlowUserConfigAndNodesApi,
  getFormConfig,
  getInfo,
  saveForm,
  submitFlowForm,
  updateForm
} from '../api/formDevReview'
import { ElMessage, ElMessageBox } from 'element-plus'
import ReportDevReviewDialog from '../report/reportDevReviewDialog.vue'
import Flow from '@/components/Flow/src/index.vue'
import FwFlowUserTable from '@/components/FwFlowUserTable/index.vue'

import { useUserStore } from '@/store/modules/user'
const emit = defineEmits(['refreshDataList'])
const useUser = useUserStore()
var EboUserInfo = useUser.user;
console.log(EboUserInfo)
const visible = ref(false)
const loading = ref(false)
const showWidth = ref('80%')
const showTitle = ref('')
const vFormRef = ref()
const reportDialogRef = ref()
const getBtnAuth = (item:any)=>{
  return item.btnCode;
}
const dataForm = reactive({
	formCode: '',
  flowId:'',
  flowStatus:'',
  flowCategory:'',
  showFlowBtn:false,
  businessNoName:'',
	formJson: {},
	formData: {},
	optionData: {},
	formId: 0,
	btnList: [],
	id: '',
	btnCode: '',
	isLook: 0,
  changeNodeHandlerJson:'',
  auditNote:'',
  flowName:'',
  flowBusinessNo:'',
  flowKey:'',
	appendButtonClickCall: {
		appendButtonClickBreakData: '',
		appendButtonClickBreakSetData: '',
		subFormRowIndex: -1,
		subFormName: ''
	}
})

const init = (formCode?: string, formData: any, isLook: number, btnCode: any, clickBtnData: any) => {
	dataForm.id = ''
	dataForm.btnCode = ''
  dataForm.changeNodeHandlerJson = ''
  dataForm.auditNote = ''
  dataForm.flowName = ''
  dataForm.flowCategory = ''
  dataForm.flowBusinessNo = ''
  dataForm.flowKey = ''
  dataForm.flowId = ''
  dataForm.showFlowBtn = false
	dataForm.isLook = isLook
  dataForm.formCode = formCode
  dataForm.btnCode = btnCode
  dataForm.businessNoName = ''

	if (formData) {
		dataForm.id = formData.id
	}
	// 重置表单数据
	if (vFormRef.value) {
		//vFormRef.value.resetFields()
		vFormRef.value.setFormData({})
	}
	if (clickBtnData) {
		if (clickBtnData.btnLinkFormWidth && clickBtnData.btnLinkFormWidth != '') {
			showWidth.value = clickBtnData.btnLinkFormWidth
		}
		if (clickBtnData.btnLinkFormTitle && clickBtnData.btnLinkFormTitle != '') {
			showTitle.value = clickBtnData.btnLinkFormTitle
		}
	}
	visible.value = true

	if (formCode) {
		showForm(formData)
	}
}


const fwFlowUserTable = ref()
const showSubmitFlow = ()=>{
  for(var i=0;i<dataForm.btnList.length;i++){
    if(dataForm.btnList[i].serviceType==10){//保存
      btnForm(dataForm.btnList[i],1)
      break
    }
  }

}
const flowAgree = () =>{
  flow.value.a()
}

const showUserList = ()=>{
  var dt = {flowCode:dataForm.flowKey}
  if(dataForm.flowId && dataForm.flowId!=''){//重新提交，重新提交时，流程人员不能改变，如要改变人员需要撤回流程重新发起
    let resList = { data: { main: [] } }
    fwFlowUserTable.value.open({
      dialogTableVisible: true,
      tableList: resList.data
    })
  }else{
    getFlowUserConfigAndNodesApi(dt).then(response => {
      let resList = { data: { main: response.data } }
      fwFlowUserTable.value.open({
        dialogTableVisible: true,
        tableList: resList.data
      })
    })
  }


}
//驳回后为发起人调用
const flowRegOwner = ()=>{
  if(dataForm.isLook==0){
    return
  }
  dataForm.isLook = 0;
  showForm(dataForm)
  //vFormRef.value.enableForm()
}

const submitFlow = (userTable: any, auditNote: any)=>{
  console.log("submitFlow")
  dataForm.auditNote = auditNote.value
  var changeNodeHandlerJson = []
  for (var i = 0; i < userTable.value.main.length; i++) {
    var node = userTable.value.main[i]
    if (node.changeHandlerIds && node.changeHandlerIds != '') {
      changeNodeHandlerJson.push(node)
    }
  }

  dataForm.changeNodeHandlerJson = JSON.stringify(changeNodeHandlerJson)

  for(var i=0;i<dataForm.btnList.length;i++){
    if(dataForm.btnList[i].serviceType==15){//提交流程
      btnForm(dataForm.btnList[i],2)
      break
    }
  }
  console.log("submitFlow",dataForm)

}

const flow = ref()
const showForm = (formData: any) => {
  var formCode = dataForm.formCode
  var data = { formCode: formCode }
	dataForm.formCode = formCode
  loading.value = true
	getFormConfig(data).then(response => {
    loading.value = false
    if(response.data.isFlow===1){
      dataForm.showFlowBtn = true
      dataForm.flowName = response.data.flowType;
      dataForm.flowKey = response.data.flowKey;
      dataForm.flowCategory = response.data.flowType;
    }else{
      dataForm.showFlowBtn = false
      dataForm.flowName = '';
      dataForm.flowKey = '';
      dataForm.flowCategory = ''
    }
    if(/(%[0-9A-F2-F]{2})+/i.test(response.data.formJson)){
      response.data.formJson = decodeURIComponent(response.data.formJson);
    }
		dataForm.formJson = JSON.parse(response.data.formJson)
		dataForm.btnList = response.data.fastFormBtnList
    dataForm.businessNoName = response.data.businessNoName
		if (dataForm.id != '') {

      getInfoDetail(0)
		} else {
			vFormRef.value.setFormJson(dataForm.formJson)
			nextTick(() => {
				//从列表透传过来的数据，如果存在，则赋值给到表单
				if (formData.reportToFormData) {
					vFormRef.value.setFormData(formData.reportToFormData)

				}
        nextTick(() => {
          vFormRef.value.handleOnMounted()
        })
			})
		}
	}).finally( ()=> {
    loading.value = false
  })
}

const getInfoDetail = (flag:number) =>{
  var obj = { devFormCode: dataForm.formCode, btnCode: dataForm.btnCode, btnFormData: { id: dataForm.id } }
  loading.value = true
  getInfo(obj).then(res => {
    loading.value = false
    dataForm.flowId = res.data.flowId
    dataForm.flowStatus = res.data.flowStatus
    dataForm.flowName = dataForm.flowName +":"+res.data[dataForm.businessNoName]
    dataForm.flowBusinessNo = res.data[dataForm.businessNoName]
    vFormRef.value.setFormJson(dataForm.formJson)
    /**
     if(res.data.spmsFileList){
     res.data.spmsFileList.forEach((f)=>{
     f.fileUrl = JSON.parse(f.fileUrl);
     })
     }**/

    nextTick(() => {
      vFormRef.value.setFormData(res.data)
      nextTick(() => {
        if(dataForm.flowId && dataForm.flowId!=''){
          flow.value.refresh()
        }
        vFormRef.value.handleOnMounted()
        if(flag==1){
          showUserList()
        }
      })
    })
  }).finally( ()=> {
    loading.value = false
  })
}

const btnFormBefore = (btnData: any,isSubmit: any) => {
  if(btnData.serviceType == 15){
    showSubmitFlow()
  }else{
    btnForm(btnData,isSubmit)
  }

}

const btnForm = (btnData: any,isSubmit: any) => {
	if (btnData.serviceType == 10 || btnData.serviceType == 15 || btnData.serviceType == 20 || btnData.serviceType == 55 || btnData.serviceType == 60) {
    submitForm(btnData,isSubmit)
	}
}
const handleClose = () => {
	visible.value = false
	vFormRef.value.setBlankFormJson()
	emit('refreshDataList')
}
const submitForm = (btnData: any,isSubmit: any) => {
	vFormRef.value
		.getFormData()
		.then(formData => {
			ElMessageBox.confirm('请确定要执行此操作吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				var obj = { devFormCode: dataForm.formCode, btnCode: btnData.btnCode, btnFormData: formData }
				console.log('form表单请求内容:', obj)
				if (dataForm.id != '') {
					obj.btnFormData.id = dataForm.id
					if (btnData.serviceType == '10') {
            loading.value = true
						updateForm(obj).then(res => {
              loading.value = false
              if(isSubmit==0) {
                ElMessage.success({
                  message: '修改成功',
                  duration: 500,
                  onClose: () => {
                    handleClose()
                  }
                })
              }else{
                getInfoDetail(1)

              }
							//请求后增强
							btnClickAfterEnhance(btnData, res, obj)
						}).finally( ()=> {
              loading.value = false
            })
					}else if (btnData.serviceType == '15') {
            formData.flowKey =  dataForm.flowKey
            formData.flowId =  dataForm.flowId
            formData.flowName = dataForm.flowName
            formData.flowCategory = dataForm.flowCategory
            formData.auditNote = dataForm.auditNote
            formData.flowBusinessNo = dataForm.flowBusinessNo
            formData.changeNodeHandlerJson = dataForm.changeNodeHandlerJson
            var obj = { devFormCode: dataForm.formCode, btnCode: btnData.btnCode, btnFormData: formData }
            loading.value = true
            submitFlowForm(obj).then(res => {
              loading.value = false
              ElMessage.success({
                message: '提交流程成功',
                duration: 500,
                onClose: () => {
                  handleClose()
                }
              })
              //请求后增强
              btnClickAfterEnhance(btnData, res, obj)
            }).finally( ()=> {
              loading.value = false
            })
          } else if (btnData.serviceType == '55') {
						defaultBtnServer(obj).then(res => {
              if(isSubmit==0) {
                ElMessage.success({
                  message: '操作成功',
                  duration: 500,
                  onClose: () => {
                    handleClose()
                  }
                })
              }else{
                getInfoDetail(1)
              }
							//请求后增强
							btnClickAfterEnhance(btnData, res, obj)
						}).finally( ()=> {
              loading.value = false
            })
					} else if (btnData.serviceType == '60') {
						btnServerUrl(btnData.btnServerUrl, obj).then(res => {
              if(isSubmit==0) {
                ElMessage.success({
                  message: '操作成功',
                  duration: 500,
                  onClose: () => {
                    handleClose()
                  }
                })
              }else{
                getInfoDetail(1)
              }
							//请求后增强
							btnClickAfterEnhance(btnData, res, obj)
						}).finally( ()=> {
              loading.value = false
            })
					}
				} else {
					if (btnData.serviceType == '10') {
            loading.value = true
						saveForm(obj).then(res => {
              loading.value = false
              dataForm.id = res.data
              if(isSubmit==0) {
                ElMessage.success({
                  message: '保存成功',
                  duration: 500,
                  onClose: () => {
                    handleClose()
                  }
                })
              }else{
                getInfoDetail(1)
              }
							//请求后增强
							btnClickAfterEnhance(btnData, res, obj)
						}).finally( ()=> {
              loading.value = false
            })
					} else if (btnData.serviceType == '55') {
            loading.value = true
						defaultBtnServer(obj).then(res => {
              loading.value = false
              if(isSubmit==0){
                ElMessage.success({
                  message: '操作成功',
                  duration: 500,
                  onClose: () => {
                    handleClose()
                  }
                })
              }else{
                getInfoDetail(1)
              }

							//请求后增强
							btnClickAfterEnhance(btnData, res, obj)
						}).finally( ()=> {
              loading.value = false
            })
					} else if (btnData.serviceType == '60') {
            loading.value = true
						btnServerUrl(btnData.btnServerUrl, obj).then(res => {
              loading.value = false
              if(isSubmit==0) {
                ElMessage.success({
                  message: '操作成功',
                  duration: 500,
                  onClose: () => {
                    handleClose()
                  }
                })
              }else{
                getInfoDetail(1)
              }
							//请求后增强
							btnClickAfterEnhance(btnData, res, obj)
						}).finally( ()=> {
              loading.value = false
            })
					}
				}
			})
		})
		.catch(error => {
      loading.value = false
			ElMessage.error({
				message: error,
				duration: 500
			})
		})
}

/**
 * 按钮请求后增强
 * @param btnData
 * @param res
 */
const btnClickAfterEnhance = (btnData: any, res: any, reqData: any) => {
	if (btnData.btnClickAfterEnhance && btnData.btnClickAfterEnhance != '') {
		console.log(res)
		console.log(reqData)
		var enhance = decodeURIComponent(btnData.btnClickAfterEnhance)
		eval(enhance)
	}
}

const testOnAppendButtonClick = (sourceCall: any) => {
	dataForm.appendButtonClickCall.appendButtonClickBreakData = sourceCall.field.options.appendButtonClickBreakData
	dataForm.appendButtonClickCall.appendButtonClickBreakSetData = sourceCall.field.options.appendButtonClickBreakSetData
	dataForm.appendButtonClickCall.subFormRowIndex = sourceCall.subFormRowIndex
	dataForm.appendButtonClickCall.subFormName = sourceCall.subFormName
	reportDialogRef.value.init(sourceCall.field.options.appendButtonClickFormCode, sourceCall.btnQueryForm,sourceCall.field.options.checkMany)
}
const closeReportDialog = (isSearch: any) => {
	console.log('closeReportDialog')
}
const reportDialogAddData = (selectedData: any) => {
	console.log('选中的数据:', selectedData)
	//表单确认返回值
	var appendButtonClickBreakData = dataForm.appendButtonClickCall.appendButtonClickBreakData.split(',')
	//表示清除数据
	if (selectedData.length == 0) {
		var obj = {}
		for (var i = 0; i < appendButtonClickBreakData.length; i++) {
			obj[appendButtonClickBreakData[i]] = ''
		}
		selectedData.push(obj)
	}
	//表单确认返设值
	var appendButtonClickBreakSetData = dataForm.appendButtonClickCall.appendButtonClickBreakSetData.split(',')
	//子表
	if (dataForm.appendButtonClickCall.subFormName && dataForm.appendButtonClickCall.subFormName != '') {
		//表格绑定数据名称
		var appendButtonTableDataName = dataForm.appendButtonClickCall.subFormName
		//表格绑定数据行
		var appendButtonTableRowIndex = dataForm.appendButtonClickCall.subFormRowIndex
		if (appendButtonTableDataName && appendButtonTableDataName != null) {
			selectedData.forEach(item => {
				for (var i = 0; i < appendButtonClickBreakData.length; i++) {
					vFormRef.value.setSubFormDataByIndex(
						appendButtonTableDataName,
						appendButtonTableRowIndex,
						appendButtonClickBreakSetData[i],
						item[appendButtonClickBreakData[i]]
					)
				}
			})
		}
	} else {
		//表单
		selectedData.forEach(item => {
			for (var i = 0; i < appendButtonClickBreakData.length; i++) {
				vFormRef.value.setFieldValue(appendButtonClickBreakSetData[i], item[appendButtonClickBreakData[i]])
			}
		})
	}
	vFormRef.value.validateForm()

	closeReportDialog()
}
defineExpose({
	init
})
</script>
