/*
 * Creator:     wyx
 * CreatDate:   2020-3-10
 * descripts：  快递服务数据维护
 * */
import React from 'react';
import store from 'store';
import 'assets/css/common.css';
import { $http } from '../../containers/config/https'
import moment from 'moment';
import { Select, Row, Col, Button, Spin, Divider, Popconfirm, DatePicker, Icon, Input, Table, Modal, message, Form } from 'antd';
import ColumnAuthoritysModel from '../../pages/columnAuthority/ColumnAuthoritysModel'
import CommonPagination from '../../components/pagination';
const FormItem = Form.Item;
const paddRightCol = {
    paddingRight: "0px"
}
const formItemLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
}
let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
const DeliveryService = Form.create()(
    class DeliveryService extends React.Component {
        constructor(props) {
            var userData = JSON.parse(sessionStorage.getItem('userData'));
            super(props);
            this.state = {
                userData: userData,
                // 表格数据
                tableData: [],
                // 表格数据总条数
                total: 0,
                page: 1,
                pageSize: 10,
                size: "small",
                search: "",
                visible: false,
                num: -1,
            };
        }
        //初始化数据
        componentWillMount() {
            this.getHopSelect()
            this.getTableData()
            this.getMainTableColumns();
        }
        componentDidMount() {
            document.querySelector(".table-body-height .ant-table-body").style.height = store.getState().tableHeight.y + 100 + 'px';
            document.querySelector(".table-body-height .ant-table-body").style.maxHeight = store.getState().tableHeight.y + 100 + 'px';
        }
        //获取医院下拉框
        getHopSelect = () => {
            let data = {
                params: [{
                    hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                    logonGroupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : "",
                    logonHospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                }],
            }
            $http.post('urlS', this, {
                code: '01040001',
                data: data,
                success: function (res) {
                    if (res.errorCode == 0) {
                        this.setState({
                            hospArr: res.result
                        })
                    }
                }
            })
        }
        // 请求列表数据
        getTableData() {
            let { page, pageSize } = this.state
            let data = {
                params: [{
                    hospID: this.state.hospitalId ? this.state.hospitalId : '',
                    clientCode: this.state.inputClientCode ? this.state.inputClientCode.state.value : '',
                    custNo: this.state.inputCustNo ? this.state.inputCustNo.state.value : ''
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page
                }]
            }
            $http.post('urlS', this, {
                code: "03030044",
                data: data,
                success: function (res) {
                    if (res.errorCode == 0) {
                        this.setState({ tableData: res.result.data, total: res.result.TotalCount })
                    } else {
                        this.setState({ tableData: [], total: 0 })
                    }
                },
                error: function (error) {
                    this.setState({
                        tableData: [], total: 0
                    })
                }
            })
        }
        //删除 
        toggleEditable = (record) => {
            let data = {}
            data = {
                params: [{
                    updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                    ID: record.ID,
                }],
            }
            $http.post('urlS', this, {
                code: '03030043',
                data: data,
                success: function (res) {
                    if (res.errorCode == 0) {
                        this. getTableData()
                        message.success("删除成功");
                    }
                }
            })
        }
        //动态表头
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }
        //国际化
        setMessage(name, message) {
            return this.state.localeProvider ? this.state.localeProvider[name][message] : ''
        }
        // 获取主列表columns
        getMainTableColumns = () => {
            let data = {
                params: [{
                    compontName: "ExpressServiceTableDataMainten",
                    reactCode: ['ExpressServiceTableDataMainten'],
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
                            return {
                                align: item.align,
                                widthNum: parseInt(item.width),
                                width: item.width,
                                dataIndex: item.dataIndex,
                                title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{this.state.userData.language == 'EN' ? item.enDescripts : item.title}</div>,
                                display: item.display,
                                key: item.seqNo,
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        this.setState({
                            columns: filterArr, widthTotal: res.totalWidth, localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
                        })
                        let seqArr = {
                            align: "center",
                            widthNum: 140,
                            width: "150px",
                            code: "edit",
                            dataIndex: "edit",
                            title: this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenOperating ? this.setMessage('ExpressServiceTableDataMaintenOperating', 'descripts') : "操作：",
                            display: "Y",
                            render: (value, row, index) => {
                                return (
                                    <span>
                                        <span className='span' onClick={() => this.handleCompile("1", row)}>{this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenEdit ? this.setMessage('ExpressServiceTableDataMaintenEdit', 'descripts') : "编辑："}</span>
                                        <Divider type="vertical" />
                                        <Popconfirm title="是否要删除此行" onConfirm={() => this.toggleEditable(row)}>
                                            <a style={{ color: "red" }} >{this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenDelete ? this.setMessage('ExpressServiceTableDataMaintenDelete', 'descripts') : "删除："}</a>
                                        </Popconfirm>
                                    </span>
                                )
                            },
                        }
                        filterArr.push(seqArr)
                        this.setState({ columns: filterArr, widthTotal: res.totalWidth })
                    }
                }
            })
        }
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        // 修改page和pageSize 跳转至---
        onChange = (e) => {
            this.setState({ page: e, pageSize: this.state.pageSize, }, () => {
                this.getTableData();
            })
        }
        //下拉选择页数
        onShowSizeChange = (page, pageSize) => {
            this.setState({ page: 1, pageSize: pageSize, search: "search" }, () => {
                this.getTableData()
            })
        }
        handleSelectChange = (e) => {
            this.setState({
                hospitalId: e
            })
        }
        //控制模态框显示
        closeModal = (bool) => {
            this.setState({ visible: bool, });
        }
        //更新
        handleCompile = (num, record) => {
            console.log(record)
            this.props.form.resetFields();
            this.setState({
                num: num,
                params: num == "1" ? record : "",
                visible: true
            })

        }
        save = () => {
            this.props.form.validateFields((err, values) => {
                const { params } = this.state
                if (!err) {
                    let data = {
                        params: [{
                            ID: params && params.ID ? params.ID : "",
                            hospID: values && values.hospID ? values.hospID : "",
                            descripts: values.descripts || "",
                            code: values.code || "",
                            custNo: values.custNo || "",
                            clientCode: values.clientCode || "",
                            checkWord: values.checkWord || "",
                            eContact: values.eContact || "",
                            eContactPhone: values.eContactPhone || "",
                            eContactMobile: values.eContactMobile || "",
                            startDate: values.startDate ? moment(values.startDate).format('YYYY-MM-DD') : undefined,
                            stopDate: values.stopDate ? moment(values.stopDate).format('YYYY-MM-DD') : '',
                            updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : ""
                        }]
                    }
                    $http.post("urlS", this, {
                        code: "03030045",
                        data: data,
                        success: function (res) {
                            if (res.errorCode == 0) {
                                if (params && params.ID) {
                                    message.success("修改成功")
                                    this.getTableData()
                                    this.closeModal(false)
                                } else {
                                    message.success("新增成功")
                                    this.getTableData()
                                    this.closeModal(false)
                                }
                            } else {
                                message.error('失败：' + res.errorMessage);
                            }

                        },
                        error: function (error) {
                            message.error('失败：' + error);
                        }
                    })

                } else {
                }
            })
        }
        render() {
            // 组件所需参数
            const param = {
                // 表格数据
                data: this.state.tableData,
                // 数据总条数
                total: this.state.total,
                // 当前页数
                page: this.state.page,
            }
            const { getFieldDecorator } = this.props.form
            const { params, columns } = this.state
            //医院
            let hosOp = []
            this.state.hospArr && this.state.hospArr.map((item) => {
                hosOp.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
            })
            return (
                <div>
                    <div className="department-header">
                        <Row style={{ minHeight: '64px', padding: '0 24px' }}>
                            <Col span={18}>
                                {this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenHospital ? this.setMessage('ExpressServiceTableDataMaintenHospital', 'descripts') : "医院："}<Select
                                    onChange={this.handleSelectChange}
                                    onSelect={this.handleStatus} style={{ width: '150px', margin: '23px 15px 0 12px' }} placeholder={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenPleaseSelectAHospital ? this.setMessage('ExpressServiceTableDataMaintenPleaseSelectAHospital', 'descripts') : "请选择医院-"}>
                                    {hosOp}
                                </Select>
                                {this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintencustNo ? this.setMessage('ExpressServiceTableDataMaintencustNo', 'descripts') : "月结卡号："}：
                                <Input placeholder={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenpleaseenter ? this.setMessage('ExpressServiceTableDataMaintenpleaseenter', 'descripts') : "请输入："} style={{ width: '150px', margin: '23px 15px 0 0' }} ref={Input => this.state.inputCustNo = Input} defaultValue="" />
                                {this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenclientCode ? this.setMessage('ExpressServiceTableDataMaintenclientCode', 'descripts') : "顾客编码"}：
                                <Input placeholder={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenpleaseenter ? this.setMessage('ExpressServiceTableDataMaintenpleaseenter', 'descripts') : "请输入："} style={{ width: '150px', margin: '23px 15px 0 0' }} ref={Input => this.state.inputClientCode = Input} defaultValue="" />
                                <Button onClick={() => this.getTableData()} style={{ margin: '23px 15px 20px 0', background: 'rgba(255,255,255,1)' }}>{this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenInquire ? this.setMessage('ExpressServiceTableDataMaintenInquire', 'descripts') : "查询："}</Button>
                            </Col>
                            <Col span={6} style={{ textAlign: 'right' }}>
                                <Button icon="plus" onClick={() => this.handleCompile()} style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '23px 15px 0 0' }}>{this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenAdd ? this.setMessage('ExpressServiceTableDataMaintenAdd', 'descripts') : "新增："}</Button>
                            </Col>
                        </Row>
                    </div>
                    <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
                    <div style={{ padding: 24 }} className="table-body-height">
                        <Table
                            columns={columns}
                            dataSource={param.data}
                            pagination={false}
                            bordered
                            style={{ height: store.getState().tableHeight.y + 68 + 'px', overflow: "auto" }}
                        />
                        <CommonPagination size={this.state.size} page={this.state.page} current={this.state.page} total={this.state.total} search={this.state.search}
                            onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={param.data}
                            onChange={this.onChange.bind(this)} />
                        <ColumnAuthoritysModel
                            clientWidth='800px'
                            compontName='ExpressServiceTableDataMainten'
                            configType="C"
                            onRef={this.onColumnRef}
                            reloadData={this.getMainTableColumns}
                        />
                        <Modal
                            title={this.state.num == "1" ? "编辑治快递服务" : "新增快递服务"}
                            visible={this.state.visible}
                            onOk={() => this.closeModal(false)}
                            onCancel={() => this.closeModal(false)}
                            width={1200}
                            footer={[
                                <Button key="submit" type="primary" loading={this.setState.loading} disabled={this.state.rowId == ""} onClick={this.save}>{this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintendetermine ? this.setMessage('ExpressServiceTableDataMaintendetermine', 'descripts') : "确定："}</Button>,
                                <Button key="cancel" type="primary" loading={this.setState.loading} onClick={() => this.closeModal(false)}>{this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintencancel ? this.setMessage('ExpressServiceTableDataMaintencancel', 'descripts') : "取消："}</Button>,
                            ]}
                        >
                            <div className="department-header">
                                <Form>
                                    <Row gutter={60} style={{ margin: '0' }}>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem {...formItemLayout} label={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintencode ? this.setMessage('ExpressServiceTableDataMaintencode', 'descripts') : "代码:"}>
                                                {getFieldDecorator('code', {
                                                    initialValue: params && params.code ? params.code : undefined,
                                                    rules: [{ required: true, message: '请填写代码' }],
                                                })(
                                                    <Input></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem {...formItemLayout} label={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintendesc ? this.setMessage('ExpressServiceTableDataMaintendesc', 'descripts') : "描述:"}>
                                                {getFieldDecorator('descripts', {
                                                    initialValue: params && params.desc ? params.desc : undefined,
                                                    rules: [{ required: true, message: '请填写描述' }],
                                                })(
                                                    <Input></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem {...formItemLayout} label={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintencustNo ? this.setMessage('ExpressServiceTableDataMaintencustNo', 'descripts') : "月结卡号:"}>
                                                {getFieldDecorator('custNo', {
                                                    initialValue: params && params.custNo ? params.custNo : undefined,
                                                    rules: [{ required: true, message: '请填写月结卡号' }],
                                                })(
                                                    <Input></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem {...formItemLayout} label={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenclientCode ? this.setMessage('ExpressServiceTableDataMaintenclientCode', 'descripts') : "顾客编码:"}>
                                                {getFieldDecorator('clientCode', {
                                                    initialValue: params && params.clientCode ? params.clientCode : undefined,
                                                    rules: [{ required: true, message: '请填写顾客编码' }],
                                                })(
                                                    <Input></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem label={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenstartDate ? this.setMessage('ExpressServiceTableDataMaintenstartDate', 'descripts') : "开始日期:"} {...formItemLayout}>
                                                {getFieldDecorator('startDate', {
                                                    initialValue: params && params.startDate ? moment(params.startDate, "YYYY-MM-DD") : moment(),
                                                    rules: [{ required: true, message: '请选择生效日期' }],
                                                })(
                                                    <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                                                        return curDate && curDate > moment().endOf('day');
                                                    }} />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem label={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenstopDate ? this.setMessage('ExpressServiceTableDataMaintenstopDate', 'descripts') : "结束日期:"} {...formItemLayout}>
                                                {getFieldDecorator('stopDate', {
                                                    initialValue: params && params.stopDate ? moment(params.stopDate, "YYYY-MM-DD") : undefined,
                                                    
                                                })(
                                                    <DatePicker style={{ width: '100%' }} />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem label={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintencheckWord ? this.setMessage('ExpressServiceTableDataMaintencheckWord', 'descripts') : "效验码:"} {...formItemLayout}>
                                                {getFieldDecorator('checkWord', {
                                                    initialValue: params && params.checkWord ? params.checkWord : undefined,
                                                    rules: [{ required: true, message: '请填写效验码' }],
                                                })(
                                                    <Input></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem label={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMainteneContact ? this.setMessage('ExpressServiceTableDataMainteneContact', 'descripts') : "联系人:"} {...formItemLayout}>
                                                {getFieldDecorator('eContact', {
                                                    initialValue: params && params.eContact ? params.eContact : undefined,
                                                    rules: [{ required: true, message: '请填写联系人' }],
                                                })(
                                                    <Input></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem label={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMainteneContactPhone ? this.setMessage('ExpressServiceTableDataMainteneContactPhone', 'descripts') : "联系电话:"} {...formItemLayout}>
                                                {getFieldDecorator('eContactPhone', {
                                                    initialValue: params && params.eContactPhone ? params.eContactPhone : undefined,
                                                    rules: [{ required: true, message: '请填写联系电话' }],
                                                })(
                                                    <Input></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem {...formItemLayout} label={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMainteneContactMobile ? this.setMessage('ExpressServiceTableDataMainteneContactMobile', 'descripts') : "联系手机:"}>
                                                {getFieldDecorator('eContactMobile', {
                                                    initialValue: params && params.eContactMobile ? params.eContactMobile : undefined,
                                                    rules: [{ required: true, message: '请填写联系手机' },{pattern: new RegExp(/^[1-9]\d*$/, "g"),message: '请输入正确内容'},{pattern: new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/, "g"),message: '请输入正确的手机号'}],
                                                })(
                                                    <Input></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <Form.Item  {...formItemLayout} label={this.state.localeProvider && this.state.localeProvider.ExpressServiceTableDataMaintenHospital ? this.setMessage('ExpressServiceTableDataMaintenHospital', 'descripts') : "医院:"}>
                                                {getFieldDecorator('hospID', {
                                                    initialValue: params && params.hospID ? params.hospID : undefined,
                                                    rules: [{ required: true, message: '请选择医院' }],
                                                })(
                                                    <Select
                                                        placeholder="请选择"
                                                        onSelect={this.handleStatus}
                                                    >
                                                        {hosOp}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </Form>

                            </div>
                        </Modal>
                    </div>
                </div>
            );
        }
    }
)
export default DeliveryService;