//合作协作医院
import React from 'react'
import { Table, Button, Select, Icon, Form, Divider, Row, Col, Card, DatePicker, Input, Popconfirm, message } from 'antd'
import { $http } from '../../containers/config/https';
import PubilcTablePagination from '../common/PubilcTablePagination.jsx'; // 公共table组件
import moment from 'moment'
const { Option } = Select;
import ContractUnitModal from './ContractUnitModal.jsx'
import store from '../../store';
import ColumnAuthoritysModel from '../../pages/columnAuthority/ColumnAuthoritysModel';



class ContractUnit extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            data: [],
            hospitalId: undefined,
            hospitalData: [],
            userInfo: {},
            // 表格数据
            tableData: [],
            showLoading: true,
            // 表格数据总条数
            total: 0,
            page: 1,
            pageSize: 10,
            tableList:[],
            columns: [],
            languageTable1: {}, // 国际化Table1
            languageTable2: {}, // 国际化Table2
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
            languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
        }
      
    }

    componentDidMount() {
        // this.child.handleLoading()
        ///初始化列表数据
        this.handleQuery()
        //初始化下拉框数据
        this.loadHospitalMsg()
        this.tableList("ContractUnit","ContractUnit");
    }
    //render 自定义项目名称
    listAdd = (i, j, languageCode) => {
        let { columns } = this.state
        columns.splice(i, j,
        {
            title: languageCode === 'CN' ? "操作" : 'Operation',
            key: 'op',
            align: "center",
            render: (text, record) => (
            <span>
                <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                <span className='span' onClick={this.handleCompile.bind(this, record)}>{languageCode === 'CN' ? "编辑" : 'Edit'}</span>
            </span>
            ),
        },
        )
    }
    onColumnRef = (ref) => {
        console.log(ref)
        this.columnRef = ref;
    }
    // 获取主列表columns
    tableList = (reactCode, compontName) => {
        var data = {
        params: [{
            "reactCode": [reactCode],
            "compontName": compontName,
            "type": "C"
        }]
    }
        console.log(1, data)
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let resC = res.result.C
                    let { languageCode } = this.state
                    for (var i = 0; i < resC.length; i++) {
                        resC[i].key = i;
                    }
                    if (languageCode === "EN") {
                        resC.map((item, i) => {
                            item.title = item.enDescripts
                        })
                    }
                
                    if (languageCode === "CN") {
                        resC.map((item, i) => {
                            item.title = item.descripts
                        })
                    }
                    let arr = res.result && resC.length > 0 ? JSON.parse(JSON.stringify(resC)).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
                        }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    this.setState({ 
                    columns: filterArr,
                    languageTable1: res.result.B || {},  // 国际化Table1
                    languageTable2: res.result.C || {},  // 国际化Table2
                    languageData: res.result.language || {},  // 国际化语言包
                    }, () => {
                    this.LanCNEN(this.state.languageCode)
                    this.listAdd(filterArr.length+1, 0,languageCode);
                    })
                }
            }
        })
    }

    LanCNEN = (code) => {
        let { languageData } = this.state
        this.setState({
            language: languageData[code]
        })
    }


    //医院下拉框
    onChangeHospitalDr = (e) => {
        this.setState({
            hospitalId: e
        }, () => {
            //刷新列表数据
            this.handleQuery()
        })
    }

    //列表数据
    handleQuery = () => {
        let { page, pageSize } = this.state;
        let data = {}
        data = {
            params: [{
                hospID: this.state.hospitalId ? this.state.hospitalId : JSON.parse(window.sessionStorage.userData).hospID
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        }
        $http.post('urls', this, {
            code: '05100083',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    for (var i = 0; i < res.result.length; i++) {
                        res.result[i].key = i;
                    }
                    this.setState({ tableData: res.result.Data, total: res.result.TotalCount, loading: false })
                } else {
                    this.setState({ tableData: [], total: 0, loading: false })
                }
            }
        })
    }

    //查询医院下拉
    loadHospitalMsg() {
        var data = {
            params: [{
                hospID: '', // 医院id
                logonGroupID: JSON.parse(window.sessionStorage.userData).groupID, 
                logonHospID: JSON.parse(window.sessionStorage.userData).userID, 
            }]
        }
        $http.post('urlS', this, {
            code: "01040001",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        hospitalData: res.depDoctor,
                    })
                    var result = res.depDoctor && res.depDoctor.some(item => {
                        if (item.id === JSON.parse(window.sessionStorage.userData).hospID) {
                            return true
                        }
                    })
                    if (!result) {
                        this.setState({
                            hospitalId: undefined
                        })
                    } else {
                        this.setState({ hospitalId: JSON.parse(window.sessionStorage.userData).hospID ? JSON.parse(window.sessionStorage.userData).hospID : undefined })
                    }
                }
            }
        });
    }

    //保存
    handleSubmit = (e) => {
        let { validateFields } = this.props.form;
        var Code = '05100084';
        validateFields({ force: true }, (err, params) => {
            if (err) {
                return;
            }
            let data = {}
            let obj = params;
            obj.createUserDr = JSON.parse(window.sessionStorage.userData).groupID
            obj.userID=JSON.parse(window.sessionStorage.userData).userID
            data = {
                params: [params]
            };
            $http.post('urlDeanlt', this, {
                code: Code,
                data: data,
                success: function (res) {
                    if (res.errorCode === '0') {
                        message.success('保存成功！')
                        //重置表单
                        this.props.form.resetFields();
                        //刷新列表数据
                        this.handleQuery()
                    }
                }
            })
        })
    }
    // 编辑
    handleCompile(record) {
        // 初始化数据
        this.setState({ flag: 'compile', userInfo: record }, () => {
            // 打开弹框
            this.modalChild.showModal(this.state.flag, record);
        });
    }

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

    //调用子组件的连接时间
    onModalRef = (ref) => {
        this.modalChild = ref
    }

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

    render() {
        let {hospID,code,descripts, address,telephone, socialCode,
            legalPerson,startDate, stopDate,handleSubmit,language} = this.state
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.columns,
            // 表格数据
            data: this.state.tableData,
            // 数据总条数
            total: this.state.total,
            // 数据页数
            page: this.state.page,
        }
        let { getFieldDecorator } = this.props.form;
        return (
            <div>
                <Card>
                    <Form layout="inline" hideRequiredMark={true}>
                        <Row>
                            <Col style={{ marginBottom: '10px' }}>
                                <Form.Item label={language.ContractUnithospID && language.ContractUnithospID.descripts}>
                                    {getFieldDecorator("hospID", {
                                        initialValue: this.state.hospitalId
                                    })(
                                        <Select showSearch optionFilterProp="title" onChange={(even) => { this.onChangeHospitalDr(even) }} style={{ width: '150px' }} placeholder={language.ContractUnithospID && language.ContractUnithospID.message}>
                                            {this.state.hospitalData && this.state.hospitalData.map(item => {
                                                return <Option key={item.id} value={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                            })}
                                        </Select>
                                    )}
                                </Form.Item>
                                <Form.Item label={language.ContractUnitcode && language.ContractUnitcode.descripts}>
                                    {getFieldDecorator("code", {
                                        rules: [{ required: false }]
                                    })(
                                        <Input style={{ width: '150px' }} placeholder={language.ContractUnitcode && language.ContractUnitcode.message} />
                                    )}
                                </Form.Item>
                                <Form.Item label={language.ContractUnitdescripts && language.ContractUnitdescripts.descripts}>
                                    {getFieldDecorator("descripts", {
                                        rules: [{ required: false }]
                                    })(
                                        <Input style={{ width: '150px' }} placeholder={language.ContractUnitdescripts && language.ContractUnitdescripts.message} />
                                    )}
                                </Form.Item>
                            </Col>
                            <Col style={{ marginBottom: '10px' }}>
                                <Form.Item label={language.ContractUnitaddress && language.ContractUnitaddress.descripts}>
                                    {getFieldDecorator("address", {
                                        rules: [{ required: false }]
                                    })(
                                        <Input style={{ width: '150px' }} />
                                    )}
                                </Form.Item>
                                <Form.Item label={language.ContractUnittelephone && language.ContractUnittelephone.descripts}>
                                    {getFieldDecorator("telephone", {
                                        rules: [{ required: false }, { pattern: /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/, message: language.ContractUnittelephone && language.ContractUnittelephone.message }]
                                    })(
                                        <Input style={{ width: '150px' }} />
                                    )}
                                </Form.Item>
                                <Form.Item label={language.ContractUnitsocialCode && language.ContractUnitsocialCode.descripts}>
                                    {getFieldDecorator("socialCode", {
                                        rules: [{ required: false }]
                                    })(
                                        <Input style={{ width: '150px' }} />
                                    )}
                                </Form.Item>
                            </Col>
                            <Col>
                                <Form.Item label={language.ContractUnitlegalPerson && language.ContractUnitlegalPerson.descripts}>
                                    {getFieldDecorator("legalPerson", {
                                        rules: [{ required: false }]
                                    })(
                                        <Input style={{ width: '150px' }} />
                                    )}
                                </Form.Item>
                                <Form.Item label={language.ContractUnitstartDate && language.ContractUnitstartDate.descripts}>
                                    {getFieldDecorator("startDate", {
                                        rules: [{ required: true }], initialValue: moment(new Date)
                                    })(
                                        <DatePicker style={{ width: '150px' }} />
                                    )}
                                </Form.Item>
                                <Form.Item label={language.ContractUnitstopDate && language.ContractUnitstopDate.descripts}>
                                    {getFieldDecorator("stopDate", {
                                        rules: [{ required: false }]
                                    })(
                                        <DatePicker style={{ width: '210px' }} />
                                    )}
                                </Form.Item>
                                <Form.Item>
                                    <Button type="primary" onClick={this.handleSubmit} style={{ background: 'rgba(247,128,93,1)', color: '#fff' }}>{language.ContractUnithandleSubmit && language.ContractUnithandleSubmit.descripts}</Button>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Card>
                <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
                <Card>
                    {/* handelThis将父组件的属性与方法给子组件访问 */}
                    <Table
                        style={{ height: store.getState().tableHeight.y + 65 + 'px' }}
                        dataSource={this.state.tableData}
                        columns={this.state.columns}
                        className='TableA'
                        //rowClassName="editable-row"
                        pagination={false}
                        scroll={{ x: 900, y: store.getState().tableHeight.y }}
                        bordered
                        loading={this.state.loading}
                        />

                    <ColumnAuthoritysModel
                        clientWidth='900px'
                        compontName='FindpatientsInfo'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.tableList}
                    />
                    
                </Card>
                <ContractUnitModal
                    onRef={this.onModalRef}
                    hospitalId={this.state.hospitalId}
                    handelThis={this}
                />
            </div>
        )
    }
}


export default Form.create()(ContractUnit)