<template>
    <div class="app-container app-container-content">
        <!-- 搜索表单 -->
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="auto"
        >
            <el-card class="search-box">
                <el-row :gutter="5" style="display: flex; justify-content: space-between">
                    <el-col :span="5" style="width: 320px">
                        <el-form-item prop="deviceName" label="装备名称">
                            <el-input
                                v-model="queryParams.deviceName"
                                placeholder="请输入装备名称"
                                clearable
                                @keyup.enter.native="handleQuery"
                                maxlength="20"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="5" style="width: 320px">
                        <el-form-item prop="orderStatus" label="订单状态">
                            <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
                                <el-option
                                    v-for="item in statusList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="5">
                        <el-form-item prop="dateRange" label="申请时间">
                            <el-date-picker
                                v-model="time"
                                type="daterange"
                                value-format="yyyy-MM-dd"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                style="width: 240px"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="5" style="width: 320px">
                        <el-form-item prop="czcompanyName" label="出租单位">
                            <el-input
                                v-model="queryParams.czcompanyName"
                                placeholder="请输入出租单位"
                                clearable
                                @keyup.enter.native="handleQuery"
                                maxlength="20"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="5" style="width: 320px">
                        <el-form-item prop="companyName" label="承租单位">
                            <el-input
                                v-model="queryParams.companyName"
                                placeholder="请输入承租单位"
                                clearable
                                @keyup.enter.native="handleQuery"
                                maxlength="20"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24" style="text-align: right">
                        <el-form-item style="margin-top: 10px; padding-right: 20px">
                            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                                >查询</el-button
                            >
                            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-card>
        </el-form>

        <el-card class="content-box">
            <div class="table-container">
                <!-- 订单列表 -->
                <template v-if="cardList.length > 0">
                    <div class="cart-tbody" v-for="(item, index) in cardList" :key="index">
                        <el-row class="order-title-info">
                            <el-col :span="8">
                                <span> <i class="el-icon-document-copy"></i>订单编号： </span>
                                <span>{{ item.code }}</span>
                            </el-col>
                            <el-col :span="8">
                                <span> 下单时间： </span>
                                <span>{{ item.orderTime }}</span>
                            </el-col>
                            <el-col :span="8">
                                <span> 装备所属公司： </span>
                                <span>{{ item.czcompanyName }}</span>
                            </el-col>
                            <div class="order-type-box">
                                <el-tag :type="orderType(item.orderStatus)" effect="light">
                                    {{ orderText(item.orderStatus) }}
                                </el-tag>
                            </div>
                        </el-row>

                        <el-row class="order-title-info">
                            <el-col :span="8">
                                <span> 出租方联系电话： </span>
                                <span>{{ item.personPhone }}</span>
                            </el-col>
                            <el-col :span="8">
                                <span> 承租方联系电话： </span>
                                <span>{{ item.phoneNumber }}</span>
                            </el-col>
                            <el-col :span="8">
                                <span> 收货地址： </span>
                                <span>{{ item.address }}</span>
                            </el-col>
                        </el-row>

                        <el-row class="order-title-info" style="border-bottom: 1px solid #ccc; margin-bottom: 10px">
                            <el-col :span="8">
                                <span> 出租方姓名： </span>
                                <span>{{ item.sellerName }}</span>
                            </el-col>
                            <el-col :span="8">
                                <span> 承租方姓名： </span>
                                <span>{{ item.buyerName }}</span>
                            </el-col>
                            <el-col :span="8">
                                <span> 承租方所属单位---： </span>
                                <span>{{ item.companyName }}</span>
                            </el-col>
                        </el-row>

                        <el-row>
                            <!-- 装备信息 -->
                            <el-col :span="14">
                                <div
                                    v-for="(goods, j) in item.detailsList"
                                    :key="j"
                                    class="order-items order-info"
                                    :style="j != item.detailsList.length - 1 ? 'border-bottom:1px solid #f0f0f0' : ''"
                                    style="min-height: 80px"
                                >
                                    <img v-if="goods.url" :src="goods.url" style="width: 110px; height: 70px" alt="" />
                                    <div v-else style="width: 110px; height: 70px; display: flex;align-items: center;justify-content: center;">暂无图片</div>
                                    <div
                                        style="
                                            min-height: 80px;
                                            flex: 1;
                                            display: flex;
                                            justify-content: space-around;
                                            flex-direction: column;
                                            padding-left: 12px;
                                            font-size: 13px;
                                        "
                                    >
                                        <el-row style="color: #169bd5; font-weight: bold">
                                            {{ goods.deviceName }}
                                        </el-row>
                                        <el-row>
                                            <el-col :span="4">租期：</el-col>
                                            <el-col :span="8">
                                                <span
                                                    style="margin-right: 10px"
                                                    :style="
                                                        item.orderStatus == 20 ? 'text-decoration: line-through' : ''
                                                    "
                                                >
                                                    {{ goods.days }} 天
                                                </span>
                                                <span v-if="item.orderStatus == 20">
                                                    {{
                                                        momentInit(goods.takeOverTime).diff(
                                                            goods.rentOverTime,
                                                            'day',
                                                        ) === 0
                                                            ? 1
                                                            : momentInit(goods.takeOverTime).diff(
                                                                  goods.rentOverTime,
                                                                  'day',
                                                              )
                                                    }}
                                                    天
                                                </span>
                                            </el-col>
                                            <!-- <el-col :span="4"> </el-col> -->
                                            <el-col :span="12" style="padding-left: 5px;">编号：{{ goods.code }}</el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="4"> 数量：</el-col>
                                            <el-col :span="8"> {{ goods.num }} 台</el-col>
                                        </el-row>
                                        <el-row v-if="isShowDayLeasePrice">
                                            <el-col :span="4"> 日租金：</el-col>
                                            <el-col :span="8" style="color: #eb190a">
                                                {{ goods.dayLeasePrice ? `${goods.dayLeasePrice}元/天` : '电话面议' }}
                                            </el-col>
                                        </el-row>
                                    </div>
                                </div>
                            </el-col>

                            <!-- 租期信息 -->
                            <el-col :span="8" class="order-items-info">
                                <div
                                    v-for="(goods, j) in item.detailsList"
                                    :key="j"
                                    class="order-info"
                                    :style="j != item.detailsList.length - 1 ? 'border-bottom:1px solid #f0f0f0' : ''"
                                    style="min-height: 80px"
                                >
                                    <div
                                        style="
                                            display: flex;
                                            justify-content: center;
                                            align-items: center;
                                            flex-direction: column;
                                        "
                                    >
                                        <div>租期</div>
                                        <div
                                            style="font-weight: bold; margin-top: 10px"
                                            :style="item.orderStatus == 20 ? 'text-decoration: line-through' : ''"
                                        >
                                            {{ formatDate(goods.rentBeginTime) }}至{{ formatDate(goods.rentEndTime) }}
                                        </div>
                                        <div style="font-weight: bold; margin-top: 10px" v-if="item.orderStatus == 20">
                                            {{ goods.takeOverTime ? goods.takeOverTime.slice(0, 10) : '' }}至
                                            {{ goods.rentOverTime ? goods.rentOverTime.slice(0, 10) : '' }}
                                        </div>
                                    </div>
                                </div>
                            </el-col>

                            <!--
          &lt;!&ndash; 状态信息 &ndash;&gt;
          <el-col :span="3" class="order-items-info">
            <div
              v-for="(goods, j) in item.detailsList"
              :key="j"
              class="order-info"
              :style="j != item.detailsList.length - 1 ? 'border-bottom:1px solid #eee' : ''"
              style="min-height: 80px; width: 95%"
            >
              <el-tag :type="orderType(goods.orderStatus)" effect="light">
                {{ orderText(goods.orderStatus) }}
              </el-tag>
            </div>
          </el-col>
-->

                            <!-- 操作按钮 -->
                            <el-col :span="2" style="display: flex;align-items: center;justify-content: center">
                                <div>
                                    <!-- <el-button @click="handleViewOrder(item)" type="primary" size="small">
                订单详情
              </el-button> -->
                                    <el-button
                                        v-if="item.orderStatus == 20"
                                        @click="handleViewRepair(item)"
                                        type="primary"
                                        size="small"
                                    >
                                        检修详情
                                    </el-button>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </template>
            </div>
            <div class="pagination-wrapper">
                <!-- 分页 -->
                <pagination
                    :total="total"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
                />
            </div>
        </el-card>
        <!-- 检修详情弹窗 -->
        <el-dialog :title="dialogTitle" width="65%" destroy-on-close :visible.sync="addOrEditDialogCostVisible">
            <el-row style="display: flex; letter-spacing: 1px; padding: 0 10px 20px; justify-content: space-between">
                <div style="flex: 1">
                    <span>订单编号：</span>
                    <span>{{ overhaulDetails.code }}</span>
                </div>
                <div style="flex: 1">
                    <span>装备套数：</span>
                    <span>{{ overhaulDetails.maNumber }}</span>
                </div>
                <div style="flex: 1">
                    <span>结算单位：</span>
                    <span>{{ overhaulDetails.leaseCompany }}</span>
                </div>
            </el-row>

            <!-- 共享费用明细 -->
            <TitleTip :titleText="`共享费用明细`" />
            <el-table
                border
                :data="orderDetailDtoList"
                show-overflow-tooltip
                :header-cell-style="{ color: '#fff', background: '#00a288' }"
                height="546"
            >
                <el-table-column prop="code" align="center" label="装备编号" />
                <el-table-column prop="deviceName" align="center" label="装备名称" />
                <el-table-column prop="typeName" align="center" label="型号" />
                <el-table-column prop="num" align="center" label="数量" />
                <el-table-column prop="days" align="center" label="共享天数" />
                <el-table-column align="center" label="租期">
                    <template #default="{ row }">
                        {{ formatDate(row.preOutboundTime) + '至' + formatDate(row.rentOverTime) }}
                    </template>
                </el-table-column>
            </el-table>

            <!-- 维修费用明细 -->
            <TitleTip :titleText="`维修费用明细`" />
            <el-table
                :data="repairRecordList"
                border
                show-overflow-tooltip
                :header-cell-style="{ background: '#00a288', color: '#fff' }"
                height="546"
            >
                <el-table-column prop="code" align="center" label="装备编号" />
                <el-table-column prop="deviceName" align="center" label="装备名称" />
                <el-table-column prop="typeName" align="center" label="型号" />
                <el-table-column prop="repairNum" align="center" label="维修数量" />
                <el-table-column align="center" label="维修费用(元)">
                    <template #default="{ row }">
                        <template v-if="row.isCheck == 0">
                            {{ row.repairPrice }}
                        </template>
                        <template v-else>
                            <el-input
                                v-model="row.repairPrice"
                                style="width: 100%"
                                placeholder="请输入改价费用"
                                clearable
                            />
                        </template>
                    </template>
                </el-table-column>
                <el-table-column prop="repairChangePrice" align="center" label="改价后费用(元)" />
                <el-table-column align="center" label="附件" width="160">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="onViewFileImg(row, 0)">查看</el-button>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="160" v-if="dialogTitle === '费用结算'">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="row.isCheck = row.isCheck === 0 ? 1 : 0">
                            {{ row.isCheck === 0 ? '改价' : '取消改价' }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 报废费用明细 -->
            <TitleTip :titleText="`报废费用明细`" />
            <el-table
                :data="scrapRecordList"
                border
                show-overflow-tooltip
                :header-cell-style="{ background: '#00a288', color: '#fff' }"
                height="546"
            >
                <el-table-column prop="code" align="center" label="装备编号" />
                <el-table-column prop="deviceName" align="center" label="装备名称" />
                <el-table-column prop="typeName" align="center" label="型号" />
                <el-table-column prop="scrapNum" align="center" label="报废数量" />
                <el-table-column prop="scrapReason" align="center" label="报废原因" />
                <el-table-column prop="scrapPrice" align="center" label="报废费用(元)">
                    <template #default="{ row }">
                        <template v-if="row.isCheck == 0">
                            {{ row.scrapPrice }}
                        </template>
                        <template v-else>
                            <el-input
                                v-model="row.scrapPrice"
                                style="width: 100%"
                                placeholder="请输入改价费用"
                                clearable
                            />
                        </template>
                    </template>
                </el-table-column>
                <el-table-column prop="scrapChangePrice" align="center" label="改价后费用(元)" />
                <el-table-column align="center" label="附件" width="160">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="onViewFileImg(row, 1)">查看</el-button>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="160" v-if="dialogTitle === '费用结算'">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="row.isCheck = row.isCheck === 0 ? 1 : 0">
                            {{ row.isCheck === 0 ? '改价' : '取消改价' }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 丢失费用明细 -->
            <TitleTip :titleText="`丢失费用明细`" />
            <el-table
                :data="lossRecordList"
                border
                show-overflow-tooltip
                :header-cell-style="{ background: '#00a288', color: '#fff' }"
                height="546"
            >
                <el-table-column prop="code" align="center" label="装备编号" />
                <el-table-column prop="deviceName" align="center" label="装备名称" />
                <el-table-column prop="typeName" align="center" label="型号" />
                <el-table-column prop="lossNum" align="center" label="丢失数量" />
                <el-table-column prop="lossPrice" align="center" label="丢失费用(元)">
                    <template #default="{ row }">
                        <template v-if="row.isCheck == 0">
                            {{ row.lossPrice }}
                        </template>
                        <template v-else>
                            <el-input
                                v-model="row.lossPrice"
                                style="width: 100%"
                                placeholder="请输入改价费用"
                                clearable
                            />
                        </template>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="附件" width="160">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="onViewFileImg(row, 2)">查看</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <!-- 附件详情弹窗 -->
        <el-dialog :visible.sync="innerVisible" width="500" title="附件详情" append-to-body>
            <el-table
                :data="viewFileInfoList"
                border
                show-overflow-tooltip
                :header-cell-style="{ background: '#00a288', color: '#fff' }"
                height="546"
            >
                <el-table-column prop="fileName" align="center" label="文件名称" />
                <el-table-column align="center" label="操作" width="120">
                    <template #default="{ row }">
                        <el-image
                            style="width: 60px; height: 60px"
                            :src="row.fileUrl"
                            :zoom-rate="1.2"
                            :max-scale="7"
                            :min-scale="0.2"
                            :preview-src-list="[row.fileUrl]"
                            :initial-index="0"
                            fit="cover"
                            :z-index="9999999999"
                            :preview-teleported="true"
                        />
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <!-- 订单详情弹窗 -->
        <OrderDetailDialog
            :visible.sync="showOrderDetail"
            :orderId="orderId"
            :orderStatus="orderStatus"
            title="订单详情"
        />
    </div>
</template>

<script>
import TitleTip from '@/components/TitleTip'
import { getOrderListApi, getOrderListInfoApi, getOverhaulApi } from '@/api/search/order'
import { getPriceShowConfigApi } from '@/api/common'
import moment from 'moment'
import OrderDetailDialog from '@/views/EquipmentSharedOrder/order/detail.vue'

export default {
    components: { OrderDetailDialog, TitleTip },
    name: 'order',
    data() {
        return {
            // 基础状态
            loading: false,
            showSearch: true,
            showOrderDetail: false,

            // 订单相关
            orderStatus: '',
            orderId: '',
            statusList: [
                { id: '1', name: '待确认' },
                { id: '2', name: '已确认' },
                { id: '3', name: '已驳回' },
            ],

            // 分页和查询
            total: 0,
            time: [],
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                keyWord: undefined,
                status: undefined,
                startTime: undefined,
                endTime: undefined,
            },

            // 数据列表
            cardList: [],

            // 弹窗相关
            dialogTitle: '',
            addOrEditDialogCostVisible: false,
            viewOrderDetailsOrderId: '',
            orderDetailDtoList: [],
            repairRecordList: [],
            scrapRecordList: [],
            lossRecordList: [],
            overhaulDetails: {},
            fileListAll: [],
            innerVisible: false,
            viewFileInfoList: [],

            // 工具
            momentInit: moment,
            isShowDayLeasePrice: false,
        }
    },
    created() {
        this.getList()
        this.getPriceShowConfig()
    },
    methods: {
        // 仅保留日期（YYYY-MM-DD）
        formatDate(dateStr) {
            if (!dateStr) return ''
            // 兼容 'YYYY-MM-DD HH:mm:ss' 或 ISO 字符串
            const s = String(dateStr)
            return s.length >= 10 ? s.slice(0, 10) : s
        },
        // 获取订单状态文本
        orderText(status) {
            const foundStatus = this.statusList.find((e) => e.id === status)
            return foundStatus ? foundStatus.name : '未知状态'
        },

        // 获取订单状态样式
        orderType(status) {
            if ([1, 2, 3, 5].includes(Number(status))) return 'primary'
            if ([4, 7].includes(Number(status))) return 'success'
            if ([6].includes(Number(status))) return 'warning'
            if ([8].includes(Number(status))) return 'danger'
            return ''
        },

        /** 查询订单列表 */
        getList() {
            this.loading = true

            // 处理日期范围
            if (this.time.length > 0) {
                this.queryParams.startTime = this.time[0]
                this.queryParams.endTime = this.time[1]
            } else {
                this.queryParams.startTime = undefined
                this.queryParams.endTime = undefined
            }

            getOrderListApi(this.queryParams)
                .then((res) => {
                    this.cardList = res.data.rows
                    this.total = res.data.total
                    this.loading = false
                })
                .catch(() => {
                    this.loading = false
                })
        },

        // 查看订单详情
        handleViewOrder(row) {
            this.showOrderDetail = true
            this.orderStatus = row.orderStatus
            this.orderId = row.orderId
        },

        // 查看检修详情
        handleViewRepair(item) {
            this.viewOrderDetailsOrderId = item.orderId
            this.dialogTitle = '检修详情'

            getOrderListInfoApi({ orderId: this.viewOrderDetailsOrderId }).then(async (res) => {
                if (item.orderStatus === 20) {
                    await getOverhaulApi(this.viewOrderDetailsOrderId).then((resTwo) => {
                        this.orderDetailDtoList = resTwo.data.orderDetailDtoList || []
                        this.repairRecordList = resTwo.data.repairRecordList || []
                        this.scrapRecordList = resTwo.data.scrapRecordList || []
                        this.lossRecordList = resTwo.data.lossRecordList || []
                        this.fileListAll = resTwo.data.fileInfoList || []
                        this.overhaulDetails = resTwo.data || {}
                    })
                }
                this.addOrEditDialogCostVisible = true
            })
        },

        // 查看附件图片
        onViewFileImg(row, index) {
            this.viewFileInfoList = this.fileListAll ? this.fileListAll.filter((e) => e.fileType === index) : []
            this.innerVisible = true
        },

        /** 重置查询条件 */
        async resetQuery() {
            await this.resetForm('queryForm')
            this.time = []
            this.queryParams.keyWord = null
            this.handleQuery()
        },

        /** 执行查询 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },

        // 获取价格显示配置
        getPriceShowConfig() {
            getPriceShowConfigApi().then((res) => {
                this.isShowDayLeasePrice = res?.rows[0].status == 0 ? true : false
            })
        },
    },
}
</script>

<style lang="scss" scoped>
.cart-tbody {
    background: #fff;
    padding: 16px;
    margin-bottom: 14px;
    border-radius: 10px;
    border: 1px solid #169bd5;
    box-shadow: 0 0 0 1px rgba(22, 155, 213, 0.2), 0 0 8px rgba(22, 155, 213, 0.3);
    // 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.cart-tbody:hover {
    border-color: #0d7aa8;
    box-shadow: 0 0 0 2px rgba(22, 155, 213, 0.3), 0 0 12px rgba(22, 155, 213, 0.4), 0 6px 16px rgba(0, 0, 0, 0.12);
}

:deep .el-form--inline .el-form-item {
    margin-right: 6px;
    width: 95%;
}

.order-title-info {
    position: relative;
    padding: 8px 0;
    font-size: 14px;
    color: #666;

    // 标签与内容的层级：标签次要、内容主要
    span:first-child {
        color: #666;
    }
    span + span {
        color: #333;
    }

    &:not(:last-child) {
        margin-bottom: 6px;
    }

    .order-type-box {
        position: absolute;
        top: 0;
        right: 0;
    }
}

.order-items {
    border-right: 1px solid #ccc;
}

.order-info {
    display: flex;
    padding: 8px 0;
    align-items: center;
    justify-content: center;
}

.order-items-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-right: 1px solid #ccc;
    font-size: 13px;
}

.red-font {
    color: #ff4800;
    font-weight: bold;
    margin-top: 10px;
}

.handle-btn {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .el-button {
        width: calc((100% - 50px) / 4);
        margin-bottom: 10px;
        margin-left: 10px !important;
    }
}

.app-container-content {
    // background-color: #f5f5f5;

    :deep(.el-dialog) {
        display: flex !important;
        flex-direction: column !important;
        margin: 0 !important;
        position: absolute !important;
        top: 50% !important;
        left: 50% !important;
        transform: translate(-50%, -50%) !important;
        max-height: 100vh !important;

        .el-dialog__body {
            flex: 1;
            overflow-y: scroll !important;
        }

        .dialog-content {
            padding: 20px;
        }
    }
}

.search-box {
    margin-bottom: 20px;
    border-radius: 8px;
    padding: 0;
    ::v-deep .el-card__body {
        padding: 20px !important;
    }
}
.el-form-item--small.el-form-item {
    margin-bottom: 0px;
}
.content-box {
    border-radius: 8px;
    height: calc(100vh - 250px);
    display: flex;
    flex-direction: column;
    overflow: hidden;

    ::v-deep .el-card__body {
        display: flex !important;
        flex-direction: column !important;
        height: 100% !important;
        padding: 20px;
    }

    .el-row:first-child {
        margin-bottom: 6px;
        flex-shrink: 0;

        .el-col {
            display: flex;
            /* justify-content: flex-end; */
            align-items: center;
            gap: 12px;
        }
    }

    .table-container {
        flex: 1;
        overflow-y: auto;
        margin-bottom: 0;
        min-height: 0;
        display: flex;
        flex-direction: column;
    }

    .pagination-wrapper {
        flex-shrink: 0;
        padding-top: 6px;
        margin-top: auto;

        ::v-deep .pagination-container {
            padding: 0px 20px !important;
            /* margin-bottom: 30px; */
        }
    }
}
</style>
