Vue.use(window["vue-dash-event"]);
moment.locale("zh_cn");
window.onload = function() {
    var vm = new Vue({
        el: "#app",
        data: function() {
            return {
                account: "",
                passWord: "",
                startValue: null,
                endValue: null,
                endOpen: false,
                columns: [
                    {
                        title: "日志追踪ID",
                        dataIndex: "Id",
                        key: "id",
                        width: 380,
                        // fixed: 'left',
                    },
                    // {
                    //     title: '父追踪ID',
                    //     dataIndex: 'ParentTraceID',
                    //     key: 'parentTraceID',
                    //     width: 200,
                    // },
                    //{
                    //    title: '系统ID',
                    //    dataIndex: 'SystemID',
                    //    key: 'systemID',
                    //    width: 200,

                    //},
                    {
                        title: "接口名称",
                        dataIndex: "ApiName",
                        key: "apiName",
                        width: 200,
                    },
                    {
                        title: "客户端的域名或IP",
                        dataIndex: "ClientHost",
                        key: "clientHost",
                        width: 200,
                    },
                    {
                        title: "服务器的域名或IP",
                        dataIndex: "ServerHost",
                        key: "serverHost",
                        width: 200,
                        // scopedSlots: {
                        //     customRender: 'serverHost'
                        // },
                    },
                    // {
                    //     title: '等级ID（从1开始）',
                    //     dataIndex: 'Level',
                    //     key: 'level',
                    //     width: 200,
                    // },
                    {
                        title: "请求时间",
                        dataIndex: "RequestTime",
                        key: "requestTime",
                        width: 200,
                    },
                    {
                        title: "响应时间",
                        dataIndex: "ResponseTime",
                        key: "responseTime",
                        width: 200,
                    },
                    {
                        title: "请求耗时(毫秒)",
                        dataIndex: "TimeCost",
                        key: "timeCost",
                        width: 200,
                    },
                    // {
                    //     title: '请求内容',
                    //     dataIndex: 'RequestBody',
                    //     key: 'requestBody',
                    //     width: 200,
                    // },
                    //  {
                    //     title: '响应内容',
                    //     dataIndex: 'ResponseBody',
                    //     key: 'responseBody',
                    //     scopedSlots: {
                    //         customRender: 'responseBody'
                    //     },
                    //     width: 200,
                    // }, 
                    // {
                    //     title: '错误内容',
                    //     dataIndex: 'ErrorBody',
                    //     key: 'errorBody',
                    //     scopedSlots: {
                    //         customRender: 'errorBody'
                    //     },
                    //     width: 200,
                    // }, 
                    // {
                    //     title: '请求头',
                    //     dataIndex: 'Headers',
                    //     key: 'headers',
                    //     scopedSlots: {
                    //         customRender: 'headers'
                    //     },
                    //     width: 200,
                    // }, 
                    {
                        title: "是否报错",
                        dataIndex: "IsError",
                        key: "isError",
                        width: 110,
                    },
                    // {
                    //     title: '操作',
                    //     key: 'x',
                    //     width: 100,
                    //     scopedSlots: {
                    //         customRender: 'action'
                    //     }
                    // },
                ],
                data: [],
                current: 1,
                total: 10,
                pageSize: 10,
                pageSizeOptions: ["5", "10", "20", "30", "40", "50"],
                clientId: null,
                domainUrl: config.apiHost,
                apiNameList: [],
                apiName: undefined,
                isErr: undefined,
                visible: false,
                jsonData: {},
                loading: false,
            };
        },
        components: {
            jsonView: window["vue-json-view"].default
        },
        computed: {
            locale: function() {
                const locales = window.antd.locales;
                return locales.zh_CN;
            },
        },
        created() {
            let _clientId = localStorage.getItem("ocr-clientId");
            let _token = localStorage.getItem("ocr-token");
            if (_clientId) {
                this.clientId = _clientId;
            }
            if (_token) {
                this.getApiLogsPageList();
                this.getAllApiName();
            } else {
                window.location.href = "login.html";
            }
        },
        methods: {
            disabledStartDate: function(startValue) {

                const endValue = this.endValue;
                if (!startValue || !endValue) {
                    return false;
                }
                return startValue.valueOf() > endValue.valueOf();
            },
            disabledEndDate: function(endValue) {

                const startValue = this.startValue;
                if (!endValue || !startValue) {
                    return false;
                }
                return startValue.valueOf() >= endValue.valueOf();
            },
            handleStartOpenChange: function(open) {
                if (!open) {
                    this.endOpen = true;
                }
            },
            handleEndOpenChange: function(open) {
                this.endOpen = open;
                console.log(this.endOpen);
            },
            onShowSizeChange: function(current, pageSize) {
                console.log(current, pageSize);
                this.current = current;
                this.pageSize = pageSize;
                this.getApiLogsPageList();
            },
            setPostAxios() {
                axios.defaults.timeout = 60 * 1000;
                axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
                axios.interceptors.request.use(
                    config => {
                        let _token = localStorage.getItem("ocr-token") || "";
                        if (_token) {
                            config.headers.common["Token"] = _token;
                        }
                        let _clientId = this.clientId || "";
                        if (_clientId) {
                            config.headers.common["ClientId"] = _clientId;
                            config.headers.common["ClientType"] = 1;
                        }
                        config.headers.common["IsLogs"] = true;
                        return config;
                    }
                );
                // 返回状态判断(添加响应拦截器)
                axios.interceptors.response.use(
                    (res) => {
                        let _res = res.Data;

                        if (_res.DetailedStatus == 1 || _res.DetailedStatus == 7) {
                        } else if (_res.DetailedStatus == 11) {
                            //登录权限过期，需要重新登录
                            this.removeToken();
                        } else {
                            this.$message.error(_res.DetailedMessage);

                        }
                        return res;
                    },
                    (error) => {
                        const config = error.config;
                        this.loading = false;
                        //是否重复请求
                        if (error && error.response) {
                            switch (error.response.status) {
                            case 400:
                                error.message = "请求错误";
                                break;
                            case 401:
                                this.removeToken();
                                error.message = "权限丢失,重新获取中";
                                break;

                            default:
                                error.message = `连接错误${error.response.status}`;
                            }
                        } else {
                            error.message = "连接到服务器失败或超时";
                        }
                        error.message && this.$message.error(error.message);

                        return Promise.reject(error);
                    }
                );
            },
            removeToken() {
                this.isLoginShow = true;
                localStorage.removeItem("ocr-token");
                localStorage.removeItem("user-info");
                window.location.href = "login.html";
            },
            /** 获取列表 */
            getApiLogsPageList() {
                this.loading = true;
                this.setPostAxios();
                let _url = this.domainUrl + "v1/ApiLogs/GetApiLogsPageList";
                let _startValue = this.startValue
                    ? moment(this.startValue).format("YYYY-MM-DD HH:mm:ss")
                    : "0001-01-01 00:00:00";
                let _endValue = this.endValue
                    ? moment(this.endValue).format("YYYY-MM-DD HH:mm:ss")
                    : "0001-01-01 00:00:00";
                let _isErr = null;
                if (this.isErr == 1) {
                    _isErr = true;
                } else if (this.isErr == 2) {
                    _isErr = false;
                }
                let params = {
                    apiName: this.apiName,
                    isError: _isErr,
                    requestTimeBegin: _startValue,
                    requestTimeEnd: _endValue,
                    pageIndex: this.current,
                    pageSize: this.pageSize,
                };
                axios
                    .post(_url, params)
                    .then(
                        res => {
                            let _res = res.Data;
                            if (_res.DetailedStatus == 1 || _res.DetailedStatus == 7) {
                                if (_res.Data) {
                                    this.total = _res.Data.Count;
                                    let _tableList = _res.Data.ApiLogs;
                                    _tableList.forEach(el => {
                                        el.key = el.Id;
                                        el.RequestTime = el.RequestTime == "0001-01-01 00:00:00" ? "" : el.RequestTime;
                                        el.ResponseTime =
                                            el.ResponseTime == "0001-01-01 00:00:00" ? "" : el.ResponseTime;
                                        el.IsError = el.IsError ? "是" : "否";
                                        if (el.Subset && el.Subset.length > 0) {
                                            el.Subset.forEach(ele => {
                                                ele.key = ele.Id;
                                                ele.IsError = ele.IsError ? "是" : "否";
                                                ele.RequestTime =
                                                    ele.RequestTime == "0001-01-01 00:00:00" ? "" : ele.RequestTime;
                                                ele.ResponseTime =
                                                    ele.ResponseTime == "0001-01-01 00:00:00" ? "" : ele.ResponseTime;
                                            });
                                        }
                                        el.children = el.Subset ? el.Subset : [];
                                    });
                                    this.data.splice(0);
                                    this.data.push(..._tableList);
                                } else {
                                    this.total = 0;
                                    this.data.splice(0);

                                }
                            }
                            this.loading = false;
                        }
                    );
            },
            /** 获取接口名称 */
            getAllApiName() {
                let _url = this.domainUrl + "v1/ApiLogs/GetAllApiName";
                axios.get(_url).then(res => {
                    let _res = res.Data;
                    if (_res.DetailedStatus == 1) {
                        let _data = _res.Data.ApiNames;
                        let _apiNameList = [];
                        _data.forEach(el => {
                            let _item = {
                                text: el,
                                value: el,
                            };
                            _apiNameList.push(_item);
                        });
                        this.apiNameList = _apiNameList;
                    }
                });
            },
            customRow(record) {
                return {
                    on: {
                        click: event => {
                            this.visible = true;
                            let _record = JSON.parse(JSON.stringify(record));
                            delete _record.Subset;
                            delete _record.children;
                            delete _record.key;
                            this.jsonData = _record;
                        }
                    },
                    class: { 'error': record.IsError == "是" }
                };
            },
            handleCancel() {
                this.visible = false;

            },
            reset() {
                this.apiName = undefined;
                this.isErr = undefined;
                this.startValue = null;
                this.endValue = null;
                this.getApiLogsPageList();
            },
            onChange(val) {
                this.current = val;
                this.getApiLogsPageList();
            },
            quitLogin() {
                this.setPostAxios();
                let _url = this.domainUrl + "v1/Login/SignOut";
                let _token = localStorage.getItem("ocr-token");
                let _params = {
                    token: _token,
                    clientId: this.clientId,
                    clientType: 1,
                    systemId: 0,
                };
                axios.post(_url, _params).then(res => {
                    const _res = res.Data;
                    if (_res.DetailedStatus == 1) {
                        this.removeToken();
                    }
                });
            },
        },
    });
};