import React from 'react';
import { Card, Row, Col, Form, Table, Select, Input, Button, message,  Switch,  } from 'antd';
import CommonPagination from 'components/pagination/index';
import { $http } from 'containers/config/https';
import './style/index.less';
import store from 'store';
import Moment from 'moment';

const { Option } = Select;
const formItemInput = {    // label 和input宽度
    labelCol: { span:7 },
    wrapperCol: { span: 17 },
};
const formItemSwitch = {    // label 和input宽度
    labelCol: { span:10 },
    wrapperCol: { span: 14 },
};
const DepartmentAssociationMaintenance = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                columns:[],
                defaultVal:[],
                modalColumns:[],
                userInfo:[],        //点击科室行数据
                locListData: [], //
                pageSize: 10,
                page: 1,
                //tableData: [], //角色数据
                total: '', //表格数据总数
                selectData: {}, //下拉数据
                hospDesc: [], //科室下拉
                rowKey: '', //点击科室行id
                rowKey2:'', //
                locDataList: {}, //科室列表数据
                language: JSON.parse(window.sessionStorage.userData),
                ChineseEnglishSize: []
            }

            this.columns = [
                {
                    key: 1,
                    title: '科室',
                    dataIndex: 'LocDr',
                    align: "center",
                    width: '100%'
                },
              ];
            this.modalColumns = [
                {
                    key: 1,
                    title: '科室',
                    dataIndex: 'SupplyLocDr',
                    align: "center",
                },
            ]
        }
              //页面中英文翻译
        getDetailTableColumns = () => {
            let {language} = this.state;
            let data = {
                params: [{
                    reactCode: ['DepartmentAssociationMaintenan'],
                    compontName: 'DepartmentAssociationMaintenan',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                        
                    if (+res.errorCode === 0) {
                        let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return  {
                                ...item,
                                key: index + 1,
                                title: <div >{language.language =='EN' ? item.enDescripts : item.title}</div>,
                            }
                        }) : '';
                        
                        this.setState({columns: arr.slice(0, 1),modalColumns:arr.slice(1, 2),ChineseEnglishSize: language.language =='EN' ? res.result.language.EN : res.result.language.CN})
                        
                            // this.setState({ChineseEnglishSize:  language.language=='EN' ? res.result.language.EN : res.result.language.CN})
                        }
                    }
                })
            };
        componentDidMount() {
            // 初始化数据
            this.getSelectData();
            this.getTableData ();
            this.getDetailTableColumns();
        }

        componentWillUnmount() {
            // 组件销毁前将静止让setState修改state的状态
            this.setState = (state, callback) => { return; }
        }
        // 科室管理下拉框数据
        getSelectData() {

            let data = {
                params: [{
                    hospID: JSON.parse(window.sessionStorage.userData).hospID
                }]
            }
            $http.post('urlS', this, {
                code: "01050029",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({selectData: res.result.Data})
                   
                    } else {
                        this.setState({hospDesc: {}})
                    }
                }
            })
        }

        // 查询
        handleQuery = () => {
            this.setState({page: 1, pageSize: 10}, () => {
                this.getTableData();
            })
        }
        // 请求列表数据
        getTableData () {
            this.setState({loading: true});
            let name = this.props.form.getFieldValue('name');
            let { page, pageSize } = this.state;
            let  data = {
                params: [{
                    Descripts: name ? name : undefined,
                }],
                pagination:[{
                    pageSize: pageSize,
                    currentPage: page,
                    sort:"ID",
                    dir:"asc",
                }]
            }
            $http.post('urlS', this, {
                code: "02020289",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result) {
                        this.setState({ total: res.result.total, loading: false, locListData:res.result.rows})
                        
                    } else {
                        this.setState({locListData: [], total: 0, loading: false})
                    }
                }
            })
        }
        //科室列表
        locDetailData=(id)=>{

            let data = {
                params: [
                    {
                        groupID: id ? id : this.state.rowKey ? this.state.rowKey : undefined
                    }
                ]
            };
            $http.post('urlS', this, {
                code: "3006",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({locListData: res.rows});
                    }
                }
            })
        };

        //保存修改关联科室
        locChangeData=()=>{
          let Loc = this.props.form.getFieldValue('Loc');
       
          let LocId=this.state.rowKey;
                let data = {
                    params: [
                        {
                            LocId: LocId ?LocId : undefined,
                            supplyLocID: Loc ? Loc : undefined,
                        
                        }
                    ]
                };
                $http.post('urlS', this, {
                    code: "02020291",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            //this.setState({userInfo:[]})
                            this.GetDepartmentAssociationDataInfo(this.state.rowKey);
                        }
                    }
                })
        };
        //删除关联科室
        deleteLocData=()=>{
            if(this.state.rowKey){
                let Loc = this.props.form.getFieldValue('Loc');
                
                let LocId=this.state.rowKey;
                      let data = {
                          params: [
                              {
                                  LocId: LocId ?LocId : undefined,
                                  supplyLocID: Loc ? Loc : undefined,
                              
                              }
                          ]
                      };
                $http.post('urlS', this, {
                    code: "02020292",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            //this.setState({userInfo:[]})
                            this.GetDepartmentAssociationDataInfo(this.state.rowKey);
                        }
                    }
                })
            }else {
                message.error('请选择删除的科室')
            }

        };

          // 科室表格行的类名
          setTableClassName = (record) => {
            return record.SupplyLocId === this.state.rowKey2 ? 'clickRowStyle' : '';
        };
          // 角色表格行的类名
          setRowClassName = (record) => {
            return record.ID === this.state.rowKey ? 'clickRowStyle' : '';
        };
        // 设置科室行属性
        onClickLoc = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    if (this.state.rowKey === '') {
                        // 保存行数据以及ID
                        this.setState({rowKey: record.id, locDataList: record});

                    } else {
                        if (this.state.rowKey !== record.id) {
                            this.setState({rowKey: record.id, locDataList: record});
                        } else {
                            this.setState({rowKey: '', locDataList: {}});
                            // this.props.form.setFieldsValue({'approve': undefined})
                        }
                    }
                }
            }
        };
    
        // 设置角色行属性
        onClickRow = (record) => {
          return {
              // 单击行选中
              onClick: (e) => {
                  e.stopPropagation();
                  this.resetFields();
                  if (this.state.rowKey === '') {
                      // 保存行数据以及ID
                      this.setState({rowKey: record.ID});
                     
                      this.GetDepartmentAssociationDataInfo(record.ID)
                  } else {
                      if (this.state.rowKey !== record.ID) {
                          this.setState({rowKey: record.ID});
                          this.GetDepartmentAssociationDataInfo(record.ID)
                      } else {
                          this.setState({rowKey: ''});
                          this.resetFields();
                      }
                  }
              }
          }
      };
        // 设置行属性
        onClickRightRow = (record) => {
           
        return {
            // 单击行选中
            onClick: (e) => {
                e.stopPropagation();
                // this.resetFields();
                if (this.state.rowKey2 === '') {
                    // 保存行数据以及ID
                    this.setState({rowKey2: record.SupplyLocId});
                //    let arr1=[];
                //     for(var i=0;i<selectData.size;i++){
                //         if(selectData[i].id==record.ID){
                //             arr1=selectData[i]
                //         }
                //     }
                    // this.setState({defaultVal:arr1})
                } else {
                    if (this.state.rowKey2 !== record.SupplyLocId) {
                        this.setState({rowKey2: record.SupplyLocId});
                        
                    } else {
                        this.setState({rowKey2: ''});
                        this.resetFields();
                    }
                }
            }
        }
    };
      //获取科室关联的科室
      GetDepartmentAssociationDataInfo=(id)=>{
        let data = {
            params: [
                {
                    cID: id
                }
            ]
        };
        $http.post('urlS', this, {
            code: "02020290",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                 this.setState({userInfo: res.result.Data})
             
                 
                }
            }
        })

    };
         //清空表格内容
         resetFields = () => {
          this.props.form.resetFields();
          this.setState({ rowKey: '', rowData: ''});
      };
        // 页码改变的回调，参数是改变后的页码及每页条数 出库单
        onChange = (page, pageSize) => {
            this.setState({page: page, pageSize: this.state.pageSize}, () => {
                // 重新调用查询方法
                this.getTableData();
            });
        };

        onShowSizeChange = (current, size) => {
            this.setState({page: current, pageSize: size}, () => {
                // 重新调用查询方法
                this.onChange(current,size);
            })
        };
        render() {
            const { getFieldDecorator } = this.props.form;
            return (
                <div className="DepartmentAssociationMaintenance">
                    <Col span={14}>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>{this.state.ChineseEnglishSize.DepartmentAssociationMaintenanQueryCriteria ? this.state.ChineseEnglishSize.DepartmentAssociationMaintenanQueryCriteria.descripts:'查询条件'}</div>}
                        >
                            <Row>
                                <Col span={19}>
                                    <Form>
                                        <Row>
                                            <Col span={19} >
                                                <Form.Item label={this.state.ChineseEnglishSize.DepartmentAssociationMaintenanNameOfDepartment ? this.state.ChineseEnglishSize.DepartmentAssociationMaintenanNameOfDepartment.descripts:'科室名称：'} {...formItemInput}>
                                                    {getFieldDecorator('name', {
                                                        initialValue: undefined,
                                                        rules: [{ required: false}]
                                                    })(
                                                        <Input placeholder={this.state.ChineseEnglishSize.DepartmentAssociationMaintenanEnterToSearch ? this.state.ChineseEnglishSize.DepartmentAssociationMaintenanEnterToSearch.descripts:'回车可搜索'} onPressEnter={this.handleQuery}/>
                                                    )}
                                                </Form.Item>
                                            </Col>
 
                                        </Row>
                                    </Form>
                                </Col>
                                <Col span={5} style={{marginTop: '4px'}}>
                                    <Row >
                                        <Button style={{marginLeft: '20px'}} onClick={this.handleQuery}>{this.state.ChineseEnglishSize.DepartmentAssociationMaintenanQuery ? this.state.ChineseEnglishSize.DepartmentAssociationMaintenanQuery.descripts:'查询'}</Button>
                                    </Row>
                                </Col>
                            </Row>
                        </Card>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{this.state.ChineseEnglishSize.DepartmentAssociationMaintenanListOfDepartments ? this.state.ChineseEnglishSize.DepartmentAssociationMaintenanListOfDepartments.descripts:'科室列表'}</div>}
                            >
                                <div>
                                    <Table
                                        columns={this.state.columns?this.state.columns:this.columns}
                                        dataSource={this.state.locListData}
                                        pagination={false}
                                        bordered
                                        style={{height: store.getState().tableHeight.y +61 + 'px'}}
                                        scroll={{ y: store.getState().tableHeight.y +10 }}
                                        rowKey={record => record.key}
                                        onRow={this.onClickRow}
                                        rowClassName={this.setRowClassName}
                                    />
                                    <CommonPagination size='small' current={this.state.page} total={this.state.total} search= 'search'
                                    onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.locListData}
                                    loading={this.state.loading} onChange={this.onChange.bind(this)} />
                                </div>
                            </Card>
                    </Col>
                    <Col span={10}>
                            <Row>
                                <Card
                                    size="small"
                                    title={<div className="card-title-left-icon"><div></div>{this.state.ChineseEnglishSize.DepartmentAssociationMaintenanRevisionOfDepartments ? this.state.ChineseEnglishSize.DepartmentAssociationMaintenanRevisionOfDepartments.descripts:'修改科室'}</div>}
                                >
                                    <Col span={10}>
                                        <Form.Item label={this.state.ChineseEnglishSize.DepartmentAssociationMaintenanDepartment ? this.state.ChineseEnglishSize.DepartmentAssociationMaintenanDepartment.descripts:'科室：'} {...formItemInput}>
                                            {getFieldDecorator('Loc', {
                                                initialValue: this.state.rowKey2 ? this.state.rowKey2 : undefined,
                                                rules: [{ required: false}]
                                            })(
                                                <Select  showSearch optionFilterProp="seatchprop" allowClear style={{width: '100%'}}>
                                                    {this.state.selectData.length>0 && this.state.selectData.map(item => {
                                                        return <Option value={item.id} key={item.id} title={item.descripts} seatchprop={item.descripts+ '^'+item.descriptsSPCode}>{item.descripts}</Option>
                                                    })}
                                                </Select>
                                            )}
                                        </Form.Item>
                                    </Col>

                                    <Col span={7} style={{marginTop: '4px'}}>
                                        <Button style={{margin: '0 20px'}} onClick={ this.locChangeData}>{this.state.ChineseEnglishSize.DepartmentAssociationMaintenansave ? this.state.ChineseEnglishSize.DepartmentAssociationMaintenansave.descripts:'保存'}</Button>
                                        <Button onClick={this.deleteLocData}>{this.state.ChineseEnglishSize.DepartmentAssociationMaintenandelete ? this.state.ChineseEnglishSize.DepartmentAssociationMaintenandelete.descripts:'删除'}</Button>
                                    </Col>
                                </Card>
                            </Row>
                            <Row >
                                <Card
                                    size="small"
                                    title={<div className="card-title-left-icon"><div></div>{this.state.ChineseEnglishSize.DepartmentAssociationMaintenanRelatedDepartments ? this.state.ChineseEnglishSize.DepartmentAssociationMaintenanRelatedDepartments.descripts:'关联科室'}</div>}
                                >
                                    <div>
                                        <Table
                                            columns={ this.state.modalColumns?this.state.modalColumns:this.modalColumns}
                                            dataSource={this.state.userInfo}
                                            pagination={false}
                                            bordered
                                            scroll={{ y: store.getState().tableHeight.y  - 13 }}
                                            style={{height: (store.getState().tableHeight.y + 65)}}
                                            rowKey={record => record.key}
                                            onRow={this.onClickRightRow}
                                            rowClassName={this.setTableClassName}
                                        />
                                        {/*<CommonPagination size='small' current={this.state.page2} total={this.state.detailTotal} search= 'search'*/}
                                        {/*onShowSizeChange={this.onShowSizeChange2.bind(this)} complete={true} dataSource={this.state.detailsListData}*/}
                                        {/*loading={this.state.detailsLoading} onChange={this.onChange2.bind(this)} />*/}
                                    </div>
                                </Card>
                            </Row>
                    </Col>
                </div>
            )
        }
    }
);
export default DepartmentAssociationMaintenance;