/*
 * Creator:     ML
 * CreatDate:   2020-04-03
 * descripts：  用户CA信息同步
*/
import React from 'react';
import { Form, Row, Col, Input, Select, Button, Table, Icon, message, } from 'antd';
import { $http } from '../../containers/config/https';
import store from '../../store';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';

const paddRightCol = {
    paddingRight: "0px"
}
const formItemLayoutType = {
    labelCol: { span: 7 },
    wrapperCol: { span: 16 }
}
const FormItem = Form.Item;
const Option = Select.Option;

const formItemLayout = { // label 和input宽度
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
}


const UserCAInformationSynchronization = Form.create()(
    class UserCAInformationSynchronization extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                loading: false,
                visible: false,
                total: 0,//表格总数据
                orderPatData: [],//查询出来的预约数据
                values: {},//查询条件数据
                searchLoading: false,//查询请求
                rowIds: '',//表格行选中 页面数据
                locId: "",//科室Id
                localArr: [],//loc下拉框数据
                columns: [],//表头
                widthTotal: 0,//
                size: "big",
                language: JSON.parse(window.sessionStorage.userData),
                selectedRowKeys_rightFry: [],
                page:1

            }
        }
        componentDidMount() {
            let self = this
            // 初始化设置table的高度以及表体的高度
            if (document.querySelector('.ant-table-body')) {
                document.querySelector('.ant-table-body').style.maxHeight = store.getState().tableHeight.y + 97 + 'px';
                document.querySelector('.ant-table-body').style.minHeight = store.getState().tableHeight.y + 97 + 'px';
                document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 97 + 'px';
            }
            this.getMainTableColumns()
            this.getHopSelect()
            if (this.state.size == "small") {
                this.setState({
                    pageSize: 10
                },()=>{
                    this.getFindDate()
                })
            } else {
                this.setState({
                    pageSize: 50
                },()=>{
                    this.getFindDate()
                })
            }
           
        }
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }
        // 获取主列表columns
        getMainTableColumns = () => {
            let { language } = this.state;
            let data = {
                params: [{
                    compontName: "CertAuthority", // 
                    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()}>{item.title}</div>,
                                display: item.display,
                                key: item.seqNo,
                                render: (text, record) => {
                                    if (item.code == "userStamp") {
                                        if (record.userStamp) {
                                            return (
                                                <img style={{ width: "100%" }} src={record.userStamp}></img>
                                            )
                                        } else {
                                            return (
                                                <span></span>
                                            )
                                        }

                                    }
                                    return text
                                }
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        let seqArr = {
                            align: "center",
                            widthNum: 140,
                            width: "50px",
                            code: "edit",
                            dataIndex: "edit",
                            title: "操作",
                            display: "Y",
                            render: (value, row, index) => {
                                return (
                                    <span>
                                        <span style={{ color: "blue", cursor: "pointer" }} onClick={() => this.handleSyncItem(row)}>同步</span>
                                    </span>
                                )
                            },
                        }
                        filterArr.push(seqArr)
                        this.setState({ columns: filterArr, widthTotal: res.totalWidth })
                    }
                }
            })
        }
        //获取医院下拉框
        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
                        })
                    }
                }
            })
        }

        //获取科室下拉框
        getPublicBaseLocSelect = () => {
            let data = {}
            data = {
                params: [{
                    hospID: this.state.hosID || "",
                }],
            }
            $http.post('urlS', this, {
                code: '01050029',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result.Data) {
                        let arr = res.result.Data && res.result.Data.map((item, index) => {
                            res.result.Data[index].key = Number(index)
                        })
                        this.setState({
                            publicLocArr: res.result.Data,
                        })
                    } else {

                    }
                }
            })
        }
        //医院
        handleBaseHosp = (id) => {
            this.props.form.setFieldsValue({ getOpenLoc: undefined })
            if (id) {
                this.setState({
                    hosID: id
                }, () => {
                    this.getPublicBaseLocSelect()
                })
            } else {
                this.setState({
                    hosID: "",
                    publicBaseLocArr: []
                }, () => {
                    this.getPublicBaseLocSelect()
                })
            }

        }

        // 修改page和pageSize 跳转至---
        onChange = (e) => {
            this.setState({ page: e, pageSize: this.state.pageSize }, () => {
                // 重新调用查询方法
                let { values } = this.state;
                this.getFindDate(values);
            })
        }
        //下拉选择页数
        onShowSizeChange = (page, pageSize) => {
            this.setState({ page: 1, pageSize: pageSize }, () => {
                // 重新调用查询方法
                let { values } = this.state;
                this.getFindDate(values, "search");
            })
        }
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }

        //获取查询数据
        getFindDate = (values, e) => {
            let { page, pageSize, } = this.state;
            if (this.state.total == 0) {
                this.setState({
                    searchLoading: true
                })
            }
            let data = {}
            data = {
                params: [{
                    hospID: values && values.getHop || "",
                    locID: values && values.getOpenLoc || "",
                    userCode: values && values.patInfo || "",
                    userName: values && values.userName || "",

                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                }]
            }
            $http.post('urlS', this, {
                code: '08010006',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            searchLoading: false,
                            rowId: "",
                            search: e
                        })
                        this.setState({
                            orderPatData: res.result.data, total: res.result.totalCount,
                        }, () => {
                        })
                    } else {
                        this.setState({
                            searchLoading: false
                        })
                    }
                },
                error: function () {
                    this.setState({
                        searchLoading: false
                    })
                }
            })
        }
        //点击查询
        findData = () => {
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    this.setState({
                        values: values,
                        rowIds: "",
                        selectedRowKeys_rightFry: []
                    })
                    this.setState({ page: 1, pageSize: this.state.pageSize }, () => {
                        let { values } = this.state;
                        this.onShowSizeChange("1", this.state.pageSize)
                    })
                }
            })
        }
        //同步单个
        handleSyncItem = (row) => {
            this.setState({
                selectedRowKeys_rightFry: []
            })
            let arr = []
            arr.push(row.certAuthorityID)
            this.handleSync(arr)
        }
        //同步 选中
        handleSync = (arr) => {
            let data = {}
            data = {
                params: [{
                    certAuthorityIDs: arr || "",
                }],
            }
            $http.post('urlS', this, {
                code: '08010007',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success("同步成功")
                        this.setState({
                            selectedRowKeys_rightFry: []
                        })
                        this.findData()
                    } else {
                        // message.warning("同步失败")
                        this.setState({
                            selectedRowKeys_rightFry: []
                        })
                    }
                }
            })
        }
        render() {
            const { getFieldDecorator } = this.props.form;
            const { searchLoading, widthTotal, columns, } = this.state;
            //医院
            let BaseHosOp = []
            this.state.hospArr && this.state.hospArr.map(item => {
                BaseHosOp.push(<Option key={item.id} onClick={() => this.handleBaseHosp(item.id)} value={String(item.id)}>{item.descripts}</Option>)
            })
            //接收科室
            let openLocOp = []
            this.state.publicLocArr && this.state.publicLocArr.map(item => {
                openLocOp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
            })
            const rowSelection_rightFry = {
                selectedRowKeys: this.state.selectedRowKeys_rightFry,
                onChange: (selectedRowKeys, selectedRows) => {
                    let selectrow = "";
                    if (selectedRowKeys.length === 0) {
                    } else {
                        selectrow = selectedRowKeys[selectedRowKeys.length - 1];
                    }
                    let arr = []
                    selectedRows.map((item, i) => {
                        arr.push(item.id)
                    })
                    this.setState({ selectedRowIds_Fry: arr, selectrow: selectrow, selectedRow_right: selectedRows, selectedRowKeys_rightFry: selectedRowKeys }, () => {
                    });
                },
                // getCheckboxProps: record => ({
                //   disabled: record.reportID === '', // Column configuration not to be checked
                // }),
                onSelectAll: (selected, selectedRows, changeRows) => {
                    let arr = []
                    selectedRows.map((item, i) => {
                        arr.push(item.id)
                    })
                    this.setState({ selectedRowIds_Fry: arr, selectedRow_right: selectedRows });
                }
            };
            return (
                <div style={{ padding: '4px 2px' }} className="patientAppDom">
                    <Form>
                        <Row gutter={60} style={{ margin: '0' }}>
                            <Col span={4} style={paddRightCol}>
                                <FormItem label='用户工号' {...formItemLayoutType}>
                                    {getFieldDecorator('patInfo', {
                                        initialValue: undefined,
                                        rules: [{ required: false, message: '' }]
                                    })(
                                        <Input
                                            allowClear
                                            onPressEnter={this.findData}
                                            style={{ width: '100%' }}
                                        />
                                    )}
                                </FormItem>
                            </Col >
                            <Col span={4} style={paddRightCol}>
                                <FormItem label='用户姓名' {...formItemLayoutType}>
                                    {getFieldDecorator('userName', {
                                        initialValue: undefined,
                                        rules: [{ required: false, message: '' }]
                                    })(
                                        <Input
                                            allowClear
                                            onPressEnter={this.findData}
                                            style={{ width: '100%' }}
                                        />
                                    )}
                                </FormItem>
                            </Col >
                            <Col span={4} style={paddRightCol}>
                                <FormItem {...formItemLayoutType} label='医院'>
                                    {getFieldDecorator('getHop', {
                                        initialValue: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID:undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Select
                                            onChange={this.handleBaseHosp}
                                        >
                                            {BaseHosOp}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>

                            <Col span={4} style={paddRightCol}>
                                <FormItem {...formItemLayoutType} label='科室'>
                                    {getFieldDecorator('getOpenLoc', {
                                        initialValue: undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Select
                                            allowClear
                                            showSearch={true}
                                            placeholder={"请先选择医院"}
                                            optionFilterProp="role"
                                        >
                                            {openLocOp}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={2} style={{ paddingLeft: "0" }}>
                                <FormItem  {...formItemLayout}>
                                    {getFieldDecorator('findData', {
                                        initialValue: undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <div style={{ display: "flex", marginTop: "4px" }}>
                                            <Button style={{ margin: "0 18px 0 10px" }} onClick={this.findData} loading={searchLoading} type="primary">查询</Button>
                                            <Button disabled={this.state.selectedRowKeys_rightFry && this.state.selectedRowKeys_rightFry.length == 0} onClick={() => this.handleSync(this.state.selectedRowKeys_rightFry)} type="primary">同步</Button>
                                        </div>
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                    <Table
                        scroll={{ x: (columns && columns.length > 0 ? widthTotal : 4000), y: store.getState().tableHeight.y - 32 }}
                        columns={columns && columns.length > 0 ? columns : []}
                        dataSource={this.state.orderPatData}
                        pagination={false}
                        rowKey={record => record.certAuthorityID}
                        onRow={this.onClickRow}
                        rowClassName={this.setRowClassNames}
                        bordered
                        rowSelection={rowSelection_rightFry}
                        style={{ height: store.getState().tableHeight.y + 146 + 'px', }}
                    />
                    <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total} search={this.state.search}
                        onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.orderPatData}
                        onChange={this.onChange.bind(this)} />
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='CertAuthority'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getMainTableColumns}
                    />
                </div>
            )
        }
    })
export default UserCAInformationSynchronization    