// 调价录入制单 -- 调价单录入
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Button, message, Popconfirm } from 'antd';
import { $http } from 'containers/config/https';
import { printAdjstmentEntry } from '../commonPrint/stkPrint';
import Moment from 'moment';
import ShiftDetailList from './component/ShiftDetailList.jsx';
import './style/index.less';

const PriceAdjustmentEntry = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: {},
                SelectData: {}, // 下拉框数据
                detailInfo: [], // 明细列表数据
                rowId: '', // 入库单Id
                pageSize: 9999,
                page: 1,
                User: JSON.parse(window.sessionStorage.userData),
                statusCode: '',
                statusId: '',
                inOpLocDr: '',
                toLocDr: '',
                stkCat: '',
                filterLoc: JSON.parse(window.sessionStorage.userData).locID,
                showPopup: true,
                ChineseEnglishSize: {}, //中英翻译
            };
            this.myRef1 = React.createRef();
            this.myRef2 = React.createRef();
            this.myRef3 = React.createRef();
            this.myRef4 = React.createRef();
            this.myRef5 = React.createRef();
            this.myRef6 = React.createRef();
            this.myRef7 = React.createRef();
            this.myRef8 = React.createRef();
            this.myRef9 = React.createRef();
        }

        componentDidMount() {
            this.getInOpLocDr();
            this.getEchoData('N');
        }

        componentWillUnmount() {
            // 组件销毁前将静止让setState修改state的状态，防止内存泄漏
            this.setState = (state, callback) => { return; }
        }

        onRef = (ref) => {
            this.childModal = ref;
        }

        detailOnRef = (ref) => {
            this.childDetail = ref;
        }

        onSelectRef = (ref) => {
            this.childSelect = ref;
        }

        // 保存
        saveHandle = () => {
            if (this.childDetail.state.data.length < 1) {
                message.error("明细列表不能为空")
            } else {
                this.props.form.validateFields((errors, values) => {
                    if (errors == null) {
                        let data = {
                            params: this.childDetail.state.data
                        }
                        $http.post('urlS', this, {
                            code: "02020040",
                            data: data,
                            success: function (res) {
                                if (+res.errorCode === 0) {
                                    // 成功提示
                                    message.success(res.errorMessage);
                                    this.getEchoData();
                                }
                            },
                            error: function (err) {
                                console.log(err)
                            }
                        })
                    }
                })

            }

        }

        // 查询
        getEchoData = (isTips) => {
            // 重置表单
            // this.props.form.resetFields(); //清空所有
            let endDate = this.props.form.getFieldValue('endDate');
            let startDate = this.props.form.getFieldValue('startDate');
            let data = {
                params: [
                    {
                        startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : '',
                        endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : '',
                        state: "NO",
                    }
                ],
                pagination: [
                    {
                        pageSize: this.state.pageSize,
                        currentPage: this.state.page,
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02020044",
                data: data,
                success: function (res) {
                    if (res.errorCode == 0 && res.result.length > 0) {
                        for (let i = 0; i < res.result.length; i++) {
                            res.result[i].key = i + "main";
                        }
                        this.setState({ detailInfo: res.result });
                    } else {
                        isTips === 'N' ? '' : message.error('没数据');
                        this.setState({ detailInfo: [] });
                    }
                }
            })
        }

        // 获取到部门的值
        getInOpLocDr = () => {
            let inOpLocDr = this.props.form.getFieldValue('frLoc');
            let toLocDr = this.props.form.getFieldValue('toLoc');
            let stkCat = this.props.form.getFieldValue('stkCat');
            this.setState({ inOpLocDr: inOpLocDr, toLocDr: toLocDr, stkCat: stkCat });
            return inOpLocDr
        }

        changeStkCat = (v) => {
            this.setState({ stkCat: v })
        }

        changesDesc = (v) => {
            this.setState({ toLocDr: v })
        }

        //显示选取请求单
        selectRequisition = () => {
            this.getInOpLocDr();
            this.childSelect.showModal(this.state.SelectData);
        }

        // 重置所有内容
        resetFieldsAll = () => {
            this.props.form.resetFields(); //清空所有
            this.setState({ detailInfo: [], rowId: "", statusId: '', filterLoc: '' });
            this.childDetail.resetFields();
            this.childDetail.deleteData();
            // this.childModal.setState({tableData: []});
        }

        // 重置表单
        resetFields = () => {
            this.resetFieldsAll()
        }

        /**
        * @ByShizi: 删除 - 药品调价界面，调价单据未保存的情况下，选中需要删除的药品，点击删除不起作用，无法删除。
        * 需求 #947
        * Create 2021-09-27
        * */
        handleDelete = () => {
            let userInfo = this.childDetail && this.childDetail.state && this.childDetail.state.userInfo ? this.childDetail.state.userInfo : {};
            if (userInfo && 'adjID' in userInfo && userInfo.adjID) {
                let data = {
                    params: [userInfo?.adjID]
                };
                $http.post('urlS', this, {
                    code: "02020077",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode == 0) {
                            message.success(res.errorMessage);
                            this.getEchoData('N');
                            this.resetFieldsAll();
                        }
                    }
                })
            } else if (userInfo && 'key' in userInfo && userInfo.key) {
                this.childDetail && this.childDetail.deleteRow(userInfo?.key || '');
                message.success('删除成功');
            } else {
                message.error('请选择需要删除的数据！');
            }
        }

        //筛选科室
        filterLoc = (e) => {
            this.setState({ filterLoc: e, inOperLocID: e });
        }

        show = () => {
            this.setState({ showPopup: false })
        }

        //获取中英版
        getChineseEnglishSize = (v) => {
            this.setState({ ChineseEnglishSize: v })
        }

        onClisckPrice = () => {
            if (this.childDetail.state.stockID) {
                printAdjstmentEntry.call(this, this.childDetail.state.stockID)
            } else {
                message.error('请选择打印数据')
            }
        }

        render() {
            const formItemInput = {
                labelCol: { span: 6 },
                wrapperCol: { span: 18 },
            };
            const { getFieldDecorator } = this.props.form;
            let { ChineseEnglishSize } = this.state;
            return (
                <div className="ShiftVouching">
                    <Card
                        size="small"
                        title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.StockTransferMakingForminventoryTransferDocument ? ChineseEnglishSize.StockTransferMakingForminventoryTransferDocument.descripts : '调价录入制单'}</div>}
                    >
                        <Row>
                            <Col span={18} className="top-form">
                                <Form>
                                    <Row>
                                        <Col span={6}>
                                            <Form.Item label={ChineseEnglishSize.PriceReviewStartDate ? ChineseEnglishSize.PriceReviewStartDate.descripts : '开始日期'} {...formItemInput}>
                                                {getFieldDecorator('startDate', {
                                                    rules: [{
                                                        required: false,
                                                        message: '不能为空'
                                                    }],
                                                    initialValue: Moment(new Date)
                                                })(<DatePicker style={{ width: '100%' }} />)}
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item label={ChineseEnglishSize.PriceReviewdeadline ? ChineseEnglishSize.PriceReviewdeadline.descripts : '结束日期'} {...formItemInput}>
                                                {getFieldDecorator('endDate', {
                                                    rules: [{
                                                        required: false,
                                                        message: '不能为空'
                                                    }],
                                                    initialValue: Moment(new Date)
                                                })(<DatePicker style={{ width: '100%' }} />)}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </Form>
                            </Col>
                            <Col span={6}>
                                <Row style={{ marginTop: '5px' }}>
                                    <Button onClick={this.getEchoData}>{ChineseEnglishSize.StockTransferMakingFormsearch ? ChineseEnglishSize.StockTransferMakingFormsearch.descripts : '查询'}</Button>
                                    <Button type="primary" style={{ margin: '0 30px' }} onClick={this.saveHandle}>{ChineseEnglishSize.StockTransferMakingFormsave ? ChineseEnglishSize.StockTransferMakingFormsave.descripts : '保存'}</Button>
                                    <Popconfirm title={ChineseEnglishSize.StockTransferMakingFormdeleteTips ? ChineseEnglishSize.StockTransferMakingFormdeleteTips.descripts : "删除不可恢复，你确定要删除吗?"} onConfirm={this.handleDelete} >
                                        <Button type="danger">{ChineseEnglishSize.StockTransferMakingFormdelete ? ChineseEnglishSize.StockTransferMakingFormdelete.descripts : '删除'}</Button>
                                    </Popconfirm>
                                    <Popconfirm title={ChineseEnglishSize.StockTransferMakingFormresetTips ? ChineseEnglishSize.StockTransferMakingFormresetTips.descripts : "重置后将初始化数据，你确定要重置吗?"} onConfirm={this.resetFields} >
                                        <Button type="primary" style={{ margin: '0 30px' }} >{ChineseEnglishSize.StockTransferMakingFormReset ? ChineseEnglishSize.StockTransferMakingFormReset.descripts : '重置'}</Button>
                                    </Popconfirm>
                                    <Button type="dashed" onClick={this.onClisckPrice}>{ChineseEnglishSize.StockTransferMakingFormprint ? ChineseEnglishSize.StockTransferMakingFormprint.descripts : '打印'}</Button>
                                </Row>
                            </Col>
                        </Row>
                    </Card>
                    <ShiftDetailList SelectData={this.state.SelectData} onRef={this.detailOnRef} detailInfo={this.state.detailInfo} handleThis={this} inOpLocDr={this.state.inOpLocDr} toLocDr={this.state.toLocDr} stkCat={this.state.stkCat} />
                </div>
            )
        }
    }
);

export default PriceAdjustmentEntry;