<template>
  <common-drawer :mask="true" :mask-closable="true" :width="900" :visible="true" @close="close">
    <template #title>
      <template v-if="titleEdit">
        <a-input
          v-focus
          type="text"
          v-model:value="title"
          @blur="editTitle"
          @keydown.enter="editTitle"
          autofocus="autofocus"
          ref="titleInputRef"
        />
      </template>
      <template v-if="!titleEdit">
        <span style="cursor: pointer" @click="titleClick">{{ title }}</span>
        <span style="padding-left: 5px; cursor: pointer" @click="titleClick"><edit-outlined /></span>
      </template>
    </template>

    <template #footer>
      <a-button type="primary" @click="save" class="border-radius">确定</a-button>
    </template>
    <div class="approve-content" v-if="formData">
      <a-tabs v-model:activeKey="tabsActiveKey">
        <a-tab-pane forceRender key="1" tab="审批人">
          <ApproverUserSelect v-model:approverConfig="formData.approverConfig"/>
        </a-tab-pane>
        <a-tab-pane forceRender key="2" tab="审批策略">
          <ApproverStrategy v-model:approverJumpStrategy="formData.approverConfig.approverJumpStrategy" />
        </a-tab-pane>
        <a-tab-pane forceRender key="3" tab="操作权限">
          <FlowOperationPermissions :buttons="operationList" v-model:formData="formData.nodeButtonPermission" />
        </a-tab-pane>
        <a-tab-pane forceRender key="4" tab="表单权限">
          <FlowFormPermissions v-model:formPermission="formData.formPermission" @reset="resetFormPermission" />
        </a-tab-pane>
        <a-tab-pane forceRender key="5" tab="流程事件">
          <FlowEvent v-model:modelEventList="formData.nodeEventList" />
        </a-tab-pane>
        <a-tab-pane forceRender key="6" tab="通知提醒">
          <ApproverNotice v-model:nodeNotice="formData.nodeNotice" />
        </a-tab-pane>
      </a-tabs>
    </div>
  </common-drawer>
</template>

<script setup name="ApproveEventPanel">
import { onMounted, ref, computed } from 'vue';
import { useWorkflowStore } from '@/store/modules/workflow';
import loadNodeData from '../../../utils/utils';
import { FlowDesignApi } from '../../../../mid/workflow/design/api/FlowDesignApi';
import FlowEvent from './form/promoter/flow-event.vue';
import ApproverNotice from './form/approveEvent/approver-notice.vue';
import ApproverStrategy from './form/approveEvent/approver-strategy.vue';
import ApproverUserSelect from './form/approveEvent/approver-user-select.vue';
import FlowFormPermissions from './form/promoter/flow-form-permissions.vue';
import FlowOperationPermissions from './form/promoter/operation-permissions.vue';
import { message } from 'ant-design-vue/es';
import { getUUID } from '@/utils/common/util';

// 公共方法
const { getNodeData, setNodeData, node } = loadNodeData();

const emits = defineEmits(['close']);

// store
const workflowStore = useWorkflowStore();

// 绑定表单列表
const formDefinitionList = computed(() => {
  return workflowStore.flowGlobalConfig.formDefinitionList;
});

// 流程变量列表
const modelVariableList = computed(() => {
  return workflowStore.flowGlobalConfig.modelVariableList;
});

// 节点数据
const nodeData = ref({});
// 标题
const title = ref('');
// 标题输入框dom
const titleInputRef = ref(null);
// 是否编辑标题
const titleEdit = ref(false);
// 当前tab选中
const tabsActiveKey = ref('1');
// 操作列表
const operationList = ref([
  {
    field: 'agree',
    buttonName: '同意',
    aliasName: 'agreeAliasName',
    content: '审批节点同意该审核之操作，审批通过，可在我已办查看'
  },
  {
    field: 'refuse',
    buttonName: '拒绝',
    aliasName: 'refuseAliasName',
    content: '节点负责人可以拒绝该流程（拒绝后流程直接结束，标记为已拒绝）'
  },
  {
    field: 'copyTo',
    buttonName: '抄送',
    aliasName: 'copyToAliasName',
    content: '允许审批人进行抄送'
  },
  {
    field: 'handOver',
    buttonName: '转交',
    aliasName: 'handOverAliasName',
    content: '转交给他人办理，依然在当前节点'
  },
  {
    field: 'backTo',
    buttonName: '退回',
    aliasName: 'backToAliasName',
    content: '退回给申请人，申请人修改完成后，流程按节点开始走'
  },
  {
    field: 'retract',
    buttonName: '撤回',
    aliasName: 'retractAliasName',
    content: '允许申请人对未进入流程（第一个流程节点为待处理状态）的申请进行撤回'
  },
  {
    field: 'addSign',
    buttonName: '加签',
    aliasName: 'addSignAliasName',
    content: '这个事情我不能完全做主，需要某些人先处理，再右我处理'
  }
]);

// 审批人数据
const formData = ref(null);

// 当前节点的数据
const currentNodeData = ref(getNodeData());

// 事件动作配置列表
const actionClassList = ref([]);

/**
 * 修改标题
 */
const editTitle = () => {
  let getGraphNodeData = getNodeData();
  getGraphNodeData.data.nodeName = title.value;

  setNodeData(getGraphNodeData);
  // 关闭标题编辑框
  titleEdit.value = false;
};

// 标题点击
const titleClick = () => {
  titleEdit.value = true;
};

onMounted(() => {
  nodeData.value = JSON.parse(node.value.data);

  // 设置弹窗标题
  title.value = nodeData.value.data.nodeName;

  if (JSON.stringify(currentNodeData.value?.data?.nodeData) != '{}') {
    formData.value = Object.assign({}, currentNodeData.value.data.nodeData);
    // 主办
    if (formData.value?.approverConfig?.mainApprover) {
      setApproverData('mainApprover');
    }
    // 协办人员配置
    if (formData.value?.approverConfig?.assistantApprover) {
      setApproverData('assistantApprover');
    }
    // 读者
    if (formData.value?.approverConfig?.readerApprover) {
      setApproverData('readerApprover');
    }
    if (formData.value.formPermission?.length == 0) {
      getFormPermissionList();
    }
  } else {
    getFormPermissionList();
  }

  getActionClassList();
  setFormPermission();
});

// 设置审批人的值
const setApproverData = name => {
  if (!formData.value.approverConfig[name].nodeApproverCustom) {
    formData.value.approverConfig[name].nodeApproverCustom = {};
  }
  if (!formData.value.approverConfig[name].nodeApproverVariableList) {
    formData.value.approverConfig[name].nodeApproverVariableList = [];
  }
  if (!formData.value.approverConfig[name].approverType) {
    formData.value.approverConfig[name].approverType = 10;
  }
  if (
    formData.value.approverConfig[name].submitterSelfFlag === undefined ||
    formData.value.approverConfig[name].submitterSelfFlag === null
  ) {
    formData.value.approverConfig[name].submitterSelfFlag = false;
  }

  setId(formData.value.approverConfig[name].nodeApproverPersonList);
  setId(formData.value.approverConfig[name].nodeApproverPolicyList);
  setId(formData.value.approverConfig[name].nodeApproverPositionList);
  setId(formData.value.approverConfig[name].nodeApproverRoleList);
  setId(formData.value.approverConfig[name].nodeApproverFormList, 'form');
  setId(formData.value.approverConfig[name].nodeApproverVariableList, 'form');
};

// 设置id
const setId = (arr, flag = '') => {
  if (arr && arr.length > 0) {
    arr.forEach(async item => {
      item.id = getUUID();

      if (flag) {
        let data = formDefinitionList.value.find(fItem => fItem.formCode == item.formCode);
        item.fieldList = [];
        if (data) {
          const res = await FlowDesignApi.getFormFieldList({ formDefinitionId: data.formDefinitionId });
          item.fieldList = res.data;
        }
      }
    });
  }
};

// 获取表单权限列表
const getFormPermissionList = () => {
  if (formDefinitionList.value.length == 0) {
    formData.value.formPermission = [];
  } else if (formDefinitionList.value.find(item => item.formType == 1)) {
    // 应用表单
    let formDefinitionIdList = formDefinitionList.value.filter(item => item.formDefinitionId).map(item => item.formDefinitionId);
    FlowDesignApi.getFormPermissionList({ formDefinitionIdList: formDefinitionIdList }).then(res => {
      formData.value.formPermission = res.data;
    });
  } else if (formDefinitionList.value.find(item => item.formType == 2)) {
    // 自定义开发表单
    let fieldPermissionList =
      modelVariableList.value.map(item => {
        return {
          fieldCode: item.variableCode,
          fieldName: item.variableName,
          edit: false,
          hide: false,
          require: false,
          subTableFieldPermissionList: null
        };
      }) ?? [];

    formData.value.formPermission = [{ formName: formDefinitionList.value[0].formName, fieldPermissionList: fieldPermissionList }];
  }
};

// 设置表单权限是否全选
const setFormPermission = () => {
  if (formData.value.formPermission?.length) {
    formData.value.formPermission.forEach(item => {
      item.edit = item.fieldPermissionList.filter(item => item.edit == undefined || item.edit == false).length == 0 ? true : false;
      item.hide = item.fieldPermissionList.filter(item => item.hide == undefined || item.hide == false).length == 0 ? true : false;
      item.require = item.fieldPermissionList.filter(item => item.require == undefined || item.require == false).length == 0 ? true : false;
    });
  }
};

// 获取事件动作配置列表
const getActionClassList = async () => {
  actionClassList.value = await FlowDesignApi.listEventConsumers();
};

// 重新导入表单权限
const resetFormPermission = () => {
  getFormPermissionList();
  setFormPermission();
  message.success('更新成功');
};

/**
 * 关闭
 */
const close = () => {
  emits('close', false);
};

// 点击保存
const save = () => {
  let saveData = getNodeData();
  saveData.data.nodeData = formData.value;
  setNodeData(saveData);
  close();
};
</script>

<style scoped lang="less">
:deep(.ant-drawer-body) {
  padding: 15px;
}
.approve-content {
  width: 100%;
  height: 100%;
}
:deep(.ant-tabs) {
  width: 100%;
  height: 100%;
}
:deep(.ant-tabs-content-holder) {
  overflow-y: auto;
}
</style>
