<template>
    <div class="app-container" style="height: calc(100vh - 84px)">
        <el-main style="height: calc(100vh - 180px - 84px)">
            <el-row :gutter="20">
                <el-col :span="6" :xs="24">
                    <el-card class="box-card">
                        <div slot="header" class="clearfix">
                            <span>选择客户</span>
                        </div>
                        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" @submit.native.prevent>
                            <el-form-item prop="phoneNumber">
                                <el-input v-model="queryParams.phoneNumber" placeholder="请输入手机号" clearable @keyup.enter.native="searchUser" />
                            </el-form-item>
                            <!--            <el-form-item label="姓名" prop="realName">-->
                            <!--              <el-input-->
                            <!--                v-model="queryParams.realName"-->
                            <!--                placeholder="请输入姓名"-->
                            <!--                clearable-->
                            <!--                @keyup.enter.native="handleQuery"-->
                            <!--              />-->
                            <!--            </el-form-item>-->
                            <el-form-item>
                                <el-button type="primary" icon="el-icon-full-screen" @click="qrcodeSearchUser">扫码</el-button>
                                <el-button type="primary" icon="el-icon-search" @click="searchUser">查询</el-button>
                            </el-form-item>
                        </el-form>

                        <el-descriptions title="用户信息" v-if="appUserInfo" :column="2">
                            <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="现金余额">
                                {{ (appUserInfo.rechargeBalance * 100) / 100 }}
                            </el-descriptions-item>
                            <el-descriptions-item label="赠送余额">
                                {{ (appUserInfo.giveBalance * 100) / 100 }}
                            </el-descriptions-item>
                            <el-descriptions-item label="福利金">
                                {{ (appUserInfo.welfareBalance * 100) / 100 }}
                            </el-descriptions-item>
                            <el-descriptions-item label="地址" :span="2">{{ appUserInfo.defaultAddress ? appUserInfo.defaultAddress.address + ' ' + appUserInfo.defaultAddress.addressDetail : '' }}</el-descriptions-item>
                        </el-descriptions>
                    </el-card>
                </el-col>
                <el-col :span="18" :xs="24">
                    <div style="width: 100%" class="verticle-view">
                        <el-form :inline="true" label-width="68px">
                            <el-form-item>
                                <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd">添加衣物</el-button>
                            </el-form-item>
                        </el-form>

                        <el-table :data="orderClothItemDTOS" fit highlight-current-row border stripe ref="clothTable">
                            <el-table-column label="序号" type="index" align="center" fixed="left" width="80"> </el-table-column>
                            <el-table-column label="衣物名称" align="center" prop="name">
                                <template slot-scope="scope">
                                    <span @click="updateClothItem(scope.$index, 0)">{{ calculateClothName(scope.$index) }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="颜色" align="center" width="120">
                                <template slot-scope="scope">
                                    <span @click="updateClothItem(scope.$index, 2)">
                                        <template v-for="(color, index) in scope.row.orderClothColorDTOS">
                                            {{ index == 0 ? color.clothColorName : ',' + color.clothColorName }}
                                        </template>
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column label="衣服品牌" align="center" prop="name" width="120">
                                <template slot-scope="scope">
                                    <span @click="updateClothItem(scope.$index, 3)">{{ scope.row.clothBrandName }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="瑕疵" align="center">
                                <template slot-scope="scope">
                                    <span @click="updateClothItem(scope.$index, 4)">
                                        <template v-for="(color, index) in scope.row.orderClothFlawDTOS">
                                            {{ index == 0 ? color.clothFlawName : ',' + color.clothFlawName }}
                                        </template>
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column label="洗涤方式" align="center" width="80">
                                <template slot-scope="scope">
                                    <span @click="changeClothWashMode(scope.$index)" style="color: #409eff">{{ scope.row.clothWashModeName }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="特殊处理（元）" align="center" prop="clothWashDayNum" width="120">
                                <template slot-scope="scope">
                                    <span style="color: #ff4949" @click="changeClothSpecialPriceEvent(scope.$index)">{{ calculateClothSpecialPrice(scope.$index) }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="单价（元）" align="center" prop="defaultPrice" width="100">
                                <template slot-scope="scope">
                                    <span style="color: #ff4949" v-if="scope.row.isChangePrice == 'Y'" @click="changeClothDefaultPriceEvent(scope.$index)">{{ scope.row.defaultPrice }}</span>
                                    <span v-else>{{ scope.row.defaultPrice }}</span>
                                </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="handleAddClothFlaw(scope.$index)">附件（{{ scope.row.orderClothAdjunctDTOS.length }}）</el-button>
                                    <!-- <el-button

                    type="text"
                    @click="handleAddClothPics(scope.$index)"
                  >
                    {{'拍照（' + scope.row.picNum + '）'}}
                  </el-button> -->
                                    <el-button type="text" icon="el-icon-camera" @click="handphotograph(scope.$index)">{{ '拍照（' + scope.row.picNum + '）' }}</el-button>
                                    <el-button type="text" style="color: #ff4949" @click="orderClothItemDTOS.splice(scope.$index, 1)">删除</el-button>
                                    <el-button type="text" @click="handleRemarkClothItem(scope.$index)">备注</el-button>
                                    <el-button type="text" @click="handleCopyClothItem(scope.$index)">复制</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-col>
            </el-row>
        </el-main>
        <el-row :gutter="10" class="box-shadow">
            <el-col :span="21">
                <el-form label-width="100px" style="height: 180px; padding-top: 20px" :inline="true" size="medium" :model="orderForm" ref="orderForm">
                    <el-form-item label="总件数:" prop="totalClothNum">
                        <span>{{ orderClothItemDTOS.length }}</span>
                    </el-form-item>
                    <el-form-item label="总金额:" prop="totalPrice">
                        <span>{{ calculateTotalPrice() }}</span>
                    </el-form-item>
                    <el-form-item label="实收金额:" prop="totalPrice">
                        <span style="color: #ff4949">{{ calculateTotalPrice() }}</span>
                    </el-form-item>

                    <el-form-item label="订单加急" prop="orderSpeed">
                        <el-select v-model="orderForm.speed" placeholder="请选择" clearable>
                            <template v-for="(item, index) in clothSpeeds">
                                <el-option v-if="index > 1" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                            </template>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="是否关联预约" prop="isAppointment">
                        <el-radio-group v-model="orderForm.isAppointment">
                            <el-radio-button v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio-button>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="预约单号" prop="orderNo" v-if="orderForm.isAppointment == 'Y'">
                        <el-input v-model="orderForm.orderNo" placeholder="请输入预约单号" clearable required />
                    </el-form-item>
                    <br />

                    <el-form-item label="会员余额:" prop="userAmount">
                        <span v-if="appUserInfo">{{ Math.round((appUserInfo.rechargeBalance + appUserInfo.giveBalance) * 100) / 100  }}</span>
                        <span v-else>0</span>
                    </el-form-item>

                    <!-- <el-form-item label="取衣时间" prop="takeClothTime">
            <el-date-picker
              v-model="orderForm.takeClothTime"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              :style="{width: '100%'}"
              placeholder="请选择取衣时间"
              clearable
            ></el-date-picker>
          </el-form-item> -->

                    <!--          <el-form-item label="取衣方式" prop="sendClothWay">-->
                    <!--            <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="备注" prop="remark">
                        <el-input v-model="orderForm.remark" placeholder="请输入订单备注" clearable />
                    </el-form-item>
                </el-form>
            </el-col>
            <el-col :span="3">
                <el-button type="danger" style="height: 100%; width: 80%; height: 120px; margin-top: 30px" icon="el-icon-shopping-cart-2" size="medium" @click="handleConfirmPay">收银</el-button>
            </el-col>
            <!--            <el-col :span="3">-->
            <!--                <el-button type="primary" style="height: 100%; width: 80%; height: 120px; margin-top: 30px" icon="el-icon-sell">取衣付款</el-button>-->
            <!--            </el-col>-->
        </el-row>

        <!-- 添加或修改洗衣订单衣服明细对话框 -->
        <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>
                    </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>
                    </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>
                    </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>
                            </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: 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>
                </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="50%">
            <el-row :gutter="20">
                <el-col :span="8">
                    <div>选择附件</div>
                    <div style="margin-left: 55px"> 
                        <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%">
            <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%">
            <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%">
            <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">
            <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">
            <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">{{ 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" size="80%" :before-close="handleClose" destroy-on-close>
            <CashCloth ref="cashCloth" :orderForm="orderForm" :orderClothItemDTOS="orderClothItemDTOS" :appUserInfo="appUserInfo" :clothSpeeds="clothSpeeds" :deductCouponVOS="deductCouponVOS" :discountCouponVOS="discountCouponVOS" @onPaySuccess="onPaySuccess" @initOrderList="initOrderList" />
        </el-dialog>

        <!-- 拍照上传 -->
        <el-dialog title="拍照上传" :visible.sync="photographType" :before-close="hidephotograph" width="55%">
            <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>
    </div>
</template>

<style>
/*.box-shadow .el-button--medium{*/
/*  font-size: 18px;*/
/*}*/
</style>

<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'

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
        }
    },
    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: {
        // 添加衣物过滤数据
        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) {
            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 {
                this.$refs.payStatusPopup.open(1, orderInfo)
                this.orderClothItemDTOS = []
                this.queryParams = {}
                this.appUserInfo = null
            }
        },

        handelPaySuccess() {
            this.orderClothItemDTOS = []
            this.queryParams = {}
            this.appUserInfo = null
        },
        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
            })
        },
        onClothItemSelect(index) {
            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() {
            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
                    })
                }
            })
        },
        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() {
            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.isAppointment == 'Y') {
                var res = await getInfoByOrderNo({ orderNo: this.orderForm.orderNo, appUserId: this.appUserInfo.id })
                if (res.data == null) {
                    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 = ''
            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'
                    // })
                    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
                })
            })
        },
        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)
            return specialPrice
        },
        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
            }
            return price
        },
        //</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 scoped lang="scss">
.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%;
                    // height: 25px;
                    // line-height: 25px;
                    background-color: rgba(255, 255, 255, 0.3);
                    text-align: center;
                    color: #fff;
                    cursor: pointer;
                    display: flex;
                    .el-button {
                        flex: 1;
                    }
                }
            }
        }
    }
}
</style>
