/*
 * Creator:     ML
 * CreatDate:   2020-02-19
 * descripts：  黑名单信息
 * */
import React from 'react';
import { Form, Input, Select, Button, message, Row, Icon, Divider, Popconfirm, DatePicker, Table, Col, Card ,Switch ,Drawer} from 'antd';
import { $http } from 'containers/config/https';
import moment from 'moment';
import store from 'store';
import './style/index.less';
import CommonPagination from 'components/pagination';
import BreakTimesModal from './component/BreakTimesModal';
import BreakReasonModal from './component/BreakReasonModal';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CardTypeRead from 'components/cardType/index';
import RangeDatePicker from 'components/rangePicker/index';

const { Option } = Select;

class BlacklistInformations extends React.Component {
    constructor() {
        super();
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            userData: userData,
            tableData: [], // 列表数据
            total: 0,
            page: 1,
            pageSize: 50,
            n:6,
            m:13,
            size: "small",
            search: "",
            ICD: "",
            diaID: "",
            isFlag:true,
            startDate:undefined,  // //开始日期
            endDate:undefined,  // //结束日期
        };
    }

    componentDidMount() {
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 88 + 'px';
        if (this.state.size == "small") {
            this.setState({
                pageSize: 10
            })
        } else {
            this.setState({
                pageSize: 50
            })
        }
        this.getFindDate()
        this.getMainTableColumns()
        this.getHopSelect()
        this.getBlackListType()
    }

    componentWillReceiveProps(nextProps) {

    }
    //调子组件
    onAttRef = (ref) => {
        this.childAtt = ref
    }
    //调子组件 爽约次数明细弹框
    onRefs = (ref) => {
        this.childRef = ref
    }
    //调用爽约次数明细弹框
    handleOpen = (e, record) => {
        this.childRef.showModal(record)
    }
    onReason= (ref) => {
        this.ReasonRef = ref
    }
    //调用原因弹框
    handleOpenReason = (v, record) => {
        this.ReasonRef.showModal(v,record)
    }
    
    //国际化
    setMessage(name, message) {
        return this.state.localeProvider ? this.state.localeProvider[name][message] : ''
    }
    //动态表头
    onColumnRef = (ref) => {
        this.columnRef = ref;
    }
    // 获取主列表columns
    getMainTableColumns = () => {
        let data = {
            params: [{
                compontName: "BlacklistInformationInterfac",
                reactCode: ['BlacklistInformationInterfac'],
                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.descripts : item.title}</div>,
                            display: item.display,
                            key: item.seqNo,
                            render: (text, record) => {
                                // console.log("record", record)
                                if (item.code == "breakTimes" && record.breakTimes > 0) {
                                    return (
                                        <span style={{ cursor: "pointer" }} onClick={(e) => this.handleOpen(e, record)}><span style={{ color: "#096dd9" }}>{record.breakTimes}</span></span>
                                    )
                                }
                                if (item.code == "activeFlag" ) {
                                        return (
                                               <Switch checkedChildren={this.state.localeProvider && this.state.localeProvider.BlacklistInformationInterfacYes ? this.setMessage('BlacklistInformationInterfacYes', 'descripts') : '是'} unCheckedChildren={this.state.localeProvider && this.state.localeProvider.BlacklistInformationInterfacNo ? this.setMessage('BlacklistInformationInterfacNo', 'descripts') : '否'} checked={record.activeFlag=="Y"?true:false} disabled={record.activeFlag=="N"} onChange={(val) => this.handleSwithChange(val, record)} />
                                            ) 
                            }
                            return text
                        }
                    }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    this.setState({ localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN, columns: filterArr, widthTotal: res.totalWidth })
                    // console.log("res.totalWidth",res.totalWidth)
                }
            }
        })
    }
     //开始日期
     startChange(date) {
        this.setState({
          startDate: date,
        })
      }
      //结束日期
      endChange(date) {
        this.setState({
          endDate: date,
        })
      }
    handleSwithChange = (v,record) => {
        if(!v){
             this.handleOpenReason(v,record)
        }
        else{
            let data = {
                params: [{
                  ID: record && record.ID ? record.ID : "",
                  activeFlag: "Y" ,//是否立即生效,
                  blackReasonDr:record && record.blackReasonID ? record.blackReasonID : "",
                  createUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                  updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                }]
              }
              $http.post('urlS', this, {
                code: '03050186',
                data: data,
                success: function (res) {
                  if (+res.errorCode === 0) {
                    message.success(this.state.localeProvider && this.state.localeProvider.BlacklistInformationInterfacUpdateCompleted ? this.setMessage('BlacklistInformationInterfacUpdateCompleted', 'descripts') : '更新成功')
                    this.getFindDate()
                  }
                }
              })
        }
       
      }
    //获取医院下拉框
    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
                    })
                }
            }
        })
    }
    //获取黑名单类型下拉框
    getBlackListType = () => {
        let data = {
            params: [{
                language: this.state.userData.language,
            }],
        }
        $http.post('urlS', this, {
            code: '03050187',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        blackListTypeArr: res.result.Data
                    })
                }
            }
        })
    }
    // 点击查询
    handleQuery = () => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.setState({
                    values,
                }, () => {
                    this.onShowSizeChange("1", this.state.pageSize)
                    // this.newAdd()
                })
            }
        })
    }
    getValue = (cardType, patCardNo) => {
        this.setState({
            cardType,
            patCardNo,
        })
    }
    //查询
    getFindDate = (e) => {
        let { page, pageSize, values,cardType,patCardNo } = this.state;
        this.props.form.validateFields((err, values) => {
           let data = {
            params: [{
                number: values&&values.number || "",
                cardTypeID: cardType,
                cardNo: patCardNo,
                hospID: values&&values.hospID || "",
                blackListTypeID: values&&values.blackListTypeID || "",
                startDate: this.state.startDate,
                endDate: this.state.endDate,
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
            }]
        } 
          $http.post('urlS', this, {
            code: '03050185',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        search: e,
                        tableData: res.result.data,
                        total: res.result.TotalCount,
                    })
                }
            }
        })
        })
        
      
    }
    // 修改page和pageSize 跳转至---
    onChange = (e) => {
        this.setState({ page: e, pageSize: this.state.pageSize, }, () => {
            // 重新调用查询方法
            this.getFindDate();
        })
    }
    //下拉选择页数
    onShowSizeChange = (page, pageSize) => {
        // console.log("page",page,"pagesize",pageSize)
        this.setState({ page: 1, pageSize: pageSize }, () => {
            // 重新调用查询方法
            this.getFindDate("search");
        })
    }
    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }
    // //点击Row
    // onClickRow = (record) => {
    //     return {
    //         onClick: () => {
    //             this.setState({
    //                 parms: record,
    //             })
    //             this.childAtt.clearInfo()
    //             if (this.state.rowIds === "") {
    //                 this.setState({
    //                     rowIds: record.ID,
    //                 })
    //                 this.childAtt.getInfo(record)
    //             } else {
    //                 if (this.state.rowIds !== record.ID) {
    //                     this.setState({
    //                         rowIds: record.ID,
    //                     });
    //                     this.childAtt.getInfo(record)
    //                 } else {
    //                     this.newAdd()
    //                 }
    //             }
    //         },
    //     };
    // }
    // newAdd = () => {
    //     this.setState({
    //         rowIds: "",
    //     });
    //     this.childAtt.clearInfo()
    // }
    //点击查询后 表格行
    setRowClassNames = (record) => {
        return record.ID === this.state.rowIds ? 'clickRowStyle' : '';
    }
    render() {
        const { tableData, total, page, rowData, 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>)
        })
        //黑名单类型
        let blackListTypeOp = []
        this.state.blackListTypeArr && this.state.blackListTypeArr.map((item) => {
            blackListTypeOp.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
        })
        const { getFieldDecorator } = this.props.form;
        const formLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 14 },
        }
        const formLayoutPerson = {
            labelCol: { span: 5 },
            wrapperCol: { span: 18 },
        }
        let searchColConfig = {
            xs: { span: 24 },
            sm: { span: 12 },
            md: { span: 10 },
            lg: { span: 6}
          }
        return (
            <div className="card-dom"> 
                <div>
                    <Form layout={'horizontal'}>
                        <Row>
                            <Col span={6}>
                                <Form.Item label={this.state.localeProvider && this.state.localeProvider.BlacklistInformationInterfacPersonIdentification ? this.setMessage('BlacklistInformationInterfacPersonIdentification', 'descripts') : '人员标识'} {...formLayoutPerson}>
                                    {getFieldDecorator('number', {
                                        initialValue: undefined,
                                        rules: [{ required: false, message: "" }],
                                    })(
                                        <Input allowClear placeholder={this.state.localeProvider && this.state.localeProvider.BlacklistInformationInterfacPatientIDNumber ? this.setMessage('BlacklistInformationInterfacPatientIDNumber', 'descripts') : "病人ID/姓名/身份证号码/手机号码"} onPressEnter={this.handleQuery}></Input>
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <CardTypeRead getValue={this.getValue} getQuery={this.handleQuery} n={this.state.n} m={this.state.m} ></CardTypeRead>
                            </Col>
                            <Col span={6}>
                                <Form.Item label={this.state.localeProvider && this.state.localeProvider.BlacklistInformationInterfacHospital ? this.setMessage('BlacklistInformationInterfacHospital', 'descripts') : '医院'} {...formLayout} {...formLayout}>
                                    {getFieldDecorator('hospID', {
                                        initialValue:  undefined,
                                        rules: [{ required: false, message: "" }],
                                    })(
                                        <Select
                                        allowClear
                                        >
                                            {hosOp}
                                        </Select>
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item label={this.state.localeProvider && this.state.localeProvider.BlacklistInformationInterfacBlacklistType ? this.setMessage('BlacklistInformationInterfacBlacklistType', 'descripts') : '黑名单类型'} {...formLayout} {...formLayout}>
                                    {getFieldDecorator('blackListTypeID', {
                                        initialValue: undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Select
                                        allowClear
                                        >
                                            {blackListTypeOp}
                                        </Select>
                                    )}
                                </Form.Item>
                            </Col>
                            </Row>
                           <Row>
                           <Col {...searchColConfig} style={{ padding: "4px 16px" }}>
                            <RangeDatePicker isChange={true} label={ this.state.userData.language == 'EN' ? 'date：' : '有效日期：' } format='YYYY-MM-DD' width={310}
                                startDate={this.state.startDate} endDate={this.state.endDate}
                                startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)}  />
                            </Col>
                            <Col span={4}>
                                <Button style={{ margin: '3px 0 0 10px' }} type="primary" onClick={this.handleQuery}>{this.state.localeProvider && this.state.localeProvider.BlacklistInformationInterfacSearch ? this.setMessage('BlacklistInformationInterfacSearch', 'descripts') : '查询'}</Button>
                            </Col>
                           </Row>
                    </Form>
                </div>
                <Row>
                    <Col span={24}>
                        <Card>
                            <Table
                                columns={columns}
                                dataSource={this.state.tableData}
                                pagination={false}
                                rowKey={record => record.key}
                                // onRow={this.onClickRow}
                                // rowClassName={this.setRowClassNames}
                                bordered
                                style={{ height: store.getState().tableHeight.y + 88 + 'px', overflow: "auto" }}
                            />
                            <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.tableData}
                                onChange={this.onChange.bind(this)} />

                        </Card>
                    </Col>
                </Row>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName='BlacklistInformationInterfac'
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getMainTableColumns}
                />
                <BreakTimesModal onRefs={this.onRefs} localeProvider={this.state.localeProvider}></BreakTimesModal>
                <BreakReasonModal onReason={this.onReason} handleQuery={this.getFindDate} localeProvider={this.state.localeProvider}></BreakReasonModal>
            </div>
        )
    }
};
const BlacklistInformation = Form.create()(BlacklistInformations);
export default BlacklistInformation;