<template>
    <div class="way-filter">
        <el-cascader clearable ref="cascader" v-model="value" class="org-cascader" placeholder="全国" size="mini"
            style="width: 230px" popper-class="wayPoper" :options="options" :show-all-levels="showAllLevels"
            @change="handleCascaderChange" :props="{
                expandTrigger: 'hover',
                checkStrictly: true,
                value: 'id',
                label: 'name',
                children: 'chirldren',
            }"></el-cascader>

        <div class="dateTime">
            <el-date-picker v-model="appDate" type="month" size="small" :clearable="false" popper-class="n_date__popper"
                style="width: 128px; cursor: pointer" @change="handelDateApp" :editable="false"></el-date-picker>
        </div>
    </div>
</template>
<script lang="jsx">
import { mapState, mapMutations } from "vuex";
import { getRoadData } from "@/api/patrolAndRescue";
export default {
    props: {
        allIds: {
            type: Boolean,
            default: false, //是否收集所有子节点id、默认false采集最后一级无子节点Id
        },
        searchCompany: {
            type: Boolean,
            default: true, //查询时是否需要上次公司
        },
        showAllLevels: {
            type: Boolean,
            default: true, //是否显示完整路径
        },
        getOrgId: {
            type: Boolean,
            default: false, //是否显示完整路径
        },
    },
    computed: {
        changeDateTime() {
            return this.$store.state.appDate;
        },
    },
    data() {
        return {
            //  默认根节点
            defaultRoot: {
                isDelete: '0',
                id: '1766017468444450816',
                name: '全国',
                parentId: '1765985726257963008',
                code: '100101',
                grade: '2',
                orgKind: 'ogn',
                demId: '1726849603896352768',
                orderNo: 145,
                isMaster: 0,
                path: '1726849603896352768.1765985726257963008.1766017468444450816.',
                pathName: '/中国铁建昆仑投资集团/高速公路运营管理公司',
                limitNum: 0,
                exceedLimitNum: 0,
                disabled: false,
                chirldren: [],
            },
            appDate: "",
            waySelected: '',
            isClearable: true,
            elprops: {
                expandTrigger: 'hover',
                checkStrictly: true,
                value: 'id',
                label: 'name',
                children: 'chirldren',
            },
            options: [],
            value: ['1766017468444450816'],
        };
    },
    watch: {
        changeDateTime(val) {
            this.appDate = val;
        },
        "$route.query.month": {
            handler(val) {
                val && this.handelDateApp(new Date(val));
            },
            immediate: true,
        },
    },
    created() {
        this.initRoadData();
    },
    mounted() {
        this.appDate = this.$store.state.appDate;
    },
    methods: {
        // 选择变化触发父级数据更新
        handleCascaderChange(val) {
            if (val && val.length) {
                this.value = val
                this.lastPath = val[val.length - 1]
                let selectedList = this.$refs.cascader.getCheckedNodes()
                this.orgIds = this.collectIds([selectedList[0].data])
                // 小于两级查询要追加公司id
                if (val.length <= 2 && this.searchCompany) {
                    this.orgIds.push('1766017468444450816')
                }
                if (val.length === 5 && this.getOrgId) {
                    this.lastPath = this.getRoadOrgId(this.lastPath, this.options)
                }
            } else {
                // 如果清空选择就默认为根节点
                this.value = ['1766017468444450816']
                this.lastPath = '1766017468444450816'
                this.orgIds = this.collectIds(this.options)
                if (this.searchCompany) {
                    this.orgIds.push('1766017468444450816')
                }
            }
            this.$emit('fullPath', this.value) // 选中节点全路径
            this.$emit('lastPath', this.lastPath, this.orgIds) // 选中节点路径
            this.$emit('orgIds', this.orgIds) // 选中节点下子节点id集合（路段id）
            this.$store.commit("changeRoad", this.orgIds);
        },
        // 路段根据路段id获取路段orgid
        getRoadOrgId(id, data) {
            for (let i = 0; i < data.length; i++) {
                if (data[i].id === id) {
                    this.tempOrg = data[i].orgId
                    break
                } else if (data[i].chirldren && data[i].chirldren.length) {
                    this.tempOrg = this.getRoadOrgId(id, data[i].chirldren)
                }
            }
            return this.tempOrg
        },
        // 递归收集最后一级无子节点的id（路段id） | allIds true 收集所有节点路段id => roadSegmentId
        collectIds(data) {
            let ids = []
            data.forEach((item) => {
                if (item.chirldren) {
                    if (this.allIds) ids.push(item.roadSegmentId)
                    const cIds = this.collectIds(item.chirldren)
                    ids.push(...cIds)
                } else {
                    ids.push(item.roadSegmentId)
                }
            })
            return ids
        },
        initRoadData() {
            getRoadData()
                .then((res) => {
                    let data = res || []
                    this.deepSetChildren(data) // 设置路段的children为null
                    this.defaultRoot.chirldren = data
                    this.options = [this.defaultRoot]
                    console.log("路段数据", this.options)
                })
                .catch((err) => {
                })
        },
        // 格式化数据：节点chirldren字段无下级则为空
        deepSetChildren(data) {
            data.forEach((i) => {
                let child = i.chirldren
                if (child && child.length !== 0) {
                    return this.deepSetChildren(child)
                } else {
                    i.chirldren = null
                }
            })
            return data
        },
        handelDateApp(val) {
            this.$store.commit("changeDate", val);
        },
    },
};
</script>
<style lang="postcss" scoped>
.way-filter {
    display: flex;
    margin-top: 15px;
    margin-bottom: 15px;
    margin-left: 12px;
}

::v-deep(.el-input__inner) {
    color: #fff;
    background: rgba(5, 15, 45, 0.5);
    border: 1px solid #2c4e91;
    height: 30px;
    cursor: pointer;
    line-height: 32px;

    &:hover {
        border: 1px solid #7ebee9;
    }
}

.dateTime {
    margin-left: 15px;
    cursor: pointer;
}
</style>
<style lang="postcss">
.wayPoper {
    background: rgba(5, 15, 45, 0.7) !important;
}

.el-cascader-node {
    color: #fff;
}

.el-cascader-node.is-selectable.in-active-path {
    color: rgba(59, 130, 246, 1) !important;
}

.el-radio__label {
    display: inline-block;
    width: 200px;
    height: 34px;
    position: absolute;
    top: -5px;
}
</style>
