<template>
  <div class="comp-content">
    <el-drawer
      v-model="visible"
      :size="400"
      title="审核状态"
      :close-on-click-modal="false"
      @close="closeFun"
    >
      <div v-if="modelValue" class="content">
        <iframe v-if="cidFlowId && cidTaskId && cidProcessInstanceId" class="iframe" :src="url" />
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import {
  systemQueryApproveInstanceApi,
  systemQueryNewApproveFlowStatusApi,
  systemQueryGetTaskIdByNodeIdApi,
} from '@/api/system/systemApprove';

const env = import.meta.env;

interface Props {
  modelValue: boolean;
  flowId: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  flowId: '',
});

const url = ref(`${env.VITE_API_CID_URL}/spdmApproval`);
const cidFlowId = ref('');
const cidTaskId = ref('');
const cidProcessInstanceId = ref('');

watch(
  () => props.modelValue,
  (val: boolean) => {
    visible.value = val;
    if (val) {
      getApproveDataFun();
    }
  }
);

const emit = defineEmits(['update:modelValue']);

const visible = ref(false);

const getApproveDataFun = () => {
  const params = {
    flowId: props.flowId,
  };
  systemQueryApproveInstanceApi(params).then((res: any) => {
    if (res.code === 200) {
      cidFlowId.value = res.data.templateId;
      cidProcessInstanceId.value = props.flowId;
      getNodeId();
    }
  });
};

const getNodeId = () => {
  const params = {
    flowId: props.flowId,
  };
  systemQueryNewApproveFlowStatusApi(params).then((res: any) => {
    if (res.code === 200) {
      const nodeId = res.data.find((item: any) => item.type === 1)?.id || '';
      getTaskIdFun(nodeId);
    }
  });
};

const getTaskIdFun = (nodeId: string) => {
  const params = {
    nodeId,
    processInstanceId: props.flowId,
  };
  systemQueryGetTaskIdByNodeIdApi(params).then((res: any) => {
    if (res.code === 200) {
      cidTaskId.value = res.data;
      url.value = `${env.VITE_API_CID_URL}/spdmApproval?flowId=${cidFlowId.value}&taskId=${cidTaskId.value}&processInstanceId=${cidProcessInstanceId.value}`;
    }
  });
};

const closeFun = () => {
  emit('update:modelValue', false);
};
</script>

<style lang="scss" scoped>
.comp-content {
  .content {
    width: 100%;
    height: 100%;
    .iframe {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
