<template>
  <!-- 发起流程 -->
  <FlowInfo
    ref="flowInfoRef"
    :backUrl="state.backUrl"
    :workflowData="state.workflowData"
    :title="state.pageTitle"
    :data="data"
    v-if="state.visible"
  >
    <block #action> </block>
    <block #footer>
      <view class="footer-box">
        <!-- 下一节点审批人 -->
        <ApproveUser
          v-if="nextTaskShow"
          :approveUserData="approveUserData"
          @submit="save"
        />
      </view>
      <view class="next-btn" @tap="saveLaunch">
        <view class="submit-btn"><text>发起流程</text></view>
      </view>
      <view
        class="two-btn"
        v-if="data.predecessorTasks.length > 0 && data.item.id"
      >
        <view class="sign-btn">
          <view class="text-list">
            <RelationTaskBtn
              :launchId="data.item.id"
              :content="data.predecessorTasks"
              @submit="changePredecessorTasks"
          /></view>
        </view>
        <view class="submit-btn" @tap="saveLaunch"><text>发起流程</text></view>
      </view>
    </block>
  </FlowInfo>
</template>

<script setup>
import { reactive, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import FlowInfo from "./components/FlowInfo.vue"; //流程详情
import {
  getStartProcessInfo,
  postLaunch,
  getWithdrawTasks,
  getReStartProcessInfo,
  postReLaunch
} from "@/common/api/workflow/index";
import RelationTaskBtn from "./components/relationTask/RelationTaskBtn.vue"; //审批按钮
import ApproveUser from "./components/ApproveUser.vue"; // 下一节点审批人
import userTaskItem from "./hooks/userTaskItem";
import { separator } from "@/utils/simpleForm/analysis";
import { getFormExecuteWorkflow } from "@/common/api/system/dictionary/index.js";
const state = reactive({
  visible: false,
  pageTitle: "发起流程",
  approvalContent: "",
  renderKey: 0,
  schemaId: "",
  backUrl: "/pages/workflow/launchList",
  workflowData: { formId: "", data: {} },
  isWithdraw:false,
  processId:''
});
const props = defineProps({
  id: String,
  rowId: String,
  formId: String,
});
const nextTaskShow = ref(false);
const flowInfoRef = ref();
const { data, approveUserData, initProcessData } = userTaskItem();
onLoad(async (options) => {
  state.searchKeyword = "";
  state.processId = "";
  if (options && options.id) {
    state.schemaId = options.id;
    try {
      if (options.formId) {
		if(options.rowId){
		  state.workflowData.formId = options.formId;
		  let formExecuteRes = await getFormExecuteWorkflow(
			options.formId,
			options.rowId
		  );
		  let formExecuteData = formExecuteRes.data;
		  state.workflowData.data = formExecuteData;
		}
        state.backUrl = "";
      }
      // 发起流程
      let res = await getStartProcessInfo(options.id);
      initProcessData(res.data);

      state.visible = true;
    } catch (error) {}
  } else if (options.processId) {
    // processId 有此参数说明是重新发起
    state.processId = options.processId;
    
    if (options.isWithdraw=='1') {
      state.isWithdraw = true;
      //撤回
      let res = await getWithdrawTasks(options.taskId);
      initProcessData(res.data);
      state.schemaId =res.data.schemaInfo.id;
    } else {
      // 重新发起
      state.isWithdraw = false;
      let res = await getReStartProcessInfo(options.taskId, options.processId);
      initProcessData(res.data);
      state.schemaId =res.data.schemaInfo.id;
    }
    state.backUrl = '';
    state.visible = true;
  }
});
function changePredecessorTasks(list) {
  data.predecessorTasks = list;
  data.renderKey++;
}

async function saveLaunch() {
  try {
    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 relationTasks = [];
        if (data.predecessorTasks && data.predecessorTasks.length > 0) {
          relationTasks = data.predecessorTasks.map((ele) => {
            return { taskId: ele.taskId, schemaId: ele.schemaId };
          });
        }
        let fileFolderIds = getUploadFileFolderIds(formModels);
        //如果传入了processId  代表是重新发起流程
        let launchRes = null;
        if(state.processId){
          try {
            launchRes = await postReLaunch(
              state.processId,
              state.schemaId,
              formModels,
              relationTasks,
              fileFolderIds,
              state.isWithdraw,
            );
          } catch (error) {
            return false;
          }
        }else{
          launchRes = await postLaunch(
          state.schemaId,
          formModels,
          relationTasks,
          fileFolderIds
        );
        }
        if (launchRes&&launchRes.success&&launchRes.code===0) {
          let res = launchRes.data;
          // 下一节点审批人
          let taskList = [];
          if (res && res.length > 0) {
            taskList = res
              .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 = state.schemaId;
              nextTaskShow.value = true;
            } else {
              save();
            }
          } else {
            save();
          }
        } else {
          uni.showToast({
            icon: "none",
            title: launchRes.msg,
						duration:5000
          });
        }
      } 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/launchList",
    });
  }
}
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>
.two-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  height: 115rpx;
  background: #ffffff;
  .sign-btn {
    height: 77rpx;
    background: #f3f4f8;
    border-radius: 38rpx 38rpx 38rpx 38rpx;
    margin: 0 38rpx;
    .text-list {
      padding: 19rpx 105rpx;
      text {
        font-size: 27rpx;
        font-weight: bold;
        color: #b7baca;
        line-height: 32rpx;
      }
    }
  }
  .submit-btn {
    flex: 1;
    height: 77rpx;
    background: #5e95ff;
    border-radius: 38rpx 38rpx 38rpx 38rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 38rpx;
    text {
      font-size: 27rpx;
      font-weight: bold;
      color: #ffffff;
      line-height: 32rpx;
    }
  }
}
.next-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  height: 135rpx;
  background: #ffffff;
  padding: 0 38rpx;
  .submit-btn {
    flex: 1;
    height: 96rpx;
    background: #5e95ff;
    border-radius: 48rpx 48rpx 48rpx 48rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    text {
      font-size: 31rpx;
      font-weight: 500;
      color: #ffffff;
      line-height: 36rpx;
    }
  }
}
.footer-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);
}
</style>
