<template>
  <a-modal
    :width="props.isBatch ? 600 : 750"
    :maskClosable="false"
    :visible="visible"
    :confirm-loading="loading"
    :forceRender="true"
    title="通过审批"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
    :class="props.isBatch ? '' : 'fix-modal'"
    @close="updateVisible(false)"
  >
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: props.isBatch ? 5 : 3 }">
      <FlowDrawerItem name="流程预测" v-show="form.nextNodeList && form.nextNodeList.length > 0">
        <NextNodeSelect v-model:form="form" ref="nextNodeSelectRef" />
      </FlowDrawerItem>
      <FlowDrawerItem name="审批意见">
        <a-form-item label="流程实例名称:" v-if="props.isBatch">
          <span>{{ getFlowName() }}</span>
        </a-form-item>
        <a-form-item label="快捷选项:" v-if="!props.isBatch">
          <a-select v-model:value="form.fastRemark" style="width: 500px" placeholder="请选择" @change="fastRemarkChange">
            <a-select-option :value="item.commentContent" v-for="item in remarkList" :key="item.id">{{
              item.commentContent
            }}</a-select-option>
          </a-select>
          <setting-filled style="margin-left: 5px; font-size: 18px; color: #999999; cursor: pointer" @click="fastRemarkSet" />
        </a-form-item>
        <a-form-item label="审批意见:" name="suggestContent">
          <a-textarea
            v-model:value="form.suggestContent"
            placeholder="请输入审批意见"
            :rows="4"
            :style="{ width: props.isBatch ? '100%' : '500px' }"
          />
        </a-form-item>
      </FlowDrawerItem>
    </a-form>

    <!-- 意见管理 -->
    <FastRemarkManage v-model:visible="showManage" v-if="showManage" :list="remarkList" @done="closeRemarkManage" />
  </a-modal>
</template>

<script setup name="AgreeOperate">
import { ref, onMounted, reactive, defineAsyncComponent } from 'vue';
import { FlowTaskApi } from '../../api/FlowTaskApi';
import { FlowRemarkApi } from '../../api/FlowRemarkApi';
import { message } from 'ant-design-vue';
import { deepClone } from '@/utils/common/util';

const FastRemarkManage = defineAsyncComponent(() => import('./fast-remark-manage.vue'));
const NextNodeSelect = defineAsyncComponent(() => import('../../../start/components/next-node-select.vue'));
const FlowDrawerItem = defineAsyncComponent(() => import('../../../../../../flow-design/layout/right/panel/common/FlowDrawerItem.vue'));

const props = defineProps({
  visible: Boolean,
  data: Array,
  // 是否是批量
  isBatch: {
    type: Boolean,
    default: true
  },
  // 表单数据
  saveformData: {
    type: Object,
    default: {}
  },
  definitionId: {
    type: String,
    default: ''
  }
});

const emits = defineEmits(['update:visible', 'done']);

// 弹框加载状态
const loading = ref(false);
// 表单数据
const form = ref({
  // 下一节点列表
  nextNodeList: [],
  fastRemark: null,
  suggestContent: ''
});
// 验证规则
const rules = reactive({
  suggestContent: [{ required: true, message: '请输入审批意见', type: 'string', trigger: 'blur' }]
});
// ref
const formRef = ref(null);
const nextNodeSelectRef = ref();

const showManage = ref(false);

const remarkList = ref([]);

onMounted(() => {
  if (props.isBatch) {
    form.value.agreeTaskIdList = props.data.map(item => item.id);
  } else {
    form.value.taskId = props.data[0].id;
    form.value.definitionId = props.definitionId;
    form.value.instanceVariable = {};

    if (props.saveformData.type == 'app') {
      form.value.instanceVariable.formData = props.saveformData.formData;
    } else if (props.saveformData.type == 'custom') {
      form.value.instanceVariable.customVueFormData = props.saveformData.formData;
    }
    getRemarkList();
    getRuntimeInstancePredict();
  }
});

// 获取下一节点列表
const getRuntimeInstancePredict = () => {
  FlowTaskApi.runtimeInstancePredict(form.value).then(res => {
    form.value.nextNodeList = res.data ?? [];
  });
};

const getRemarkList = async () => {
  remarkList.value = await FlowRemarkApi.flowUserCommentList();

  if (remarkList.value?.length > 0) {
    form.value.fastRemark = remarkList.value[0].commentContent;
    form.value.suggestContent = remarkList.value[0].commentContent;
  } 
};

// 切换弹框显示隐藏状态
const updateVisible = value => {
  emits('update:visible', value);
};

// 点击保存
const save = async () => {
  let params = deepClone(form.value);
  if (!props.isBatch) {
    let flagArr = [];
    form.value.nextNodeList.forEach(item => {
      if (item.approverNodeType == 10 && item.approverPersons && item.approverPersons.length > 1) {
        flagArr.push(true);
      } else {
        flagArr.push(false);
      }
    });
    if (flagArr.includes(true)) {
      return message.warning('单人活动只能有一个审批人');
    }
    await nextNodeSelectRef.value.$refs.formRef.validate();
    let pointNodeApproverUserId = {};
    Object.keys(form.value.nextNodeList).forEach(key => {
      pointNodeApproverUserId[form.value.nextNodeList[key].nextNodeId] = form.value.nextNodeList[key].approverPersons.map(item => item.id);
    });
    params.instanceVariable.pointNodeApproverUserId = pointNodeApproverUserId;
  }

  await formRef.value.validate();
  let result;
  if (props.isBatch) {
    result = FlowTaskApi.ruTaskBatchAgree(form.value);
  } else {
    result = FlowTaskApi.ruTaskAgree(params);
  }
  result.then(res => {
    if (res.code == '00000') {
      message.success(res.message);
      emits('update:visible', false);
      emits('done');
    }
  });
};

// 获取流程名称
const getFlowName = () => {
  let name = '';
  if (props.data && props.data.length > 0) {
    name = props.data.map(item => item.definitionIdWrapper.modelName).join(',');
  }
  return name;
};

// 快捷意见改变
const fastRemarkChange = val => {
  form.value.suggestContent = val;
};

const fastRemarkSet = () => {
  showManage.value = true;
};

const closeRemarkManage = data => {
  remarkList.value = data;
};
</script>

<style scoped></style>
