<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="表单权限">
          <FlowFormPermissions v-model:formPermission="formData.formPermission" @reset="resetFormPermission" />
        </a-tab-pane>
        <a-tab-pane forceRender key="3" tab="通知提醒">
          <ApproverNotice v-model:nodeNotice="formData.nodeNotice" />
        </a-tab-pane>
      </a-tabs>
    </div>
  </common-drawer>
</template>

<script setup name="SendEventPanel">
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 ApproverNotice from './form/approveEvent/approver-notice.vue';
import ApproverUserSelect from './form/approveEvent/approver-user-select.vue';
import FlowFormPermissions from './form/promoter/flow-form-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 formData = ref(null);

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

/**
 * 修改标题
 */
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();
  }
  setFormPermission();
});

// 获取表单权限列表
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 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 && !item.nodeApproverCustom) {
        item.nodeApproverCustom = {};
      }

      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 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>
