import React from 'react';
import { Form, Row, Col, Input, Select, DatePicker, Button, Modal, message, Divider, Icon, Table, TimePicker, Popconfirm } from 'antd';
import moment from 'moment';
import { $http } from '../../../containers/config/https';
import "./Style/consultation.less"

const FormItem = Form.Item;
const Option = Select.Option;
const warning = Modal.warning;
let userData;
const style = {
    // padding: "0 6px"
}
const formItemLayoutName = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
}

// 点击编辑时记录当前行数据
let tableRecord = {};

const ConsultationAuditModel = Form.create()(
    class ConsultationAuditModel extends React.Component {
        constructor(props) {
            userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {};
            super(props);
            this.state = {
                visible: false,
                data: [],
                consultID: '',
                conItemRequireUserID: '',
                conItemRequireContact: '',
                tableData: [],
                consultLoc: [],
                conUserData: [],
                removeConsultLoc: [],
                index: '',
                editingKey: '',
                hospID: '',
                clickFlag: false,        //按钮点击标志
                tableLocID: '',          //table科室id
                titleID: '',             //职称id               
                conContactTell: '',      //会诊联系人电话
                conHospLoc: [],          //会诊医院下所有科室
                conHospID: '',           //会诊医院ID
                tableLocID: '',          //table科室id
                titleID: '',             //职称id
                tableUserID: '',         //table人员
                cbTitleData: [],        //职称下拉数据
                disabledFlag: false,
                conApplyLocID: ''
            }
        }
        componentDidMount() {
            this.props.onRef(this);
            this.setState({ showLoading: false });
            this.getSelectData();
            this.initData();
        }

        initData() {
            this.columns = [
                {
                    key: 1,
                    title: '科室',
                    dataIndex: 'locDesc',
                    align: "center",
                    width: 130,
                    render: (text, record) => {
                        // var that = this;
                        if (record.editable) {
                            return (
                                <Select
                                    allowClear
                                    style={{ width: "100%", textAlign: "center" }}
                                    onSelect={this.handleFieldChange.bind(this, record.key, 'locID')}
                                    showSearch={true}
                                    optionFilterProp='role'
                                    disabled={record.disabledFlag}
                                >
                                    {
                                        this.state.conHospLoc && this.state.conHospLoc.map((item) => {
                                            if (item.id != this.state.conApplyLocID) {
                                                return (
                                                    <Option key={item.id}>
                                                        {item.descripts}
                                                    </Option>
                                                )
                                            }
                                        })
                                    }
                                </Select>
                            )
                        }
                        return text
                    }
                },
                {
                    key: 2,
                    title: '职称',
                    dataIndex: 'conItemRequireTitleID',
                    align: "center",
                    width: 130,
                    render: (text, record, index) => {
                        return (
                            <Select
                                allowClear
                                style={{ width: "100%", textAlign: "center" }}
                                onSelect={this.handleFieldChange.bind(this, record.key, 'conItemRequireTitleID')}
                                value={record.conItemRequireTitleID + ""}
                                disabled={record.disabledFlag}
                            >
                                {this.titleItem(record)}
                            </Select>
                        )
                    }
                },
                {
                    key: 3,
                    title: '医生',
                    dataIndex: 'conItemRequireUserID',
                    align: "center",
                    width: 130,
                    render: (text, record) => (
                        <Select
                            onFocus={this.getLocUserTableData.bind(this, record.locID, record.conItemRequireTitleID)}
                            defaultValue={record.conItemRequireUserID}
                            style={{ width: '100%' }}
                            onSelect={this.handleFieldChange.bind(this, record.key, 'conItemRequireUserID')}
                            disabled={record.disabledFlag}
                        >
                            {this.doctorItem(record)}
                        </Select>
                    )
                },
                {
                    key: 4,
                    title: '联系电话',
                    dataIndex: 'conItemRequireContact',
                    align: "center",
                    width: 130,
                    render: (text, record) => (
                        <Input
                            value={text}
                            disabled={record.disabledFlag}
                            onChange={this.handleFieldChange.bind(this, record.key, 'conItemRequireContact')}
                        />
                    )
                },
                {
                    title: '操作',
                    key: 9,
                    align: "center",
                    width: 130,
                    render: (text, record) => {
                        return record.editable ? (
                            <span>
                                <a onClick={(e) => this.handleUpdate(record, e)}>确认</a>
                                <Divider type="vertical" />
                                <a onClick={(e) => this.cut(record, e)}>取消</a>
                            </span>
                        ) : (
                                <span>
                                    <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
                                        <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                                    </Popconfirm>
                                </span>
                            )
                    }
                }
            ]
        }
        /** 去重*/
        unique5(arr) {
            var x = new Set(arr);
            return [...x];
        }
        titleItem = (record) => {
            let titleOption = [];
            if (record.conItemRequireTitleID != "") {
                titleOption.push(
                    <Option key={record.conItemRequireTitleID + ""} title={record.conItemRequireTitle}>
                        {record.conItemRequireTitle}
                    </Option>
                )
            }
            let cbTitleData = [].concat(this.state.cbTitleData);
            if (cbTitleData) {
                cbTitleData.map((item, index) => {
                    if (item.id != record.conItemRequireTitleID) {
                        titleOption.push(
                            <Option key={item.id + ""} title={item.descripts}>
                                {item.descripts}
                            </Option>
                        )
                    }
                })
            }
            return titleOption;

        }
        doctorItem = (record) => {
            let optionItem = [];
            if (record.conItemRequireUserID != "") {
                optionItem.push(
                    <Option key={record.conItemRequireUserID + ""} title={record.conItemRequireUserDesc}>
                        {record.conItemRequireUserDesc}
                    </Option>
                )
            }
            let conUserData = [].concat(this.state.conUserData);
            if (conUserData) {
                conUserData.map((item, index) => {
                    if (item.id != record.conItemRequireUserID) {
                        optionItem.push(
                            <Option key={item.id} title={item.descripts}>
                                {item.descripts}
                            </Option>
                        )
                    }
                })
                return optionItem;
            }
        }
        handleQuery = () => {
            let data = {
                params: [{
                    consultID: this.props.consultID,
                    type: 'apply'
                }]
            };
            $http.post('urlS', this, {
                code: '04090014',
                data: data,
                success: (res) => {
                    if (res.errorCode === "0") {
                        for (var index = 0; index < res.Data[0].consultLoc.length; index++) {
                            res.Data[0].consultLoc[index].key = index;
                            res.Data[0].consultLoc[index].disabledFlag = this.state.disabledFlag;
                        }
                        this.setState({
                            tableData: res.Data,
                            conHospID: res.Data[0].conHospID,
                            consultLoc: res.Data[0].consultLoc,
                            index: index,
                            conApplyLocID: res.Data[0].conApplyLocID
                        });
                    }
                }
            });
        }

        // 获取下拉框数据
        getSelectData = () => {
            let data = {
                "params": [{
                    hospID: userData && userData.hospID ? userData.hospID : '', // 登录医院id       
                    locID: userData.locID,
                    groupID: userData.groupID,
                    userID: userData.userID,
                    type: 'apply'
                }]
            };
            $http.post('urlDeault', this, {
                code: "04090011",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            cbTitleData: res.result.title,
                        })
                    }
                },
                error: function (error) {
                    message.error('失败：' + error);
                }
            });
        }

        // 添加行
        addRow = () => {
            const { consultLoc } = this.state;
            const newData = consultLoc.map((item) => ({ ...item }));
            newData.push({
                conHospID: '',
                key: this.state.index.toString(),
                conItemID: '',
                conItemRequireTitleID: '',
                locID: '',
                conItemRequireUserID: '',
                conItemRequireContact: '',
                editable: true
            });
            //点击增加时获取会诊医院下所属科室
            if (this.state.conHospLoc.length === 0) {
                this.getConHospLocData();
            }
            this.setState({
                consultLoc: newData,
                index: this.state.index + 1,
            });
        }

        // 通过id获取对应code
        getCodeByID = (id, dataSource) => {
            for (let i = 0; i < dataSource.length; i++) {
                if (dataSource[i].id == id) {
                    return dataSource[i].code
                }
            }
        }


        getConHospLocData = () => {
            let data = {
                "params": [{
                    hospID: this.state.conHospID ? this.state.conHospID : userData.hospID,          // 会诊医院id
                }]
            };
            $http.post('urlDeault', this, {
                code: "04020008",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            conHospLoc: res.result.Data
                        })
                    }
                },
                error: function (error) {
                    message.error('失败：' + error);
                }
            });
        }

        //获取操作行数据对象
        getRowByKey(key, newData) {
            const { consultLoc } = this.state;
            return (newData || consultLoc).filter(item => item.key === key)[0];
        }

        // 表格下拉框选中
        handleFieldChange = (index, code, value, opt) => {
            let { consultLoc } = this.state;
            let valCode = '';
            if (code == 'conItemRequireTitleID') {
                valCode = "conItemRequireTitle"
            }
            if (code == 'conItemRequireUserID') {
                valCode = "conItemRequireUserDesc"
            }
            if (code == 'conItemRequireContact') {
                value = value.target.value
            }
            consultLoc[index][code] = value;
            if (valCode !== '') {
                consultLoc[index][valCode] = opt.props.title;
            }
            this.setState({ consultLoc });
            // const newData = consultLoc.map(item => ({ ...item }));
            // const target = this.getRowByKey(index, newData);
            // if (target) {
            //     target[code] = value;
            //     this.setState({ consultLoc: newData });
            // }

            if ((code == 'locID') && (value !== '')) {
                this.setState({
                    tableLocID: value
                }
                    // ,() => {this.getLocUserTableData(this.state.tableLocID,this.state.titleID)}
                );
            }
            if ((code == 'conItemRequireTitleID') && (value !== '')) {
                this.setState({ titleID: value }
                    // ,() => {
                    //     if(this.state.tableLocID !== ''){
                    //         this.getLocUserTableData(this.state.tableLocID,this.state.titleID);  
                    //  }
                    // }
                );
            }
            if ((code == 'conItemRequireUserID') && (value !== '')) {
                let deptDocData = this.state.conUserData.filter((item) => { return item.id === opt.key })
                if (deptDocData[0].userContactAry.length > 0) {
                    let conContactTell = deptDocData[0].userContactAry[0].userContactValue
                    consultLoc[index]["conItemRequireContact"] = conContactTell
                }
            }
        }

        // 增加获取表格科室人员
        getLocUserTableData = (locID, title) => {
            this.setState({
                conUserData: []
            })
            let data = {
                "params": [{
                    hospID: this.state.conHospID ? this.state.conHospID : userData.hospID,
                    locID,
                    title,
                    power: 'select',
                    deptEffective: 'Y',
                }]
            };
            $http.post('urlDeault', this, {
                code: "01040021",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            conUserData: res.result.Data
                        })
                    }
                },
                error: function (error) {
                    message.error('失败：' + error);
                }
            });
        }



        // 删除会诊科室
        handleDelete = (record, e) => {
            // e.preventDefault();
            let { removeConsultLoc } = this.state
            let { consultLoc } = this.state;
            consultLoc.splice(record.key,1);
            if (record.conItemID !== '') {
                removeConsultLoc.push(record.conItemID);
                this.setState({ removeConsultLoc });
            }
              // 重新给key赋值
            for (let i=0;i<consultLoc.length;i++)
            {
                consultLoc[i].key = i;
            }
            this.setState({ consultLoc });
        }

        // 确认会诊科室
        handleUpdate = (record, e) => {
            e.preventDefault();
            let { consultLoc } = this.state;
            consultLoc[record.key]["disabledFlag"] = true
        }

        // 取消编辑
        cut = (record, e) => {
            const { consultLoc } = this.state;
            // const { onChange } = this.props;
            const newData = consultLoc.filter(item => item.key !== record.key);
            this.setState({
                consultLoc: newData,
                index: this.state.index - 1,
            });
            // onChange(newData);
        }


        //清除数据
        cleanData = () => {
            this.props.form.resetFields();
            this.setState({
                consultLoc: [],
            }, () => {
                this.handleQuery();
            })
        }
        // 保存
        save = () => {
            this.setState({
                clickFlag: true,
                // editingKey: '',
                // disabledAll:(code === 'SE')?true:false
            });
            this.props.form.validateFields((err, value) => {
                if (err) {
                    this.setState({
                        clickFlag: false,
                        disabledAll: false
                    });
                }
            });
            const formData = this.props.form.getFieldsValue();
            // 过滤科室为空的table数据
            for (let i = 0; i < this.state.consultLoc.length; i++) {
                if ((this.state.consultLoc[i] !== undefined) && (this.state.consultLoc[i].locID == '')) {
                    delete this.state.consultLoc[i];
                }
            }
            const consultLoc = this.state.consultLoc.filter(item => item)
            let data = {
                "params": [{
                    consultID: this.props.consultID ? this.props.consultID : this.state.consultID,
                    hospID: userData.hospID,
                    code: 'AU',
                    conRequirePlace: formData.conRequirePlace,
                    conRequireDate: formData.conRequireDate ? moment(formData.conRequireDate).format('YYYY-MM-DD') : null,
                    conRequireTime: formData.conRequireTime ? moment(formData.conRequireTime).format('HH:mm:ss') : null,
                    updateUserID: userData.userID,
                    consultLoc: consultLoc,
                    removeConsultLoc: this.state.removeConsultLoc,
                    conReason: formData.conReason
                }]
            };
            // return;
            $http.post('urlADS', this, {
                code: "04090015",
                data: data,
                success: function (res) {
                    if (+res.errorCode == '0') {
                        message.success(res.errorMessage);
                        this.props.handthis.handleQuery();
                    }
                    this.handleCancel()
                },
                error: function (error) {
                    message.error('失败：' + error);
                    this.setState({ clickFlag: false, disabledFlag: false })
                }
            });
        }
        // 驳回
        handleReject = () => {
            const formData = this.props.form.getFieldsValue();
            let data = {
                "params": [{
                    consultID: this.props.consultID ? this.props.consultID : this.state.consultID,
                    hospID: userData.hospID,
                    code: 'REJ',
                    updateUserID: userData.userID,
                    conReason: formData.conReason,
                    // conAuditUserID:userData.userID,
                    // conAuditDate: moment().format('YYYY-MM-DD'),
                    // conAuditTime: moment().format('HH:mm'),
                }]
            };
            $http.post('urlADS', this, {
                code: "04090015",
                data: data,
                success: function (res) {
                    if (+res.errorCode == '0') {
                        message.success(res.errorMessage);
                        this.props.handleOk();
                        this.props.handthis.handleQuery();
                    }
                    this.handleCancel()
                },
                error: function (error) {
                    message.error('失败：' + error);
                }
            });
        }
        showModal = () => {
            this.setState({
                visible: true,
            });
        };

        handleCancel = (e) => {
            this.props.handleOk();
        };

        render() {
            const { getFieldDecorator } = this.props.form;
            let consultInfo = this.state.tableData.length > 0 ? this.state.tableData[0] : {};
            return (
                <div>
                    <Modal
                        className="consDom"
                        title="审核"
                        width='900px'
                        visible={this.props.visible}
                        onCancel={this.handleCancel}
                        footer={null}
                    // cancelText='驳回'
                    // okText='审核'
                    >
                        <div className='registerDom1' style={{ height: "100%", overflow: "hidden", paddingTop: "0" }}>
                            <Row gutter={12} className="cardTitle">
                                <Divider type="vertical" className="verticalLine" />
                                <span>申请信息</span>
                            </Row>
                            <Divider />
                            <div className="baseInfoDom">
                                <Row gutter={70}>
                                    <Col span={8} style={style}>
                                        <FormItem {...formItemLayoutName} label='申请科室'>
                                            {getFieldDecorator('conApplyLocDesc', {
                                                initialValue: consultInfo.conApplyLocDesc ? consultInfo.conApplyLocDesc : '',
                                                rules: [{ required: false, message: '请输入申请科室', }],

                                            })(
                                                <Input disabled />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={8}>
                                        <FormItem  {...formItemLayoutName} label='申请医生'>
                                            {getFieldDecorator('conAppUserDesc', {
                                                initialValue: consultInfo.conAppUserDesc ? consultInfo.conAppUserDesc : '',
                                                rules: [{ required: false, message: ' ' }],
                                            })(
                                                <Input disabled />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={8} >
                                        <FormItem  {...formItemLayoutName} label='申请时间'>
                                            {getFieldDecorator('conApplyDate', {
                                                initialValue: consultInfo.conApplyDate ? consultInfo.conApplyDate : '',
                                                rules: [{ required: false, message: '请选择申请时间' }],
                                            })(
                                                <Input disabled />
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row gutter={60}>
                                    <Col span={8} style={{ padding: "0" }}>
                                        <FormItem {...formItemLayoutName} label={"会诊类型"}>
                                            {getFieldDecorator('conType',
                                                {
                                                    initialValue: consultInfo.conType ? consultInfo.conType : '',
                                                    rules: [{ required: false, message: '请填写输入会诊类型' }],
                                                })(
                                                    <Input disabled />
                                                )}
                                        </FormItem>
                                    </Col>
                                    <Col span={8} style={{ padding: '0' }}>
                                        <FormItem {...formItemLayoutName} label={'医院名称'}>
                                            {getFieldDecorator('conHospDesc', {
                                                initialValue: consultInfo.conHospDesc ? consultInfo.conHospDesc : '',
                                                rules: [{ required: false, message: '医院名称' }],
                                            })(
                                                <Input disabled />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={8} style={{ padding: '0' }}>
                                        <FormItem {...formItemLayoutName} label={'驳回理由'}>
                                            {getFieldDecorator('conReason', {
                                                initialValue: consultInfo.conReason ? consultInfo.conReason : '',
                                                rules: [{ required: false, message: '驳回理由' }],
                                            })(
                                                <Input />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={8}>
                                    </Col>
                                </Row>
                                <Row gutter={60}>
                                    <Col span={8} style={style}>
                                        <FormItem {...formItemLayoutName} label='会诊地点'>
                                            {getFieldDecorator('conRequirePlace', {
                                                initialValue: consultInfo.conRequirePlace ? consultInfo.conRequirePlace : '',
                                                rules: [{ required: false, message: '请选择会诊地点' }],
                                            })(
                                                <Input />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={8} style={{ padding: "0" }}>
                                        <FormItem {...formItemLayoutName} label='会诊日期'>
                                            {getFieldDecorator('conRequireDate', {
                                                initialValue: moment(consultInfo.conRequireDate, 'YYYY-MM-DD'),
                                                rules: [{ required: false, message: '会诊日期' }],
                                            })(
                                                <DatePicker />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={8}>
                                        <FormItem label={"会诊时间"}  {...formItemLayoutName} className="lastRightBorder">
                                            {getFieldDecorator('conRequireTime',
                                                {
                                                    initialValue: moment(consultInfo.conRequireTime, 'HH:mm:ss'),
                                                    rules: [{ required: false, message: '' }],
                                                })(
                                                    <TimePicker />
                                                )}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row type="flex" justify="center">
                                    <Col span={24}>
                                        <Divider orientation="left" style={{ marginTop: '5px', marginBottom: '5px' }}>
                                            会诊科室&nbsp;&nbsp;&nbsp;
                                        <Button
                                                type='primary'
                                                size='small'
                                                onClick={this.addRow}
                                                icon='plus'
                                            // disabled={(((this.state.consultLoc).filter(item => item).length === 1)&&(this.getCodeByID(getFieldDecorator.getFieldValue('conTypeID'),this.state.conTypeData) === 'CDC'))?true:this.state.disabledAll}
                                            >添加科室
                                        </Button>
                                        </Divider>
                                        <Table
                                            // style={{minHeight: '228px' }}
                                            columns={this.columns}
                                            dataSource={this.state.consultLoc}
                                            pagination={false}
                                            bordered
                                        />
                                    </Col>
                                </Row>
                                <Row style={{
                                    display: "flex",
                                    justifyContent: "center"
                                }}>
                                    <Col span={2}>
                                        <Button type='primary' onClick={this.save}>
                                            审核
                                    </Button>
                                    </Col>
                                    <Col span={2}>
                                        <Button type='primary' onClick={this.handleReject}>
                                            驳回
                                    </Button>
                                    </Col>
                                </Row>
                            </div>
                            {/* <Table
                            style={{ height: '300px' }}
                            dataSource={this.state.consultLoc}
                            columns={this.columns}
                            pagination={false}
                            bordered
                        /> */}

                        </div>
                    </Modal>
                </div>
            )
        }
    })
export default ConsultationAuditModel