<template>
    <div style="display: flex; flex-direction: column; height: 100vh">
        <div style="width: 100%; background-color: #f5f5f5">
            <Header class="wapper" />
        </div>
        <div class="container">
            <el-breadcrumb separator="/" class="primary-lease">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>提交订单</el-breadcrumb-item>
            </el-breadcrumb>

            <div class="cart-title">
                <div></div>
                <div style="margin: 0 8px">提交订单</div>
                <div>({{ amountNum }})</div>
            </div>

            <el-row class="cart-th">
                <el-col :span="2">
                    <!-- <div>
                    <el-checkbox v-model="allChecked" @change="onChangeAll" :key="allKey">
                        全选
                    </el-checkbox>
                </div> -->
                </el-col>
                <el-col :span="8">
                    <div>装备信息</div>
                </el-col>
                <el-col :span="4">
                    <div>租期</div>
                </el-col>
                <el-col :span="2">
                    <div>日租金/元</div>
                </el-col>
                <el-col :span="2">
                    <div>天数</div>
                </el-col>
                <el-col :span="2">
                    <div>数量</div>
                </el-col>
                <el-col :span="2">
                    <div>总金额/元</div>
                </el-col>
                <el-col :span="2">
                    <div>操作</div>
                </el-col>
            </el-row>

            <div class="cart-tbody" v-for="(item, index) in orderList" :key="index">
                <el-row style="border-bottom: 1px solid #ccc">
                    <el-col :span="1">
                        <div style="text-align: center">
                            <!-- <el-checkbox
                            v-model="item.isChecked"
                            @change="onChangeCompany($event, index, item)"
                        >
                        </el-checkbox> -->
                        </div>
                    </el-col>
                    <el-col :span="22" class="cart-user-info">
                        <div>{{ item.companyName }}</div>
                        <div class="user-name">{{ item.person }}</div>
                        <div class="user-phone">{{ item.personPhone }}</div>
                    </el-col>
                </el-row>

                <el-row class="cart-list">
                    <el-col :span="1">
                        <!-- <div style="text-align: center">
                        <el-checkbox v-model="goods.isChecked" @change="onChangeGoods(index)">
                        </el-checkbox>
                    </div> -->
                    </el-col>
                    <el-col :span="9" class="goods-info">
                        <img :src="item.picUrl" alt="" />
                        <div class="goods-code">
                            <div style="font-size: 14px; font-weight: bold">
                                {{ item.deviceName }}
                            </div>
                            <div>装备编号： {{ item.code }}</div>
                            <div>装备型号： {{ item.typeName }}</div>
                        </div>
                    </el-col>
                    <el-col :span="4">
                        <div class="lease-date">
                            <!-- <div>{{ item.lease_date_string }}</div> -->
                            <div style="margin-bottom: 8px">
                                {{ item.rentBeginTime }}
                                <span v-if="item.rentBeginTime && item.rentEndTime">-</span>
                                {{ item.rentEndTime }}
                            </div>
                            <!-- <el-date-picker
                            style="width: 100px; margin-top: 10px"
                            v-model="item.lease_date"
                            type="daterange"
                            size="small"
                            value-format="YYYY-MM-DD"
                            @change="onLeaseDateChange($event, item)"
                        /> -->
                            <CustomDatePickerButton
                                :modelValue="item.lease_date"
                                :companyIndex="index"
                                :goodsIndex="index"
                                type="primary"
                                size="large"
                                placeholder="选择日期"
                                @onLeaseDateChange="onLeaseDateChange"
                            />
                        </div>
                    </el-col>
                    <el-col :span="2">
                        <div class="red-font">
                            {{ item.dayLeasePrice }}
                        </div>
                    </el-col>
                    <el-col :span="2">
                        <div class="red-font" style="color: #0062ff">
                            {{ item.days }}
                        </div>
                    </el-col>
                    <el-col :span="2">
                        <div>
                            <el-input-number
                                v-model="item.num"
                                style="width: 100px; margin-left: 10px"
                                :min="1"
                                :max="item.deviceCount"
                                size="small"
                            />
                        </div>
                    </el-col>
                    <el-col :span="2">
                        <div class="red-font" style="margin-left: 20px">
                            {{ item.num * item.dayLeasePrice * item.days }}
                        </div>
                    </el-col>
                    <el-col :span="2">
                        <div>
                            <el-button
                                @click="onDeleteGoods(index)"
                                link
                                style="color: #ff4800; font-weight: bold"
                            >
                                删除
                            </el-button>
                        </div>
                    </el-col>
                </el-row>
            </div>

            <div class="protocol-handle">
                <el-row style="margin: 15px 0">
                    <el-col :span="24">
                        <el-collapse v-model="activeNames">
                            <el-collapse-item :title="addressTitle" name="1">
                                <template v-if="addressList.length > 0">
                                    <div
                                        :key="index"
                                        class="address-item"
                                        @click="onSelectAddress(item.addressName)"
                                        v-for="(item, index) in addressList"
                                    >
                                        {{ item.addressName }}
                                    </div>
                                </template>

                                <template v-else>
                                    <div style="width: 100%; text-align: center; font-size: 14px">
                                        当前没有收货地址...
                                        <a
                                            style="
                                                color: #00a288;
                                                cursor: pointer;
                                                margin-left: 5px;
                                                text-decoration: underline;
                                            "
                                            @click="onAddAddress"
                                        >
                                            点击新增
                                        </a>
                                    </div>
                                </template>
                            </el-collapse-item>
                        </el-collapse>
                    </el-col>
                </el-row>
                <el-row style="display: flex; align-items: center">
                    <el-col :span="16">
                        <div class="checkbox-container">
                            <el-checkbox v-model="protocolChecked">
                                我已阅读并同意签署
                                <a href="#"> 《xxxx公司租赁服务合同》 </a>
                            </el-checkbox>
                        </div>
                    </el-col>
                    <el-col :span="3">
                        <div>
                            共：<span style="color: #ff4800; font-weight: bold">{{
                                amountDevice
                            }}</span>
                            件装备
                        </div>
                    </el-col>
                    <el-col :span="3">
                        <div class="red-font">
                            订单总金额：<span style="color: #ff4800; font-weight: bold"
                                >{{ orderAmountPice }} 元</span
                            >
                        </div>
                    </el-col>
                    <el-col :span="2">
                        <div style="text-align: right">
                            <el-button
                                size="small"
                                @click="onCartSubmit"
                                style="padding: 12px 24px; background-color: #1abc9c; color: #fff"
                                >提交</el-button
                            >
                        </div>
                    </el-col>
                </el-row>
            </div>
        </div>
        <FooterInfo />
    </div>
</template>

<script setup lang="ts">
import Header from '../../components/header/index.vue'
import FooterInfo from '../../components/FooterInfo/index.vue'
import { ElMessage } from 'element-plus'
import { getBookCarDetailByMaId, submitBookCarApi } from '../../http/api/order/index'
import CustomDatePickerButton from '../cart/components/date-picker-button.vue'
import { getAddressListApi } from 'http/api/address-manage/index'
import { getDetail } from 'http/api/equip'
import moment from 'moment'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from '../../store/user'
const userStore = useStore()
const router = useRouter()
const route = useRoute()
const pageParams = route.params
console.log(pageParams.maId)
const activeNames = ref('')
const protocolChecked = ref<boolean>(false)
const orderList = ref<any>([])
const addressTitle = ref('请选择收货地址')
const addressList = ref<any>([])

const getOrderListData = async () => {
    const addParams = {
        maId: Number(pageParams.maId),
    }
    const res: any = await getDetail(route.query.id, false)
    console.log(res, '装备详情')
    orderList.value = []
    // orderList.value = res.data

    // 组装参数
    const orderInfo = {
        rentBeginTime: '',
        rentEndTime: '',
        lease_date: '',
        days: 0,
        num: 1,
        ...res.data,
    }

    orderList.value.push(orderInfo)
    // orderList.value.forEach((e: any) => {
    //     e.isChecked = false
    //     e.goods_num = 1
    //     e.lease_day = 1
    //     // e.devInfoVoList.forEach((j: any) => {
    //     //     j.isChecked = false
    //     // })
    // })

    // console.log(orderList.value, '***********')
    // console.log(res, '购物车详情')
}

onMounted(() => {
    setTimeout(() => {
        getOrderListData()
    }, 500)
})

// 日期change事件
// const onLeaseDateChange = (e: any, item: any) => {
//     item.lease_date_string = `${e[0]}至${e[1]}`
//     item.lease_day = moment(e[1]).diff(e[0], 'day')
// }
const onLeaseDateChange = (value: any, companyIndex: number, goodsIndex: number) => {
    orderList.value.forEach((e: any) => {
        if (!value) {
            e.rentBeginTime = ''
            e.rentEndTime = ''
            e.days = 0
        } else {
            e.rentBeginTime = value[0]
            e.rentEndTime = value[1]
            e.days = moment(value[1]).diff(value[0], 'day')
        }
    })
}

// 删除按钮
const onDeleteGoods = (index: number) => {
    // console.log('删除---', index)
    orderList.value.splice(index, 1)
}

// 全选change事件
const onChangeAll = (e: boolean) => {
    orderList.value.forEach((item: any) => {
        item.isChecked = e
        // item.devInfoVoList.forEach((j: any) => {
        //     j.isChecked = e
        // })
    })
}

// 公司全选事件
const onChangeGoods = (index: number) => {
    orderList.value[index].isChecked = orderList.value[index].devInfoVoList.every(
        (e: any) => e.isChecked === true,
    )
}
// 公司全选事件
const onChangeCompany = (e: boolean, index: number, item: any) => {
    orderList.value[index].devInfoVoList.every((j) => (j.isChecked = e))
}

// 计算所有装备
const amountNum = computed(() => {
    let amountNum = 0
    orderList.value.forEach((e) => {
        amountNum = amountNum + 1
    })
    return amountNum
})
// 计算全选按钮的选中状态
const allChecked = computed(() => {
    return orderList.value.every((e: any) => e.isChecked === true)
})

// 已勾选的装备数量
const amountDevice = computed(() => {
    // let amountNum = 0
    // orderList.value.forEach((e) => {
    //     if (e.isChecked) {
    //         amountNum++
    //     }
    // })
    return 1
})
// 已勾选的装备数量
const amountDeviceList = computed(() => {
    let selectList: any = []
    orderList.value.forEach((e: any) => {
        if (e.isChecked) {
            selectList.push(e)
        }
    })
    return selectList
})

// 计算订单总价格
const orderAmountPice = computed(() => {
    let orderAmountPice = 0
    orderList.value.forEach((e) => {
        // if (e.isChecked) {

        // }
        orderAmountPice = e.num * e.dayLeasePrice * e.days
    })
    return orderAmountPice
})

// 提交按钮
const onCartSubmit = async () => {
    // ElMessage.closeAll()
    // if (amountDevice.value < 1) {
    //     ElMessage({
    //         showClose: false,
    //         message: '请选择装备',
    //         type: 'error',
    //     })
    //     return
    // }
    // console.log(amountDeviceList.value[0].lease_date == undefined)
    if (orderList.value[0].days < 1) {
        ElMessage({
            showClose: false,
            message: '请选择租期',
            type: 'error',
        })
        return
    }
    if (!protocolChecked.value) {
        ElMessage({
            showClose: false,
            message: '请阅读公司合同',
            type: 'error',
        })
        return
    }

    if (addressTitle.value === '请选择收货地址') {
        ElMessage({
            showClose: false,
            message: '请选择收货地址',
            type: 'error',
        })
        return
    }

    const orderInfo = orderList.value[0]
    const submitInfo = {
        maId: orderInfo.maId,
        id: orderInfo.id,
        rentBeginTime: orderInfo.rentBeginTime + ' ' + '00:00:00',
        rentEndTime: orderInfo.rentEndTime + ' ' + '23:59:59',
        manageType: orderInfo.manageType,
        days: orderInfo.days,
        num: orderInfo.num,
        costs: orderInfo.num * orderInfo.days * orderInfo.dayLeasePrice,
    }

    const submitParams = {
        cost: orderAmountPice.value,
        address: addressTitle.value.split('：')[1],
        detailsList: [submitInfo],
    }
    // console.log('submitParams', submitParams)
    const res: any = await submitBookCarApi([submitParams])
    if (res.code === 200) {
        ElMessage({
            showClose: false,
            message: '提交成功',
            type: 'success',
        })
        userStore.editcurrentMenuItem('orderManagement')
        setTimeout(() => {
            router.push({
                name: 'my-user',
            })
        }, 500)

        // router.push({
        //     path: `/equipDetail/${pageParams.maId}`,
        // })
    }
}

// 获取收货地址
const getReceiptGoodsAddress = async () => {
    const res: any = await getAddressListApi({})
    addressList.value = res.rows.map((e: any) => {
        return {
            addressName: `${e.provinceName}${e.cityName}${e.areaName}${e.address}`,
        }
    })
}

// 去往地址管理
const onAddAddress = () => {
    userStore.editcurrentMenuItem('address-manage')
    setTimeout(() => {
        router.push({
            name: 'my-user',
        })
    }, 500)
}
// 选择收货地址
const onSelectAddress = (address: any) => {
    addressTitle.value = '收货地址：' + address
    activeNames.value = ''
}

getReceiptGoodsAddress()
</script>

<style lang="scss" scoped>
.container {
    width: 1553px;
    margin: 15px auto;
    flex: 1;
    // min-height: 550px;
    background: #eeeff6;
    font-size: 16px;
    padding: 20px 10px;
    background-color: #fff;
    border-radius: 15px;

    .cart-title {
        margin-top: 20px;
        padding: 10px 0;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: bold;
        letter-spacing: 1px;
    }

    .cart-title div:first-child {
        width: 5px;
        height: 20px;
        background-color: #4fabfe;
    }

    .cart-th {
        margin: 15px 0;
        font-size: 18px;
        div {
            text-align: center;
        }
    }

    .cart-tbody {
        background: #fff;
        padding: 8px 12px;
        margin: 10px;

        .cart-user-info {
            display: flex;
            align-items: center;
            // font-size: 13px;

            .user-name,
            .user-phone {
                padding: 3px 18px;
                border: 1px solid #ccc;
            }

            .user-name {
                margin-left: 20px;
                border-right: none;
            }
        }

        .cart-list {
            margin: 15px 0;
            display: flex;
            align-items: center;
            // font-size: 13px;
            div {
                text-align: center;
            }

            .goods-info {
                display: flex;
                align-content: center;

                img {
                    width: 160px;
                    height: 100px;
                }

                .goods-code {
                    margin-left: 20px;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-around;

                    div {
                        text-align: left;
                    }
                }
            }

            .lease-date {
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                // font-size: 12px;
            }

            .red-font {
                color: #ff4800;
                font-weight: bold;
            }
        }
    }

    .protocol-handle {
        background: #fff;
        padding: 8px 12px;
        margin: 10px;
        // font-size: 13px;
        .checkbox-container a {
            color: #ff4800;
            text-decoration: underline;
        }
    }
}

.address-item {
    margin: 0 auto;
    padding: 6px 10px;
    cursor: pointer;
}
.address-item:hover {
    background-color: #c9e7e5;
}
</style>
