<template>
    <view class="flex direction-column height-100pre width-100per">
        <easy-tab ref="tabProcess" type="line" @change="onTabChange">
            <easy-tab-item v-for="(item, index) in process" :value="item.processId">{{item.processName}}</easy-tab-item>
        </easy-tab>
        <view class="flex items-center padding-lr">
            <easy-combobox ref="comboboxStatus" width="160" @change="changeStatus">
                <easy-combobox-option v-if="isDispatch" :value="1" text="派工"></easy-combobox-option>
                <easy-combobox-option v-if="isDispatch" :value="2" text="派工确认"></easy-combobox-option>
                <easy-combobox-option v-if="!isDispatch" :value="3" text="报工"></easy-combobox-option>
            </easy-combobox>
            <uni-search-bar placeholder="单号、型号" clearButton="none" class="grow-1" v-model="searchValue"
                @confirm="load"></uni-search-bar>
            <button size="mini" type="primary" @tap="load">搜索</button>
        </view>
        <!-- <view class="flex padding-lr child-gap">
            <uni-datetime-picker type="date" placeholder="开始时间"></uni-datetime-picker>
            <uni-datetime-picker type="date" placeholder="结束时间"></uni-datetime-picker>
        </view> -->
        <view class="grow-1 height-0 scroll padding">
            <view class="dispatch-row" v-for="(item, index) in items" key="number">
                <view class="grow-1 padding-right">
                    <view class="dispatch-row-cells child-gap">
                        <view class="dispatch-row-title">{{item.orderNumber}}
                        </view>
                        <view class="dispatch-row-quantity">数量：{{item.quantity}}</view>
                    </view>
                    <view class="dispatch-row-cells child-gap">订单号：{{item.orderNumber}}</view>
                    <view class="dispatch-row-cells child-gap">计划号：{{item.planNumber}}</view>
                    <view class="dispatch-row-cells child-gap">工艺：{{item.processName}}</view>
                    <view class="dispatch-row-cells child-gap">料号：{{item.inventoryNumber}}</view>
                    <view class="dispatch-row-cells child-gap">品名：{{item.inventoryName}}</view>
                    <view class="dispatch-row-cells child-gap">规格：{{item.spec}}</view>
                    <view class="dispatch-row-cells child-gap">数量：{{item.quantity}}</view>
                    <view class="dispatch-row-cells child-gap">状态：{{item.statusText}}</view>
                </view>
                <view class="shrink-0">
                    <button size="mini" :type="item.buttonType"
                        @tap="details(item.dispatchOrderId)">{{item.buttonText}}</button>
                </view>
            </view>
        </view>

        <uni-drawer ref="drawer" mode="right" :width="280">
            <scroll-view style="height: 100%;" scroll-y="true">
                <view class="drawer-title">{{currentItem.buttonText}}</view>
                <view class="padding">
                    <view class="dispatch-row-cells child-gap">订单号：{{currentItem.orderNumber}}</view>
                    <view class="dispatch-row-cells child-gap">计划号：{{currentItem.planNumber}}</view>
                    <view class="dispatch-row-cells child-gap">工艺：{{currentItem.processName}}</view>
                    <view class="dispatch-row-cells child-gap">料号：{{currentItem.inventoryNumber}}</view>
                    <view class="dispatch-row-cells child-gap">品名：{{currentItem.inventoryName}}</view>
                    <view class="dispatch-row-cells child-gap">规格：{{currentItem.spec}}</view>
                    <view class="dispatch-row-cells child-gap">数量：{{currentItem.quantity}}</view>
                    <view class="dispatch-row-cells child-gap">状态：{{currentItem.statusText}}</view>
                    <view class="dispatch-row-cells child-gap" v-if="currentItem.isInput">
                        <view class="dispatch-row-cell">工作组：</view>
                        <view class="dispatch-row-cell grow-1 flex width-0">
                            <view class="flex child-gap">
                                <uni-easyinput class="grow-1" :disabled="true"
                                    :value="currentWorkingTeam?.teamName || ''"></uni-easyinput>
                                <view class="flex items-center">
                                    <button size="mini" type="primary" @tap="selectWorkingTeam">选择</button>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="dispatch-row-cells child-gap" v-if="currentItem.isInput">
                        <view class="dispatch-row-cell">备注：</view>
                        <view class="dispatch-row-cell grow-1">
                            <textarea class="drawer-textarea" v-model="currentDescription"></textarea>
                        </view>
                    </view>
                    <view class="margin-top flex justify-center">
                        <button :type="currentItem.buttonType" @tap="action">{{currentItem.buttonText}}</button>
                    </view>
                </view>
            </scroll-view>
        </uni-drawer>
    </view>
</template>

<script>
    import extend from '../../utils/extend';
    import message from '../../utils/message';
    import request from '../../utils/request';
    import url from '../../utils/url';
    import user from '../../utils/user';
    import status from '../../script/status';

    let userinfo = user.get();

    export default {
        name: "page-dispatch",
        props: {
            url: {
                type: String,
                default: ''
            },
            method: {
                type: String,
                default: 'get'
            },
            isDispatch: {
                type: Boolean,
                default: true
            }
        },
        data() {
            return {
                searchValue: '',
                process: [],
                items: [],
                currentItem: null,
                currentDescription: '',
                currentWorkingTeam: null,
                currentStatus: 1,
                currentProcessId: 0
            };
        },
        async created() {
            // await this.load();
            await this.getProcess();
            this.currentStatus = this.$refs.comboboxStatus.getValue();
            this.$refs.tabProcess.select(0);
        },
        methods: {
            async onTabChange(e) {
                this.currentProcessId = e.value;
                await this.load();
            },
            
            async load() {
                let url = '';
                let rows = [];
                switch (this.currentStatus) {
                    case 1:
                        url = 'dispatching-order/search';
                        break;
                    case 2:
                        url = 'dispatch-order/search';
                        break;
                    case 3:
                        url = 'report-order/search';
                        break;
                }
                if (extend.isEmptyString(url)) {
                    return;
                }
                uni.showLoading();
                let res = await request.sendToken({
                    url: url,
                    method: this.method,
                    data: {
                        userId: userinfo.systemUserId,
                        process: this.currentProcessId
                    }
                });
                uni.hideLoading();
                if (res.success) {
                    if (extend.isObject(res.data) && extend.isArray(res.data.rows)) {
                        rows = this.parseRows(res.data.rows);
                        this.items = rows;
                        console.log('orders：', res.data.rows);
                    }
                } else {
                    uni.showModal({
                        title: '错误',
                        content: res.message
                    });
                }
                return rows;
            },

            async getProcess() {
                let res = await request.sendToken({
                    url: `process/search`,
                    data: {
                        name: '',
                        groupNumber: '',
                        // workshopSectionId: 0,
                        opened: true
                    }
                });
                if (res.success) {
                    this.process = res.data.rows;
                    console.log('process:', res.data.rows);
                } else {
                    uni.showModal({
                        title: '错误',
                        content: res.message
                    });
                }
            },

            changeStatus(option) {
                this.currentStatus = option.value;
                console.log('changeStatus', option);
                this.load();
            },

            getRowById(id) {
                let res = null;
                for (let i = 0; i < this.items.length; i++) {
                    if (this.items[i].dispatchOrderId === id) {
                        res = this.items[i];
                        break;
                    }
                }
                return res;
            },

            parseRows(rows) {
                let res = [];
                if (extend.isArray(rows)) {
                    for (let i = 0; i < rows.length; i++) {
                        switch (rows[i].status) {
                            case status.dispatchOrderSatus.dispatching:
                                rows[i].buttonText = '派工';
                                rows[i].actionUrl = 'produce/dispatch';
                                rows[i].buttonType = 'orange';
                                rows[i].isInput = true;
                                if (this.isDispatch) {
                                    res.push(rows[i]);
                                }
                                break;
                            case status.dispatchOrderSatus.dispatched:
                                rows[i].buttonText = '确认派工';
                                rows[i].actionUrl = 'produce/dispatch/confirm';
                                rows[i].buttonType = 'danger';
                                rows[i].isInput = false;
                                if (this.isDispatch) {
                                    res.push(rows[i]);
                                }
                                break;
                            case status.dispatchOrderSatus.confirmed:
                                rows[i].buttonText = '报工';
                                rows[i].actionUrl = 'produce/report';
                                rows[i].buttonType = 'ok';
                                rows[i].isInput = false;
                                if (!this.isDispatch) {
                                    res.push(rows[i]);
                                }
                                break;
                            default:
                                return res;
                        }
                    }
                }
                return res;
            },

            selectWorkingTeam() {
                uni.navigateTo({
                    url: '/pages/workingTeam/select'
                });
            },

            details(id) {
                this.currentItem = this.getRowById(id);
                this.$refs.drawer.open();
            },

            getActionData() {
                let res = null;
                if (extend.isNull(this.currentItem)) {
                    return res;
                }
                console.log('currentItem: ', this.currentItem);
                switch (this.currentItem.status) {
                    case status.dispatchOrderSatus.dispatching:
                        if (this.isDispatch && extend.isObject(this.currentWorkingTeam)) {
                            res = [{
                                dispatchingOrderId: this.currentItem.dispatchOrderId,
                                workingTeamId: this.currentWorkingTeam.workingTeamId,
                                description: this.currentDescription
                            }];
                        }
                        break;
                    case status.dispatchOrderSatus.dispatched:
                        if (this.isDispatch) {
                            res = [this.currentItem.dispatchOrderId];
                        }
                        break;
                    case status.dispatchOrderSatus.confirmed:
                        if (!this.isDispatch) {
                            res = [this.currentItem.dispatchOrderId];
                        }
                        break;
                }
                return res;
            },

            async action() {
                if (extend.isNull(this.currentItem)) {
                    return;
                }
                let row = this.getRowById(this.currentItem.dispatchOrderId);
                if (extend.isNull(row) && extend.isNonEmptyString(this.buttonUrl)) {
                    return;
                }
                let data = this.getActionData();
                console.log('data: ', data);
                let r = await uni.showModal({
                    title: `${this.currentItem.buttonText}操作`,
                    content: `是否${this.currentItem.buttonText}单号为 ${row.orderNumber} 的生产订单？`
                });
                if (r.cancel) {
                    return;
                }
                uni.showLoading();
                let res = await request.sendToken({
                    url: `${row.actionUrl}`,
                    method: 'post',
                    data: data
                });
                uni.hideLoading();
                if (res.success) {
                    this.$refs.drawer.close();
                    await this.load();
                    message.showSuccess({
                        title: `已${this.currentItem.buttonText}`
                    });
                } else {
                    uni.showModal({
                        title: '错误',
                        content: res.message
                    });
                }
            }
        }
    }
</script>

<style lang="scss">
    .dispatch-row {
        position: relative;
        display: flex;
        padding: 20upx 0;
        align-items: center;
    }

    .dispatch-row-title {
        font-size: 36upx;
    }

    .dispatch-row-quantity {
        color: #666666;
        font-size: 24upx;
    }

    .dispatch-row-cells {
        position: relative;
        display: flex;
        color: #666666;
        justify-content: space-between;
        align-items: center;
        margin-top: 20upx;
        flex-wrap: wrap;
        font-size: 24upx;
        box-sizing: border-box;
    }

    .dispatch-row-cell {
        flex-shrink: 0;
        font-size: 24upx;
        box-sizing: border-box;
    }

    .dispatch-row+.dispatch-row {
        border-top: 1upx solid #dfdfdf;
    }

    .drawer-title {
        position: relative;
        width: 100%;
        display: flex;
        justify-content: center;
        padding-top: 20upx;
        font-size: 36upx;
    }

    .drawer-textarea {
        border: 1upx solid #dfdfdf;
        width: 100%;
        border-radius: 20upx;
        padding: 10upx;
        box-sizing: border-box;
    }
</style>