<template>
    <div class="para-tree2">
        <Row>
            <div class="para-tree2-content">
                <div class="layout-2">
                    <!-- search -->
                    <Row v-if="search" style="padding: 10px;">
                        <Col :span="20" :offset="2">
                            <slot name="search">
                                <Row style="padding: 10px 10px 0;">
                                    <Col :span="20" :offset="2">
                                        <slot name="search">
                                            <Row type="flex" justify="space-between">
                                                <Col :span="21">
                                                    <InputSearch :placeholder="placeholder"
                                                                 v-model="searchKeyWords"
                                                                 @pressEnter="onSearch"
                                                                 @search="onClear"
                                                    >
                                                        <Button slot="enterButton">{{Lang.clear[language]}}</Button>
                                                    </InputSearch>
                                                </Col>
                                                <Col :span="2">
                                                    <Button icon="search" type="primary" @click="onSearch"></Button>
                                                </Col>
                                            </Row>
                                        </slot>
                                    </Col>
                                </Row>
                            </slot>
                        </Col>
                    </Row>
                    <header>
                        <div class="header-back" @click="goBack" v-if="title && route.length > 1 && showRouter">
                            <Icon type="left"/>
                            <span class="header-title">{{title}}</span>
                        </div>
                        <div class="header-back" v-else>
                            <slot name="header" v-if="title">
                                <Icon type="home"/>
                            </slot>
                            <span class="header-title" v-if="title">{{title}}</span>
                        </div>
                        <!-- 路由 -->
                        <div :class="{ 'header-breadcrumb' : title }" :dir="xdir">
                            <Breadcrumb>
                                <template v-for="item in route">
                                    <!-- 存在link的时候 -->
                                    <BreadcrumbItem v-if="item.link" :key="item.title">
                                        <a @click="getListDataByRoute($event,item)">{{item.title}}</a>
                                    </BreadcrumbItem>
                                    <!-- 全部的时候 -->
                                    <BreadcrumbItem v-else-if="item.link === null" :key="item.title">
                                        <a @click="getListDataByRoute($event,item)">{{item.title}}</a>
                                    </BreadcrumbItem>
                                    <BreadcrumbItem v-else :key="item.title">
                                        <template v-if="route.length > 1">
                                            <a @click="getListDataByRoute($event,item)">{{item.title}}</a>
                                        </template>
                                        <template v-else>{{item.title}}</template>
                                    </BreadcrumbItem>
                                </template>
                            </Breadcrumb>
                        </div>
                    </header>
                    <div class="layout-2-content el-anime"
                         :style="{height:search?'calc(100% - 142px)' : 'calc(100% - 51px)'}">
                        <LayoutCard :data-source="dataSource"
                                    :selectable="selectables"
                                    :multiple="multiples"
                                    :radio="radios"
                                    :no-array="noArray"
                                    :is-object="isObject"
                                    :back-field="backField"
                                    :html-formatter="htmlFormatter"
                                    v-model="checkedKeys"
                                    @on-change="checkedKeySequlization"
                                    @click="clickCurrentItem"
                                    :custom="custom"
                                    @change="getItemClick"
                                    @more="getMoreDataByItem"
                        >
                            <template #lazys>
                                <slot name="lazy"></slot>
                            </template>
                            <template #custromRender="{scope}">
                                <slot name="custom" :slotScope="scope"></slot>
                            </template>
                            <template #next>
                                <slot name="nexts"></slot>
                            </template>
                        </LayoutCard>
                    </div>
                </div>
            </div>
        </Row>
    </div>
</template>

<script>
    import {Breadcrumb, Button, Col, Icon, Input, Pagination, Row} from "ant-design-vue";
    import {cloneDeep, isArray, isEmpty, isFunction, isObject, isString} from "lodash";
    import {
        $http as http,
        $Local as Local,
        $objectConverParameters as objectConverParameters,
        $parametersConverObject
    } from "@chenxihub/sweet";
    import LayoutCard from "./layout-card.vue";

    const Lang =  {
        clear: {
          zh_CN: "清除",
          en_GB: "Clear",
        },
        all: {
          zh_CN: "全部",
          en_GB: "All",
        },
        name: {
          zh_CN: "查看更多",
          en_GB: "More",
        },
      };

    export default {
        name: "para-tree2",
        mixins: [Local],
        components: {
            LayoutCard,
            Row,
            Breadcrumb,
            Icon,
            Col,
            BreadcrumbItem: Breadcrumb.Item,
            InputSearch: Input.Search,
            Button,
            Pagination
        },
        props: {
            showRouter: {
                type: Boolean,
                default: true
            },
            xdir: {
                type: String,
                default: "rtl"
            },
            data: {
                type: Array,
                default() {
                    return [];
                }
            },
            selectable: Boolean,
            request: [Object, Array],
            value: [Array, Object, String],
            requestCallback: Function,
            title: {
                type: String,
                default() {
                    return "title";
                }
            },
            dataFormat: Function,
            search: Boolean,
            /* para-select-params */
            multiple: Boolean,
            radio: Boolean,
            config: Object,
            noArray: Boolean,
            isObject: Boolean,
            backField: Array,
            custom: Boolean,
            customCallback: Function,
            placeholder: {
                type: String,
                default() {
                    return "请输入名称";
                }
            },
            pagination: {
                type: Boolean,
                default() {
                    return false;
                }
            },
            queryFormatter: Function
        },
        data() {
            return {
                MORE_DATA: {
                    name: Lang.name[this.language],
                    entityType: "more",
                    kind: "more",
                    scopedSlots: {icon: "ellipsis", title: "title"},
                    format: "more",
                    page: 2,
                    size: 25,
                    key: Math.random()
                },
                Lang,
                route: [{title: this.title || Lang.all[this.language], link: null, key: null}],
                dataSource: [],
                checkedKeys: [],
                baseURL: null,
                selectables: false,
                multiples: false,
                radios: false,
                searchKeyWords: "",
                beforeParams: null,
                htmlFormatter: null
            };
        },
        computed: {
            language() {
                return JSON.parse(window.localStorage[window.$project]).setting.language || "zh_CN";
            }
        },
        watch: {
            request: {
                immediate: true,
                deep: true,
                handler(value) {
                    this.route = [{title: this.title || Lang.all[this.language], link: null, key: null}]; // 恢复默认值
                    if (isObject(value)) {
                        this.requestOnServiceByObject(value);
                    } else if (isString(value)) {
                        this.requestOnService(`${value}`);
                    } else {
                        throw Error("请确定request类型(Object/String)传入是否正确？");
                    }
                }
            },
            value: {
                immediate: true,
                handler(value) {
                    if (value) {
                        if (isObject(value)) {
                            isEmpty(value) ? this.checkedKeys = [] : this.checkedKeys = [value.key];
                        }
                        if (isString(value)) {
                            isEmpty(value) ? this.checkedKeys = [] : this.checkedKeys = [value];
                        }
                        if (isArray(value)) {
                            this.checkedKeys = [];
                            isEmpty(value) ? this.checkedKeys = [] : value.forEach(data => {
                                if (isObject(data)) {
                                    this.checkedKeys.push(data.key);
                                }
                                if (isString(data)) {
                                    this.checkedKeys.push(data);
                                }
                            });
                        }
                    }
                }
            }
        },
        created() {
            if (this.config) {
                const {multiple, radio, htmlFormatter} = this.config;
                if (htmlFormatter && isFunction(htmlFormatter)) this.htmlFormatter = htmlFormatter;
                if (multiple || radio) {
                    this.selectables = true;
                    if (multiple) {
                        this.radios = false;
                        this.multiples = true;
                    }
                    if (radio) {
                        this.radios = true;
                        this.multiples = false;
                    }
                } else {
                    this.selectables = false;
                }
            }
        },
        methods: {
            onClear() {
                this.searchKeyWords = "";
                delete this.request.params.fiql;
                this.requestOnServiceByObject(this.request);
            },
            onSearch() {
                const keywords = this.searchKeyWords;
                if (!keywords) return false;
                if (this.request && this.request.params) {
                    Object.assign(this.request.params, {
                        "fiql": encodeURIComponent(`name==*${keywords}*`)
                    });
                }
                this.requestOnServiceByObject(this.request);
            },
            checkedKeySequlization(data) {
                this.$emit("input", data);
            },
            refresh() {
                this.requestOnServiceByObject(this.request);
            },
            async requestOnService(url) {
                let data = await http.$paraGET(url);
                data = data.list ? data.list : data.data;
                if (this.requestCallback && isFunction(this.requestCallback)) {
                    this.requestCallback({
                        data,
                        type: "search"
                    }, (nValue) => {
                        this.dataSource = nValue;
                    });
                } else {
                    this.dataSource = data.data;
                }
            },
            async requestOnServiceByObject({
                                               url, method, project, params, ...args
                                           }) {
                const conf = {};
                if (!url) throw Error("请传入请求地址");
                let cloneParams = null;
                if (params) {
                    cloneParams = cloneDeep(params);
                    if (params.dataKey) {
                        delete cloneParams.dataKey;
                    }
                    conf.url = url.indexOf("?") > -1
                        ? `${url}&${objectConverParameters(cloneParams)}`
                        : `${url}?${objectConverParameters(cloneParams)}`;
                } else {
                    conf.url = url;
                }
                const nParams = await this.sequlizeQuery(params, null);
                if (nParams) {
                    params = nParams;
                }
                method ? method = method.toLocaleUpperCase() : method = "GET";
                if (project) conf.project = project;
                this.beforeParams = cloneDeep(params);
                let data = await http[`$para${method}`](Object.assign({}, ...conf, args));
                /* 新增分页 */
                data = data.list ? data.list : data.data;
                if (this.requestCallback && isFunction(this.requestCallback)) {
                    this.requestCallback({
                        data,
                        type: "server"
                    }, async (nValue) => {
                        //  是否需要添加分页
                        this.dataSource = await this.isPaginationSequlizeData(nValue.list);
                    });
                } else {
                    this.dataSource = await this.isPaginationSequlizeData(data.data.list);
                }
            },
            async sequlizeQuery(params, info) {
                if (this.queryFormatter) {
                    return this.queryFormatter(params, info);
                } else if (this.config["queryFormatter"]) {
                    return this.config["queryFormatter"](params, info);
                } else {
                    return params;
                }
            },
            async isPaginationSequlizeData(oData) {
                let nData = null;
                if (this.pagination || this.config["pagination"]) {
                    // console.log('序列化数据============>', oData);
                    if (this.request["more"]) {
                        nData = [...oData, this.request["more"]];
                    } else {
                        oData.length >= 25
                            ? nData = [...oData, this.MORE_DATA]
                            : nData = [...oData];
                    }
                } else {
                    nData = oData;
                }
                return nData;
            },
            /* 路由的处理 */
            routeSliceByDynamic(info) {
                const isIncludes = this.route.some(item => item.key === info.key);
                if (isIncludes) {
                    const index = this.route.findIndex(item => item.key === info.key);
                    if (index < this.route.length) {
                        /* 应该切割掉 */
                        this.route = this.route.slice(0, index + 1);
                    }
                } else {
                    this.route.push({
                        title: info.name,
                        key: info.key,
                        link: info.key
                    });
                }
            },
            getListDataByRoute(e, info) {
                if (info.link === null) {
                    e.preventDefault();
                    this.requestOnServiceByObject(this.request);
                    this.routeSliceByDynamic(info);
                } else {
                    if (!this.custom) {
                        e.preventDefault();
                        if (info.key) {
                            this.clickCurrentItem(info); // 路由获取数据更新
                        } else {
                            this.requestOnServiceByObject(this.request);
                            this.routeSliceByDynamic(info);
                        }
                    } else {
                        e.preventDefault();
                        this.$emit("routeChange", info);
                        if (info.key) {
                            this.clickCurrentItem(info); // 路由获取数据更新
                        } else {
                            this.requestOnServiceByObject(this.request);
                            this.routeSliceByDynamic(info);
                        }
                    }
                }
            },
            async getListDataByKey(url, info) {
                const httpAjax = async () => {
                    const params = {};
                    params.url = url;
                    this.request.project ? params.project = this.request.project : "";
                    this.beforeParams = cloneDeep(params);
                    return await http.$paraGET(params);
                };
                if (info) {
                    /* 来源正常的分页 */
                    let data = await httpAjax();
                    data = data.list ? data.list : data.data;
                    if (this.dataFormat && isFunction(this.dataFormat)) {
                        this.dataFormat(data, (d) => {
                            this.dataSource = d;
                        });
                    } else {
                        // // console.log('data', data);
                        this.dataSource = await this.isPaginationSequlizeData(data.data.list);
                    }
                    this.routeSliceByDynamic(info);
                } else {
                    /* 来源于更多 */
                    let data = await httpAjax();
                    data = data.list ? data.list : data.data;
                    if (this.dataFormat && isFunction(this.dataFormat)) {
                        this.dataFormat(data, (d) => {
                            this.dataSource = d;
                        });
                    } else {
                        const nData = await this.isPaginationSequlizeData(data.data.list);
                        // // console.log('来源于更多data', data, nData);
                        const cDSata = cloneDeep(this.dataSource);
                        cDSata.pop();
                        this.dataSource = [...cDSata, ...nData];
                    }
                }
            },
            goBack() {
                this.requestOnServiceByObject(this.request);
                this.$emit("routeChange");
                // $easing('.el-anime', 'x', -799, 500);
                this.route = [{title: this.title, link: null, key: null}];
            },
            /* 获取当前的下一级key的数据 */
            async clickCurrentItem(info) {
                if (!this.custom) {
                    const {key} = info;
                    let url;
                    let params;
                    if (isObject(this.request)) {
                        if (this.request.params && this.request.params.type) {
                            /* 构建请求参数 */
                            params = {
                                type: this.request.params.type,
                                page: 1,
                                size: 25
                            };
                            if (this.request.params.dataKey) {
                                params[this.request.params.dataKey] = key;
                            }
                            const nParams = await this.sequlizeQuery(params, info);
                            if (nParams) {
                                params = nParams;
                            }
                            url = this.request.url.indexOf("?") > -1
                                ? `${this.request.url}&${objectConverParameters(params)}`
                                : `${this.request.url}?${objectConverParameters(params)}`;
                        } else if (this.request.params) {
                            /* params */
                            url = this.request.url.indexOf("?") > -1
                                ? `${this.request.url}&${objectConverParameters(this.request.params)}`
                                : `${this.request.url}?${objectConverParameters(this.request.params)}`;
                        } else {
                            url = this.request.url;
                        }
                    } else {
                        url = this.request;
                    }
                    this.baseURL = url;
                    this.getListDataByKey(url, info);
                } else {
                    /* custom */
                    this.$emit("click", info);
                    this.customCallback(value => this.dataSource = value, info);
                    this.routeSliceByDynamic(info);
                }
            },
            /* 点击更多的more事件 */
            getMoreDataByItem() {
                const queryAjax = (oParams) => {
                    oParams["page"] = Number(oParams["page"]);
                    oParams["page"]++;
                    let url = this.request.url.indexOf("?") > -1
                        ? `${this.request.url}&${objectConverParameters(oParams)}`
                        : `${this.request.url}?${objectConverParameters(oParams)}`;
                    this.getListDataByKey(url, false);
                };
                if (this.beforeParams && this.beforeParams.url) {
                    let oParams = cloneDeep($parametersConverObject(this.beforeParams.url));
                    queryAjax(oParams);
                } else {
                    /* 没有参数的加载更多 */
                    let oParams = cloneDeep(this.beforeParams);
                    queryAjax(oParams);
                }
            },
            /* 获取每一栏的点击事件 */
            getItemClick(e, info) {
                e.stopPropagation();
                if (this.custom && info.kind !== "people") {
                    this.$emit("click", info);
                    this.customCallback(value => this.dataSource = value, info);
                    this.routeSliceByDynamic(info);
                } else {
                    this.$emit("change", Object.assign({}, e, {info}));
                }

            }
        }
    };
</script>
