export const information = {
    debug: false,
    // baseUrl: '',
    baseUrl: 'http://127.0.0.1:20080',
    title: '可信供给中心',
}

export function useAmis(amisObject) {
    document.title = information.title
    let amis = amisRequire('amis/embed')
    let struct = amisObject(information)
    if (information.debug) {
        console.log(struct)
    }
    amis.embed(
        '#app',
        struct,
        {
            data: {
                debug: information.debug,
                base: information.baseUrl,
            },
        },
        {
            theme: 'antd',
            enableAMISDebug: information.debug,
        }
    )
}

export function crudCommonOptions() {
    return {
        affixHeader: false,
        stopAutoRefreshWhenModalIsOpen: true,
        resizable: false,
        syncLocation: false,
        silentPolling: true,
    }
}

export function readOnlyDialogOptions() {
    return {
        actions: [],
        showCloseButton: false,
        closeOnEsc: true,
        closeOnOutside: true,
        disabled: true,
    }
}

export function horizontalFormOptions() {
    return {
        mode: 'horizontal',
        canAccessSuperData: false,
        horizontal: {
            left: 3,
        },
    }
}

export function paginationCommonOptions(perPage = true, maxButtons = 5) {
    let option = {
        type: 'pagination',
        layout: [
            'pager'
        ],
        maxButtons: maxButtons,
        showPageInput: false,
        perPageAvailable: [10, 15, 20, 50, 100, 200],
    }
    if (perPage) {
        option.layout.push('perPage')
    }
    return option
}

export function paginationTemplate(perPage = 20, maxButtons = 5) {
    return {
        perPage: perPage,
        headerToolbar: [
            "reload",
            paginationCommonOptions(true, maxButtons),
        ],
        footerToolbar: [
            "statistics",
            paginationCommonOptions(true, maxButtons),
        ],
    }
}

export const size5MB = 5242880
export const size100MB = 104857600
export const size500MB = 524288000
export const size1GB = 1073741824

export function inputFileFormItemCommonOptions(accept = '*', maxSize = size5MB) {
    return {
        useChunk: true,
        accept: accept,
        maxSize: maxSize,
        autoUpload: false,
        drag: true,
        startChunkApi: apiPost('${base}/upload/start'),
        chunkApi: apiPost('${base}/upload/slice'),
        finishChunkApi: apiPost('${base}/upload/finish'),
    }
}

/**
 * @param {string} field
 * @param {string} label
 * @param {string} tips
 * @param {number} ignoreLength
 * @param {{}} extra
 */
export function copyField(field, label, tips = '复制', ignoreLength = 0, extra = undefined) {
    let tpl = ignoreLength === 0 ? `\${${field}}` : `\${TRUNCATE(${field}, ${ignoreLength})}`
    let content = extra
        ? {
            type: 'action',
            level: 'link',
            label: `\${${field}}`,
            className: 'text-current underline',
            size: 'xs',
            ...extra,
        }
        : {
            type: 'tpl',
            className: 'mr-1',
            tpl: tpl,
        }
    return {
        name: field,
        label: label,
        type: 'wrapper',
        size: 'none',
        className: 'nowrap',
        body: [
            content,
            {
                type: 'action',
                level: 'link',
                label: '',
                icon: 'fa fa-copy',
                size: 'xs',
                actionType: 'copy',
                content: `\$${field}`,
                tooltip: `${tips}`,
            },
        ]
    }
}

/**
 * @param {string} label
 * @param {number} width
 * @param {Array} buttons
 */
export function operationField(label, width = 100, buttons = []) {
    return {
        label: label,
        width: width,
        type: 'operation',
        fixed: 'right',
        className: 'nowrap',
        buttons: buttons,
    }
}

/**
 * @param {string} field
 * @param {string} label
 * @param {number} width
 */
export function timeField(field, label, width = 150) {
    return {
        label: label,
        width: width,
        align: 'center',
        type: 'tpl',
        tpl: `\${IF(${field}, DATETOSTR(${field}), '-')}`
    }
}

export function stringWrapField(field, label, width = undefined) {
    return stringField(field, label, width, true)
}

/**
 * @param {string} field
 * @param {string} label
 * @param {number} width
 * @param {boolean} wrap
 */
export function stringField(field, label, width = undefined, wrap = false) {
    let data = {
        name: field,
        label: label,
    }
    if (width) {
        data['width'] = width
    }
    if (!wrap) {
        data['className'] = 'nowrap'
    }
    return data
}

/**
 * @param {string} field
 * @param {string} label
 * @param {[{label: *, value: *, color: string}]} mapping
 * @param {number} width
 */
export function mappingField(field, label, mapping, width = 80) {
    let mapData = {
        '*': `<span class='label bg-gray-300'>\${${field}}</span>`,
    }
    mapping.forEach(item => {
        mapData[item['value']] = `<span class='label ${item['color']}'>${item['label']}</span>`
    })
    return {
        label: label,
        type: 'mapping',
        width: width,
        value: `\${${field}}`,
        align: 'center',
        map: mapData,
    }
}

function mappingItem(label, value, color = 'bg-info') {
    return {
        label: label,
        value: value,
        color: color,
    }
}

export const userRoleMapping = [
    mappingItem('数据提供方', 'PROVIDER', 'bg-blue-500'),
    mappingItem('数据使用方', 'CUSTOMER', 'bg-purple-500'),
    mappingItem('审核监管方', 'CHECKER', 'bg-cyan-500'),
    mappingItem('系统管理员', 'ADMINISTRATOR', 'bg-green-500'),
]

export const userStateMapping = [
    mappingItem('审查中', 'CHECKING', 'bg-warning'),
    mappingItem('正常', 'NORMAL', 'bg-success'),
    mappingItem('禁用', 'DISABLED', 'bg-danger'),
]

export const permissionStateMapping = [
    mappingItem('未确权', 'NONE'),
    mappingItem('草稿', 'DRAFT', 'bg-primary'),
    mappingItem('审查中', 'CHECKING', 'bg-warning'),
    mappingItem('用户审查中', 'OWNER_CHECKING', 'bg-warning'),
    mappingItem('通过', 'NORMAL', 'bg-success'),
    mappingItem('驳回', 'REJECT', 'bg-danger'),
]

export const checkTypeMapping = [
    mappingItem('确权审查', 'CONFIRMATION', 'bg-blue-500'),
    mappingItem('授权审查', 'AUTHENTICATION', 'bg-purple-500'),
    mappingItem('上架审查', 'MARKET', 'bg-green-500'),
]

export const checkOverMapping = [
    mappingItem('进行中', 'CHECKING', 'bg-warning'),
    mappingItem('已撤销', 'RETRACT', 'bg-primary'),
    mappingItem('已办结', 'OVER', 'bg-success'),
]

function api(method, url) {
    return {
        method: method,
        url: url,
        headers: {
            token: '${token|default:undefined}',
        }
    }
}

export function apiGet(url) {
    return api('get', url)
}

export function apiPost(url) {
    return api('post', url)
}

export function arrayInCheck(array, field) {
    return `\${ARRAYINCLUDES(['${array.join("','")}'], ${field})}`
}

export function arrayOutCheck(array, field) {
    return `\${!ARRAYINCLUDES(['${array.join("','")}'], ${field})}`
}

export const checkState = {
    none: 'NONE',
    draft: 'DRAFT',
    checking: 'CHECKING',
    ownerChecking: 'OWNER_CHECKING',
    normal: 'NORMAL',
}

export function roleCheck(roles) {
    return `\${ARRAYINCLUDES(['${roles.join("','")}'], role)}`
}

export const role = {
    administrator: 'ADMINISTRATOR',
    checker: 'CHECKER',
    provider: 'PROVIDER',
    customer: 'CUSTOMER',
}

export const administratorOnly = roleCheck([role.administrator])
export const checkerOnly = roleCheck([role.administrator, role.checker])
export const userOnly = roleCheck([role.administrator, role.provider, role.customer])
export const providerOnly = roleCheck([role.administrator, role.provider])
export const customerOnly = roleCheck([role.administrator, role.customer])


export const formInputClearable = {
    clearable: true,
    clearValueOnEmpty: true,
}

const formInputFileStaticColumns = [
    {
        name: 'filename',
        label: '文件名',
    },
    {
        type: 'operation',
        label: '操作',
        width: 140,
        buttons: [
            {
                type: 'action',
                label: '预览',
                level: 'link',
                icon: 'fas fa-eye'
            },
            {
                type: 'action',
                label: '下载',
                level: 'link',
                icon: 'fa fa-download',
                actionType: 'ajax',
                api: {
                    ...apiGet('${base}/upload/download/${id}'),
                    responseType: 'blob',
                }
            }
        ]
    }
]

export function formInputSingleFileStatic(field, label) {
    return {
        visibleOn: '${detail}',
        type: 'control',
        label: label,
        required: true,
        body: {
            type: 'table',
            source: `\${${field}|asArray}`,
            columns: formInputFileStaticColumns,
        }
    }
}

export function formInputMultiFileStatic(field, label) {
    return {
        visibleOn: '${detail}',
        type: 'input-table',
        label: label,
        name: field,
        required: true,
        resizable: false,
        columns: formInputFileStaticColumns,
    }
}

export function formCreatedUserAndModifiedUser() {
    return [
        {
            type: 'group',
            body: [
                {
                    type: 'input-text',
                    name: 'createdUsername',
                    label: '创建人',
                },
                {
                    type: 'input-datetime',
                    name: 'createdTime',
                    label: '创建时间',
                },
            ]
        },
        {
            type: 'group',
            body: [
                {
                    type: 'input-text',
                    name: 'modifiedUsername',
                    label: '最后修改人',
                },
                {
                    type: 'input-datetime',
                    name: 'modifiedTime',
                    label: '最后修改时间',
                },
            ]
        },
    ]
}
