<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :model="queryParams" ref="queryForm" @submit.native.prevent :inline="true" label-width="80px">
                <el-form-item label="订单状态" prop="orderStatus">
                    <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable style="width: 160px">
                        <el-option key="6" label="清洗中" value="6" />
                        <el-option key="7" label="已出厂" value="7" />
                        <el-option key="8" label="已到店" value="8" />
                        <el-option key="9" label="待送衣" value="9" />
                        <el-option key="10" label="送衣中" value="10" />
                    </el-select>
                </el-form-item>
                <el-form-item label="订单来源" prop="flowStatus">
                    <el-select v-model="queryParams.flowStatus" placeholder="请选择订单来源" clearable style="width: 160px">
                        <el-option key="0" label="线上" value="0" />
                        <el-option key="1" label="线下" value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="订单编号" prop="orderNo">
                    <el-input v-model="queryParams.orderNo" placeholder="请扫描订单编号" clearable @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="时间范围">
                    <el-date-picker v-model="createTimeRange" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 240px"> </el-date-picker>
                </el-form-item>
                <el-form-item label="会员手机" prop="appUserPhoneNumber">
                    <el-input v-model="queryParams.appUserPhoneNumber" placeholder="请输入会员手机" clearable @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="会员条码" prop="userId">
                    <el-input v-model="queryParams.userId" placeholder="请扫描会员条码" clearable @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 数据列表 -->
        <el-card class="table-card">
            <div class="table-operations" slot="header">
                <div class="left">
                    <span class="title">取衣列表</span>
                </div>
                <div class="right">
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </div>
            </div>

            <el-table v-loading="loading" :data="clothOrderList" border stripe highlight-current-row>
                <el-table-column label="订单编号" align="center" prop="orderNo" min-width="200" fixed="left" />
                <el-table-column label="衣物数量" align="center" prop="orderClothCount" width="100" />
                <el-table-column label="支付信息" align="center" width="200">
                    <template slot-scope="scope">
                        <div class="payment-info">
                            <span class="amount">¥{{ scope.row.payAmount }}</span>
                            <span class="payment-type">
                                <i :class="getPaymentIcon(scope.row.payType)"></i>
                                {{ getPaymentText(scope.row.payType) }}
                            </span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="客户信息" align="center" width="220">
                    <template slot-scope="scope">
                        <div class="customer-info">
                            <div class="source">
                                <el-tag size="small" :type="scope.row.orderSource === 'OFFLINE' ? 'warning' : 'success'">
                                    {{ scope.row.orderSource === 'OFFLINE' ? '线下' : '线上' }}
                                </el-tag>
                            </div>
                            <div class="user">
                                <span class="name">{{ scope.row.appUserName }}</span>
                                <span class="phone">{{ scope.row.appUserPhoneNumber }}</span>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="订单时间" align="center" prop="createTime" width="180" />
                <el-table-column label="预计取衣时间" align="center" prop="planSendToUserTime" width="180" />
                <el-table-column label="状态" align="center" width="100">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.cloth_order_status" :value="scope.row.orderStatus" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right" width="240">
                    <template slot-scope="scope">
                        <template v-if="scope.row.payTimeType == '1' && scope.row.payStatus != 1">
                            <el-button type="text" size="mini" icon="el-icon-money" @click="toPay(scope)">立刻支付</el-button>
                        </template>
                        <template v-else>
                            <el-button type="text" size="mini" icon="el-icon-box" @click="handleDetail(scope.row)">取衣</el-button>
                            <el-button v-if="(scope.row.orderStatus == '8' || scope.row.orderStatus == '9') && scope.row.sendClothWay == 1" type="text" size="mini" icon="el-icon-user" @click="selectDeliveryMan(scope)"> 分配派送员 </el-button>
                            <el-button v-if="scope.row.orderStatus == '9' && scope.row.sendClothWay == 1" type="text" size="mini" icon="el-icon-check" @click="confirmSend(scope)"> 确认送达 </el-button>
                        </template>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>

        <!-- 取衣详情弹窗 -->
        <el-dialog :title="title" :visible.sync="open" width="80%" :close-on-click-modal="false" class="take-clothes-dialog" append-to-body>
            <div class="order-detail">
                <!-- 订单基本信息 -->
                <el-card class="info-card">
                    <div class="order-info">
                        <div class="info-item">
                            <span class="label">订单号：</span>
                            <span class="value">{{ orderDetail.orderNo }}</span>
                        </div>
                        <div class="info-item">
                            <span class="label">支付方式：</span>
                            <span class="value">
                                {{ getPaymentText(orderDetail.payType) }}
                                <span class="amount">¥{{ orderDetail.payAmount }}</span>
                            </span>
                        </div>
                        <div class="info-item">
                            <span class="label">客户姓名：</span>
                            <span class="value">{{ orderDetail.appUserName }}</span>
                        </div>
                        <div class="info-item">
                            <span class="label">联系电话：</span>
                            <span class="value">{{ orderDetail.appUserPhoneNumber }}</span>
                        </div>
                        <div class="info-item">
                            <span class="label">下单时间：</span>
                            <span class="value">{{ orderDetail.createTime }}</span>
                        </div>
                        <div class="info-item">
                            <span class="label">备注信息：</span>
                            <span class="value">{{ orderDetail.remark || '无' }}</span>
                        </div>
                    </div>
                </el-card>

                <!-- 衣物列表 -->
                <el-card class="clothes-card">
                    <div slot="header">
                        <span>衣物列表</span>
                        <el-button type="primary" size="small" icon="el-icon-printer" style="float: right" @click="printTicket" :disabled="!selectedClothes.length"> 打印小票 </el-button>
                    </div>
                    <el-table :data="orderClothDetails" border stripe @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55" align="center" :selectable="(row) => row.flowStatus != '5'" />
                        <el-table-column label="衣物条码" prop="washCode" width="180" />
                        <el-table-column label="衣服名称" prop="clothItemName" min-width="150" />
                        <el-table-column label="重洗" align="center" prop="repeatCount" width="100">
                          <template slot-scope="scope">
                            <span style="color: red" v-if="scope.row.repeatCount>0">{{ scope.row.repeatCount || 0 }}次</span>
                            <span v-else>无</span>
                          </template>
                        </el-table-column>
                        <el-table-column label="品牌" prop="clothBrandName" width="120" />
                        <el-table-column label="颜色" width="150">
                            <template slot-scope="scope">
                                <el-tag v-for="item in scope.row.orderClothColors" :key="item.id" size="small" style="margin-right: 4px">
                                    {{ item.clothColorName }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="瑕疵" width="150">
                            <template slot-scope="scope">
                                <el-tag v-for="item in scope.row.orderClothFlaws" :key="item.id" type="warning" size="small" style="margin: 2px">
                                    {{ item.clothFlawName }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="洗衣速度" prop="clothSpeedName" width="120" />
                        <el-table-column label="附件" width="150">
                            <template slot-scope="scope">
                                <el-tag v-for="item in scope.row.orderClothAdjuncts" :key="item.id" type="info" size="small" style="margin: 2px"> {{ item.adjunctName }}×{{ item.num }} </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="挂衣号" width="120">
                            <template slot-scope="scope">
                                <span v-if="scope.row.clothHanger" class="hanger-code"> {{ scope.row.clothHanger.name }}#{{ scope.row.clothHangerCode }} </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" width="100">
                            <template slot-scope="scope">
                                <dict-tag :options="dict.type.order_cloth_flow_status" :value="scope.row.flowStatus" />
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
                          <template slot-scope="scope">
                            <el-button type="text" @click="repeatOrderClothItem(scope.row.orderNo, scope.row.id)" v-if="scope.row.flowStatus!=0">返洗 </el-button>
                          </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </div>

            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitForm" :disabled="!selectedClothes.length"> 确认取衣 ({{ selectedClothes.length }}) </el-button>
            </div>
        </el-dialog>

         <!-- 配置派送员 -->
        <el-dialog title="配置派送员" :visible.sync="deliveryOpen" width="80%" :close-on-click-modal="false" class="take-clothes-dialog" append-to-body>
            <el-row :gutter="15">
                    <el-form ref="form" :model="selectDeliveryForm" :rules="rules" label-width="100px">
                        <el-col :span="24">
                            <el-form-item label="配送方式" prop="service_trans_id">
                                <el-radio-group v-model="selectDeliveryForm.service_trans_id">
                                    <el-radio-button key="0" label="0">第三方配送</el-radio-button>
                                    <el-radio-button key="1" label="1">门店自送</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" v-if="selectDeliveryForm.service_trans_id == 1">
                            <el-form-item label="派送员" prop="takeClothAppUserId">
                                <el-select v-model="selectDeliveryForm.deliveryManId" placeholder="请选择派送员" clearable>
                                    <el-option v-for="man in deliveryManList" :key="man.appUserId" :label="man.realName" :value="man.appUserId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-form>
                </el-row>

                <div>
                    <el-button type="primary" @click="submitDelivery" style="margin-left: 40%">提交</el-button>
                </div>
        </el-dialog>


        <pay-status-popup ref="payStatusPopup" hidePointer @paySuccess="handlePaySuccess" @confirm="handlePayConfirm" @error="handlePayError"> </pay-status-popup>
    </div>
</template>

<style lang="scss" scoped>
.app-container {
    padding: 20px;

    .search-card {
        margin-bottom: 20px;
    }

    .table-card {
        .table-operations {
            display: flex;
            justify-content: space-between;
            align-items: center;

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

.take-clothes-dialog {
    .order-detail {
        .info-card {
            margin-bottom: 20px;

            .order-info {
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 16px;

                .info-item {
                    .label {
                        color: #909399;
                        margin-right: 8px;
                    }

                    .value {
                        color: #303133;
                        font-weight: 500;

                        .amount {
                            color: #f56c6c;
                            margin-left: 8px;
                        }
                    }
                }
            }
        }

        .clothes-card {
            .hanger-code {
                color: #409eff;
                font-weight: 500;
            }
        }
    }
}

.payment-info {
    display: flex;
    flex-direction: column;
    gap: 4px;

    .amount {
        font-size: 16px;
        font-weight: bold;
        color: #f56c6c;
    }

    .payment-type {
        color: #909399;

        i {
            margin-right: 4px;
        }
    }
}

.customer-info {
    .source {
        margin-bottom: 4px;
    }

    .user {
        display: flex;
        flex-direction: column;
        gap: 2px;

        .name {
            font-weight: 500;
        }

        .phone {
            color: #909399;
        }
    }
}
</style>

<script>
import { getSendClothOrderList, refundOrderCloth, takeCloth, setSendDelivery, setIntracityExpress, setDeliveryManByAppointment, confirmSend, getInfoByOrderNo } from '../../../api/order/cloth'
import { cancelOrderInFactory, listOrderClothItem, reFlowClothByStore } from '../../../api/order/clothItem'
import { getDeliveryManListByOrg } from '../../../api/app/delivery'
import { getLodop } from '@/utils/lodopUtils'
import payStatusPopup from '@/components/payStatusPopup'
import { findUserByPhoneNumber } from '@/api/app/user'

export default {
    name: 'ClothItem',
    dicts: ['sys_yes_no', 'order_cloth_flow_status', 'order_cloth_flow_action', 'cloth_order_status'],
    components: {
        payStatusPopup
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 洗衣订单衣服明细表格数据
            clothOrderList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            deliveryOpen: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10
            },
            createTimeRange: [],
            // 表单参数
            form: {},
            selectDeliveryForm: {},
            orderDetail: {},
            orderClothDetails: [],
            deliveryManList: [],
            // 表单校验
            rules: {},
            LODOP: null,
            number: 1,
            pointerList: [],
            selectedClothes: []
        }
    },
    created() {
        this.getDeliveryList()
        this.getList()
    },
    mounted() {
        this.number = 1
        const printerTime = setInterval(() => {
            this.LODOP = getLodop()
            this.number++
            if (this.number == 25) {
                clearInterval(printerTime)
            }
            if (this.LODOP) {
                clearInterval(printerTime)
            }
        }, 200)

        this.pointerList = JSON.parse(this.$cache.local.get('printerSeting'))
    },
    methods: {
        getDeliveryList() {
            getDeliveryManListByOrg().then((response) => {
                this.deliveryManList = response.data
            })
        },
        /** 查询洗衣订单衣服明细列表 */
        getList() {
            this.loading = true
            if (null != this.createTimeRange && '' != this.createTimeRange) {
                this.queryParams['beginCreateTime'] = this.createTimeRange[0]
                this.queryParams['endCreateTime'] = this.createTimeRange[1]
            } else {
                delete this.queryParams.beginCreateTime
                delete this.queryParams.endCreateTime
            }
            getSendClothOrderList(this.queryParams).then((response) => {
                this.clothOrderList = response.data.records
                this.total = response.data.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.selectedClothes = []
            this.form = {}
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.selectedClothes = selection
            this.ids = selection.map((item) => item.washCode)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加洗衣订单衣服明细'
        },

        // 去支付
        toPay(scope) {
            if (!this.$refs.payStatusPopup) {
                this.$message.error('支付组件加载失败')
                return
            }
            try {
                this.$refs.payStatusPopup.openSelected(scope.row)
            } catch (error) {
                console.error('支付调用失败:', error)
                this.$message.error('支付调用失败，请重试')
            }
        },

      repeatOrderClothItem(orderNo, orderClothItemId) {
        this.$confirm('确定要返洗这件衣服吗，返洗后将重新入厂？')
          .then((_) => {
            reFlowClothByStore({ orderClothItemId: orderClothItemId }).then((res) => {
              listOrderClothItem({ pageSize: 99999, pageNum: 1, orderNo: orderNo }).then((res) => {
                this.orderClothDetails = res.rows
              })
            })
          })
          .catch((_) => {})
      },

        /** 详情按钮 */
        handleDetail(scope) {
            console.log('handleDetail', scope)
            this.reset()
            this.orderClothDetails = []
            this.ids = []
            this.orderDetail = scope
            listOrderClothItem({ pageSize: 99999, pageNum: 1, orderNo: scope.orderNo }).then((res) => {
                this.orderClothDetails = res.rows
                this.title = '订单详情'
                this.open = true
            })
        },
        selectDeliveryMan(scope) {
            this.selectDeliveryForm = {}
            this.orderDetail = scope.row
            this.deliveryOpen = true
        },
        handleClose(row) {
            var _this = this
            var content = '退单金额如下：'
            if (row.payType == '0') {
                content += '微信 '
            } else if (row.payType == '1') {
                content += '支付宝 '
            } else if (row.payType == '2') {
                content += '现金 '
            } else if (row.payType == '3') {
                content += '余额 '
            }
            content += row.payAmount + '元！是否确定撤单？'
            this.$confirm(content).then(function () {
                refundOrderCloth({ orderId: row.id }).then((res) => {
                    _this.$message({
                        type: 'success',
                        message: '撤单成功'
                    })
                    _this.getList()
                })
            })
        },
        checkClose(done) {
            this.$confirm('是否关闭表单，关闭后数据将丢失？')
                .then(function () {
                    done()
                })
                .then(() => {})
                .catch(() => {})
        },
        async submitForm() {
            if (this.selectedClothes.length === 0) {
                this.$message.error('请先选择衣服')
                return
            }

            const params = {
                washCodes: this.ids.join(','),
                orderId: this.orderDetail.id
            }

            try {
                await this.$modal.confirm(`是否确认取衣衣服编号为"${params.washCodes}"的数据项？`)
                const res = await takeCloth(params)
                this.$message.success('取衣成功')
                this.open = false
                this.getList()

                // 询问是否打印小票
                if (this.LODOP) {
                    try {
                        await this.$modal.confirm('是否打印小票？')
                        const orderInfo = await getInfoByOrderNo({ orderNo: this.orderDetail.orderNo })
                        let p_name = ''
                        this.pointerList.forEach((pointer) => {
                            if (pointer.printType == 0) {
                                p_name = pointer.printName
                            }
                        })
                        orderInfo.data.sendToUserTime = orderInfo.data.updateTime
                        this.sendClothPrinter(this.LODOP, orderInfo.data, p_name)
                    } catch (e) {
                        // 用户取消打印
                    }
                } else {
                    this.$modal.msgError('请安装打印机软件')
                }
            } catch (e) {
                // 用户取消操作或接口错误
            }
        },
        submitDelivery() {
            if (this.selectDeliveryForm.service_trans_id == '0') {
                setIntracityExpress({ orderNo: this.orderDetail.orderNo }).then((res) => {
                    this.$message.success('派单成功')
                    this.deliveryOpen = false
                    this.getList()
                })
            //   setDeliveryManByAppointment({
            //     // deliveryId: this.form.takeClothAppUserId,
            //     orderNo: this.orderDetail.orderNo
            //   }).then((response) => {
            //     this.$modal.msgSuccess('派单成功')
            //     this.open = false
            //     this.getList()
            //   })
            } else {
                if (this.isEmpty(this.selectDeliveryForm.deliveryManId)) {
                    this.$message.error('请先选择配送员')
                    return
                }

                setSendDelivery({ deliveryManId: this.selectDeliveryForm.deliveryManId, orderNo: this.orderDetail.orderNo }).then((res) => {
                    this.$message.success('派单成功')
                    this.deliveryOpen = false
                    this.getList()
                })
            }

        },
        confirmSend(scope) {
            this.$confirm('确认这笔订单已经完成吗？？')
                .then(() => {
                    confirmSend({ orderId: scope.row.id }).then((response) => {
                        this.$modal.msgSuccess('提交成功')
                        this.getList()
                    })
                })
                .catch(() => {})
        },
        // 获取支付方式图标
        getPaymentIcon(type) {
            const icons = {
                0: 'el-icon-mobile-phone',
                1: 'el-icon-mobile-phone',
                2: 'el-icon-money',
                3: 'el-icon-wallet'
            }
            return icons[type] || 'el-icon-money'
        },

        // 获取支付方式文本
        getPaymentText(type) {
            const texts = {
                0: '微信支付',
                1: '支付宝',
                2: '现金支付',
                3: '余额支付',
                8: '组合支付'
            }
            return texts[type] || '其他'
        },

        // 获取状态类型
        getStatusType(status) {
            const types = {
                6: 'warning',
                7: 'info',
                8: 'primary',
                9: 'success'
            }
            return types[status] || ''
        },

        // 行点击事件
        handleRowClick(row) {
            if (row.payTimeType !== '1' || row.payStatus === 1) {
                this.handleDetail(row)
            }
        },

        // 打印小票
        printTicket() {
            if (!this.LODOP) {
                this.$modal.msgError('请安装打印机软件')
                return
            }

            this.$modal.confirm('是否打印小票？').then(() => {
                getInfoByOrderNo({ orderNo: this.orderDetail.orderNo }).then((res) => {
                    let p_name = ''
                    this.pointerList.forEach((pointer) => {
                        if (pointer.printType == 0) {
                            p_name = pointer.printName
                        }
                    })
                    findUserByPhoneNumber({ phoneNumber: res.data.contactPhone }).then(userInfo => {
                        console.log(res.data)
                        res.data.memberPrice = userInfo.data.rechargeBalance + userInfo.data.giveBalance + userInfo.data.welfareBalance
                        this.sendClothPrinter(this.LODOP, res.data, p_name)
                    })

                })
            })
        },
        // 支付成功回调
        handlePaySuccess() {
            this.handleQuery()
        },

        // 确认回调
        handlePayConfirm(data) {
            this.handleDetail(data)
        },

        // 支付错误处理
        handlePayError(error) {
            console.error('支付错误:', error)
            this.$message.error('支付失败，请重试')
        }
    }
}
</script>
