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

enum Api {
    CallProvider = '/callProvider',
    Update = '/datastore/file/uploadFile/1fcf0fc166206ceb7f2780302ec8f854',
    Download = '/datastore/file/download',
    SelectUserRes = '/base-center/resources/selectUserRes',

}

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

const interfaceType = { apiUrl2: true };

export function list(params) {
    const formData = new FormData();
    formData.append("interfaceName", "antu.space.provider.sservicebase.ServiceBaseMetaDataViewProvider");
    formData.append("methodName", "getResourcePagedList");//getResourcePagedList
    formData.append("args[]", session.getItem('tokenV2'));

    var obj = {
        type: params.type,
        pageIndex: 1,//params.page,
        pageSize: 1000 || params.pageSize,
        // userid: session.getItem('userId')
    }
    if (params.filterValue) obj.filterValue = params.filterValue;
    if (params.status != null && params.status != undefined && params.status != 7) {
        obj.status = params.status;
    }

    formData.append("args[]", JSON.stringify(obj));
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: formData, ...interfaceType })
            .then((r) => {
                let result = r.result === '' ? [] : JSON.parse(r.result)
                if (result?.items) {
                    result.items.forEach((item, index) => {
                        item['xh'] = index + 1
                    })
                }
                console.log("审核资源列表:", result)
                resolve(result);
            })
    })
}

/**
 * @description:获取组件资源列表
 */
export function list2(text) {
    const formData = new FormData();
    var str = '';
    if (text && (text.source || text.servicename || text.status)) {
        delete text.pageSize;
        delete text.page;
        str = {
            'type': 'SR',
            'servicetype': 'WidgetService',
            "status": text.status,
            'filterValue': text.servicename
        }
        str = JSON.stringify(str);
    } else {
        str = `{ 'type': 'SR', 'servicetype': 'WidgetService'}`
    }
    listPage(text);
    formData.append("interfaceName", "antu.space.provider.sservicebase.ServiceBaseMetaDataViewProvider");
    formData.append("methodName", "getResourceList2");
    formData.append("args[]", session.getItem('tokenV2'));
    formData.append("args[]", str);
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: formData, ...interfaceType })
            .then((r) => {
                var e = r.result ? JSON.parse(r.result) : [];
                console.log("获取组件资源列表:", e);
                resolve(e);
            })
    })
}


/**
 * @description:获取审核通过的是否加入申请库
 */
export function listApproved2(text: any) {
    const formData = new FormData();
    formData.append("interfaceName", "antu.space.provider.sservicebase.ServiceBaseMetaDataViewProvider");
    formData.append("methodName", "getRSResourceList");
    formData.append("args[]", session.getItem('tokenV2'));
    formData.append("args[]", `{"pagesize":10000,"tag":"1","userid":"${session.getItem('userId')}","SR":{"index":0,"total":0,"filterField":"SERVICETYPE,SERVICENAME,DESCRIPTION,UPDATEDATE"},"keywords":"${text && text.key || ''}","type":"SR","isShowUnLinked":true,"text":""}`);
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: formData, ...interfaceType })
            .then((r) => {
                var e = r.result ? JSON.parse(r.result) : [];
                resolve(e.items);
            })
    })
}
/**
 * @description:获取审核通过的组件
 */
export async function listApproved(text) {
    var info = await listApproved2()
    const formData = new FormData();
    var str = `{ 'type': 'SR','servicetype': 'WidgetService','filterValue':'${text.filterValue || ''}','sqkzt':'${text.sqkzt || ''}','userid': '${session.getItem("userId")}'}`

    //sqkzt
    formData.append("interfaceName", "antu.space.provider.sservicebase.ServiceBaseMetaDataViewProvider");
    formData.append("methodName", "getResourceList2");
    formData.append("args[]", session.getItem('tokenV2'));
    // formData.append("args[]", JSON.stringify(str));
    formData.append("args[]", str);
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: formData, ...interfaceType })
            .then((r) => {
                var e = r.result ? JSON.parse(r.result) : [];

                if (info) {
                    for (var i = 0; i < e.length; i++) {
                        for (var j = 0; j < info.length; j++) {
                            if (e[i].serviceid == info[j].SERVICEID) {
                                e[i].SFJRSQK = info[j].SFJRSQK;
                            }
                        }
                    }
                    e.map(i => {
                        if (!i.SFJRSQK) i.SFJRSQK = '未加入';
                        for (let key in i) {
                            if (i.hasOwnProperty(key)) {
                                const lowercaseKey = key.toLowerCase();
                                i[lowercaseKey] = i[key];
                            }
                        }
                    })
                }
                console.log("组件服务列表:", e)
                resolve(e);
            })
    })
}

/**
 * @description:查询已经加入到申请库中的组件
 */
export function getAssemblyLibs(params) {
    params.userId = session.getItem('userId');
    if (params.sqsj) {
        var o = JSON.parse(JSON.stringify(params.sqsj));
        params.sqsj = o[0];
        params.endSqsj = o[1];
    }
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.SelectUserRes, params, })
            .then((res) => {
                if (res?.datas?.length) {
                    var list = res.datas.filter(i => i.applyCarInfo.workflowType === 'ASSEMBLY');
                    list.map(i => i.id = i.resInfo.SERVICEID)
                    console.log("申请库中的组件", list)
                    resolve(list);
                } else {
                    resolve([])
                }
            }).
            catch((e) => {
                reject(e);
            })
    })
}

/**
 * @description:查询已经加入到申请库中的组件
 */
export function getAssemblyLibsTotal() {
    var params = {
        page: 1,
        pageSize: 1000000,
        userId: session.getItem('userId')
    }
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.SelectUserRes, params })
            .then((res) => {
                if (res?.datas?.length) {
                    var list = res.datas.filter(i => i.applyCarInfo.workflowType === 'ASSEMBLY');
                    resolve(list.length);
                } else {
                    resolve(0)
                }
            }).catch((e) => {
                reject(e);
            })
    })
}

/**
 * @description:获取资源类型字典
 */
export function getServiceTypes() {
    const formData = new FormData();
    formData.append("interfaceName", "antu.space.provider.sservicebase.SServicebaseProvider");
    formData.append("methodName", "getSServiceTypes");
    formData.append("args[]", session.getItem('tokenV2'));
    formData.append("args[]", '{"abbreviation":"MR","pid":"MapResource"}');
    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 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 queryDicsByName(name) {
    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[]", name);
    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 queryCoors() {
    const formData = new FormData();
    formData.append("interfaceName", "antu.space.provider.geomname.GeomNameCDProvider");
    formData.append("methodName", "getGeomNameList");
    formData.append("args[]", session.getItem('tokenV2'));
    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 insertService(params) {
    if (!params) return
    params.servicebase.appid = "CBEC5C04E50E4088AB9D343314912674";
    params.servicebase.servicetype = 'WidgetService';
    params.metadata.servicetype = 'WidgetService';
    const str = JSON.stringify([params])
    const formData = new URLSearchParams();
    formData.append("interfaceName", "antu.space.provider.sservicebase.ServiceBaseMetaDataViewProvider");
    formData.append("methodName", "insertList");
    formData.append("args[]", session.getItem('tokenV2'));
    formData.append("args[]", str)
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: formData, ...interfaceType })
            .then((r) => {
                resolve(r);
            })
    })
}
/**
 * @description:修改组件资源
 */
export function updateService(params) {
    if (!params) return
    params.servicebase.appid = "CBEC5C04E50E4088AB9D343314912674";
    params.servicebase.servicetype = 'WidgetService';
    params.metadata.servicetype = 'WidgetService';
    const str = JSON.stringify(params)
    const formData = new URLSearchParams();
    formData.append("interfaceName", "antu.space.provider.sservicebase.ServiceBaseMetaDataViewProvider");
    formData.append("methodName", "update");
    formData.append("args[]", session.getItem('tokenV2'));
    formData.append("args[]", str)
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: formData, ...interfaceType })
            .then((r) => {
                resolve(r);
            })
    })
}



/**
 * @description:删除组件资源
 */
export function deleteService(param) {
    if (!param) return
    const formData = new FormData();
    formData.append("interfaceName", "antu.space.provider.sservicebase.ServiceBaseMetaDataViewProvider");
    formData.append("methodName", "delete");
    formData.append("args[]", session.getItem('tokenV2'));
    formData.append("args[]", param)
    return new Promise<void>((resolve, reject) => {
        defHttp.post({ url: Api.CallProvider, params: formData, ...interfaceType })
            .then((r) => {
                resolve(r);
            })
    })
}


/**
 * @description:文件资源上传
 */
export function update(param, id) {
    return new Promise<void>((resolve, reject) => {
        defHttp.post({
            url: Api.Update,
            params: param,
            headers: {
                bucketId: id,
            }
        })
            .then((r) => {
                resolve(r);
            }).catch(e => {
                resolve()
            })
    })
}

/**
 * @description:文件资源上传
 */
export function getImgUrl(id, pid) {
    var data = local.getItem(id + pid);
    if (data) {
        return new Promise<void>((resolve, reject) => {
            resolve(data);
        })
    } else {
        return new Promise<void>((resolve, reject) => {
            try {
                defHttp.post({
                    url: Api.Download,
                    params: {
                        objs: [{ id: id, objType: "FILE", userId: "" }],
                        parentId: pid
                    },
                })
                    .then((r) => {
                        if (r && r.resp_code == 0 && r.resp_msg == "OK") {
                            resolve(r.datas[0].url);
                            local.setItem(id + pid, r.datas[0].url);
                        } else {
                            resolve()
                        }
                    }).catch(e => {
                        resolve()
                    })
            } catch (error) {
                resolve()
            }
        })
    }
}