<template>
    <div class="addMaterialDistribution">
        <a-spin tip="加载中..." :spinning="spinning">
            <div style="padding: 16px">
                <div style="font-size: 18px;font-weight: 600">
                    <span>调拨分配</span>
                </div>
                <a-form-model ref="formRef" :model="formData" :rules="formRules" :labelCol="{span: 7}"
                              :wrapperCol="{span: 15}">

                    <div style="margin: 30px 0px">
                        <div class="divider_my"><span class="midText">分配信息</span></div>
                    </div>
                    <div style="clear: both"></div>
                    <div>
                        <a-row>
                            <a-col :span="8">
                                <a-form-model-item label="发货人姓名" prop="sendContact">
                                    <a-input
                                            v-toInputNum="{num:15}"
                                            placeholder="请填写发货人，最多可输入15个字"
                                             v-model="formData.sendContact"
                                    ></a-input>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-model-item label="发货人联系电话" prop="sendPhone">
                                    <a-input placeholder="请填写发货人电话" v-model="formData.sendPhone"></a-input>
                                </a-form-model-item>
                            </a-col>

                            <a-col :span="8">
                                <a-form-model-item label="发货日期" prop="sendDate">
                                    <a-date-picker v-model="formData.sendDate" style="width: 100%"/>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-model-item label="收货单位" prop="receiveUnitId">
                                    <a-select v-model="formData.receiveUnitId" placeholder="请选择"
                                              @click.native="getChildUnitList">
                                        <a-select-option v-for="item in childUnitList"
                                                         :key="item.id" :value="item.id"
                                        >
                                            {{item.unitName}}
                                        </a-select-option>
                                    </a-select>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-model-item label="收货人姓名" prop="receiver">
                                    <a-input
                                             v-toInputNum="{num:15}"
                                             placeholder="请填写收货人，最多可输入15个字"
                                             v-model="formData.receiver"
                                    ></a-input>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-model-item label="收货人联系电话" prop="receivePhone">
                                    <a-input placeholder="请填写收货人电话" v-model="formData.receivePhone"></a-input>
                                </a-form-model-item>
                            </a-col>
                        </a-row>
                    </div>
                    <div>
                        <div class="divider_my"><span class="midText">分配详情</span></div>
                    </div>
                    <div style="clear: both"></div>
                    <a-table :dataSource="formData.detailedList" rowKey="id" :pagination="false" class="modal_table"
                             bordered>
                        <a-table-column title="品牌" data-index="brandName"></a-table-column>
                        <a-table-column title="供应商名称" data-index="supplierName"></a-table-column>
                        <a-table-column title="批次号" data-index="batchNumber"></a-table-column>
                        <a-table-column title="当前库存" data-index="number"></a-table-column>
                        <a-table-column title="分配数量" width="190px">
                            <template slot-scope="text, record, index">
                                <a-form-model-item :prop="'detailedList.' + index + '.sendNum'"
                                                   :rules="formRules.sendNum" class="tab_input_r">
                                    <a-input type="number"
                                             v-toInt="{notNum: '0'}"
                                             v-model="record.sendNum"
                                             placeholder="请输入分配数量"
                                             style="width: 150px;"
                                             @change="getChangeRecord(record)"
                                    >

                                    </a-input>
                                </a-form-model-item>
                            </template>
                        </a-table-column>
                        <a-table-column title="操作" align="center" width="70px">
                            <template slot-scope="text, record, index">
                                <!-- <a-button type="link" class="table_delbtn" @click="deleteGoodsList(index)">删除</a-button> -->
                                <a-popconfirm
                                        title="确定移除该物资吗？"
                                        ok-text="是"
                                        cancel-text="否"
                                        @confirm="confirm(index)"
                                >
                                    <a-button class="ant-table-btn" size="small">删除</a-button>
                                </a-popconfirm>
                            </template>
                        </a-table-column>
                    </a-table>
                </a-form-model>
                <div style="text-align: center;margin-top: 16px">
                    <a-button class="ant-table-btn" @click="goBack">取消</a-button>
                    <a-button type="primary" @click="addMaterialDis" :loading="subLoad" style="margin-left: 8px">调拨分配
                    </a-button>
                </div>
            </div>
        </a-spin>
    </div>

</template>

<script>
    import {checkPhone, closedDetail} from "../../../utils/common";
    import moment from 'moment'

    let vm = this
    let recordInfo = {}
    export default {
        data() {
            return {
                unitInfo: JSON.parse(window.sessionStorage.getItem('userInfo')),
                routerParams: {},
                spinning: false,
                subLoad: false,
                // 弹窗内表单
                formData: {
                    detailedList: [],
                    sendUnitId: undefined,
                    sendUnitName: undefined,
                    receiveUnitId: undefined,
                    sendDate: moment(new Date()).format('YYYY-MM-DD'),
                    sendContact: undefined,
                    sendPhone: undefined,
                    receivePhone: undefined,
                    receiver: undefined
                },
                childUnitList: [],
                formRules: {
                    sendUnitName: [
                        {required: true, message: '请选择发货单位'}
                    ],
                    receivePhone: [
                        {required: true, message: '请填写收货人电话'},
                        {validator: checkPhone},
                    ],
                    receiveUnitId: [
                        {required: true, message: '请选择收货单位'}
                    ],
                    sendDate: [
                        {required: true, message: '请选择发货日期'}
                    ],
                    sendNum: [
                        {required: true, message: '请填写分配数量'},
                        {
                            validator: (rule, value, callback) => {
                                if (value == '' || value == undefined) {
                                    callback()
                                }
                                if (value <= recordInfo.number) {
                                    callback()
                                } else {
                                    callback(new Error('分配数量不能超出当前库存！'));
                                }
                            },
                        },
                    ],
                    sendContact: [
                        {required: true, message: '请填写发货人姓名'}
                    ],
                    receiver: [
                        {required: true, message: '请填写收货人姓名'}
                    ],
                    sendPhone: [
                        {required: true, message: '请填写发货人联系电话'},
                        {validator: checkPhone},
                    ],
                },
            }
        },
        created() {
            this.routerParams = this.$route.query
            this.getSelectedMedical()
            this.formData.sendUnitId = this.unitInfo.unitId;
            this.formData.sendUnitName = this.unitInfo.unitName;
            this.getChildUnitList();
        },
        methods: {
            // 删除药具
            confirm(index) {
                this.formData.detailedList.splice(index, 1);
            },
            //获取改变的当前项
            getChangeRecord(record) {
                recordInfo = record
            },
            getSelectedMedical() {//获取被选中的药具
                let par = {
                    idList: this.$route.query.selected,
                    menuId: this.routerParams.menuId
                }
                this.$api.stockManage.fetchMedicalListByIds(par).then(({data = []}) => {
                    this.formData.detailedList = data
                })

            },
            // 获取当前单位的下级单位
            getChildUnitList() {
                //this.childUnitList = [{id:16625, unitName:'gcl'}]
                let par = {
                    menuId: this.routerParams.menuId
                }
                this.$api.common.fetchAllChildOrgInfo(par).then(({code, data}) => {
                    if (code === 'SUCCESS') {
                        this.childUnitList = data;
                    }
                });
            },
            addMaterialDis() {//调拨分配
                this.$refs.formRef.validate(valid => {
                    if (valid) {
                        if (this.formData.detailedList.length === 0) {
                            this.$message.warning('分配物资不能为空！');
                        } else {
                            this.subLoad = true;
                            let params = {}
                            let reviceUnitName = this.childUnitList.filter(item => item.id == this.formData.receiveUnitId)[0].unitName;
                            let treeNodeId = this.childUnitList.filter(item => item.id == this.formData.receiveUnitId)[0].treeNodeId;
                            let unitInfo = JSON.parse(window.sessionStorage.getItem('unitInfo'));
                            params = {
                                ...this.formData,
                                receiveNodeId: treeNodeId,
                                receiveNodeName: reviceUnitName,
                                sendDate: moment(this.formData.sendDate).format('YYYY-MM-DD'),
                                receiveUnitName: reviceUnitName,
                                sendUnitName: unitInfo.unitName
                            };
                            let detailedList = [];
                            this.formData.detailedList.forEach(item => {
                                detailedList.push({
                                    ...item,
                                    stockId: item.id
                                });
                            });
                            params.detailedList = detailedList;
                            params.menuId = this.routerParams.menuId
                            this.$api.stockManage.fetchDispatchGoods(params).then(({code}) => {
                                this.subLoad = false;
                                if (code === 'SUCCESS') {
                                    this.$message.success('调拨分配成功！');
                                    this.goBack()
                                }
                            }).catch(() => {
                                this.subLoad = false;
                            })
                        }
                    }
                });
            },
            goBack() {
                window.top.postMessage({messageType:'THIRD_PAGECHANGE',name:`${this.routerParams.menuCode}`,source:"yesuan"}, '*')
                // closedDetail('/inStock/addMaterialDistribution', '/Home/inStock')
            }
        }
    }
</script>

<style lang="less">
    .detail_title {
        padding: .1px 16px;
        border: 1px solid #F0F0F0;
        border-bottom: 0px
    }

    .addMaterialDistribution {
        .ant-table-thead > tr > th, .ant-table-tbody > tr > td {
            padding: 10px !important;
        }
    }

    .modal_table {
        .ant-form-item {
            margin-bottom: 0px !important;
        }
    }
</style>
