import { defHttp } from '/@/utils/http/axios';
import { local, session } from "/@/utils/Memory.js";
import type { ErrorMessageMode } from '/#/axios';
import md5 from 'js-md5';


enum Api {
    CallProvider = '/callProvider',
    Apply = '/base-center/resources/addResToCar',
    SelectUserRes = '/base-center/resources/selectUserRes',
    ClearUserResCar = '/base-center/resources/clearUserResCar',
    DeleteUserRes = '/base-center/resources/deleteUserRes',
    DeleteBussinfo = '/base-center/flow/deleteBussinfo'
}

const client = {
    grant_type: "password",
    scope: "all",
    client_id: "space",
    client_secret: 'e10adc3949ba59abbe56e057f20f883e',
}

const interfaceType = { apiUrl2: true };

/**
 * @description:获取地图资源列表
 */
export function list() {
    const formData = new FormData();
    formData.append("interfaceName", "antu.space.provider.sservicebase.ServiceBaseMetaDataViewProvider");
    formData.append("methodName", "getResourcePagedList");
    formData.append("args[]", session.getItem('token'));
    formData.append("args[]", '{ "type": "MR", "fields": { "DATA": ["serviceid", "servicename", "servicetype", "servicealiasname"], "METADATA": ["publisher ", "publishdate"] }, "pageIndex": 1, "pageSize": 4 }');
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: formData, ...interfaceType })
            .then((r) => {
                // resolve(JSON.parse(r.result));
                resolve({});
            })
    })
}

/**
 * @description:获取地图资源目录树结构
 */
export function directoryTree() {
    const f = new URLSearchParams();
    f.append("interfaceName", "antu.space.provider.sdatacatlog.SDataCatlogProvider");
    f.append("methodName", "findUserResourcesTree");
    f.append("args[]", session.getItem('tokenV2'));
    f.append("args[]", '981ad898-6fbc-758b-5048-a866f2af5e72');
    f.append("args[]", '{ "EMPLOYEE": "27AF004A-8BDN-885T-30FU-89DE3388762B", "ROLES": ["ed5e2ffa-bdfc-aeb7-89c7-70b593458207", "1F899E7A-748N-609T-99CU-3FCE7FBEA814", "090B70041E1EB211EA864C7C0ACCBF73", "BF03E5DD1C1EB211738485703976FFEE", "space"] }');
    f.append("args[]", false);
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: f, ...interfaceType })
            .then((r) => {
                resolve(r.result ? JSON.parse(r.result) : false);
            }).
            catch((e) => {
                reject(e);
            })
    })
}


/**
 * @description:获取服务预览图片
 */
export function img(id) {
    const f = new URLSearchParams();
    f.append("interfaceName", "antu.space.provider.servicemetadata.ServiceMetadataProvider");
    f.append("methodName", "findIconsByServiceIdList");
    f.append("args[]", session.getItem('tokenV2'));
    f.append("args[]", id);
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: f, ...interfaceType })
            .then((r) => {
                resolve(r.result ? JSON.parse(r.result) : false);
            }).
            catch((e) => {
                reject(e);
            })
    })
}

/**
 * @description:获取资源详情
 */
export function getResViewInfo(resId) {
    const f = new URLSearchParams();
    f.append("interfaceName", "antu.space.provider.sservicebase.ServiceBaseMetaDataViewProvider");
    f.append("methodName", "getResourceView");
    f.append("args[]", session.getItem('tokenV2'));
    f.append("args[]", resId);
    f.append("args[]", '{"EMPLOYEE":"27AF004A-8BDN-885T-30FU-89DE3388762B","ROLES":["ed5e2ffa-bdfc-aeb7-89c7-70b593458207","1F899E7A-748N-609T-99CU-3FCE7FBEA814","090B70041E1EB211EA864C7C0ACCBF73","BF03E5DD1C1EB211738485703976FFEE","space"]}');
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: f, ...interfaceType })
            .then((r) => {
                resolve(r.result ? JSON.parse(r.result) : false);
            }).
            catch((e) => {
                reject(e);
            })
    })
}

/**
 * @description:获取资源标签
 */
export function queryServiceTags() {
    const formData = new FormData();
    formData.append("interfaceName", "antu.space.provider.tags.TagsProvider");
    formData.append("methodName", "getAllByType");
    formData.append("args[]", session.getItem('tokenV2'));
    formData.append("args[]", '业务类型,服务专题,数据类型,年度');
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: formData, ...interfaceType })
            .then((r) => {
                let result = r.result === '' ? [] : JSON.parse(r.result)
                resolve(result);
            })
    })
}


/**
 * @description:获取地图资源列表
 */
export function platList(text) {
    console.log("获取地图资源列表请求参数:", text);
    let userInfo = session.getItem('userInfo')
    let rolesId = []
    userInfo.ROLES.forEach(item => { rolesId.push(item.ROLE_ID) })
    rolesId.push('space')
    let userParams = {
        EMPLOYEE: userInfo?.EMPLOYEE.EMPLOYEE_ID,
        ROLES: rolesId
    }
    const f = new URLSearchParams();
    f.append("interfaceName", "antu.space.provider.sservicebase.ServiceBaseMetaDataViewProvider");
    f.append("methodName", "getAllResourceByRootId");
    f.append("args[]", session.getItem('tokenV2'));
    // f.append("args[]", text || '981ad898-6fbc-758b-5048-a866f2af5e72');
    f.append("args[]", text?.id || '981ad898-6fbc-758b-5048-a866f2af5e72');
    f.append("args[]", JSON.stringify(userParams))
    f.append("args[]", `{"pagesize":${text?.pageSize || 12},"tag":"1","nodeId":"${text?.id || "981ad898-6fbc-758b-5048-a866f2af5e72"}",
    "MR":{"index":${text?.pageIndex || 0},"total":0,"filterField":"SERVICETYPE,SERVICENAME,DESCRIPTION,UPDATEDATE"},
    "SR":{"index":${text?.pageIndex || 0},"total":0,"filterField":"SERVICETYPE,SERVICENAME,DESCRIPTION,UPDATEDATE"},
    "ER":{"index":${text?.pageIndex || 0},"total":0,"filterField":"SERVICETYPE,SERVICENAME,DESCRIPTION,UPDATEDATE"},
    "DR":{"index":${text?.pageIndex || 0},"total":0,"filterField":"SERVICETYPE,SERVICENAME,DESCRIPTION,UPDATEDATE"},
    "DT":{"index":${text?.pageIndex || 0},"total":0,"filterField":"R_NAME,R_TABLENAME,COORDINATENAME,DATAFORMAT,CREATTIME"},
    "keywords":"${text?.keywords || ""}","sqkzt":"${text?.sqkzt || ""}","type":"all","isShowUnLinked":false,"text":"${text?.filterValue || ""}"}`);
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: f, ...interfaceType })
            .then((r) => {
                var oldList = [
                    { count: 0, keywords: '', type: "MR", typeName: "地图", items: [] },
                    { count: 0, keywords: '', type: "ER", typeName: "场景", items: [] },
                    { count: 0, keywords: '', type: "DR", typeName: "数据", items: [] },
                ]
                var list = r.result ? JSON.parse(r.result) : false;
                console.log("资源中心列表:", list)
                if (list?.length) {
                    if (list.length == 3) {
                        resolve(list);
                    } else {
                        oldList.forEach(i => { const item = list.find(j => i.type === j.type); if (item) Object.assign(i, item) });
                        resolve(oldList);
                    }
                } else {
                    resolve(oldList);
                }
            }).catch((e) => {
                reject(e);
            })
    })
}

/**
 * @description:根据目录ID获取地图资源列表
 * @description:改了之后这个没用了，直接在上面的接口传目录id获取
 */
export function platListByMenuId(id) {
    let userInfo = session.getItem('userInfo')
    let rolesId = []
    userInfo.ROLES.forEach(item => {
        rolesId.push(item.ROLE_ID)
    })
    rolesId.push('space')
    let userParams = {
        EMPLOYEE: userInfo?.EMPLOYEE.EMPLOYEE_ID,
        ROLES: rolesId
    }
    const f = new URLSearchParams();
    f.append("interfaceName", "antu.space.provider.sservicebase.ServiceBaseMetaDataViewProvider");
    f.append("methodName", "getResourceByDidWithSubInfo");
    f.append("args[]", session.getItem('tokenV2'));
    f.append("args[]", id);
    // f.append("args[]", '{"EMPLOYEE":"27AF004A-8BDN-885T-30FU-89DE3388762B","ROLES":["ed5e2ffa-bdfc-aeb7-89c7-70b593458207","1F899E7A-748N-609T-99CU-3FCE7FBEA814","090B70041E1EB211EA864C7C0ACCBF73","BF03E5DD1C1EB211738485703976FFEE","space"]}');
    f.append("args[]", JSON.stringify(userParams))
    f.append("args[]", `{"pagesize":12,"tag":"1","nodeId":"${id}",
    "MR":{"index":0,"total":0,"filterField":"SERVICETYPE,SERVICENAME,DESCRIPTION,UPDATEDATE"},
    "SR":{"index":0,"total":0,"filterField":"SERVICETYPE,SERVICENAME,DESCRIPTION,UPDATEDATE"},
    "ER":{"index":0,"total":0,"filterField":"SERVICETYPE,SERVICENAME,DESCRIPTION,UPDATEDATE"},
    "DR":{"index":0,"total":0,"filterField":"SERVICETYPE,SERVICENAME,DESCRIPTION,UPDATEDATE"},
    "DT":{"index":0,"total":0,"filterField":"R_NAME,R_TABLENAME,COORDINATENAME,DATAFORMAT,CREATTIME"},
    "keywords":"","type":"all","isShowUnLinked":false,"text":""}`);
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: f, ...interfaceType })
            .then((r) => {
                resolve(r.result ? JSON.parse(r.result) : false);
            }).
            catch((e) => {
                reject(e);
            })
    })
}

/**
 * @description:获取所有的标签
 */
export function tag() {
    const f = new URLSearchParams();
    f.append("interfaceName", "antu.space.provider.tags.TagsProvider");
    f.append("methodName", "getAll");
    f.append("args[]", session.getItem('tokenV2'));
    var obj = local.getItem("tagLabel");
    if (obj) {
        return new Promise<void>((resolve, reject) => {
            resolve(obj);
        })
    } else {
        return new Promise<void>((resolve, reject) => {
            defHttp.post({ url: Api.CallProvider, params: f, ...interfaceType })
                .then((r) => {
                    var obj = r.result ? JSON.parse(r.result) : false;
                    resolve(obj);
                    local.setItem("tagLabel", obj)
                }).
                catch((e) => {
                    reject(e);
                })
        })
    }
}

export const tagAjax = tag;

/**
 * @description:加入申请库
 */
export function apply(params) {
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.Apply, params, })
            .then((r) => {
                resolve(r);
            }).
            catch((e) => {
                reject(e);
            })
    })
}

/**
 * @description:查询已加入申请库的资源
 */
export function getResInCar(params) {
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.SelectUserRes, params })
            .then((r) => {
                resolve(r);
            }).
            catch((e) => {
                reject(e);
            })
    })
}

/**
 * @description:清空已加入申请库的资源
 */
export function clearResInCar(params) {
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.ClearUserResCar, params, })
            .then((r) => {
                resolve(r);
            }).
            catch((e) => {
                reject(e);
            })
    })
}

/**
 * @description:移除已加入申请库的资源
 */
export async function deleteResInCar(params, obj) {
    console.log("移除已加入申请库的资源:", obj);
    var res = true;
    if (obj.shzt == "审核不通过") {
        res = await deleteBussinfo({ id: obj.resInCarId })
    }
    if (res) {
        return new Promise<void>((resolve, reject) => {
            defHttp.post({ url: Api.DeleteUserRes, params, })
                .then((r) => {
                    resolve(r);
                }).
                catch((e) => {
                    reject(e);
                })
        })
    }
}

/**
 * @description:删除审核业务信息
 */
export function deleteBussinfo(params) {
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.DeleteBussinfo, params, })
            .then((r) => {
                resolve(true);
            }).
            catch((e) => {
                reject(false);
            })
    })
}

