<template>
    <div>
        <div class="i-layout-page-header">
            <PageHeader :title="$route.meta.title"
                :content="$route.meta.description"
                hidden-breadcrumb />
        </div>
        <Card :bordered="false"
            dis-hover
            class="ivu-mt">
            <view-table ref="table"
                :filter="filter"
                :selectEnable="true"
                @create="createNew">
                <template slot="filterCommand">
                    <Button size="small"
                        type="info"
                        custom-icon="fa fa-print"
                        @click="print">打印</Button>
                </template>
                <template slot-scope="{ row, index }"
                    slot="command">
                    <Button size="small"
                        title="明细"
                        type="info"
                        custom-icon="fa fa-bars"
                        @click="$refs.itemTable.open({'movePlanID': row.id})"></Button>
                </template>
            </view-table>
        </Card>
        <modal-form ref="form"
            :defaultData="defaultData"
            @on-change="formChange">
            <template slot="bottom">
                <view-table ref="itemEditTable"
                    :static="true"
                    :height="360">
                    <template slot="filterCommand">
                        <Button type="primary"
                            custom-icon="fa fa-clipboard-list"
                            v-if="itemSelectEnable"
                            @click="selectItem()"
                            size="small">明细选择</Button>
                    </template>
                    <template slot-scope="{ row, index }"
                        slot="command">
                        <Button size="small"
                            title="删除"
                            type="warning"
                            custom-icon="fa fa-trash-alt"
                            @click="removeItem(row, index)"></Button>
                    </template>
                </view-table>
            </template>
            <template slot="footer">
                <Button type="primary"
                    custom-icon="fa fa-upload"
                    @click="submit">提交</Button>
                <!-- <Button type="primary"
                    custom-icon="fa fa-save"
                    @click="save">保存</Button> -->
            </template>
        </modal-form>
        <modal-table ref="itemTable">
        </modal-table>
        <Modal v-model="itemSelectOpened"
            scrollable
            width="1500">
            <div slot="header">
                <span class="title">明细选择</span>
                <span class="description">Item Select</span>
            </div>
            <Row :gutter="24">
                <Col span="14">
                <Card :bordered="false"
                    dis-hover>
                    <div slot="title">
                        <Avatar icon="md-apps"
                            size="small"
                            v-color="'#1890ff'"
                            v-bg-color="'#e6f7ff'" />
                        <span class="ivu-pl-8">待选择</span>
                    </div>
                    <view-table ref="selectSourceTable"
                        :selectEnable="true"
                        :filter="selectFilter"
                        :height="480"
                        @on-select-change="selectedChange">
                    </view-table>
                </Card>
                </Col>
                <Col span="10">
                <Card :bordered="false"
                    dis-hover>
                    <div slot="title">
                        <Avatar icon="md-checkmark"
                            size="small"
                            v-color="'#1890ff'"
                            v-bg-color="'#e6f7ff'" />
                        <span class="ivu-pl-8">已选择</span>
                    </div>
                    <view-table ref="selectTargetTable"
                        :static="true"
                        :height="480">
                        <template slot-scope="{ row, index }"
                            slot="command">
                            <Button size="small"
                                title="删除"
                                type="warning"
                                custom-icon="fa fa-trash-alt"
                                @click="selectedRemove(index)"></Button>
                        </template>
                    </view-table>
                </Card>
                </Col>
            </Row>
            <div slot="footer">
                <Button type="primary"
                    custom-icon="fa fa-save"
                    @click="saveSelect">
                    确定
                </Button>
                <Button type="default"
                    custom-icon="fa fa-times"
                    @click="itemSelectOpened = false">
                    关闭
                </Button>
            </div>
        </Modal>
    </div>
</template>
<script>
    import { mixinPage } from '/src/index.js';
    import moveTypeApi from '../../api/moveType';
    import movePlanApi from '../../api/movePlan';

    export default {
        name: 'warehouse-movePlan',
        mixins: [mixinPage],
        components: {},
        data() {
            return {
                filter: {}, // 筛选
                defaultData: {}, // 默认值
                moveType: {}, // 移库类型
                itemSelectEnable: false, // 是否显示明细选择按钮
                itemSelectOpened: false, // 明细选择界面打开
                selectFilter: {} // 明细选择界面筛选
            };
        },
        computed: {},
        created() {
            this.init(this.$route.meta.data.type);
        },
        watch: {
            $route(to, from) {
                this.init(this.$route.meta.data.type);
            }
        },
        methods: {
            // 初始化
            async init(type) {
                this.moveType = await moveTypeApi.getByCode(type);
                this.filter['moveType.code'] = type;

                this.$refs.table.init('MovePlan_' + type, () => {
                    this.$refs.table.loadData();
                });
                this.$refs.form.init('MovePlanEdit_' + type);
                this.$refs.itemTable.init('MovePlanItemModal_' + type);
                this.$refs.itemEditTable.init('MovePlanItemEdit_' + type);

                this.defaultData['moveTypeCode'] = this.moveType.code;
                this.defaultData['moveTypeID'] = this.moveType.id;
                this.$refs.form.setDefault();

                if (this.moveType.preType == 'PO') {
                    this.$refs.selectSourceTable.init('PurchaseOrderItemSource');
                    this.$refs.selectTargetTable.init('PurchaseOrderItemTarget');
                }
            },
            createNew() {
                this.$refs.form.open();
            },
            selectItem() {
                this.itemSelectOpened = true;
            },
            formChange(sender, oldValue, newValue, selected) {
                const data = this.$refs.form.data;
                const columns = this.$refs.form.columns;

                if (sender && sender.code == 'preID' && selected != null) {
                    if (this.moveType.preType == 'PO') {
                        // 采购订单
                        data.sourceCompanyID = selected.supplierID;
                        data.sourceCompany = selected.supplier;
                        //data.targetWarehouseID = selected.warehouseID;
                        //data.targetWarehouse = selected.warehouse;
                        data.estFinishTime = selected.estArrivalTime;
                    } else if (this.moveType.preType == 'SO') {
                    }
                }

                if (data.preID) {
                    if (this.moveType.preType == 'PO') {
                        // 采购订单
                        this.selectFilter.purchaseOrderID = data.preID;
                    } else if (this.moveType.preType == 'SO') {
                    }

                    this.itemSelectEnable = true;
                    this.$refs.selectSourceTable.loadData();
                } else {
                    this.itemSelectEnable = false;
                }

                this.$refs.form.forceUpdate();
            },
            selectedChange() {
                let selected = this.$refs.selectSourceTable.getSelected();

                console.log(selected);

                this.$refs.selectTargetTable.loadData(selected);
            },
            selectedRemove(index) {
                let selectedSource = this.$refs.selectTargetTable.data;
                selectedSource.splice(index, 1);
                this.$refs.selectTargetTable.loadData(selectedSource);

                this.$refs.selectSourceTable.setSelected(selectedSource);
            },
            saveSelect() {
                let movePlanItems = this.$refs.itemEditTable.data;
                if (this.moveType.preType == 'PO') {
                    let selected = this.$refs.selectTargetTable.data;

                    // 保留存在的选择项
                    let exists = movePlanItems.filter(item => {
                        return selected.some(i => {
                            i.id == item.preID;
                        });
                    });

                    movePlanItems.length = 0;

                    exists.forEach(item => {
                        movePlanItems.push(item);
                    });

                    // 加入新的选择项
                    selected.forEach(item => {
                        if (
                            !movePlanItems.some(i => {
                                return i.preID == item.id;
                            })
                        ) {
                            let quantity = item.quantity - item.planQuantity || 0;
                            if (quantity < 0) {
                                quantity = 0;
                            }

                            movePlanItems.push({
                                materialID: item.materialID,
                                material: item.material,
                                //batchNumber: item.batchNumber,
                                quantity,
                                unit: item.unit,
                                preID: item.id,
                                preNo: item.itemNo
                            });
                        }
                    });
                }

                this.$refs.itemEditTable.loadData(movePlanItems);
                this.itemSelectOpened = false;
            },
            removeItem(row, index) {
                this.confirm('确定要移除该项吗？', () => {
                    let movePlanItems = this.$refs.itemEditTable.data;
                    let selectedSource = this.$refs.selectTargetTable.data;
                    movePlanItems.splice(index, 1);
                    this.$refs.itemEditTable.loadData(movePlanItems);

                    const selectedIndex = selectedSource.findIndex(item => {
                        return item.id == row.preID;
                    });
                    selectedSource.splice(selectedIndex, 1);
                    this.$refs.selectTargetTable.loadData(selectedSource);

                    this.$refs.selectSourceTable.setSelected(selectedSource);
                });
            },
            async save() {
                this.confirm('确定要保存吗？', async () => {
                    this.success('保存成功!', () => {});
                });
            },
            async submit() {
                let isOK = await this.$refs.form.validate();

                if (!isOK) {
                    this.error('有内容不符合要求，请正确填写！');
                } else {
                    this.confirm('确定要提交吗？', async () => {
                        await movePlanApi.submit(this.$refs.form.data, this.$refs.itemEditTable.data);

                        this.success('提交成功!', () => {
                            this.$refs.table.loadData();
                            this.$refs.form.close();
                        });
                    });
                }
            },
            print() {
                let ids = this.$refs.table.getSelected().map(x => {
                    return x.id;
                });
                if (ids.length > 0) {
                    movePlanApi.print(ids);
                } else {
                    this.error('请选择需要打印的数据！');
                }
            }
        }
    };
</script>
