<template>
  <!-- 审批流程 -->
  <FlowInfo ref="flowInfoRef" :backUrl="state.backUrl"  :title="state.pageTitle" :data="data" v-if="state.visible">
    <block #footer>
      <view class="footer-box">
        <!-- 下一节点审批人 -->
          <ApproveUser v-if="nextTaskShow" :approveUserData="approveUserData" @submit="save" />
      </view>
      <ApprovalBtn
        :processId="data.processId"
        :taskId="data.taskId"
        :schemaId="data.item.id"
        :buttonConfigs="approvalData.buttonConfigs"
        :isAddOrSubSign="approvalData.isAddOrSubSign"
				:approvedContent="approvalData.approvedContent"
        :hasStamp="data.hasStamp"
        :hasStampPassword="data.hasStampPassword"
        @submit="submit"
      />
    </block>
  </FlowInfo>
</template>

<script setup>
import { ref, reactive } from "vue";
import FlowInfo from "./components/FlowInfo.vue"; //流程详情
import ApprovalBtn from "./components/ApprovalBtn.vue"; //审批按钮
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { getProcessInfo, postApproval,stagingProcess } from "@/common/api/workflow/index";
import ApproveUser from "./components/ApproveUser.vue"; // 下一节点审批人
import userTaskItem from "./hooks/userTaskItem";
import { separator } from '@/utils/simpleForm/analysis';
import { ApproveType } from "@/common/enums/workflow.ts";
import { useExclusiveApprovalProcess } from '@/common/hooks/useExclusiveApprovalProcess';

const title = "审批流程";
const state = reactive({
  visible: false,
  pageTitle: "",
  approvalContent: "",
  renderKey: 0,
  schemaId: "",
  stampList: [],
  backUrl:'/pages/workflow/index?type=todo',
});
const props = defineProps({
  processId: String,
  taskId: String,
  type: String,
  backUrl: String,
});
const nextTaskShow = ref(false);
const flowInfoRef = ref();
const { data, approveUserData, initProcessData } = userTaskItem();
let approvalData = reactive({
  isCountersign: false, //是否会签节点
  isAddOrSubSign: false, //是否加签减签
  buttonConfigs: [],
	approvedContent:''
});
const { handleOpenExclusiveApprovalProcess, handleCLoseExclusiveApprovalProcess } = useExclusiveApprovalProcess();
onLoad(async(options) => {
  state.searchKeyword = '';
  if(options&&options.taskId&&options.processId){
    try {
	  await handleOpenExclusiveApprovalProcess(options.taskId);
      let res = await getProcessInfo(options.taskId, options.processId);
		if(!res.data){
			setTimeout(()=>{
				uni.navigateBack({
				  delta: 1,
				});
			},1500)
		}
      initProcessData(res.data);
      if (res.data.buttonConfigs) {
        approvalData.buttonConfigs = res.data.buttonConfigs;
      }
      if (res.data.relationTasks) {
        data.predecessorTasks = res.data.relationTasks;
      }
      if (res.data.isAddOrSubSign) {
        approvalData.isAddOrSubSign = res.data.isAddOrSubSign;
      }
			if (res.data.isStaging && res.data.approveDto) {
				approvalData.approvedContent=res.data.approveDto.approvedContent
			}
      data.processId = options.processId;
      data.taskId = options.taskId;
      // state.pageTitle = title + data.item.name;
      state.pageTitle = title;
      if(options.backUrl !=undefined){
        state.backUrl = "";
      }
      state.visible = true;
    } catch (error) {
      console.log('error: ', error);
    }
    
  }
});
	
onUnload(async()=>{
	await handleCLoseExclusiveApprovalProcess();
})

async function submit(approvalBtnData) {
  let { approvalData: approvalData, stamp } = approvalBtnData; 
	if(approvalData.approvedType==ApproveType.STAGING){
		let formModels = await flowInfoRef.value.getFormModels();
		let fileFolderIds = getUploadFileFolderIds(formModels);
		let params = {
		  approvedType: approvalData.approvedType,
		  approvedResult: approvalData.approvedResult, // approvalData.approvedType 审批结果 如果为 4 就需要传buttonCode
		  approvedContent: approvalData.approvedContent,
		  formData: formModels,
		  rejectNodeActivityId: approvalData.rejectNodeActivityId,
		  taskId: data.taskId,
		  fileFolderIds,
		  circulateConfigs: approvalData.circulateConfigs,
		  stampId: stamp.stampId,
		  stampPassword: stamp.stampPassword,
		};
		let res= await stagingProcess(params)
		if (res.code == 0) {
		  save();
		} else {
		  uni.showToast({
		    icon: "none",
		    title: res.msg,
		  });
		}
		return;
	} 
  try {
    if (data.hasStamp && stamp.stampId == "") {
      uni.showToast({
        icon: "none",
        title: "必须选择签章",
      });
      return;
    }
    if (data.hasStampPassword && stamp.stampPassword == "") {
      uni.showToast({
        icon: "none",
        title: "必须填写签章密码",
      });
      return;
    }
    let validateForms = await flowInfoRef.value.validateForm();
    if (validateForms.length > 0) {
      let successValidate = validateForms.filter((ele) => {
        return ele.validate;
      });
      if (successValidate.length == validateForms.length) {
        let formModels = await flowInfoRef.value.getFormModels();
        let fileFolderIds = getUploadFileFolderIds(formModels);
        let params = {
          approvedType: approvalData.approvedType,
          approvedResult: approvalData.approvedResult, // approvalData.approvedType 审批结果 如果为 4 就需要传buttonCode
          approvedContent: approvalData.approvedContent,
          formData: formModels,
          rejectNodeActivityId: approvalData.rejectNodeActivityId,
          taskId: data.taskId,
          fileFolderIds,
          circulateConfigs: approvalData.circulateConfigs,
          stampId: stamp.stampId,
          stampPassword: stamp.stampPassword,
        };
        let postApprovalRes = await postApproval(params);
        // 下一节点审批人
        let taskList = [];
        if (postApprovalRes && postApprovalRes.data && postApprovalRes.data.length > 0) {
          taskList = postApprovalRes.data
            .filter((ele) => {
              return ele.isMultiInstance == false && ele.isAppoint == true;
            })
            .map((ele) => {
              return {
                taskId: ele.taskId,
                taskName: ele.taskName,
                provisionalApprover: ele.provisionalApprover,
                selectIds: [],
              };
            });
          if (taskList.length > 0) {
            approveUserData.list = taskList;
            approveUserData.schemaId = data.item.id;
            nextTaskShow.value =true;
          } else {
            save();
          }
        } else {
          if (postApprovalRes.code == 0) {
            save();
          } else {
            uni.showToast({
              icon: "none",
              title: postApprovalRes.msg,
            });
          }
        }
      } else {
        uni.showToast({
          icon: "none",
          title: "失败",
        });
      }
    }
  } catch (error) {
    uni.showToast({
      icon: "none",
      title: "失败",
    });
  }
}
function save() {
  uni.showToast({
    icon: "none",
    title: "成功",
  });
  if(state.backUrl==''){
      uni.navigateBack({
      delta: 1,
    });
  }else{
    uni.navigateTo({
		url: "/pages/workflow/index?type=todo"
	})
  }
  
}
function getUploadFileFolderIds(formModels) {
  let fileFolderIds = [];
  let uploadComponentIds = flowInfoRef.value.getUploadComponentIds();
  uploadComponentIds.forEach((ids) => {
    if (ids.includes(separator)) {
      let arr = ids.split(separator);
      if (arr.length == 2 && formModels[arr[0]][arr[1]]) {
        fileFolderIds.push(formModels[arr[0]][arr[1]]);
      } else if (
        arr.length == 3 &&
        formModels[arr[0]][arr[1]] &&
        Array.isArray(formModels[arr[0]][arr[1]])
      ) {
        formModels[arr[0]][arr[1]].forEach((o) => {
          fileFolderIds.push(o[arr[2]]);
        });
      }
    }
  });
  return fileFolderIds;
}
</script>

<style lang="scss" scoped>
.approval-box {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  font-weight: 400;
  font-style: normal;
  font-size: 12px;
  color: #02071a;
  line-height: 20px;
  z-index: 2;
  background-color: #fff;
  box-shadow: 5px -5px 8px hsla(0, 0%, 89.8%, 0.3);
}
.approval-content-box {
  padding: 14px;
  background-color: #fff;
}
.approval-content {
  background-color: #f5f6fa;
}
</style>
