// 接口服务配置
import React from 'react';
import { Select, Input, Row, Col, Button, Spin, message, Icon, Form, Modal, Card, Switch, DatePicker } from 'antd';
import { $http } from '../../containers/config/https';
import PubilcTablePagination from '../common/PubilcTablePagination.jsx';
import store from 'store';
import moment from 'moment';
import '../../assets/css/system.css';

const { Option } = Select;
const FormItem = Form.Item;

const formItemLayout = {
    labelCol: { span: 10 },
    wrapperCol: { span: 14 },
}

const InterfaceServiceConfigDetail = Form.create()(
    class InterfaceServiceConfigDetail extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                data: [],
                values: {},
                productCat: [],     // 产品分类          
                serviceType: [],    // 服务类型           
                productModule: [],  // 产品模块
                rwServiceType: []   // 读写服务类型
            }
        }

        componentDidMount() {
            this.getSelectData();
        }

        //获取下拉框数据
        getSelectData() {
            let data = {
                params: [{}]
            }
            $http.post('urlS', this, {
                code: "01040119",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            serviceType: res.result.serviceType,
                            productCat: res.result.productCat,
                            rwServiceType: res.result.rwServiceType,
                            productModule: res.result.productModule,
                            productModuleData: res.result.productModule,
                        })
                    }
                }
            })
        }

        setRowClassName = (record) => {
            return record.hospID === this.state.rowId ? 'clickRowStyle' : '';
        }

        FindData = () => {
            const { propMethod: { findData } } = this.props;
            this.showModal(false);
            findData();
            this.reset();
        }

        handleStatus = (v) => {
        }

        save = () => {
            this.props.form.validateFields((err, values) => {
                const { data: params } = this.props;
                if (!err) {
                    let data = {
                        params: [{
                            id: params && params.id ? params.id : "",
                            code: values.code || "",
                            descripts: values.descripts || "",
                            className: values.className || "",
                            methodName: values.methodName || "",
                            serviceType: values.serviceType || "",
                            productCatID: values.productCatID || "",
                            productModuleID: values.productModuleID || "",
                            seqNo: values.seqNo || "",
                            sessionFlag: values.sessionFlag ? 'Y' : 'N',
                            tokenFlag: values.tokenFlag ? 'Y' : 'N',
                            tokenOverTime: values.tokenOverTime || "",
                            rwServiceTypeID: values.rwServiceTypeID || "",
                            startDate: values.startDate ? moment(values.startDate).format('YYYY-MM-DD') : '',
                            stopDate: values.stopDate ? moment(values.stopDate).format('YYYY-MM-DD') : ''
                        }]
                    }
                    $http.post("urlS", this, {
                        code: "01040123",
                        data: data,
                        success: function (res) {
                            if (+res.errorCode === 0) {
                                if (params && params.id) {
                                    message.success("修改成功")
                                    this.FindData();
                                } else {
                                    message.success("新增成功")
                                    this.FindData();
                                }
                            } else {
                                message.error('失败：' + res.errorMessage);
                            }
                        },
                        error: function (error) {
                            message.error('失败：' + error);
                        }
                    })
                } else {
                }
            })
        }

        reset = () => {
            this.props.form.resetFields();
        }

        resetProductModule = (val, opt) => {
            let productModule = [];
            if (val != undefined) {
                productModule = this.state.productModuleData.filter((item) => item.productCatID == val)
            } else {
                productModule = this.state.productModuleData
            }
            this.props.form.setFieldsValue({ productModuleID: '' }, () => this.setState({ productModule }))
        }

        showModal = (bool) => {
            const { propMethod: { showModal } } = this.props;
            showModal(bool);
            this.reset();
        }

        render() {
            const { modalVisible, data: params } = this.props;
            const { getFieldDecorator } = this.props.form;
            const { productCat, serviceType, productModule, rwServiceType } = this.state;

            return (
                <Modal onCancel={() => this.showModal(false)} title={<span>{params ? params.hospDesc : ''}</span>} visible={modalVisible} width={1200} footer={<div style={{ display: "flex", justifyContent: "flex-end" }}>
                    <Button style={{ marginRight: '30px' }} onClick={() => this.showModal(false)}>取消</Button>
                    <Button style={{ marginRight: '30px' }} type="primary" onClick={this.save}>{params && params ? "更新" : "新增"}</Button>
                    <Button type="primary" onClick={this.reset}>重置</Button>
                </div>} >
                    <Row style={{ margin: "0" }}>
                        <Col span={24} style={{ paddingLeft: "0px" }}>
                            <Card>
                                <Form style={{ height: "100%", overflow: "hidden auto" }}>
                                    <Row>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label='代码'>
                                                {getFieldDecorator('code', {
                                                    initialValue: params && params.code ? params.code : undefined,
                                                    rules: [{ required: true, message: '请输入代码', },
                                                    ],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label='描述'>
                                                {getFieldDecorator('descripts', {
                                                    initialValue: params && params.descripts ? params.descripts : undefined,
                                                    rules: [{ required: true, message: '请输入描述' }],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label='类名'>
                                                {getFieldDecorator('className', {
                                                    initialValue: params && params.className ? params.className : undefined,
                                                    rules: [{ required: true, message: '请输入类名' }],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label='方法名'>
                                                {getFieldDecorator('methodName', {
                                                    initialValue: params && params.methodName ? params.methodName : undefined,
                                                    rules: [{ required: true, message: '请输入方法名' }],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label='服务类型'>
                                                {getFieldDecorator('serviceType', {
                                                    initialValue: params && params.serviceType ? String(params.serviceType) : undefined,
                                                    rules: [{ required: true, message: '请选择服务类型', },
                                                    ],
                                                })(
                                                    <Select placeholder="请输入首拼/汉字进行检索" showSearch allowClear optionFilterProp="role" >
                                                        {
                                                            serviceType && serviceType.map(item => {
                                                                return <Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>
                                                            })
                                                        }
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label='产品分类'>
                                                {getFieldDecorator('productCatID', {
                                                    initialValue: params && params.productCatID ? String(params.productCatID) : undefined,
                                                    rules: [{ required: true, message: '请选择产品分类', },
                                                    ],
                                                })(
                                                    <Select placeholder="请输入首拼/汉字进行检索" onChange={this.resetProductModule} showSearch allowClear optionFilterProp="role" >
                                                        {productCat && productCat.map(item => {
                                                            return <Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label='产品模块'>
                                                {getFieldDecorator('productModuleID', {
                                                    initialValue: params && params.productModuleID ? String(params.productModuleID) : undefined,
                                                    rules: [{ required: true, message: '请选择产品模块', },
                                                    ],
                                                })(
                                                    <Select placeholder="请输入首拼/汉字进行检索" showSearch allowClear optionFilterProp="role" >
                                                        {productModule.map(item => {
                                                            return <Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label='读写服务类型'>
                                                {getFieldDecorator('rwServiceTypeID', {
                                                    initialValue: params && params.rwServiceTypeID ? String(params.rwServiceTypeID) : undefined,
                                                    rules: [{ message: '请选择读写服务类型', },
                                                    ],
                                                })(
                                                    <Select placeholder="请输入首拼/汉字进行检索" showSearch allowClear optionFilterProp="role" >
                                                        {rwServiceType && rwServiceType.map(item => {
                                                            return <Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={6} >
                                            <FormItem {...formItemLayout} label='序号'>
                                                {getFieldDecorator('seqNo', {
                                                    initialValue: params && params.seqNo ? params.seqNo : undefined,
                                                    rules: [{ message: '', },
                                                    ],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6} >
                                            <FormItem label='生效日期' {...formItemLayout}>
                                                {getFieldDecorator('startDate', {
                                                    initialValue: params && params.startDate ? moment(params.startDate, "YYYY-MM-DD") : moment(),
                                                    rules: [{ required: true, message: '请选择开始日期' }],
                                                })(
                                                    <DatePicker style={{ width: '100%' }} placeholder={'开始日期'} />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6} >
                                            <FormItem label='失效日期' {...formItemLayout}>
                                                {getFieldDecorator('stopDate', {
                                                    initialValue: params && params.stopDate ? moment(params.stopDate, "YYYY-MM-DD") : undefined,
                                                })(
                                                    <DatePicker style={{ width: '100%' }} />
                                                )}
                                            </FormItem>
                                        </Col >
                                        <Col span={6} >
                                            <FormItem {...formItemLayout} label='超时时长'>
                                                {getFieldDecorator('tokenOverTime', {
                                                    initialValue: params && params.tokenOverTime ? params.tokenOverTime : undefined,
                                                    rules: [{ message: '请选择超时时长' }],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={6} >
                                            <FormItem {...formItemLayout} label='是否验证session'>
                                                {getFieldDecorator('sessionFlag', {
                                                    initialValue: params && params.sessionFlag == 'Y' ? true : false,
                                                    valuePropName: 'checked',
                                                    rules: [{ required: true, message: '', }],
                                                })(
                                                    <Switch checkedChildren="是" unCheckedChildren="否" />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6} >
                                            <FormItem {...formItemLayout} label='是否验证token'>
                                                {getFieldDecorator('tokenFlag', {
                                                    initialValue: params && params.tokenFlag == 'Y' ? true : false,
                                                    valuePropName: 'checked',
                                                    rules: [{ required: true, message: '' }]
                                                })(
                                                    <Switch checkedChildren="是" unCheckedChildren="否" />
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </Form>
                            </Card>
                        </Col>
                    </Row>
                </Modal>
            );
        }
    });

class InterfaceServiceConfig extends React.Component {
    constructor() {
        super();
        this.state = {
            tableData: [],      // 表格数据          
            total: 0,           // 表格数据总条数
            column: [],         // 表头
            showLoading: true,
            page: 1,
            pageSize: 10,
            headerHeight: 0,
            modalVisible: false,
            editData: {}
        };
    }

    componentDidMount() {
        // 初始化列表数据
        this.handleQuery();
        this.getColumn();
        // 组件加载完毕关闭loading
        this.setState({ showLoading: false });
    }

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

    // 获取表头信息
    getColumn = () => {
        let data = {
            params: [{
                compontName: "InterfaceServiceConfig",
                type: "C",
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    let column = 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: item.title,
                            display: item.display,
                            key: item.seqNo
                        }
                    }) : '';
                    let obj = {
                        title: '操作',
                        key: column.length + 1,
                        align: "center",
                        width: 50,
                        render: (text, record) => (
                            <span>
                                <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                                <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
                            </span>
                        )
                    }
                    column.push(obj);
                    this.setState({ column })
                }
            }
        })
    }

    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }

    // 提供修改page和pageSize的回调函数
    compilePage(page, pageSize) {
        // 修改page，或者pageSize
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            let { status, name, quarters } = this.state;
            this.getTableData(name, status, quarters);
        })
    }

    // 请求列表数据
    getTableData() {
        let { page, pageSize } = this.state;
        let data = {};
        this.props.form.validateFields((error, values) => {
            if (error) {
                return;
            }
            data = {
                params: [{
                    code: values.code ? values.code : '',
                    descripts: values.descripts ? values.descripts : '',
                    className: values.className ? values.className : '',
                    methodName: values.methodName ? values.methodName : '',
                    status: values.status ? values.status : '',
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                    sortColumn: "",
                    sortOrder: ""
                }]
            };
            $http.post('urlS', this, {
                code: "01040124",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result) {
                        this.setState({ tableData: res.result.Data, total: res.result.TotalCount }, () => {
                            // 数据加载成功关闭loading
                            this.child.handleLoading()
                        })
                    } else {
                        this.setState({ tableData: [], total: 0 }, () => {
                            // 数据加载成功关闭loading
                            this.child.handleLoading();
                        })
                    }
                },
                error: function () {
                    this.setState({ tableData: [], total: 0 }, () => {
                        // 数据加载成功关闭loading
                        this.child.handleLoading();
                    })
                }
            });
        });
    }

    // 查询
    handleQuery = () => {
        this.setState({ page: 1, pageSize: 10 }, () => {
            this.getTableData();
        })
    }

    // 新增跳转到新增界面
    handleAdd = () => {
        this.setState({ editData: undefined });
        this.showModal(true);
    }

    // 编辑
    handleCompile = (record) => {
        this.setState({ editData: record });
        this.showModal(true);
    }

    //控制模态框显示
    showModal = (bool) => {
        this.setState({ modalVisible: bool });
    }

    // 获取主列表columns
    getMainTableColumns = () => {
        let data = {
            params: [{
                compontName: 'InterfaceServiceConfig', // 接口服务
                type: 'C',
            }]
        }
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.state.column,
            // 表格数据
            data: this.state.tableData,
            // 数据总条数
            total: this.state.total,
            // 当前页数
            page: this.state.page,
            // 表格的宽度
            x: '100%',
            componentName: 'InterfaceServiceConfig',
            y: store.getState().tableHeight.y + 12,
            height: store.getState().tableHeight.y + 62 + 'px',
        }
        const statusArr = [
            {
                id: '',
                descripts: '全部',
                descriptsSPCode: 'QB',
            }, {
                id: '1',
                descripts: '可用',
                descriptsSPCode: 'KY',
            }, {
                id: '0',
                descripts: '不可用',
                descriptsSPCode: 'BKY',
            },];
        let statusoP = []
        statusArr && statusArr.map(item => {
            statusoP.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
        });
        return (
            <Spin tip="加载中..." spinning={this.state.showLoading}>
                <div>
                    <Form>
                        <Row style={{ margin: '23px 0 0 0' }}>
                            <Col span={4} >
                                <FormItem {...formItemLayout} label='接口代码'>
                                    {getFieldDecorator('code', {
                                        //initialValue: params && params.healBureauID ? String(params.healBureauID) : undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Input title="输入内容后可回车检索" placeholder="请输入( Enter )" onPressEnter={this.handleQuery} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={4} >
                                <FormItem {...formItemLayout} label='接口描述'>
                                    {getFieldDecorator('descripts', {
                                        //initialValue: undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Input title="输入内容后可回车检索" placeholder="请输入( Enter )" onPressEnter={this.handleQuery} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={4} >
                                <FormItem {...formItemLayout} label='类名'>
                                    {getFieldDecorator('className', {
                                        //initialValue: params && params.healBureauID ? String(params.healBureauID) : undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Input title="输入内容后可回车检索" placeholder="请输入( Enter )" onPressEnter={this.handleQuery} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={4} >
                                <FormItem {...formItemLayout} label='方法名'>
                                    {getFieldDecorator('methodName', {
                                        //initialValue: undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Input title="输入内容后可回车检索" placeholder="请输入( Enter )" onPressEnter={this.handleQuery} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={4} >
                                <FormItem {...formItemLayout} label='状态'>
                                    {getFieldDecorator('status', {
                                        //initialValue: undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Select
                                            style={{ width: '70%' }}
                                            onSelect={this.handleStatus}
                                        >
                                            {statusoP}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={2}>
                                <Button onClick={this.handleQuery} style={{ margin: '4px 15px 20px 0', background: 'rgba(255,255,255,1)' }}>查询</Button>
                            </Col>
                            <Col span={2}>
                                <Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '4px 0 0 0' }}>新增</Button>
                            </Col>
                        </Row>
                    </Form>
                </div>
                <div style={{ width: '100%', height: '10px', background: '#f0f2f5' }}></div>
                <div style={{ padding: '24px' }} className="table-body-height">
                    {/* handelThis将夫组件的属性与方法给子组件访问 */}
                    <PubilcTablePagination
                        param={param}
                        handelThis={this}
                        onRef={this.onRef}
                        getColumns={this.getColumn}
                    />
                </div>
                <InterfaceServiceConfigDetail data={this.state.editData} modalVisible={this.state.modalVisible} propMethod={{ showModal: this.showModal, findData: this.handleQuery }} />
            </Spin>
        )
    }
}
export default Form.create()(InterfaceServiceConfig);
