/*
 * Creator:     ML
 * CreatDate:   2020-05-16
 * descripts：  互联网坐诊--- 咨询模板 快捷回复模板
*/
import React from 'react';
import { Form, Row, Col, Input, Select, DatePicker, Button, Popconfirm, Table, message, Divider, Spin, Icon } from 'antd';
import { $http } from '../../../containers/config/https';
import moment from 'moment';
const { TextArea } = Input;
const ConsultationTemplate = Form.create()(
    class ConsultationTemplate extends React.Component {
        cacheOriginData = {};
        constructor(props) {
            super(props)
            let userData = sessionStorage.getItem("userData") ? JSON.parse(sessionStorage.getItem("userData")) : {};
            this.state = {
                userData,
                recordData: [],
                rightData: [],
                selectedRowKeys_right: [],//右侧勾选中行
                selectedRow_right: [],
                btnStatus: true,
                isAdd: false,//是否点击添加
                disAdd: false,//是否可新增
                canSaveStatus: true,//能否保存
                loadingDom:false,
            }
            this.diagInput = React.createRef();
        }
        componentDidMount() {
            this.getData()
            this.props.onConsultationTemplate(this)
        }
        getData = () => {
            let { userData } = this.state;
            let data = {}
            data = {
                "params": [{
                    hospID: userData && userData.hospID || "",
                    locID: userData && userData.locID || "",
                    userID: userData && userData.userID || "",
                }]
            };
            $http.post('urlDeault', this, {
                code: "03100028",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        res.result.data && res.result.data.map((item, i) => {
                            item.key = item.ID
                        })
                        this.setState({
                            rightData: res.result.data
                        })
                    }
                }
            });
        }
        //国际化
        setMessage(name, message) {
            return this.props.localeProvider ? this.props.localeProvider[name][message] : ''
        }
        //点击右侧表格行
        onClickRightRow = (record) => {
            const { rightData } = this.state
            return {
                onClick: () => {
                    this.setState({
                        initRored: record
                    })
                    if (this.state.selectrow === "") {
                        this.setState({
                            selectrow: record.id,
                        }, () => {
                        });
                    } else {
                        if (this.state.selectrow !== record.id) {
                            this.setState({
                            }, () => {
                            });
                        } else {
                            this.setState({
                                selectrow: "",
                            });
                        }
                    }
                },
            }
        }
        setRowClassNames = (record) => {
            return (("^" + this.state.selectedRowKeys_right.join("^") + "^").indexOf("^" + record.seqNo + "^") > -1) ? 'clickRowStyle' : '';
            // return record.ordTempletDetailTemplItemTypeID === this.state.selectedRowKeys_right ? 'clickRowStyle' : '';
        }
        //编辑 
        toggleEditable = (e, record) => {
            e.preventDefault();
            this.setState({
                ordTempletDetailItemDesc: record.diagDesc,
                ordTempletDetailID: record.seqNo,
            })
            const { rightData } = this.state;
            const newData = rightData.map(item => ({ ...item }));
            const target = this.getRowByKey(record.ID, newData);
            if (target) {
                if (!target.editable) {
                    this.cacheOriginData[record.ID] = { ...target };
                }
                target.editable = !target.editable;
                this.setState({
                    rightData: newData,
                })
            }
            this.getFocusDom(e, record)
            // setTimeout(() => {
            //     this.diagInput.current.focus();
            // }, 300)
        }
        //光标定位到文本最后 
        getFocusDom = (e, record) => {
            var fDOM = document.getElementById(record.key);
            var len = record.templet.length;
            this.setSelectionRange(fDOM, len, len);
        }
        setSelectionRange = (input, selectionStart, selectionEnd) => {
            if (input.setSelectionRange) {
                input.focus();
                input.setSelectionRange(selectionStart, selectionEnd);
            }
            else if (input.createTextRange) {
                var range = input.createTextRange();
                range.collapse(true);
                range.moveEnd('character', selectionEnd);
                range.moveStart('character', selectionStart);
                range.select();
            }
        }
        //取消 
        cancel = (e, key) => {
            this.clickedCancel = true;
            e.preventDefault();
            const { rightData } = this.state;
            const newData = rightData.map((item) => ({ ...item }));
            const target = this.getRowByKey(key, newData);
            if (this.cacheOriginData[key]) {
                Object.assign(target, this.cacheOriginData[key]);
                delete this.cacheOriginData[key];
            }
            target.editable = false;
            this.setState({ rightData: newData, canSaveStatus: true, disAdd: false, });
            this.ClickedCancel = false;
        }
        //删除 
        cut = (e, key) => {
            const { rightData } = this.state;
            const newData = rightData.filter(item => item.key !== key);
            let bs = false
            newData.map((item, i) => {
                if (item.seqNo && item.editable && item.editable == true) {
                    bs = true
                    this.setState({
                        canSaveStatus: false,
                        disAdd: false,
                        rightData: newData,
                    })
                    return
                }
            })
            if (!bs) {
                this.setState({ rightData: newData, disAdd: false, canSaveStatus: true, });
            }
        }
        //新增
        addOrd = () => {
            const { rightData, rowId, userData } = this.state;
            const newData = {
                // templateID: rowId,
                ID: "",
                templet: "",
                key: rightData && rightData.length > 0 ? rightData.length + 1 : 1,
                seqNo: rightData && rightData.length > 0 ? rightData.length + 1 : 1,
                editable: true,
                isAdd: true,
                docDesc: userData && userData.userName || "",
                userID: userData && userData.userID || "",
                hospDesc: userData && userData.hospDesc || "",
                hospID: userData && userData.hospID || "",
                locDesc: userData && userData.locDesc || "",
                locID: userData && userData.locID || "",
                startDate: moment(moment()).format('YYYY-MM-DD'),
                stopDate: "",
                // note: ""
                // seqNo: 1
                // startDate: "2020-04-27"
                // stopDate: ""
                // templet: "你好!"
                // templetCat: ""
                // userCount: 2
            }
            this.setState({ ordTempletDetailID: "", ordDetailValue: "", isAdd: true, disAdd: false, ordTemPrice: 0, rightData: [...rightData, newData] }, () => {
                setTimeout(() => {
                    this.diagInput.current.focus();
                }, 300)
            });
        }
        //获取操作行数据对象
        getRowByKey(key, newData) {
            const { rightData } = this.state;
            return (newData || rightData).filter(item => item.key === key)[0];
        }
        //文本框数据修改
        handleFieldChange = (e, fieldName, key) => {
            const { rightData } = this.state;
            const newData = rightData.map(item => ({ ...item }));
            const target = this.getRowByKey(key, newData);
            if (target) {
                target[fieldName] = e.target.value;
                this.setState({
                    rightData: newData,
                    canSaveStatus: false,
                    ordDetailValue: e.target.value
                })

            }
        }
        //保存/修改
        handleSave = () => {
            const { rightData, rowId } = this.state
            this.setState({
                loadingDom:true
            })
            let data = {}
            data = {
                params: rightData,
            }
            $http.post('urlS', this, {
                code: '03100025',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            selectedRowKeys_right: [],
                            btnStatus: true,
                            canSaveStatus: true
                        })
                        message.success("保存成功")
                        this.getData()
                        this.setState({
                            selectedRowKeys_right: [],
                            btnStatus: true,
                            disAdd: false,
                            canSaveStatus: true,
                            loadingDom:false
                        })
                    }else{
                        this.setState({
                            loadingDom:false
                        })
                    }
                },error:function(){
                    this.setState({
                        loadingDom:false
                    })
                }
            })
        }
        //删除
        handleDetele = () => {
            const { selectedRow_right, userData } = this.state
            let arr = []
            if (selectedRow_right && selectedRow_right.length > 0) {
                selectedRow_right.map(item => {
                    arr.push(item.ID)
                })
                let data = {
                    params: [{
                        userID: userData && userData.userID || "",
                        ID: arr
                    }]
                }
                $http.post('urlS', this, {
                    code: '03100026',
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success('删除成功');
                            this.getData()
                            this.setState({
                                selectedRowKeys_right: [],
                                btnStatus: true,
                                canSaveStatus: true,
                                disAdd: false,
                                // ordShow:false,
                            })
                        }
                    },
                    error: function (error) {
                        message.error('删除失败：' + error);
                    }
                })
            }
        }
        render() {
            const { } = this.state
            let localeData = this.props.localeProvider
            const rowSelection_right = {
                selectedRowKeys: this.state.selectedRowKeys_right,
                onChange: (selectedRowKeys, selectedRows) => {
                    let btnStatus = false;
                    let canSaveStatus = false;
                    let selectrow = "";
                    if (selectedRowKeys.length === 0) {
                        btnStatus = true;
                        canSaveStatus = true;
                    } else {
                        selectrow = selectedRowKeys[selectedRowKeys.length - 1];
                    }
                    this.setState({ btnStatus: btnStatus, canSaveStatus: canSaveStatus, selectrow: selectrow, selectedRow_right: selectedRows, selectedRowKeys_right: selectedRowKeys });
                },
                onSelectAll: (selected, selectedRows, changeRows) => {
                    if (selectedRows.length > 0) {
                        this.setState({
                            btnStatus: false,
                            canSaveStatus: false,
                        })
                    } else {
                        this.setState({
                            btnStatus: true,
                            canSaveStatus: true,
                        })
                    }
                    this.setState({ selectedRow_right: selectedRows });
                }
            };
            const Columns = [
                {
                    width: 50,
                    align: "center",
                    title: '序号',
                    dataIndex: 'seqNo',
                    key: 'seqNo',
                    render: (text, record, index) => {
                        if (record.seqNo) {
                            return (
                                <span>{record.seqNo}</span>
                            )
                        }
                        return text;
                    },
                },
                {
                    align: "center",
                    title: '模板内容',
                    dataIndex: 'templet',
                    key: 'templet',
                    editable: true,
                    render: (text, record, index) => {
                        if (record.editable) {
                            return (
                                <TextArea ref={this.diagInput} id={record.key} value={text} onChange={(e) => this.handleFieldChange(e, 'templet', record.key)} />
                            )
                        } if (!record.editable) {
                            return (
                                <TextArea readOnly id={record.key} style={{ resize: "none", border: "0" }} value={text} />
                            )
                        }
                        return text;
                    },
                },
                {
                    title: '操作',
                    dataIndex: 'operation',
                    align: "center",
                    key: 'operation',
                    width: 80,
                    render: (text, record, index) => {
                        if (record.isAdd) {
                            return (
                                   <Popconfirm title="删除不可恢复，您确定要删除吗?" onConfirm={(e) => this.cut(e, record.key)}>
                                   <a style={{ color: "red" }} >删除</a>
                               </Popconfirm>
                            )
                        }
                        if (!record.editable) {
                            return (
                                <span style={{ textAlign: "center" }}>
                                    <a onClick={(e) => this.toggleEditable(e, record)}>编辑</a>
                                </span>
                            )
                        } else {
                            return (
                                <span style={{ textAlign: "center" }}>
                                    <a onClick={(e) => this.cancel(e, record.key)}>取消</a>
                                </span>
                            )
                        }
                    }
                }
            ];
            return (
                <Spin spinning={this.state.loadingDom} tip="加载中...">
                <div className="template">
                    <Row style={{ margin: "12px 0" }} className="editSpan">
                        <Button disabled={this.state.disAdd} onClick={this.addOrd} size="small" style={{ border: "0" }}> <Icon className='add-splice' />添加</Button>
                        <Divider type="vertical" />
                        <Popconfirm title="删除不可恢复，您确定要删除吗?" onConfirm={() => this.handleDetele()}>
                        <Button disabled={this.state.btnStatus} size="small" style={{ marginRight: '10px', background: "#fff", border: "0" }}>
                            <Icon className="delete-splice" />删除</Button>
                               </Popconfirm>
                        <Button disabled={this.state.canSaveStatus} onClick={this.handleSave} size="small" type="primary" style={{ float: "right" }}>保存</Button>
                    </Row>
                    <Table
                        bordered
                        columns={Columns}
                        pagination={false}
                        rowClassName={this.setRowClassNames}
                        onRow={this.onClickRightRow}
                        // expandedRowRender={expandedRowRender}
                        dataSource={this.state.rightData}
                        rowKey={record => record.seqNo}
                        rowSelection={rowSelection_right}
                        className="clearBackground"
                    />
                </div>
                </Spin>
            )
        }
    })
export default ConsultationTemplate    