<template>
  <view class="havedone-container">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      :title="uniNavBarTitle"
      background-color="#157A2C"
      color="#fff"
      @clickLeft="back"
    ></uni-nav-bar>
    <view v-if="processInstance.processDefinition">
      <taskForm
        id="async-biz-form-component"
        :taskId="listData.taskId"
        :businessId="listData.businessId"
        :id="listData.id"
        :taskDefinitionKey="listData.taskDefinitionKey"
        ref="bziRef"
      ></taskForm>
    </view>
    <view v-if="listData.type !='view'">
      <view v-for="(item, index) in runningTasks" :key="index">
        <div v-if="processInstance.processDefinition">
          <taskSubmit
            id="async-sub-form-component"
            :taskId="listData.taskId"
            :businessId="listData.businessId"
            :id="listData.id"
            :taskDefinitionKey="listData.taskDefinitionKey"
            @handleAudit="handleAudit"
            @getTableValue="getTableValue"
            ref="subForm"
          >
          </taskSubmit>
        </div>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import {
  getProcessInstance,
  getTaskListByProcessInstanceId,
} from "@/api/wt/index.js";
import taskForm from "./taskForm.vue";
import taskSubmit from "./taskSubmit.vue";

export default {
  name: "processTask",
  components: { taskForm, taskSubmit },
  data() {
    return {
      uniNavBarTitle: "",
      processInstanceLoading: false,
      listData: {},
      processInstance: {},
      runningTasks: [],
      auditForms: [],
    };
  },

  onLoad(option) {
    this.listData = option || {};
    this.getDetail();
  },

  methods: {
    async getDetail() {
      this.processInstanceLoading = true;
      this.runningTasks = [];
      this.auditForms = [];

      if (!this.listData.id) {
        this.processInstanceLoading = false;
        return;
      }

      try {
        const response = await getProcessInstance({
          id: this.listData.id,
        });
        if (!response) {
          uni.showToast({
            title: "查询不到流程信息",
            icon: "none",
            duration: 3000,
          });
          this.processInstanceLoading = false;
          return;
        }
        this.processInstance = response;
        this.uniNavBarTitle = `${response.name}`;
      } catch (err) {
        this.processInstanceLoading = false;
        uni.showModal({
          title: "getProcessInstance 失败",
          content: String((err && err.message) || err),
          showCancel: false,
        });
        return;
      }

      this.processInstanceLoading = false;

      try {
        const response = await getTaskListByProcessInstanceId({
          processInstanceId: this.listData.id,
        });
        if (!Array.isArray(response)) {
          uni.showModal({
            title: "任务列表格式异常",
            content: JSON.stringify({ raw: response }).slice(0, 1700),
            showCancel: false,
          });
          return;
        }

        this.tasks = [];
        response.forEach((task) => {
          if (task.result !== 4) {
            this.tasks.push(task);
          }
        });
        this.tasks.sort((a, b) => {
          if (a.endTime && b.endTime) {
            return b.endTime - a.endTime;
          } else if (a.endTime) {
            return 1;
          } else if (b.endTime) {
            return -1;
          } else {
            return b.createTime - a.createTime;
          }
        });

        const userInfo = uni.getStorageSync("userInfo") || {};
        const userId = userInfo.userId;

        this.tasks.forEach((task) => {
          if (task.result !== 1 && task.result !== 6) {
            return;
          }
          if (userId == null) {
            return;
          }
          if (!task.assigneeUser || task.assigneeUser.id !== userId) {
            return;
          }
          if (task.taskDefinitionKey !== this.listData.taskDefinitionKey) {
            return;
          }
          this.runningTasks.push({
            ...task,
          });
          this.auditForms.push({
            reason: "",
          });
        });
      } catch (err) {
        uni.showModal({
          title: "getTaskList 或解析失败",
          content: String((err && err.message) || err),
          showCancel: false,
        });
      }
    },

    handleAudit(data) {
      let text = data.status === 1 ? "通过" : "不通过";
      this.$refs.uToast.show({
        type: "success",
        message: `审批${data.title || text}成功！`,
        iconUrl: "https://cdn.uviewui.com/uview/demo/toast/success.png",
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    },
    getTableValue(fn) {
      fn(this.$refs.bziRef.getTableValue());
    },
  },
};
</script>

<style></style>
