import { message } from 'ant-design-vue';
import { FormType } from '/@/enums/workflowEnum';
import {
  FormConfigItem,
  FormSettingItem,
  TableItem,
  // TableItem
} from '/@/model/workflow/formSetting';
import {
  getCustomJson,
  getSystemJson,
  importWorkflowPermission,
} from '/@/utils/formSettings/formJson';
import { randomTime } from '/@bpmn/util/random';
import { updateFormFieldIdRelevance } from './useUpdateAllFormInfo';
import { getWorkflowPermissionConfig } from '/@/hooks/web/useWorkFlowForm';
export const visitorsBookType = 'opinion'; //意见簿类型
export const hiddenComponentType = 'hiddenComponent'; //隐藏组件类型
export const titleType = 'title'; //标题类型
export const dividerType = 'divider'; //分割线类型
export const infoType = 'info'; //信息体
export const autoCodeType = 'auto-code'; //编码
export const buttonType = 'button'; //按钮
// 标题，分割线、信息体，按钮，编码，意见簿，只允许查看权限
export const disableTypes = [
  visitorsBookType,
  titleType,
  dividerType,
  infoType,
  autoCodeType,
  'qrcode', //二维码组件
]; //表单字段仅仅只有查看权限
// 开关，滑块，颜色选择，评分，图片 组件权限中，必填权限为disable
export const requiredDisabled = [
  visitorsBookType,
  titleType,
  dividerType,
  infoType,
  autoCodeType,
  buttonType,
  'switch',
  'slider',
  'rate',
  'picker-color',
  'image',
];
export const doNotShowControl = ['qrcode', 'SunForm']; //表单设置不显示编辑和必填操作项的组件
export const doNotTypes = [visitorsBookType, titleType, dividerType, 'image', 'qrcode']; //不需要考虑的类型
export async function formPermissionList(list: Array<FormSettingItem>) {
  const returnList: Array<FormConfigItem> = [];
  if (list.length > 0) {
    for (let index = 0; index < list.length; index++) {
      const formConfig = await getFormConfig(list[index]);
      returnList.push(formConfig);
    }
  }
  return returnList;
}
export async function getFormConfig(item: {
  key?: string;
  formId: string;
  formName: string;
  formType: FormType;
  name?: string;
}) {
  const formId = item.formId;
  const formType = item.formType;
  const formName = item.formName;
  const name = item.name ? item.name : item.formName;
  const key = item.key ? item.key : 'form_' + item.formId + '_' + randomTime();
  const formConfig: FormConfigItem = {
    key,
    formType,
    formId,
    formName,
    name,
    showChildren: false,
    requiredAll: true,
    viewAll: true,
    editAll: true,
    children: [],
    type: '',
  };
  if (formType == FormType.CUSTOM) {
    const schema = await getSchemasList(formId, formType);
    if (schema && schema.length > 0) {
      formConfig.children = getWorkflowPermissionConfig(schema);
    }
  } else if (formType == FormType.SYSTEM) {
    const systemJson = await getSchemasList(formId, formType);
    try {
      const val = await importWorkflowPermission(systemJson.systemComponent);
      formConfig.children = val.permissionList;
    } catch (error) {
      //兼容旧系统表单
      const schema = await getSchemasList(formId, 1);
      if (schema && schema.length > 0) {
        formConfig.children = getWorkflowPermissionConfig(schema);
      }
    }
  }
  return formConfig;
}
// 删除表单：表单中字段被删除：删除已引用该表单数据字段的所有配置
function updateFormDataRelevance(
  oldData: FormConfigItem,
  oldChildMap: Map<string, FormConfigItem>,
  newData: FormConfigItem,
) {
  const formKey = oldData.key;
  const oldChild = oldData.children;
  const newChildMap = new Map();
  const newChild = newData?.children || [];
  if (newChild && Array.isArray(newChild)) {
    newChild.forEach((ele) => {
      if (ele?.children.length > 0) {
        ele.children.forEach((item) => {
          newChildMap.set(item.tableName + item.key, item);
        });
      }
      if (ele) newChildMap.set(ele.key, ele);
    });
  }

  // 旧表单的字段有，却在新表单中被上删除了，那么就要查找然后删除对应关联了
  if (oldChild && Array.isArray(oldChild)) {
    oldChild.forEach((oldItem) => {
      if (oldItem && oldChildMap.has(oldItem.key) && !newChildMap.has(oldItem.key)) {
        updateFormFieldIdRelevance(formKey, oldItem.key);
      }
      //子表不会被关联
      // if (newItem.children.length > 0) {
      // }
    });
  }
}
export function compareFormInfo(oldData: FormConfigItem, newData: FormConfigItem) {
  const oldChildMap = new Map();
  const oldChild = oldData.children;
  if (oldChild && Array.isArray(oldChild)) {
    oldChild.forEach((old) => {
      if (old.children.length > 0) {
        old.children.forEach((item) => {
          oldChildMap.set(item.tableName + item.key, item);
        });
      }
      oldChildMap.set(old.key, old);
    });
  }
  const newChild = newData.children;
  const children: Array<TableItem> = [];
  updateFormDataRelevance(oldData, oldChildMap, newData);
  if (newChild && Array.isArray(newChild)) {
    newChild.forEach((newItem) => {
      const tempChildren: Array<TableItem> = [];
      if (newItem.children.length > 0) {
        newItem.children.forEach((item) => {
          tempChildren.push(
            oldChildMap.has(item.tableName + item.key)
              ? changePermission(oldChildMap.get(item.tableName + item.key), item)
              : item,
          );
        });
      }
      newItem.children = tempChildren;
      newItem = oldChildMap.has(newItem.key)
        ? changePermission(oldChildMap.get(newItem.key), newItem)
        : newItem;
      children.push(newItem);
    });
  }
  newData.children = children;
  return newData;
}
function changePermission(old, newitem) {
  //置换权限，更新表单的时候新表单继续沿用旧表单权限
  newitem.required = old.required;
  newitem.view = old.view;
  newitem.edit = old.edit;
  return newitem;
}
export async function getSchemasList(formId: string, formType: FormType) {
  try {
    if (formType == FormType.CUSTOM) {
      const customJson: any = await getCustomJson(formId);
      if (customJson && customJson.schemas) {
        return customJson.schemas;
      }
    } else if (formType == FormType.SYSTEM) {
      const systemJson = await getSystemJson(formId);
      if (systemJson) {
        return systemJson;
      } else {
        message.error('读取系统表单失败');
        return [];
      }
    } else {
      return [];
    }
  } catch (error) {
    return [];
  }
}
