<template>
    <div class="app-container collect-cloth-wrapper">
        <!-- 左侧用户信息栏 -->
        <div class="left-panel">
            <el-card class="user-card">
                <div slot="header" class="clearfix">
                    <span>选择客户</span>
                </div>

                <!-- 搜索区域 -->
                <el-form :model="queryParams"  @submit.native.prevent  ref="queryForm">
                    <div class="search-box">
                        <el-input
                            v-model="queryParams.phoneNumber"
                            placeholder="请输入手机号"
                            clearable
                            @keyup.enter.native="searchUser">
                            <el-button slot="append" icon="el-icon-search" @click="searchUser">查询</el-button>
                        </el-input>
                        <el-button type="primary" icon="el-icon-full-screen" @click="qrcodeSearchUser">扫码</el-button>
                    </div>
                </el-form>

                <!-- 用户信息展示 -->
                <el-descriptions
                    v-if="appUserInfo"
                    class="user-info"
                    :column="1"
                    border>
                    <el-descriptions-item label="用户名">
                        {{ appUserInfo.realName }}
                    </el-descriptions-item>
                    <el-descriptions-item label="手机号">
                        {{ appUserInfo.phoneNumber }}
                    </el-descriptions-item>
                    <el-descriptions-item label="等级">
                        {{ appUserInfo.level }}
                    </el-descriptions-item>
                    <el-descriptions-item label="现金余额">
                        <span class="amount">{{ (appUserInfo.rechargeBalance * 100) / 100 }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="赠送余额">
                        <span class="amount">{{ (appUserInfo.giveBalance * 100) / 100 }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="福利金">
                        <span class="amount">{{ (appUserInfo.welfareBalance * 100) / 100 }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="地址">
                        {{ appUserInfo.defaultAddress ? appUserInfo.defaultAddress.address + ' ' + appUserInfo.defaultAddress.addressDetail : '' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="预约订单">
                        <div class="appointment-info">
                            <template v-if="orderForm.orderNo">
                                <a class="link-text">{{ orderForm.orderNo }}</a>
                                <a class="link-text delete" @click="clearAppointment">删除</a>
                            </template>
                            <a v-else class="link-text" @click="showAdvanceOrder = true">选择预约订单</a>
                        </div>
                    </el-descriptions-item>
                </el-descriptions>
            </el-card>
        </div>

        <!-- 右侧衣物操作区 -->
        <div class="right-panel">
            <div class="cloth-container">
                <!-- 操作栏 -->
                <div class="operation-bar">
                    <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd">添加衣物</el-button>
                </div>

                <!-- 衣物列表 -->
                <div class="cloth-list">
                    <el-table
                        :data="orderClothItemDTOS"
                        border
                        stripe
                        highlight-current-row
                        height="100%">
                        <el-table-column label="序号" type="index" width="60" align="center" fixed="left"/>
                        <el-table-column label="衣物名称" min-width="180">
                            <template slot-scope="scope">
                                <el-button type="text" @click="updateClothItem(scope.$index, 0)">
                                    {{ calculateClothName(scope.$index) }}
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="颜色" width="120">
                            <template slot-scope="scope">
                                <el-button type="text" @click="updateClothItem(scope.$index, 2)">
                                    {{ scope.row.orderClothColorDTOS.map(c => c.clothColorName).join(',') }}
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="衣服品牌" width="120">
                            <template slot-scope="scope">
                                <el-button type="text" @click="updateClothItem(scope.$index, 3)">
                                    {{ scope.row.clothBrandName }}
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="瑕疵" min-width="120">
                            <template slot-scope="scope">
                                <el-button type="text" @click="updateClothItem(scope.$index, 4)">
                                    {{ scope.row.orderClothFlawDTOS.map(f => f.clothFlawName).join(',') }}
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="洗涤方式" width="100">
                            <template slot-scope="scope">
                                <el-button type="text" @click="changeClothWashMode(scope.$index)">
                                    {{ scope.row.clothWashModeName }}
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="特殊处理" width="120">
                            <template slot-scope="scope">
                                <el-button
                                    type="text"
                                    class="price-text"
                                    @click="changeClothSpecialPriceEvent(scope.$index)">
                                    ¥{{ calculateClothSpecialPrice(scope.$index) }}
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="单价" width="100">
                            <template slot-scope="scope">
                                <template v-if="scope.row.isChangePrice == 'Y'">
                                    <el-button
                                        type="text"
                                        class="price-text"
                                        @click="changeClothDefaultPriceEvent(scope.$index)">
                                        ¥{{ scope.row.defaultPrice }}
                                    </el-button>
                                </template>
                                <span v-else class="price-text">¥{{ scope.row.defaultPrice }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="280" fixed="right">
                            <template slot-scope="scope">
                                <div class="operation-buttons">
                                    <el-button type="text" @click="handleAddClothFlaw(scope.$index)">
                                        附件({{ getFlawCount(scope.row.orderClothAdjunctDTOS)  }})
                                    </el-button>
                                    <el-button type="text" icon="el-icon-camera" @click="handphotograph(scope.$index)">
                                        拍照({{ scope.row.picNum }})
                                    </el-button>
                                    <el-button type="text" @click="handleRemarkClothItem(scope.$index)">备注</el-button>
                                    <el-button type="text" @click="handleCopyClothItem(scope.$index)">复制</el-button>
                                    <el-button type="text" class="delete-btn" @click="orderClothItemDTOS.splice(scope.$index, 1)">
                                        删除
                                    </el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <!-- 底部结算区 -->
                <div class="settlement-bar">
                    <div class="order-info">
                        <div class="info-group">
                            <div class="info-item">
                                <span class="label">总件数:</span>
                                <span class="value">{{ orderClothItemDTOS.length }}</span>
                            </div>
                            <div class="info-item">
                                <span class="label">总金额:</span>
                                <span class="value">¥{{ calculateTotalPrice() }}</span>
                            </div>
                            <div class="info-item highlight">
                                <span class="label">实收金额:</span>
                                <span class="value">¥{{ calculateTotalPrice() }}</span>
                            </div>
                        </div>

                        <div class="order-settings">
                            <el-form :model="orderForm" :inline="true" size="small">
                                <el-form-item label="订单加急">
                                    <el-select v-model="orderForm.speed" placeholder="请选择" clearable>
                                        <el-option
                                            v-for="item in clothSpeeds"
                                            v-if="item.id > 1"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>

                                <el-form-item
                                    v-if="orderForm.isAppointment == 'Y'"
                                    label="取衣方式">
                                    <el-select v-model="orderForm.sendClothWay" placeholder="请选择" clearable>
                                        <el-option
                                            v-for="dict in dict.type.cloth_send_type"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"/>
                                    </el-select>
                                </el-form-item>

                                <el-form-item label="备注">
                                    <el-input v-model="orderForm.remark" placeholder="请输入订单备注" clearable/>
                                </el-form-item>
                            </el-form>
                        </div>
                    </div>

                    <div class="action-area">
                        <el-button
                            type="danger"
                            class="checkout-btn"
                            icon="el-icon-shopping-cart-2"
                            :loading="confirmLoading"
                            @click="handleConfirmPay">
                            收银
                        </el-button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加或修改洗衣订单衣服明细对话框 -->
        <el-dialog :title="title" :visible.sync="open" size="50%" append-to-body>
            <el-row :gutter="15">
                <el-col :span="24">
                    <el-steps :active="addClothActiveTab" finish-status="success" simple>
                        <el-step title="衣服分类"></el-step>
                        <el-step title="选择衣服"></el-step>
                        <el-step title="衣服颜色"></el-step>
                        <el-step title="衣服品牌"></el-step>
                        <el-step title="衣服瑕疵"></el-step>
                        <el-step title="衣服附件"></el-step>
                    </el-steps>
                </el-col>
                <el-col>
                    <div style="height: 20px"></div>
                </el-col>
                <el-col :span="24" v-if="addClothActiveTab == 0">
                    <div style="margin-left: 55px">
                        <el-input v-model="defaultList.type" placeholder="请输入要搜索的衣服分类" style="width: 300px" clearable>
                            <el-button slot="append" icon="el-icon-search" @click="searchCloth('type', 'clothTypes')"></el-button>
                        </el-input>
                    </div>
                    <div style="margin-left: 40px">
                        <el-tag :key="item.id" type="info" v-for="item in clothTypes" style="margin-top: 15px; margin-left: 15px" size="medium" @click="onClothTypeSelect(item.id)">
                            {{ item.name }}
                        </el-tag>
                    </div>
                </el-col>
                <el-col :span="24" v-if="addClothActiveTab == 1">
                    <div style="margin-left: 55px; margin-bottom: 10px">
                        <el-input v-model="defaultList.item" placeholder="请输入要搜索的衣服类型" style="width: 300px" clearable>
                            <el-button slot="append" icon="el-icon-search" @click="searchCloth('item', 'clothItems')"></el-button>
                        </el-input>
                        <el-button type="primary" @click="changeClothActiveTab(0)" style="margin-left: 10px">上一步</el-button>
                    </div>
                    <div style="margin-left: 40px">
                        <div class="horizontal-view" style="margin-left: 15px">
                            <span style="font-size: 14px; line-height: 19px">衣服类型：</span>
                            <el-checkbox-group style="margin-left: 20px" v-model="form.clothTypeKeys">
                                <el-checkbox v-for="dict in dict.type.cloth_type" :key="dict.value" :label="dict.value">{{ dict.label }}</el-checkbox>
                            </el-checkbox-group>
                        </div>

                        <el-tag :key="item.id" type="info" v-for="(item, index) in clothItems" style="margin-top: 15px; margin-left: 15px" size="medium" @click="onClothItemSelect(index)">
                            {{ item.name }}
                        </el-tag>
                    </div>
                </el-col>
                <el-col :span="24" v-if="addClothActiveTab == 2" >
                    <div style="margin-left: 55px; margin-bottom: 10px">
                        <el-input v-model="defaultList.color" placeholder="请输入要搜索的衣服颜色" style="width: 300px" clearable>
                            <el-button slot="append" icon="el-icon-search" @click="searchCloth('color', 'clothColors')"></el-button>
                        </el-input>
                        <el-button type="primary" @click="changeClothActiveTab(1)" style="margin-left: 10px" v-if="!isUpdateClothItem">上一步</el-button>
                    </div>
                    <div style="margin-left: 40px; display: flex; flex-wrap: wrap">
                        <template v-for="(item, index) in clothColors">
                            <div class="verticle-view" :style="'text-align: center;margin-top: 15px;margin-left: 15px;border-radius: 5px;border: 1px solid ' + (item.isSelect == true ? '#1890ff' : '#FFFFFF')" @click="onClothColorSelect(index)">
                                <template v-if="item.colorType == 0">
                                    <div :style="'width: 50px;height: 50px;border:1px solid #ededed;border-radius: 5px;background-color:' + item.code"></div>
                                </template>
                                <template v-if="item.colorType == 1">
                                    <img :src="item.imgUrl" style="width: 50px; height: 50px; border-radius: 5px" />
                                </template>
                                <span style="height: 40px; line-height: 40px">{{ item.name }}</span>
                            </div>
                        </template>
                    </div>
                </el-col>
                <el-col :span="24" v-if="addClothActiveTab == 3">
                    <div style="margin-left: 55px">
                        <el-input v-model="defaultList.brand" placeholder="请输入要搜索的衣服品牌" style="width: 300px" clearable>
                            <el-button slot="append" icon="el-icon-search" @click="searchCloth('brand', 'clothBrands')"></el-button>
                        </el-input>
                        <el-button type="primary" @click="changeClothActiveTab(2)" style="margin-left: 10px" v-if="!isUpdateClothItem">上一步</el-button>
                    </div>
                    <div style="margin-left: 40px">
                        <el-tag :key="item.id" type="info" v-for="item in clothBrands" style="margin-top: 15px; margin-left: 15px" size="medium" @click="onClothBrandSelect(item.id)">
                            {{ item.name }}
                        </el-tag>
                    </div>
                </el-col>
                <el-col :span="24" v-if="addClothActiveTab == 4">
                    <el-tabs type="border-card" @tab-click="changeClothTab">
                        <el-tab-pane label="全部">
                            <div style="margin-left: 15px">
                                <el-input v-model="defaultList.flaw" placeholder="请输入要搜索的衣服瑕疵" style="width: 300px" clearable>
                                    <el-button slot="append" icon="el-icon-search" @click="searchCloth('flaw', 'clothFlaws')"></el-button>
                                </el-input>
                                <el-button type="primary" @click="changeClothActiveTab(3)" style="margin-left: 10px" v-if="!isUpdateClothItem">上一步</el-button>
                            </div>
                            <el-tag :key="item.id" :type="item.isSelect ? 'success' : 'info'" v-for="(item, index) in clothFlaws" style="margin-top: 15px; margin-left: 15px" size="medium" @click="onClothFlawSelect(index)">
                                {{ item.name }}
                            </el-tag>
                        </el-tab-pane>
                        <el-tab-pane :label="clothFlawType.name" v-for="clothFlawType in clothFlawTypes">
                            <div style="margin-left: 15px">
                                <el-input v-model="defaultList.flaw" placeholder="请输入要搜索的衣服瑕疵" style="width: 300px" clearable>
                                    <el-button slot="append" icon="el-icon-search" @click="searchCloth('flaw', 'clothFlaws')"></el-button>
                                </el-input>
                            </div>
                            <template v-for="(item, index) in clothFlaws">
                                <el-tag :key="item.id" :type="item.isSelect ? 'success' : 'info'" v-if="item.flawTypeId == clothFlawType.id" style="margin-top: 15px; margin-left: 15px" size="medium" @click="onClothFlawSelect(index)">
                                    {{ item.name }}
                                </el-tag>
                            </template>
                        </el-tab-pane>
                    </el-tabs>
                </el-col>
                <el-col :span="24" v-if="addClothActiveTab == 5">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <div>选择附件</div>
                            <div style="margin-left: 15px; margin-top: 10px">
                                <el-input v-model="defaultList.adjunct" placeholder="请输入要搜索的衣服附件" style="width: 200px" clearable>
                                    <el-button slot="append" icon="el-icon-search" @click="searchCloth('adjunct', 'clothAdjuncts')"></el-button>
                                </el-input>
                                <el-button type="primary" @click="changeClothActiveTab(4)" style="margin-left: 10px" v-if="!isUpdateClothItem">上一步</el-button>
                            </div>
                            <el-tag :key="item.id" type="info" v-for="item in clothAdjuncts" style="margin-top: 15px; margin-left: 15px" @click="onClothAdjunctSelect(item)">
                                {{ item.name }}
                            </el-tag>
                        </el-col>
                        <el-col :span="16">
                            <el-table :data="addClothAdjuncts" style="width: 100%">
                                <el-table-column label="附件" align="center" prop="adjunctName" />
                                <el-table-column label="数量" align="center" prop="num">
                                    <template slot-scope="scope">
                                        <el-input-number v-model="scope.row.num" size="small" :precision="0" :min="1" :max="999"></el-input-number>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" align="center">
                                    <template slot-scope="scope">
                                        <el-button type="text" icon="el-icon-delete" @click="removeClothAdjunct(scope.$index)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-col>
                    </el-row>
                </el-col>
            </el-row>
            <div slot="footer" class="dialog-footer" v-if="addClothActiveTab == 2 || addClothActiveTab == 4 || addClothActiveTab == 5">
                <el-button type="primary" @click="addClothItemConfirm" style="margin-left: 5%">确定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="衣服附件" :visible.sync="addClothAdjunctOpen" width="60%" append-to-body>
            <el-row :gutter="20">
                <el-col :span="8">
                    <div>选择附件</div>
                    <div style="margin-left: 15px; margin-top: 10px">
                        <el-input v-model="defaultList.adjunct" placeholder="请输入要搜索的衣服附件" style="width: 300px" clearable>
                            <el-button slot="append" icon="el-icon-search" @click="searchCloth('adjunct', 'clothAdjuncts')"></el-button>
                        </el-input>
                    </div>
                    <el-tag :key="item.id" type="info" v-for="item in clothAdjuncts" style="margin-top: 15px; margin-left: 15px" @click="onClothAdjunctSelect(item)">
                        {{ item.name }}
                    </el-tag>
                </el-col>
                <el-col :span="16">
                    <el-table :data="addClothAdjuncts" style="width: 100%">
                        <el-table-column label="附件" align="center" prop="adjunctName" />
                        <el-table-column label="数量" align="center" prop="num">
                            <template slot-scope="scope">
                                <el-input-number v-model="scope.row.num" size="small" :precision="0" :min="1" :max="999"></el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" icon="el-icon-delete" @click="removeClothAdjunct(scope.$index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addClothAdjunctOpen = false">取 消</el-button>
                <el-button type="primary" @click="addClothAdjunctSubmit">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="衣服照片" :visible.sync="addClothPicOpen" width="50%" append-to-body>
            <form ref="picForm">
                <image-upload :limit="9" v-model="addClothPics"></image-upload>
            </form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addClothPicOpen = false">取 消</el-button>
                <el-button type="primary" @click="addClothPicSubmit">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="洗衣方式" :visible.sync="addClothWashModeOpen" width="30%" append-to-body>
            <div style="margin-bottom: 50px">
                <el-tag :key="item.id" type="info" v-for="(item, index) in clothWashModes" style="margin-top: 15px; margin-left: 15px" size="medium" @click="onClothWashModeSelect(index)">
                    {{ item.washModeName + '（￥' + item.price + '）' }}
                </el-tag>
            </div>
        </el-dialog>

        <!--  设置备注  -->
        <el-dialog title="备注" :visible.sync="addClothRemarkOpen" width="30%" append-to-body>
            <form ref="remarkForm">
                <el-input type="textarea" :rows="5" placeholder="请输入备注" v-model="clothRemark"> </el-input>
            </form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addClothPicOpen = false">取 消</el-button>
                <el-button type="primary" @click="addClothRemarkSubmit">确 定</el-button>
            </span>
        </el-dialog>

        <!--  设置默认价格  -->
        <el-dialog title="设置价格" :visible.sync="setClothDefaultPriceOpen" width="30%" :before-close="handleClose" append-to-body>
            <form ref="remarkForm">
                <el-input-number placeholder="请输入价格" v-model="defaultPrice"> </el-input-number>
            </form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setClothDefaultPriceOpen = false">取 消</el-button>
                <el-button type="primary" @click="setClothDefaultPriceSubmit">确 定</el-button>
            </span>
        </el-dialog>

        <!--  特殊衣物  -->
        <el-dialog title="特殊衣物" :visible.sync="setClothSpecialPriceOpen" width="55%" :before-close="handleClose" append-to-body>
            <el-form ref="remarkForm">
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-card class="box-card">
                            <div slot="header" class="clearfix">
                                <span>工艺加价</span>
                            </div>
                            <template v-for="(item, index) in clothSpecialForm.clothCrafts">
                                <el-form-item>
                                    <el-checkbox v-model="item.isSelect" @change="changeClothCraftSelect()" style="width: 100px">{{ item.clothCraftName }}</el-checkbox>
                                    <el-input-number v-model="item.price" :min="0" :max="9999" :precision="2" @change="changeClothCraftSelect"></el-input-number>
                                </el-form-item>
                            </template>
                        </el-card>
                    </el-col>
                    <el-col :span="12">
                        <el-card class="box-card">
                            <div slot="header" class="clearfix">
                                <span>保值加急</span>
                            </div>
                            <el-form-item>
                                <el-checkbox v-model="clothSpecialForm.isHedging" @change="changeClothHedgingSelect()" style="width: 100px">保值</el-checkbox>
                                <el-input-number v-model="clothSpecialForm.hedgingPrice" :min="0" :max="9999" :precision="0" @change="changeClothHedgingSelect()"></el-input-number>
                                <span style="margin-left: 5px">元 {{ clothSpecialForm.hedgingPrice && clothSpecialForm.isHedging ? '（￥' + clothSpecialForm.hedgingPrice * 0.01 + '）' : '' }}</span>
                            </el-form-item>
                            <template v-for="(item, index) in clothSpecialForm.clothSpeeds">
                                <el-form-item v-if="item.isDefault != 'Y' && selectClothItemIndex > -1">
                                    <el-checkbox v-model="item.isSelect" @change="changeClothSpeedSelect(index)" style="width: 100px" :disabled="clothSpecialForm.isHedging && index == 1">
                                        <span v-if="item.isSelect && orderClothItemDTOS[selectClothItemIndex]">{{ item.name + '（￥' + orderClothItemDTOS[selectClothItemIndex].defaultPrice * (item.multiple - 1) + '）' }}</span>
                                        <span v-else>{{ item.name }}</span>
                                    </el-checkbox>
                                    <span>{{ item.price }}</span>
                                </el-form-item>
                            </template>
                        </el-card>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setClothSpecialPriceOpen = false">取 消</el-button>
                <el-button type="primary" @click="addClothSpecialSubmit">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="收银" :visible.sync="confirmPayOpen" width="90%" :before-close="handleClose" destroy-on-close append-to-body>
            <CashCloth ref="cashCloth" :orderForm="orderForm" :orderClothItemDTOS="orderClothItemDTOS" :appUserInfo="appUserInfo" :clothSpeeds="clothSpeeds" :deductCouponVOS="deductCouponVOS" :discountCouponVOS="discountCouponVOS" @onPaySuccess="onPaySuccess" @initOrderList="initOrderList" @confirm="handelPaySuccess"/>
        </el-dialog>

        <!-- 拍照上传 -->
        <el-dialog title="拍照上传" :visible.sync="photographType" :before-close="hidephotograph" width="55%" append-to-body>
            <div class="photo_content">
                <div class="video_content">
                    <div class="loading" v-if="videoType">
                        <el-button type="text" :loading="true" disabled>加载中请稍后</el-button>
                    </div>
                    <video class="videoElement" ref="videoElement" autoplay></video>
                </div>

                <div class="view">
                    <div class="btn_box">
                        <el-button class="btn_photo" :loading="photoType" :disabled="photoType" icon="el-icon-camera" type="primary" plain @click="takePhoto" v-if="!videoType">拍照上传</el-button>

                        <el-upload v-if="photographimgList.length < 9" class="btn_upload" :action="uploadAction" :before-upload="handleBeforeUpload" :on-success="handleUploadSuccess" :on-error="handleUploadError" accept="image/*" :show-file-list="false" ref="fileUpload">
                            <el-button icon="el-icon-folder" plain type="primary">上传本地文件</el-button>
                        </el-upload>
                    </div>

                    <div class="image_list" v-if="photographimgList.length">
                        <div class="image_item" v-for="(item, index) in photographimgList" :key="index">
                            <el-image style="width: 120px; height: 120px" :src="item.src ? item.src : item.url" :preview-src-list="previewimgList"> </el-image>

                            <div class="image_bottom">
                                <el-button type="danger" icon="el-icon-delete" @click="btn_remove(item, index)"></el-button>
                                <el-button v-if="item.type" type="success" icon="el-icon-check"></el-button>
                            </div>
                        </div>
                    </div>

                    <el-empty :image-size="200" v-else></el-empty>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="hidephotograph">关 闭</el-button>
                <el-button type="primary" @click="btn_submit">保 存</el-button>
            </span>
        </el-dialog>
        <pay-status-popup ref="payStatusPopup" @paySuccess="handelPaySuccess"></pay-status-popup>
        <el-dialog title="预约订单" :visible.sync="showAdvanceOrder" width="55%" append-to-body>
            <el-table :data="advanceOrderList">
                <el-table-column prop="orderNo" label="预约单号" width="180"> </el-table-column>
                <el-table-column prop="appointmentTime" label="预约时间" width="180"></el-table-column>
                <el-table-column prop="isLargeItem" label="是否大件" width="180">
                    <template slot-scope="scope">
                        <span v-if="scope.row.isLargeItem == 'Y'">是</span>
                        <span v-if="scope.row.isLargeItem == 'N'">否</span>
                    </template>
                </el-table-column>
                <el-table-column prop="appointmentCount" label="件数" width="180"> </el-table-column>
                <el-table-column prop="remark" label="备注" width="180" show-overflow-tooltip> </el-table-column>
                <el-table-column prop="date" label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button type="text" @click="changeAdanceOrder(scope.row)">选择订单</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>


<script>
import CashCloth from './component/cashCloth'
import payStatusPopup from '@/components/payStatusPopup'
import { listClothItem, getClothItem, delClothItem, addClothItem, updateClothItem, updateClothItemStatus } from '@/api/order/clothItem'
import { uploadBase64OSS, uploadOSS, saveOrderClothPics } from '@/api/upload'
import { getOrderStatusByOrderNo } from '../../../api/order/cloth'

import { allList } from '@/api/core/clothType'
import { allClothItem } from '../../../api/core/clothItem'
import { allClothColor } from '../../../api/core/color'
import { allClothFlaw } from '@/api/core/flaw'
import { allClothFlawType } from '@/api/core/flawType'
import { allClothAdjunct } from '../../../api/cloth/adjunct'
import { findUserByPhoneNumber } from '@/api/app/user'
import { listWashModePriceByClothId } from '../../../api/cloth/price'
import { allClothSpeed } from '../../../api/cloth/speed'
import { allClothCraft } from '../../../api/cloth/craft'
import { collectCloth, getInfoByOrderNo, clothOrderPay } from '../../../api/order/cloth'
import { allBrand } from '../../../api/cloth/brand'
import { getCouponItemlistByAppUserId, getDiscountByStoreId } from '../../../api/coupon/item'
import { add, multi, minute, sub } from '../../../utils/math'
import request from '@/utils/request'


export default {
    name: 'CollectCloth',
    components: { CashCloth, payStatusPopup },
    dicts: ['sys_yes_no', 'cloth_type', 'cloth_send_type'],
    data() {
        return {
            uploadAction: `${process.env.VUE_APP_BASE_API}` + '/common/uploadOSS',
            appUserInfo: null,

            checkOrderStatusNum: 0,
            checkOrderIntervalId: null,

            addClothActiveTab: 0,
            defaultList: {
                type: '',
                clothTypes: [],
                item: '',
                clothItems: [],
                color: '',
                clothColors: [],
                brand: '',
                clothBrands: [],
                flaw: '',
                clothFlaws: [],
                adjunct: '',
                clothAdjuncts: []
            },
            clothBrands: [],
            clothTypes: [],
            clothItems: [],
            clothColors: [],
            clothFlawTypes: [],
            clothFlaws: [],
            clothAdjuncts: [],
            clothWashModes: [],
            clothCrafts: [],
            clothSpeeds: [],

            orderForm: {
                isSpecial: 'N',
                isAppointment: 'N',
                authCode: '',
                payType: '3'
            },

            // 总条数
            total: 0,
            // 洗衣订单衣服明细表格数据
            orderClothItemDTOS: [],
            selectClothItemIndex: -1,
            selectCoupons: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            isUpdateClothItem: false,

            //衣服特殊价格设置
            setClothSpecialPriceOpen: false,
            clothSpecialForm: {},

            //衣服附件相关
            addClothAdjunctOpen: false,
            addClothAdjuncts: [],
            //衣服照片相关
            addClothPicOpen: false,
            addClothPics: null,

            //衣服洗衣方式
            addClothWashModeOpen: false,

            //衣服备注
            addClothRemarkOpen: false,
            clothRemark: '',

            setClothDefaultPriceOpen: false,
            defaultPrice: 0,

            confirmPayOpen: false,
            confirmCouponTabIndex: '0',
            confirmDeductTabIndex: '0',
            setCouponOpen: false, //是否选择优惠券
            discountCouponVOS: [], //可选择的折扣券
            deductCouponVOS: [], //可选择的抵扣券
            changeDiscountCouponIndex: -1,
            changeDiscountCouponOpen: false,
            changeDiscountCouponTitle: '',
            changeDiscountCouponSelectCloths: [],
            changeDiscountCouponCanSelectCloths: [],
            // 查询参数
            queryParams: {},
            // 表单参数
            form: {},
            // 表单校验
            rules: {},

            photographType: false,
            photographimgList: [],
            previewimgList: [],
            uploadList: [],
            photoLoading: true,
            clothId: null,
            stream: null,
            fileType: ['png', 'jpg', 'jpeg'],
            videoType: true,
            photoType: false,

            collectClothDetail: null,
            showAdvanceOrder: false,
            advanceOrderList: [],
            confirmLoading: false
        }
    },
    mounted() {
        if (process.env.ENV != 'production') {
            window.vue = this
        }
    },
    created() {
        allClothCraft().then((res) => {
            this.clothCrafts = res.data
            this.clothCrafts.forEach((item) => {
                item.defaultPrice = 20
            })
        })
        allClothSpeed().then((speedRes) => {
            this.clothSpeeds = speedRes.data
        })
    },
    methods: {
        // 展示附件数量
        getFlawCount(e) {
            let count = 0
            e.forEach((item) => {
                count += item.num
            })
            return count
        },

        // 添加衣物过滤数据
        searchCloth(k1, k2) {
            if (!this.defaultList[k1]) {
                this[k2] = this.defaultList[k2]
            } else {
                this[k2] = this.defaultList[k2].filter((item) => {
                    return item.name.indexOf(this.defaultList[k1]) > -1
                })
            }
        },

        // 切换衣服瑕疵分页
        changeClothTab() {
            this.defaultList.flaw = ''
            this.clothFlaws = this.defaultList.clothFlaws
        },

        // 上传前校检格式和大小
        handleBeforeUpload(file) {
            // 校检文件类型
            if (this.fileType) {
                const fileName = file.name.split('.')
                const fileExt = fileName[fileName.length - 1]
                const isTypeOk = this.fileType.indexOf(fileExt) >= 0
                if (!isTypeOk) {
                    this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join('/')}格式文件!`)
                    return false
                }
            }
            // 校检文件大小
            const isLt = file.size / 1024 / 1024 < 3
            if (!isLt) {
                this.$message.error(`上传文件大小不能超过 3MB!`)
                return false
            }
            this.$modal.loading('正在上传文件，请稍候...')
            return true
        },
        handleUploadSuccess(res, file) {
            if (res.code === 200) {
                this.previewimgList.push(res.data.src)
                this.uploadList.push({ name: res.data.fileName, url: res.data.src })
                this.uploadedSuccessfully()
            } else {
                this.$modal.closeLoading()
                this.$modal.msgError(res.msg)
                this.$refs.fileUpload.handleRemove(file)
                this.uploadedSuccessfully()
            }
        },
        handleUploadError() {
            this.$modal.msgError('上传文件失败，请重试')
            this.$modal.closeLoading()
        },
        // 上传结束处理
        uploadedSuccessfully() {
            if (this.uploadList.length) {
                // this.fileList = this.fileList.concat(this.uploadList);
                this.uploadList.forEach((item) => {
                    this.photographimgList.push({
                        src: item.url,
                        fileName: item.fileName,
                        type: true
                    })
                })
                this.uploadList = []
                this.$modal.closeLoading()

                this.getuploadState()
            }
        },
        //根据上传文件状态判断显示
        getuploadState() {
            // 初始状态值
            let state = true

            // 判断数组中的所有元素是否都为true
            if (this.photographimgList.every((item) => item.type === true)) {
                state = false
            } else {
                state = true
            }

            return state
        },
        // 取消按钮
        cancel() {
            this.confirmPayOpen = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                orderClothCraftDTOS: [], //衣服工艺
                orderClothAdjunctDTOS: [],
                orderClothTypeDTOS: [],
                clothTypeKeys: [],
                specialPrice: 0,
                clothSpeedMultiple: 1,
                picNum: 0,
                isCustomPrice: 'N',
                remark: '',
                defaultPrice: 0
            }
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /** 新增按钮操作 */
        handleAdd() {
            allList().then((res) => {
                this.defaultList.type = ''
                this.defaultList.clothTypes = res.data
                this.clothTypes = res.data
                this.reset()
                this.selectClothItemIndex = -1
                this.addClothActiveTab = 0
                this.isUpdateClothItem = false
                this.open = true
                this.title = '添加衣物'
            })
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getClothItem(id).then((response) => {
                this.form = response.data
                this.open = true
                this.title = '编辑衣物信息'
            })
        },
        initOrderList(e) {
            console.log('sssss', e)
            this.orderClothItemDTOS = e.concat()
        },

        onPaySuccess(orderInfo) {
            console.log('aaaaa')
            this.confirmPayOpen = false
            console.log('res', orderInfo)
            if (orderInfo.payTimeType == '0') {
                //第三方支付
                console.log('第三方支付')
                this.$refs.payStatusPopup.open(3, orderInfo, this.appUserInfo)
                // this.checkOrderStatusNum = 0
                // if (this.checkOrderIntervalId) {
                //     clearInterval(this.checkOrderIntervalId)
                // }
                // this.checkOrderIntervalId = setInterval(() => {
                //     this.intervalCheckOrderStatus(orderInfo.orderNo)
                // }, 4000)
            } else {
                if (orderInfo.payType) {
                    this.$refs.payStatusPopup.open(1, orderInfo)
                } else {
                    this.$refs.payStatusPopup.open(6, orderInfo)
                }
                this.orderClothItemDTOS = []
                this.queryParams = {}
                this.appUserInfo = null
                this.orderForm = {}
            }
        },

        handelPaySuccess() {
            console.log("AAAAA")
            this.orderClothItemDTOS = []
            this.queryParams = {}
            this.confirmPayOpen = false
            this.appUserInfo = null
            // this.orderForm = {}
        },
        intervalCheckOrderStatus(orderno) {
            getOrderStatusByOrderNo({ orderNo: orderno }).then((response) => {
                if (this.checkOrderStatusNum > 15) {
                    clearInterval(this.checkOrderIntervalId)
                    return
                }
                if (response.data == '4') {
                    return
                }
                if (response.data == '100') {
                    //已取消
                    this.$notify.error({
                        title: '支付失败',
                        message: '支付超时或客户已取消支付'
                    })
                    clearInterval(this.checkOrderIntervalId)
                    return
                }
                this.$notify({
                    title: '支付成功',
                    message: '客户已成功支付订单',
                    type: 'success'
                })

                this.pointerType = true
                clearInterval(this.checkOrderIntervalId)
            })
        },
        /** 关闭按钮 */
        close() {
            const obj = { path: '/workbench/collectCloth' }
            this.$tab.closeOpenPage(obj)
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal
                .confirm('是否确认删除洗衣订单衣服明细编号为"' + ids + '"的数据项？')
                .then(function () {
                    return delClothItem(ids)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess('删除成功')
                })
                .catch(() => {})
        },
        checkClose(done) {
            this.$confirm('是否关闭表单，关闭后数据将丢失？')
                .then(function () {
                    done()
                })
                .then(() => {})
                .catch(() => {})
        },
        onClothTypeSelect(id) {
            allClothItem({ clothTypeId: id }).then((res) => {
                this.defaultList.item = ''
                this.defaultList.clothItems = res.data
                this.clothItems = res.data
                this.addClothActiveTab = 1
            })
        },
        changeClothActiveTab(index) {
            this.addClothActiveTab = index
            switch (index) {
                case 0:
                    this.form.clothTypeKeys = []
                    this.form.orderClothTypeDTOS = []
                    this.form.clothWashModeId = ''
                    this.form.clothWashModeName = ''
                    break
                case 1:
                    this.clothColors.forEach((item) => {
                        item.isSelect = false
                    })
                    this.form.orderClothColorDTOS = []
                    break
                case 2:
                    this.form.clothBrandId = ''
                    this.form.clothBrandName = ''
                    break
                case 3:
                    this.form.orderClothFlawDTOS = []
                    break 
                 case 4:
                   
                    break 
            }
        },
        onClothItemSelect(index) {
            this.form.orderClothTypeDTOS = []
            for (let i = 0; i < this.form.clothTypeKeys.length; i++) {
                var orderClothTypeDTO = { orderClothTypeCode: this.form.clothTypeKeys[i] }
                if (this.form.clothTypeKeys[i] == '1') {
                    orderClothTypeDTO.clothTypeName = '加厚'
                    orderClothTypeDTO.clothTypePrice = this.clothItems[index].plusPrice
                }
                if (this.form.clothTypeKeys[i] == '2') {
                    orderClothTypeDTO.clothTypeName = '羊绒'
                    orderClothTypeDTO.clothTypePrice = this.clothItems[index].silkPrice
                }
                if (this.form.clothTypeKeys[i] == '3') {
                    orderClothTypeDTO.clothTypeName = '真丝'
                    orderClothTypeDTO.clothTypePrice = this.clothItems[index].sheepPrice
                }
                if (this.form.clothTypeKeys[i] == '4') {
                    orderClothTypeDTO.clothTypeName = '儿童'
                    orderClothTypeDTO.clothTypePrice = this.clothItems[index].childPrice
                }
                this.form.orderClothTypeDTOS.push(orderClothTypeDTO)
            }
            this.form.clothWashModeId = this.clothItems[index].washId
            this.form.clothWashModeName = this.clothItems[index].washName
            if (this.isUpdateClothItem) {
                //修改已选择的衣服
                this.form.clothItemId = this.clothItems[index].id
                this.form = { ...this.form, ...this.clothItems[index] }
                this.form.isCustomPrice = 'N'
                this.orderClothItemDTOS[this.selectClothItemIndex] = this.form
                this.orderClothItemDTOS = this.orderClothItemDTOS.concat()
                for (let i = 0; i < this.form.clothTypeKeys.length; i++) {
                    if (this.form.clothTypeKeys[i] == '1') {
                        this.form.defaultPrice += this.clothItems[index].plusPrice
                    }
                    if (this.form.clothTypeKeys[i] == '2') {
                        this.form.defaultPrice += this.clothItems[index].silkPrice
                    }
                    if (this.form.clothTypeKeys[i] == '3') {
                        this.form.defaultPrice += this.clothItems[index].sheepPrice
                    }
                    if (this.form.clothTypeKeys[i] == '4') {
                        this.form.defaultPrice += this.clothItems[index].childPrice
                    }
                }

                this.open = false
                this.$forceUpdate()
            } else {
                allClothColor().then((res) => {
                    this.defaultList.color = ''
                    this.defaultList.clothColors = res.data
                    this.clothColors = res.data
                    this.form.clothItemId = this.clothItems[index].id
                    this.form = { ...this.form, ...this.clothItems[index] }

                    for (let i = 0; i < this.form.clothTypeKeys.length; i++) {
                        if (this.form.clothTypeKeys[i] == '1') {
                            this.form.defaultPrice += this.clothItems[index].plusPrice
                        }
                        if (this.form.clothTypeKeys[i] == '2') {
                            this.form.defaultPrice += this.clothItems[index].silkPrice
                        }
                        if (this.form.clothTypeKeys[i] == '3') {
                            this.form.defaultPrice += this.clothItems[index].sheepPrice
                        }
                        if (this.form.clothTypeKeys[i] == '4') {
                            this.form.defaultPrice += this.clothItems[index].childPrice
                        }
                    }
                    this.addClothActiveTab = 2
                })
            }
        },
        onClothColorSelect(index) {
            this.clothColors[index].isSelect = this.clothColors[index].isSelect ? false : true
            this.$forceUpdate()
        },
        onClothBrandSelect(id) {
            var brand = this.clothBrands.find((item) => item.id == id)
            this.form.clothBrandId = id
            this.form.clothBrandName = brand.name
            if (this.isUpdateClothItem) {
                this.orderClothItemDTOS[this.selectClothItemIndex].clothBrandId = id
                this.orderClothItemDTOS[this.selectClothItemIndex].clothBrandName = brand.name
                this.open = false
            } else {
                allClothFlawType().then((res) => {
                    this.clothFlawTypes = res.data

                    allClothFlaw().then((res1) => {
                        this.defaultList.flaw = ''
                        this.defaultList.clothFlaws = res1.data
                        this.clothFlaws = res1.data
                        this.addClothActiveTab = 4
                    })
                })
            }
        },
        addClothItemConfirm() {
            console.log(this.addClothActiveTab)
            if (this.addClothActiveTab == 2) {
                //选择颜色
                var clothColorDTOS = []
                this.clothColors.forEach((item) => {
                    if (item.isSelect) {
                        clothColorDTOS.push({ clothColorId: item.id, clothColorName: item.name })
                    }
                })
                if (clothColorDTOS.length == 0) {
                    this.$message.error('请先选择颜色')
                    return
                }

                this.form.orderClothColorDTOS = clothColorDTOS
                if (this.isUpdateClothItem) {
                    //修改已选择的衣服
                    this.orderClothItemDTOS[this.selectClothItemIndex] = this.form
                    this.orderClothItemDTOS = this.orderClothItemDTOS.concat()
                    this.open = false
                    this.$forceUpdate()
                } else {
                    allBrand().then((res) => {
                        res.data.push({
                            id: '0',
                            name: '无'
                        })
                        this.defaultList.brand = ''
                        this.defaultList.clothBrands = res.data
                        this.clothBrands = res.data
                        this.addClothActiveTab = 3
                    })
                }
            } else if (this.addClothActiveTab == 4) {
                //选择瑕疵
                var clothFlawDTOS = []
                this.clothFlaws.forEach((item) => {
                    if (item.isSelect) {
                        clothFlawDTOS.push({ clothFlawId: item.id, clothFlawName: item.name })
                    }
                })
                if (clothFlawDTOS.length == 0) {
                    this.$message.error('请先选择瑕疵')
                    return
                }
                this.form.orderClothFlawDTOS = clothFlawDTOS
                if (this.isUpdateClothItem) {
                    this.orderClothItemDTOS[this.selectClothItemIndex] = this.form
                    this.orderClothItemDTOS = this.orderClothItemDTOS.concat()
                    this.open = false
                    this.$forceUpdate()
                } else {
                    // this.orderClothItemDTOS.push(this.form)
                    // console.log(this.orderClothItemDTOS)
                    // this.open = false
                    allClothAdjunct().then((res) => {
                        this.defaultList.clothAdjuncts = res.data
                        this.defaultList.adjunct = ''
                        this.clothAdjuncts = res.data
                        this.addClothActiveTab = 5
                        let index = this.orderClothItemDTOS.length
                        this.selectClothItemIndex = index
                        this.addClothAdjuncts = []
                        this.$forceUpdate()
                    })
                }
            } else if (this.addClothActiveTab == 5) {
                this.orderClothItemDTOS.push(this.form)
                this.addClothAdjunctSubmit()
                this.open = false
            }
        },
        onClothFlawSelect(index) {
            this.clothFlaws[index].isSelect = this.clothFlaws[index].isSelect ? false : true
            this.$forceUpdate()
        },
        //条码搜索用户
        qrcodeSearchUser() {},
        //搜索用户
        searchUser() {
            this.$refs['queryForm'].validate((valid) => {
                if (valid) {
                    findUserByPhoneNumber(this.queryParams).then((res) => {
                        this.appUserInfo = res.data
                        this.getAdvanceOrder(res.data.id)
                    })
                }
            })
        },

        getAdvanceOrder(id) {
            request({
                url: '/mapi/order/cloth/list',
                method: 'get',
                params: {
                    pageNum: 1,
                    pageSize: 100,
                    userId: id,
                    isAppointment: 'Y'
                }
            }).then((data) => {
                if (data && data.code === 200) {
                    console.log('预约订单', data)
                    // this.pagination.total = data.total
                    // if (this.renderFun) {
                    //     this.renderFun(data.rows, data)
                    // } else {
                    //     this.data = data.rows
                    // }
                    this.advanceOrderList = data.rows
                    if (this.advanceOrderList.length) {
                        this.showAdvanceOrder = true
                    }
                } else {
                    this.$message.error(data.msg)
                }
            })
        },

        changeAdanceOrder(e) {
            // orderForm.isAppointment orderForm.orderNo
            this.orderForm.isAppointment = 'Y'
            this.orderForm.orderNo = e.orderNo
            this.showAdvanceOrder = false
        },

        clearAppointment() {
            this.orderForm.isAppointment = 'N'
            this.orderForm.orderNo = ''
        },

        handleAddClothFlaw(index) {
            allClothAdjunct().then((res) => {
                this.defaultList.clothAdjuncts = res.data
                this.defaultList.adjunct = ''
                this.clothAdjuncts = res.data
                this.addClothAdjunctOpen = true
                this.selectClothItemIndex = index
                this.addClothAdjuncts = this.orderClothItemDTOS[index].orderClothAdjunctDTOS.concat()
                this.$forceUpdate()
            })
        },
        handleAddClothPics(index) {
            this.addClothPicOpen = true
            this.selectClothItemIndex = index
            this.addClothPics = this.orderClothItemDTOS[index].pics
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then((_) => {
                    done()
                })
                .catch((_) => {})
        },
        onClothAdjunctSelect(item) {
            var isContains = false
            for (let i = 0; i < this.addClothAdjuncts.length; i++) {
                if (this.addClothAdjuncts[i].adjunctId == item.id) {
                    if (this.addClothAdjuncts[i].num >= 999) {
                        return
                    }
                    this.addClothAdjuncts[i].num++
                    isContains = true
                    break
                }
            }
            if (!isContains) {
                this.addClothAdjuncts.push({ adjunctId: item.id, num: 1, adjunctName: item.name })
            }
        },
        removeClothAdjunct(index) {
            this.addClothAdjuncts.splice(index, 1)
        },
        addClothAdjunctSubmit() {
            console.log(this.orderClothItemDTOS[this.selectClothItemIndex])
            this.orderClothItemDTOS[this.selectClothItemIndex].orderClothAdjunctDTOS = this.addClothAdjuncts.concat()
            this.addClothAdjunctOpen = false
        },
        updateClothItem(index, tabIndex) {
            if (tabIndex == 0) {
                allList().then((res) => {
                    this.defaultList.type = ''
                    this.defaultList.clothTypes = res.data
                    this.clothTypes = res.data
                    this.selectClothItemIndex = index
                    this.form = { ...this.orderClothItemDTOS[index] }
                    this.isUpdateClothItem = true
                    this.addClothActiveTab = tabIndex
                    this.open = true
                    this.title = '修改衣物信息'
                })
            }
            if (tabIndex == 2) {
                allClothColor().then((res) => {
                    this.defaultList.color = ''
                    this.defaultList.clothColors = res.data
                    this.clothColors = res.data
                    this.selectClothItemIndex = index
                    this.form = { ...this.orderClothItemDTOS[index] }
                    this.isUpdateClothItem = true
                    this.addClothActiveTab = tabIndex
                    this.open = true
                    this.title = '修改衣物信息'
                })
            }
            if (tabIndex == 3) {
                allBrand().then((res) => {
                    this.defaultList.brand = ''
                    this.defaultList.clothBrands = res.data
                    this.clothBrands = res.data
                    this.selectClothItemIndex = index
                    this.form = { ...this.orderClothItemDTOS[index] }
                    this.isUpdateClothItem = true
                    this.addClothActiveTab = tabIndex
                    this.open = true
                    this.title = '修改衣服品牌'
                })
            }
            if (tabIndex == 4) {
                //修改瑕疵
                allClothFlawType().then((res) => {
                    this.clothFlawTypes = res.data

                    allClothFlaw().then((res1) => {
                        this.defaultList.flaw = ''
                        this.defaultList.clothFlaws = res1.data
                        this.clothFlaws = res1.data
                        this.selectClothItemIndex = index
                        this.form = { ...this.orderClothItemDTOS[index] }
                        this.isUpdateClothItem = true
                        this.addClothActiveTab = tabIndex
                        this.open = true
                        this.title = '修改衣物信息'
                    })
                })
            }
        },
        addClothPicSubmit() {
            this.orderClothItemDTOS[this.selectClothItemIndex].pics = this.addClothPics
            if (this.isEmpty(this.addClothPics)) {
                this.orderClothItemDTOS[this.selectClothItemIndex].picNum = 0
            } else {
                this.orderClothItemDTOS[this.selectClothItemIndex].picNum = this.addClothPics.split(',').length
            }
            // this.orderClothItemDTOS = this.orderClothItemDTOS.concat()
            this.addClothPicOpen = false
            // this.$forceUpdate()
            // console.log(this.orderClothItemDTOS)
        },
        //复制衣服
        handleCopyClothItem(index) {
            this.orderClothItemDTOS.push({ ...this.orderClothItemDTOS[index] })
        },
        //修改洗衣方式
        changeClothWashMode(index) {
            listWashModePriceByClothId({ clothId: this.orderClothItemDTOS[index].id }).then((res) => {
                this.clothWashModes = res.data
                this.addClothWashModeOpen = true
                this.selectClothItemIndex = index
            })
        },
        //洗衣方式被选择
        onClothWashModeSelect(index) {
            this.orderClothItemDTOS[this.selectClothItemIndex].clothWashModeName = this.clothWashModes[index].washModeName
            this.orderClothItemDTOS[this.selectClothItemIndex].clothWashModeId = this.clothWashModes[index].washModeId
            this.orderClothItemDTOS[this.selectClothItemIndex].defaultPrice = this.clothWashModes[index].price
            for (let i = 0; i < this.orderClothItemDTOS[this.selectClothItemIndex].clothTypeKeys.length; i++) {
                if (this.orderClothItemDTOS[this.selectClothItemIndex].clothTypeKeys[i] == '1') {
                    this.orderClothItemDTOS[this.selectClothItemIndex].defaultPrice += this.orderClothItemDTOS[this.selectClothItemIndex].plusPrice
                }
                if (this.orderClothItemDTOS[this.selectClothItemIndex].clothTypeKeys[i] == '2') {
                    this.orderClothItemDTOS[this.selectClothItemIndex].defaultPrice += this.orderClothItemDTOS[this.selectClothItemIndex].silkPrice
                }
                if (this.orderClothItemDTOS[this.selectClothItemIndex].clothTypeKeys[i] == '3') {
                    this.orderClothItemDTOS[this.selectClothItemIndex].defaultPrice += this.orderClothItemDTOS[this.selectClothItemIndex].sheepPrice
                }
                if (this.orderClothItemDTOS[this.selectClothItemIndex].clothTypeKeys[i] == '4') {
                    this.orderClothItemDTOS[this.selectClothItemIndex].defaultPrice += this.orderClothItemDTOS[this.selectClothItemIndex].childPrice
                }
            }

            this.addClothWashModeOpen = false
        },
        handleRemarkClothItem(index) {
            this.selectClothItemIndex = index
            this.clothRemark = this.orderClothItemDTOS[this.selectClothItemIndex].remark
            this.addClothRemarkOpen = true
        },
        addClothRemarkSubmit() {
            this.orderClothItemDTOS[this.selectClothItemIndex].remark = this.clothRemark
            this.addClothRemarkOpen = false
        },
        //特殊价格处理
        changeClothSpecialPriceEvent(index) {
            this.selectClothItemIndex = index
            this.clothSpecialForm = {}
            var clothCrafts = []
            this.clothCrafts.forEach((item) => {
                var isSet = false
                for (let i = 0; i < this.orderClothItemDTOS[this.selectClothItemIndex].orderClothCraftDTOS.length; i++) {
                    if (this.orderClothItemDTOS[this.selectClothItemIndex].orderClothCraftDTOS[i].clothCraftId == item.id) {
                        isSet = true
                        clothCrafts.push({
                            clothCraftId: item.id,
                            clothCraftName: item.craftName,
                            price: this.orderClothItemDTOS[this.selectClothItemIndex].orderClothCraftDTOS[i].price,
                            isSelect: true
                        })

                        break
                    }
                }
                if (!isSet) {
                    clothCrafts.push({
                        clothCraftId: item.id,
                        clothCraftName: item.craftName,
                        price: item.defaultPrice,
                        isSelect: false
                    })
                }
            })

            var clothSpeeds = []
            this.clothSpeeds.forEach((item) => {
                var clothSpeed = { ...item }
                clothSpeed.isSelect = clothSpeed.id == this.orderClothItemDTOS[this.selectClothItemIndex].clothSpeedId
                clothSpeeds.push(clothSpeed)
            })

            this.clothSpecialForm.clothCrafts = clothCrafts
            this.clothSpecialForm.clothSpeeds = clothSpeeds
            this.clothSpecialForm.isHedging = this.orderClothItemDTOS[this.selectClothItemIndex].isHedging == 'Y'
            this.clothSpecialForm.hedgingPrice = this.orderClothItemDTOS[this.selectClothItemIndex].hedgingPrice
            this.clothSpecialForm.clothSpeedId = this.orderClothItemDTOS[this.selectClothItemIndex].clothSpeedId
            this.clothSpecialForm.clothSpeedName = this.orderClothItemDTOS[this.selectClothItemIndex].clothSpeedName
            this.setClothSpecialPriceOpen = true
            console.log(this.clothSpecialForm)
        },
        changeClothDefaultPriceEvent(index) {
            this.selectClothItemIndex = index
            this.defaultPrice = this.orderClothItemDTOS[this.selectClothItemIndex].defaultPrice || null
            this.setClothDefaultPriceOpen = true
        },
        /**
         * 提交默认价格
         */
        setClothDefaultPriceSubmit() {
            if (this.isEmpty(this.defaultPrice)) {
                this.$message.error('请输入价格')
                return
            }

            this.orderClothItemDTOS[this.selectClothItemIndex].defaultPrice = this.defaultPrice
            this.orderClothItemDTOS[this.selectClothItemIndex].isCustomPrice = 'Y'
            this.orderClothItemDTOS = this.orderClothItemDTOS.concat()
            this.setClothDefaultPriceOpen = false
        },
        changeClothCraftSelect() {
            console.log(this.clothSpecialForm)
            this.$forceUpdate()
        },
        changeClothHedgingSelect(index) {
            if (this.clothSpecialForm.isHedging) {
                this.clothSpecialForm.clothSpeeds[1].isSelect = true
                for (let i = 2; i < this.clothSpecialForm.clothSpeeds.length; i++) {
                    this.clothSpecialForm.clothSpeeds[i].isSelect = false
                }
            }
            this.$forceUpdate()
        },
        changeClothSpeedSelect(index) {
            if (index == 1 && this.clothSpecialForm.isHedging) {
                this.clothSpecialForm.clothSpeeds[1].isSelect = true
            } else {
                if (this.clothSpecialForm.isHedging) {
                    this.clothSpecialForm.isHedging = false
                }

                for (let i = 1; i < this.clothSpecialForm.clothSpeeds.length; i++) {
                    if (i != index) {
                        this.clothSpecialForm.clothSpeeds[i].isSelect = false
                    }
                }
            }

            this.$forceUpdate()
        },
        addClothSpecialSubmit() {
            var param = {}
            param.orderClothCraftDTOS = []
            for (let i = 0; i < this.clothSpecialForm.clothCrafts.length; i++) {
                if (this.clothSpecialForm.clothCrafts[i].isSelect) {
                    if (this.isEmpty(this.clothSpecialForm.clothCrafts[i].price)) {
                        this.$message.error(this.clothSpecialForm.clothCrafts[i].clothCraftName + '价格未设置')
                        return
                    }
                    param.orderClothCraftDTOS.push(this.clothSpecialForm.clothCrafts[i])
                }
            }

            param.isHedging = this.clothSpecialForm.isHedging ? 'Y' : 'N'
            param.hedgingPrice = this.clothSpecialForm.hedgingPrice
            var isHighSpeed = false
            for (let i = 1; i < this.clothSpecialForm.clothSpeeds.length; i++) {
                if (this.clothSpecialForm.clothSpeeds[i].isSelect) {
                    isHighSpeed = true
                    param.clothSpeedId = this.clothSpecialForm.clothSpeeds[i].id
                    param.clothSpeedName = this.clothSpecialForm.clothSpeeds[i].name
                    param.clothSpeedMultiple = this.clothSpecialForm.clothSpeeds[i].multiple
                    break
                }
            }
            if (!isHighSpeed) {
                param.clothSpeedId = this.clothSpecialForm.clothSpeeds[0].id
                param.clothSpeedMultiple = this.clothSpecialForm.clothSpeeds[0].multiple
            }

            this.orderClothItemDTOS[this.selectClothItemIndex] = { ...this.orderClothItemDTOS[this.selectClothItemIndex], ...param }
            console.log(this.orderClothItemDTOS)
            this.setClothSpecialPriceOpen = false
            this.orderClothItemDTOS = this.orderClothItemDTOS.concat()
            this.$forceUpdate()
        },

        async handleConfirmPay() {
            // this.$refs.payStatusPopup.open(1, {
            //     id: 18
            // }, this.appUserInfo);
            // return
            const _ = this;
            if (this.orderClothItemDTOS.length == 0) {
                this.$message.error('请先添加衣服')
                return
            }
            if (!this.appUserInfo) {
                this.$message.error('请先选择客户')
                return
            }
            if (this.orderForm.isAppointment == 'Y' && this.isEmpty(this.orderForm.orderNo)) {
                this.$message.error('请先输入预约订单号')

                return
            }
            // if (!this.orderForm.sendClothWay) {
            //     this.$message.error('请先选取衣方式')
            //     return
            // }
            if (this.orderForm.isAppointment == 'Y') {
                var res = await getInfoByOrderNo({ orderNo: this.orderForm.orderNo, appUserId: this.appUserInfo.id })
                if (res.data == null) {
                    this.$message.error('未查询到预约订单')
                    return
                }
                // if (!this.orderForm.sendClothWay) {
                //     this.$message.error('请先选取衣方式')
                //     return
                // }
                // this.orderForm.sendClothWay = res.data.sendClothWay
            }

            //
            var params = { appUserId: this.appUserInfo.id, discountWay: '2' }
            var clothIds = []
            this.orderClothItemDTOS.forEach((item) => {
                clothIds.push(item.id)
            })
            params.clothIds = clothIds
            this.orderForm.isSpecial = 'N'
            this.orderForm.authCode = ''
            this.orderForm.payType = ''
            // this.orderForm.sendClothWay = '0'
            _.confirmLoading = true
            getDiscountByStoreId({ appUserId: this.appUserInfo.id }).then((res) => {
                this.discountCouponVOS = res.data
                params.discountWay = '0'
                getCouponItemlistByAppUserId(params).then((res) => {
                    // console.log(res.data)
                    // res.data.forEach(item => {
                    //     item.isUnique = 'N'
                    // })
                    _.confirmLoading = false
                    this.deductCouponVOS = res.data

                    this.selectCoupons = []
                    this.orderClothItemDTOS.forEach((item, index) => {
                        item.index = index
                        item.deductAmount = 0
                        item.totalPrice = this.calculateClothSpecialPrice(index) + item.defaultPrice
                    })
                    delete this.orderForm.cashDeductAmount
                    delete this.orderForm.discountCouponId
                    delete this.orderForm.discountCoupon
                    this.confirmPayOpen = true
                }).catch((res) => {
                    _.confirmLoading = false;
                });
            })
        },
        onCouponTabChange(tab, event) {
            console.log('tab.index:' + tab.index)
            // if(tab.index == '1'){
            //   this.$refs['couponRef'].focus()
            // }
        },
        //计算某一件衣服的优惠金额，并配置到orderClothItemDTOS中
        calculateClothDiscountAmount(index) {
            var cloth = this.orderClothItemDTOS[index]
            cloth.deductAmount = 0
            this.selectCoupons.forEach((i) => {
                var selectCloth = i.orderCouponClothDTOS.find((item) => item.clothIndex == cloth.index)
                if (selectCloth) {
                    cloth.deductAmount = cloth.deductAmount + selectCloth.deductAmount
                }
            })
        },
        //<editor-folder desc="计算相关函数"/>
        calculateClothSpecialPrice(index) {
            // console.log('calculateClothSpecialPrice')
            var specialPrice = 0
            for (let i = 0; i < this.orderClothItemDTOS[index].orderClothCraftDTOS.length; i++) {
                specialPrice += this.orderClothItemDTOS[index].orderClothCraftDTOS[i].price
            }
            if (this.orderClothItemDTOS[index].isHedging == 'Y') {
                specialPrice += this.orderClothItemDTOS[index].hedgingPrice * 0.01
            }
            for (let i = 0; i < this.clothSpeeds.length; i++) {
                if (this.orderClothItemDTOS[index].clothSpeedId == this.clothSpeeds[i].id) {
                    specialPrice += this.orderClothItemDTOS[index].defaultPrice * (this.clothSpeeds[i].multiple - 1)
                    break
                }
            }
            // console.log('specialPrice:' + specialPrice)
            let num = Math.round(specialPrice * 100) / 100
            return num
        },
        calculateClothName(index) {
            var clothName = this.orderClothItemDTOS[index].name
            console.log(this.orderClothItemDTOS[index].orderClothTypeDTOS)
            this.orderClothItemDTOS[index].orderClothTypeDTOS.forEach((item) => {
                clothName += '【' + item.clothTypeName + '】'
            })
            return clothName
        },
        calculateTotalPrice() {
            var price = 0
            for (let i = 0; i < this.orderClothItemDTOS.length; i++) {
                price += this.calculateClothSpecialPrice(i) + this.orderClothItemDTOS[i].defaultPrice
            }
            let num = Math.round(price * 100) / 100
            return num
        },
        //</editor-folder>

        //打开拍照弹框 调用摄像头
        async handphotograph(index) {
            this.selectClothItemIndex = index

            if (this.orderClothItemDTOS[index].pics) {
                let imgList = this.orderClothItemDTOS[index].pics.split(',')
                imgList.forEach((item) => {
                    this.previewimgList.push(item)
                    this.photographimgList.push({
                        type: true,
                        src: item
                    })
                })
            }

            this.photographType = true
            try {
                this.stream = await navigator.mediaDevices.getUserMedia({ video: true })
                this.$refs.videoElement.srcObject = this.stream
                this.videoType = false
            } catch (error) {
                this.$modal.msgError('无法访问摄像头')
                // console.error("无法访问摄像头:", error);
                // this.photographType = false
            }
        },
        //点击拍照 处理成base64
        async takePhoto() {
            this.photoType = true
            try {
                const canvas = document.createElement('canvas')
                const context = canvas.getContext('2d')
                canvas.width = this.$refs.videoElement.videoWidth
                canvas.height = this.$refs.videoElement.videoHeight
                context.drawImage(this.$refs.videoElement, 0, 0, canvas.width, canvas.height)
                const imageDataUrl = canvas.toDataURL('image/jpeg')
                if (this.photographimgList.length >= 9) {
                    this.$modal.msgError('照片仅限上传9张')
                    this.photoType = false
                    return
                }

                let response = await fetch(imageDataUrl)
                let blob = await response.blob() // 获取图片的 Blob 对象
                let file = new File([blob], 'image.jpeg', { type: blob.type })
                //创建form对象
                let formdata = new FormData()
                //通过append向form对象添加数据
                formdata.append('file', file)

                uploadOSS(formdata)
                    .then((res) => {
                        this.previewimgList.push(res.data.src)
                        this.photographimgList.push({
                            type: true,
                            src: res.data.src
                        })
                        this.photoType = false
                    })
                    .catch(() => {
                        // resolve(false);
                        this.photoType = false
                    })

                // 上传照片或处理imageDataUrl
                // this.uploadImage(imageDataUrl); // 调用上传接口或本地处理逻辑
            } catch (error) {
                this.photoType = false
                // console.error("拍照失败:", error);
            } finally {
                // this.$refs.videoElement.srcObject.getTracks().forEach((track) => track.stop());
            }
        },
        // 关闭拍照弹框后清除视频流
        hidephotograph() {
            const that = this
            this.$confirm('是否确认关闭当前拍照功能？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    that.photographType = false
                    that.photographimgList = []
                    that.clothId = null
                    if (that.stream) {
                        that.stream.getTracks().forEach((track) => track.stop()) // 停止访问摄像头并释放资源
                        that.$refs.videoElement.srcObject = null // 清除视频流对象
                    }
                })
                .catch(() => {})
        },
        //删除照片
        btn_remove(item, index) {
            const that = this
            this.$confirm('是否确认删除该照片？')
                .then(function () {})
                .then(() => {
                    that.photographimgList.splice(index, 1)
                    that.$modal.msgSuccess('删除成功')
                })
                .catch(() => {})
        },
        //保存图片
        btn_submit() {
            if (this.photographimgList.length < 1) {
                this.$modal.msgError('请拍照上传后保存')
                return
            }

            const srcString = this.photographimgList.map((obj) => obj.src).join(',')

            this.orderClothItemDTOS[this.selectClothItemIndex].pics = srcString

            if (!this.photographimgList.length) {
                this.orderClothItemDTOS[this.selectClothItemIndex].picNum = 0
            } else {
                this.orderClothItemDTOS[this.selectClothItemIndex].picNum = this.photographimgList.length
            }

            this.$modal.msgSuccess('保存成功')

            this.photographType = false
            this.photographimgList = []
            this.clothId = null
            if (this.stream) {
                this.stream.getTracks().forEach((track) => track.stop()) // 停止访问摄像头并释放资源
                this.$refs.videoElement.srcObject = null // 清除视频流对象
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.collect-cloth-wrapper {
    height: calc(100vh - 84px);
    display: flex;
    background: #f5f7fa;
    padding: 16px;
    gap: 16px;

    .left-panel {
        width: 360px;
        flex-shrink: 0;

        .user-card {
            height: 100%;

            .search-box {
                display: flex;
                gap: 8px;
                margin-bottom: 16px;

                .el-input {
                    flex: 1;
                }
            }

            .user-info {
                .amount {
                    color: #f56c6c;
                    font-weight: 500;
                }

                .appointment-info {
                    .link-text {
                        color: #409eff;
                        cursor: pointer;
                        margin-right: 8px;

                        &.delete {
                            color: #f56c6c;
                        }
                    }
                }
            }
        }
    }

    .right-panel {
        flex: 1;
        min-width: 0;

        .cloth-container {
            height: 100%;
            display: flex;
            flex-direction: column;
            background: #fff;
            border-radius: 4px;

            .operation-bar {
                padding: 16px;
                border-bottom: 1px solid #ebeef5;
            }

            .cloth-list {
                // flex: 1;
                height: calc(100vh - 300px);
                overflow: auto;
                padding: 0 16px;

                .price-text {
                    color: #f56c6c;
                }

                .operation-buttons {
                    display: flex;
                    gap: 8px;
                    justify-content: center;

                    .delete-btn {
                        color: #f56c6c;
                    }
                }
            }

            .settlement-bar {
                border-top: 1px solid #ebeef5;
                padding: 16px;
                display: flex;
                justify-content: space-between;
                align-items: flex-end;
                background: #fff;

                .order-info {
                    flex: 1;

                    .info-group {
                        display: flex;
                        gap: 24px;
                        margin-bottom: 16px;

                        .info-item {
                            display: flex;
                            align-items: center;
                            gap: 8px;

                            .label {
                                color: #606266;
                            }

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

                            &.highlight .value {
                                color: #f56c6c;
                                font-size: 20px;
                            }
                        }
                    }

                    .order-settings {
                        .el-form {
                            display: flex;
                            flex-wrap: wrap;
                            gap: 16px;
                        }
                    }
                }

                .action-area {
                    .checkout-btn {
                        width: 120px;
                        height: 48px;
                        font-size: 16px;
                    }
                }
            }
        }
    }
}

// 保留原有的照片上传相关样式
.photo_content {
    display: flex;
    .video_content {
        flex-shrink: 0;
        width: 50%;
        position: relative;
        .loading {
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            background-color: rgba(0, 0, 0, 0.8);
            z-index: 10;
            .el-button {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                z-index: 15;
                border: none;
                color: #ffffff;
                padding: 10px 20px;
            }
        }
        .videoElement {
            width: 100%;
            height: auto;
        }
    }
    .view {
        flex: 1;
        padding: 20px;
        .btn_box {
            display: flex;
            .btn_upload {
                margin: 0 10px;
            }
        }
        .image_list {
            margin-top: 20px;
            .image_item {
                display: inline-block;
                margin: 0 10px 10px 0;
                position: relative;
                border-radius: 5px;
                overflow: hidden;
                .image_bottom {
                    position: absolute;
                    left: 0;
                    bottom: 0;
                    width: 100%;
                    background-color: rgba(255, 255, 255, 0.3);
                    text-align: center;
                    color: #fff;
                    cursor: pointer;
                    display: flex;
                    .el-button {
                        flex: 1;
                    }
                }
            }
        }
    }
}
</style>
