<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item prop="orderStatus">
                <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
                    <el-option key="6" label="清洗中" value="6" />
                    <el-option key="7" label="已上挂" value="7" />
                    <el-option key="8" label="待送衣" value="8" />
                    <el-option key="9" label="送衣中" value="9" />
                </el-select>
            </el-form-item>
            <el-form-item prop="orderSource">
                <el-select v-model="queryParams.flowStatus" placeholder="请选择订单来源" clearable>
                    <el-option key="0" label="线上" value="0" />
                    <el-option key="1" label="线下" value="1" />
                </el-select>
            </el-form-item>
            <el-form-item prop="orderNo">
                <el-input v-model="queryParams.orderNo" placeholder="请输入订单条码" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-date-picker v-model="createTimeRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item prop="appUserPhoneNumber">
                <el-input v-model="queryParams.appUserPhoneNumber" placeholder="请输入会员手机" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item prop="userId">
                <el-input v-model="queryParams.userId" placeholder="会员条码" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" fit highlight-current-row border stripe :data="clothOrderList">
            <el-table-column label="订单编号" align="center" prop="orderNo" min-width="200" fixed="left" />
            <el-table-column label="数量" align="center" prop="orderClothCount" width="100" />
            <el-table-column label="合计" align="center" prop="clothItemName" width="200">
                <template slot-scope="scope">
                    <span>合计：{{ scope.row.payAmount }}元</span>
                    <br />
                    <span v-if="scope.row.payType == '0'">支付方式：微信</span>
                    <span v-if="scope.row.payType == '1'">支付方式：支付宝</span>
                    <span v-if="scope.row.payType == '2'">支付方式：现金</span>
                    <span v-if="scope.row.payType == '3'">支付方式：余额</span>
                </template>
            </el-table-column>
            <el-table-column label="客户信息" align="center" width="200">
                <template slot-scope="scope">
                    <span v-if="scope.row.orderSource == 'OFFLINE'">订单来源：线下</span>
                    <span v-else>订单来源：线上</span>
                    <br />
                    <span>{{ scope.row.appUserName + ' ' + scope.row.appUserPhoneNumber }}</span>
                </template>
            </el-table-column>
            <el-table-column label="订单时间" align="center" prop="createTime" min-width="200" />
            <el-table-column label="预计取衣时间" align="center" prop="planSendToUserTime" min-width="200" />
            <el-table-column label="状态" align="center" width="150">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.cloth_order_status" :value="scope.row.orderStatus" />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="250">
                <template slot-scope="scope">
                    <template v-if="scope.row.payTimeType == '1' && scope.row.payStatus != 1">
                        <el-button type="text" icon="el-icon-s-order" @click="toPay(scope)">立刻支付</el-button>
                    </template>
                    <template v-else>
                        <el-button type="text" icon="el-icon-s-order" @click="handleDetail(scope.row)">取衣</el-button>
                        <el-button type="text" icon="el-icon-price-tag" v-if="scope.row.orderStatus == '8' || scope.row.orderStatus == '9'" @click="selectDeliveryMan(scope)">分配派送员</el-button>

                        <el-button type="text" icon="el-icon-price-tag" v-if="scope.row.orderStatus == '9'" @click="confirmSend(scope)">确认送达</el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>

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

        <!-- 添加或修改洗衣订单衣服明细对话框 -->
        <el-dialog :title="title" :visible.sync="open" size="70%" append-to-body>
            <el-row :gutter="15" style="margin-bottom: 80px; margin-left: 20px; width: calc(100% - 20px)">
                <el-col :span="24">
                    <el-descriptions class="margin-top" :column="2" border>
                        <el-descriptions-item>
                            <template slot="label"> 订单号 </template>
                            {{ orderDetail.orderNo }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template slot="label"> 支付方式 </template>
                            <template v-if="orderDetail.payType == '0'">微信</template>
                            <template v-if="orderDetail.payType == '1'">支付宝</template>
                            <template v-if="orderDetail.payType == '2'">现金</template>
                            <template v-if="orderDetail.payType == '3'">余额</template>
                            （{{ orderDetail.payAmount }}元）
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template slot="label"> 姓名 </template>
                            {{ orderDetail.appUserName }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template slot="label"> 电话 </template>
                            {{ orderDetail.appUserPhoneNumber }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template slot="label"> 总金额（元） </template>
                            {{ orderDetail.orderClothPrice }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template slot="label"> 时间 </template>
                            {{ orderDetail.createTime }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template slot="label"> 订单备注 </template>
                            {{ orderDetail.remark }}
                        </el-descriptions-item>
                    </el-descriptions>
                </el-col>
                <el-col :span="24" style="margin-top: 10px">
                    <el-table :data="orderClothDetails" fit highlight-current-row border stripe @selection-change="handleSelectionChange">
                        <el-table-column
                            type="selection"
                            width="55"
                            align="center"
                            :selectable="
                                (row, index) => {
                                    return row.flowStatus != '5'
                                }
                            "
                        />
                        <el-table-column label="衣物条码" align="center" prop="washCode" width="180" fixed="left" />
                        <el-table-column label="衣服名称" align="center" prop="clothItemName" min-width="150" />
                        <el-table-column label="品牌" align="center" prop="clothBrandName" min-width="120" />
                        <el-table-column label="颜色" align="center" width="150">
                            <template slot-scope="scope">
                                <template v-for="(item, index) in scope.row.orderClothColors">
                                    {{ index == 0 ? item.clothColorName : ',' + item.clothColorName }}
                                </template>
                            </template>
                        </el-table-column>
                        <el-table-column label="瑕疵" align="center" width="100">
                            <template slot-scope="scope">
                                <el-tag size="small" v-for="item in scope.row.orderClothFlaws" style="margin-right: 10px; margin-bottom: 2.5px; margin-top: 2.5px">{{ item.clothFlawName }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="洗衣速度" align="center" prop="clothSpeedName" width="150" />
                        <el-table-column label="附件" align="center" width="150">
                            <template slot-scope="scope">
                                <el-tag size="small" v-for="item in scope.row.orderClothAdjuncts" style="margin-right: 10px; margin-bottom: 2.5px; margin-top: 2.5px">{{ item.adjunctName + '*' + item.num }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="挂衣号" align="center" width="150">
                            <template slot-scope="scope">
                                <span v-if="scope.row.clothHanger">
                                    {{ scope.row.clothHanger.name + '#' + scope.row.clothHangerCode }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" align="center" prop="flowStatus" width="80">
                            <template slot-scope="scope">
                                <dict-tag :options="dict.type.order_cloth_flow_status" :value="scope.row.flowStatus" />
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" style="margin-left: 5%">取衣</el-button>
                <el-button @click="cancel">关 闭</el-button>
            </div>
        </el-dialog>

        <!-- 添加或修改洗衣订单对话框 -->
        <el-dialog :title="title" :visible.sync="deliveryOpen" width="20%" append-to-body>
            <el-row :gutter="15">
                <el-form ref="form" :model="selectDeliveryForm" :rules="rules" label-width="70px">
                    <el-col :span="24">
                        <el-form-item label="派送员" prop="deliveryManId">
                            <el-select v-model="selectDeliveryForm.deliveryManId" placeholder="请选择派送员" clearable>
                                <el-option v-for="man in deliveryManList" :key="man.appUserId" :label="man.realName" :value="man.appUserId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>

            <div>
                <el-button type="primary" @click="submitDelivery" style="margin-left: 40%">提交</el-button>
            </div>
        </el-dialog>
        <pay-status-popup ref="payStatusPopup" hidePointer @paySuccess="handleQuery" @confirm="handleDetail"></pay-status-popup>
    </div>
</template>

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

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

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

        // 去支付
        toPay(scope) {
            this.$refs.payStatusPopup.open(2, scope.row)
        },

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

            this.$modal.confirm('是否确认取衣衣服编号为"' + params.washCodes + '"的数据项？').then(function () {
                takeCloth(params).then((res) => {
                    _this.$message.success('取衣成功')
                    _this.open = false
                    _this.getList()
                    if (!_this.LODOP) {
                        _this.$modal.msgError('请安装打印机软件')
                        return
                    }
                    _this.$modal.confirm('是否打印小票？').then(function () {
                        getInfoByOrderNo({ orderNo: _this.orderDetail.orderNo }).then((res) => {
                            let p_name = ''
                            _this.pointerList.forEach((pointer) => {
                                if (pointer.printType == 0) {
                                    p_name = pointer.printName
                                }
                            })
                            _this.sendClothPrinter(_this.LODOP, res.data, p_name)
                        })
                    })
                })
            })
        },
        submitDelivery() {
            if (this.isEmpty(this.selectDeliveryForm.deliveryManId)) {
                this.$message.error('请先选择配送员')
                return
            }
            setSendDelivery({ deliveryManId: this.selectDeliveryForm.deliveryManId, orderId: this.orderDetail.id }).then((res) => {
                this.$message.success('设置成功')
                this.deliveryOpen = false
                this.getList()
            })
        },
        confirmSend(scope) {
            this.$confirm('确认这笔订单已经完成吗？？')
                .then(() => {
                    confirmSend({ orderId: scope.row.id }).then((response) => {
                        this.$modal.msgSuccess('提交成功')
                        this.getList()
                    })
                })
                .catch(() => {})
        }
    }
}
</script>
