<template>
    <div class="equipList">
        <NavMenu></NavMenu>

        <div class="class-container" v-if="currentIndex !== null">
            <a
                v-for="(item, index) in currentIndex == 1 ? levelList : levelList_2"
                :key="index"
                :style="index + 1 == currentIndex ? 'color:#000' : 'color: #333'"
                >{{ item.title
                }}{{
                    currentIndex == 1
                        ? index == levelList.length - 1
                            ? ''
                            : '>'
                        : index == levelList_2.length - 1
                        ? ''
                        : '>'
                }}
            </a>
        </div>
        <div class="screen">
            <div class="choose">
                <template v-for="(v, i) in screenChooseList" :key="i">
                    <div class="line" v-if="v.isShow">
                        <div class="label">
                            {{ v.name }}
                        </div>
                        <div class="select">
                            <template v-for="(val, index) in v.list" :key="index">
                                <div
                                    class="item"
                                    @click="selectScreen(v.type, val, i)"
                                    :class="{
                                        active: val.isChecked,
                                    }"
                                >
                                    <span>{{ val.name }}</span>
                                </div>
                            </template>

                        </div>
                    </div>
                </template>
                <div class="line" v-if="screenTags.length > 0">
                    <div class="label">已选条件：</div>
                    <div class="select tags">
                        <el-tag
                            v-for="(tag, i) in screenTags"
                            :key="i"
                            class="item"
                            @close="handleClose(tag)"
                            closable
                        >
                            {{ tag.name }}
                        </el-tag>

                        <span class="clear-btn" @click="onClearTags"> 清除选项 </span>
                    </div>
                </div>
            </div>
            <div class="btns">
                <div
                    class="item"
                    @click="changeOption(v)"
                    :class="v.id == optionActive && 'active'"
                    v-for="(v, i) in screenOptionList"
                    :key="i"
                >
                    {{ v.name }}
                    <template v-if="v.sort">
                        <el-icon class="icon" v-show="v.sort == 'DESC'">
                            <CaretBottom />
                        </el-icon>
                        <el-icon class="icon" v-show="v.sort == 'ASC'">
                            <CaretTop />
                        </el-icon>
                    </template>
                </div>
            </div>
        </div>

        <!-- <div class="showScreen">
            <div class="title">筛选条件：</div>
            <div class="tags">
                <el-tag
                    v-for="(tag, i) in screenTags"
                    :key="i"
                    class="item"
                    @close="handleClose(tag, i)"
                    closable
                >
                    {{ tag.name }}
                </el-tag>
                <el-tag
                    class="item"
                    v-if="screenTags.length > 0"
                    type="danger"
                    @close="tagClear"
                    closable
                >
                    清空所有条件
                </el-tag>
            </div>
        </div> -->

        <div class="showList" v-if="total > 0">
            <EquipCardHall
                class="card"
                v-for="(v, i) in equipList"
                :key="i"
                :url="v.picUrl"
                :name="v.deviceName"
                :price="v.dayLeasePrice"
                :company="v.companyName"
                :personPhone="v.personPhone"
                :typeName="v.typeName"
                :ma_status="v.maStatus || v.ma_status"
                @click="onHandleDetails(v.maId)"
            />
        </div>
        <div class="noData" v-else>
            <el-empty :image-size="200" />
        </div>

        <div class="pagination">
            <el-pagination
                size="small"
                background
                layout="prev, pager, next"
                :page-size="pageData.pageSize"
                :total="total"
                class="mt-4"
                @current-change="onCurrentChange"
                v-if="total > 0"
            />
        </div>
    </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import EquipCard from '@/components/equipCard.vue'
import EquipCardHall from '@/components/equipCardHall/index.vue'

import { useRoute, useRouter } from 'vue-router'
import {
    apiGetAddressList,
    apiGetEquipTypeList,
    getTypeListApi,
    getDeviceListApi,
    getCompanyCountApi,
} from 'http/api/equip'
import { getCompanyListApi, getGoodsClassListApi } from 'http/api/home'
import $bus from '@/utils/bus'
import NavMenu from '@/components/Navmenu/index.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route: any = useRoute()
const startPrice: any = ref(0)
const endPrice: any = ref(0)
const levelList = ref<any>([{ title: '一级分类' }, { title: '二级分类' }])
const levelList_2 = ref<any>([{ title: '一级分类' }, { title: '二级分类' }, { title: '三级分类' }])
let currentIndex = route.query.level || null

const onConfirmPrice = () => {
    ElMessage.closeAll()
    let rex = /^[1-9][0-9]*$/
    if (!rex.test(startPrice.value) || !rex.test(endPrice.value)) {
        ElMessage({
            type: 'warning',
            message: '请输入大于0且不能以0开头的正整数',
        })
        return
    }

    if (parseInt(endPrice.value) < parseInt(startPrice.value)) {
        ElMessage({
            type: 'warning',
            message: '结束值不可小于起始值',
        })
        return
    }

    const itemInfo = {
        name: `${parseInt(startPrice.value)}-${parseInt(endPrice.value)}`,
        value: [parseInt(startPrice.value), parseInt(endPrice.value)],
        isChecked: true,
        index: 2,
        isShow: false,
        isAdd: true,
    }

    screenChooseList[3].list[0].isChecked = false
    screenChooseList[3].list.push(itemInfo)

    getDeviceListData()
}

//筛选条件列表数据
const screenChooseList: any = reactive([
    {
        name: '使用年限：',
        type: 'userYear',
        isShow: true,
        list: [
            {
                isChecked: true,
                name: '全部',
                value: '',
                index: 0,
            },
            {
                isChecked: false,
                name: '0-1年',
                value: [0, 1],
                index: 0,
            },
            {
                isChecked: false,
                name: '1-3年',
                value: [1, 3],
                index: 0,
            },
            {
                isChecked: false,
                name: '3-5年',
                value: [3, 5],
                index: 0,
            },
            {
                isChecked: false,
                name: '5-8年',
                value: [5, 8],
                index: 0,
            },
            {
                isChecked: false,
                name: '10年以上',
                value: ['', 10],
                index: 0,
            },
        ],
    },
    {
        type: 'deviceClass',
        name: '装备分类：',
        isShow: true,
        list: [
            {
                name: '全部',
                value: '',
                isChecked: true,
                index: 1,
            },
        ],
    },
    {
        type: 'deviceClass',
        name: '下级分类：',
        isShow: currentIndex === null ? false : true,
        list: [
            {
                name: '全部',
                value: '',
                isChecked: true,
                index: 2,
            },
        ],
    },
    {
        type: 'companyId',
        name: '所属公司',
        isShow: true,
        list: [
            {
                isChecked: true,
                name: '全部',
                value: '',
                index: 4,
            },
        ],
    },
    {
        type: 'temp',
        name: '',
        isShow: false,
        list: [],
    },
])

// 已选条件的tag标签
const screenTags = computed(() => {
    const selectTagList: any = []
    screenChooseList.forEach((e: any) => {
        e.list.forEach((j: any) => {
            if (j.isChecked && j.name !== '全部') {
                console.log(j, '******')
                selectTagList.push(j)
            }
        })
    })

    return selectTagList
})
// 综合排序 更新时间 月租金 排序按钮
const screenOptionList: any = reactive([
    {
        name: '综合排序',
        id: 0,
        sort: '',
    },
    {
        name: '共享剩余时间',
        id: 1,
        sort: 'DESC',
    },
    {
        name: '上架时间',
        id: 2,
        sort: 'DESC', //desc or desc
    },
])
//激活 排序按钮
const optionActive = ref(0)

//分页参数
const pageData = reactive({
    pageNum: 1,
    pageSize: 20,
})

// 总条数
const total = ref(0)

//装备列表
const equipList: any = ref([])

// 获取装备分类
const getTypeListData = async () => {
    let params: any = {}
    if (route.query.level > 1) {
        params.id = route.query.typeId
    }
    const res = await getTypeListApi()
    const typeList = res.data.map((e: any) => {
        return { ...e, name: e.typeName, value: e.typeId, isChecked: false, index: 1 }
    })
    screenChooseList[1].list.push(...typeList)
}
// 获取下级分类
const lowerClassData = async () => {
    const res = await getTypeListApi({
        typeId: route.query.typeId,
        level: route.query.level,
    })

    const typeList_1 = res.data
        .filter((e: any) => e.level == route.query.level)
        .map((j: any) => {
            return { ...j, name: j.typeName, value: j.typeId, isChecked: false, index: 1 }
        })
    const typeList_2 = res.data
        .filter((e: any) => e.level == route.query.level * 1 + 1)
        .map((j: any) => {
            return { ...j, name: j.typeName, value: j.typeId, isChecked: false, index: 1 }
        })

    console.log(typeList_2, 'typeList_2')

    screenChooseList[1].list.push(...typeList_1)
    screenChooseList[2].list.push(...typeList_2)

    // const typeList = res.data.map((e: any) => {
    //     return { ...e, name: e.typeName, value: e.typeId, isChecked: false, index: 1 }
    // })
    // screenChooseList[2].list.push(...typeList)
}

// 获取设备所在地
const getCompanyAddressListData = async () => {
    const res: any = await getCompanyListApi()
    const addressList = res.data
        .filter((e: any) => e.isShow)
        .map((e: any) => {
            // console.log('🚀 ~ addressList ~ e:', e)
            return { ...e, name: e.companyName, value: e.companyId, isChecked: false, index: 4 }
        })
    screenChooseList[4].list.push(...addressList)
}
// 获取分类

// 查询装备列表数据
const getDeviceListData = async (params: any = null, keyWord: any = null) => {
    // 组装查询参数
    const searchParams: any = {
        keyWord: keyWord ? keyWord : keyWordsSearch.value ? keyWordsSearch.value : '',
        ageMin: '',
        ageMax: '',
        companyId: '',
        dayLeasePriceMin: '',
        dayLeasePriceMax: '',
        typeId: '',
        level: '',
        maStatus: 2,
        dayLeasePriceOrderBy:
            optionActive.value == 1 ? screenOptionList[optionActive.value].sort : '',
        updateTimeOrderBy: optionActive.value == 2 ? screenOptionList[optionActive.value].sort : '',
    }

    screenChooseList.forEach((e: any, index: number) => {
        e.list.forEach((j: any) => {
            if (index === 0 && j.isChecked && j.value.length > 0) {
                searchParams.ageMin = j.value[0]
                searchParams.ageMax = j.value[1]
            }
            if (index === 1 && j.isChecked) {
                searchParams.typeId = j.value
                searchParams.level = j.level
            }
            if (index === 2 && j.isChecked && currentIndex !== null && j.value != '') {
                searchParams.typeId = j.value
                searchParams.level = j.level
            }
            if (index === 3 && j.isChecked && j.value.length > 0) {
                searchParams.dayLeasePriceMin = j.value[0]
                searchParams.dayLeasePriceMax = j.value[1]
            }
            if (index === 4 && j.isChecked) {
                searchParams.companyId = j.value
            }
        })
    })

    if (params) {
        searchParams.level = params.level ? params.level : ''
        searchParams.typeId = params.typeId ? params.typeId : ''
        searchParams.companyId = params.companyId ? params.companyId : ''
        searchParams.keyWord = params.keyWord ? params.keyWord : ''
    }

    Object.assign(searchParams, pageData)
    const { data: res } = await getDeviceListApi(searchParams)

    const searchParams_2 = JSON.parse(JSON.stringify(searchParams))
    searchParams_2.companyId = ''
    const result: any = await getCompanyCountApi(searchParams_2)
    screenChooseList[4].list.forEach((e: any, index: any) => {
        if (index != 0) {
            e.name = e.companyName + `(${0})`
        }
    })
    for (let key in result.data) {
        screenChooseList[4].list.forEach((e: any, index: any) => {
            if (e.companyId == key) {
                e.name = ''
                e.name = e.companyName + `(${result.data[key]})`
            }
        })
    }
    equipList.value = res.rows
    total.value = res.total
}

// 清除筛选条件
const onClearTags = () => {
    screenChooseList.forEach((e: any, i: any) => {
        e.list.forEach((j: any, index: number) => {
            j.isChecked = false
            if (i != 5) {
                if (index === 0) {
                    j.isChecked = true
                }
            }
            if (j.isAdd) {
                startPrice.value = 0
                endPrice.value = 0
                screenChooseList[2].list = screenChooseList[2].list.filter(
                    (e: any) => e.isAdd != true,
                )
            }
        })
    })
    getDeviceListData()
}

//删除条件
const handleClose = (tag: any) => {
    console.log(tag, '***')
    tag.isChecked = false
    if (tag.index != 5) {
        screenChooseList[tag.index].list[0].isChecked = true
    }

    if (tag.isAdd) {
        startPrice.value = 0
        endPrice.value = 0
    }
    screenChooseList[tag.index].list = screenChooseList[tag.index].list.filter(
        (e: any) => e.isAdd != true,
    )
    getDeviceListData()
}

// 排序操作
const changeOption = (val: any) => {
    if (val.sort && optionActive.value == val.id) {
        val.sort = val.sort == 'ASC' ? 'DESC' : 'ASC'
    }

    console.log(screenOptionList, 'screenOptionList')
    optionActive.value = val.id
    getDeviceListData()
}

//选中后添加到 大类中的select字段
const selectScreen = async (type: any, item: any, index: number) => {
    screenChooseList[index].list.forEach((e: any) => {
        e.isChecked = false
    })

    if (index == 1) {
        screenChooseList[2].list = screenChooseList[2].list.slice(0, 1)

        const params = {
            typeId: '',
            level: '',
        }
        if (item.value) {
            params.typeId = item.typeId
            params.level = item.level
        } else {
            params.typeId = route.query.typeId
            params.level = route.query.level
        }
        const res = await getTypeListApi(params)

        const typeList_2 = res.data
            .filter((e: any) => e.level == route.query.level * 1 + 1)
            .map((j: any) => {
                return { ...j, name: j.typeName, value: j.typeId, isChecked: false, index: 1 }
            })
        screenChooseList[2].list.push(...typeList_2)
    }

    if (index == 2) {
        currentIndex = route.query.level * 1 + 1
    }
    item.isChecked = !item.isChecked
    getDeviceListData()
}

//分页page变化
const onCurrentChange = (val: number) => {
    pageData.pageNum = val
    getDeviceListData()
}
const keyWordsSearch = ref('')
onMounted(() => {
    $bus.on('search', (val: any) => {
        keyWordsSearch.value = val
        getDeviceListData(null, val)
    })
    let routeParams: any = null
    if (route.query.level && route.query.typeId) {
        routeParams = {
            level: route.query.level,
            typeId: route.query.typeId,
        }

        Promise.all([getCompanyAddressListData(), lowerClassData()]).then(() => {
            if (route.query.level == 1) {
                screenChooseList[1].list.forEach((e: any, index: number) => {
                    if (index == 0) {
                        e.isChecked = false
                    }
                    if (route.query.typeId == e.typeId) {
                        e.isChecked = true
                    }
                })
            }

            if (route.query.level == 2 || route.query.level == 3) {
                screenChooseList[1].list.forEach((e: any, index: number) => {
                    if (index == 0) {
                        e.isChecked = false
                    }
                    if (route.query.typeId == e.typeId) {
                        e.isChecked = true
                    }
                })
            }

            if (route.query.companyId) {
                routeParams = {
                    companyId: route.query.companyId,
                }
                screenChooseList[4].list[0].isChecked = false
                screenChooseList[4].list.forEach((e: any) => {
                    if (route.query.companyId == e.companyId) {
                        e.isChecked = true
                    }
                })
            }
            getDeviceListData(routeParams, null)
        })
    }

    if (route.query.keyWord) {
        routeParams = {
            keyWord: route.query.keyWord,
        }
    }

    if (!route.query.level && !route.query.typeId) {
        Promise.all([getCompanyAddressListData(), getTypeListData()]).then(() => {
            if (route.query.level == 1) {
                screenChooseList[1].list.forEach((e: any) => {
                    if (route.query.typeId == e.typeId) {
                        e.isChecked = true
                    }
                })
            }

            if (route.query.level == 2 || route.query.level == 3) {
                {
                    const item = {
                        isChecked: true,
                        name: route.query.name,
                        value: route.query.typeId,
                        index: 5,
                    }
                    screenChooseList[5].list = []
                    screenChooseList[5].list.push(item)
                }
            }
            if (route.query.companyId) {
                routeParams = {
                    companyId: route.query.companyId,
                }
                screenChooseList[4].list[0].isChecked = false
                screenChooseList[4].list.forEach((e: any) => {
                    if (route.query.companyId == e.companyId) {
                        e.isChecked = true
                    }
                })
            }
            getDeviceListData(routeParams, null)
        })
    }
})

onUnmounted(() => {
    $bus.off('search')
})

// 点击跳转装备详情
const onHandleDetails = (id: number | string) => {
    router.push({
        name: 'equipDetail',
        query: {
            id,
        },
    })
}
</script>
<style lang="scss" scoped>
.equipList {
    .showScreen {
        margin: 15px 0;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #ccc;
        // height: 30px;

        .title {
            font-size: 16px;
            font-weight: 500;
            color: #949494;
        }
    }

    .screen {
        margin-bottom: 20px;
        padding-bottom: 20px;
        border-bottom: 1px solid #ccc;
        .choose {
            margin-top: 10px;

            .line {
                padding: 14px 0;
                display: flex;
                align-items: center;
                // border-bottom: 1px solid #dddddd;

                .label {
                    // width: 100px;
                    box-sizing: border-box;

                    // padding: 0 15px;
                    // background: #f3f3f3;
                }

                .select {
                    flex: 1;
                    display: flex;
                    flex-wrap: wrap;
                    box-sizing: border-box;
                    padding: 0 15px;

                    .item {
                        padding: 2px 16px;
                        margin-right: 15px;
                        cursor: pointer;
                        color: #333;
                        // font-size: 15px;
                        font-size: 17px;
                        line-height: 25px;
                        height: 25px;

                        &:hover {
                            color: #3cb4a6;
                        }
                    }

                    .active {
                        background-color: #3cb4a6;
                        color: #fff !important;
                        border-radius: 25px;
                    }
                }

                .tags {
                    display: flex;
                    align-items: center;
                    color: #138472;
                    .item {
                        margin-left: 10px;
                    }

                    .clear-btn {
                        cursor: pointer;
                    }

                    .el-tag {
                        background-color: #fff;
                        border: 1px solid #138472;
                        color: #138472;
                    }
                    :deep .el-tag .el-tag__close {
                        color: #138472;
                    }
                }
            }
        }

        .active {
            color: #138472 !important;
            font-weight: bold !important;
        }

        .btns {
            display: flex;
            align-items: center;
            // margin-top: 20px;

            .item {
                background: #f7f9fa;
                border-radius: 12px;
                padding: 10px 20px;

                // font-size: 17px;
                font-weight: 500;
                color: #9d9d9d;
                margin-right: 10px;
                cursor: pointer;
                user-select: none;

                .icon {
                    font-size: 15px;
                }
            }
        }
    }

    .showList {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .card {
            width: calc((100% - 45px) / 4);
            margin-right: 15px;
            cursor: pointer;
            &:nth-child(4n) {
                margin-right: 0;
            }

            margin-bottom: 15px !important;
        }
    }

    .pagination {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }
}

:deep.el-pagination.is-background .el-pager li.is-active {
    background-color: #3cb4a6;
}

.class-container {
    margin-top: 20px;
    // font-size: 14px;
    color: #ccc;

    a {
        margin-right: 6px;
    }
}
:deep(.el-button--primary) {
  background-color: #3cb4a6 !important;
  border-color: #3cb4a6 !important;
}
:deep(.el-button--primary:hover),
:deep(.el-button--primary:focus),
:deep(.el-button--primary:active) {
  background-color: #2fa18f !important;
  border-color: #2fa18f !important;
}
</style>
