/**
 * 添加号源分发机制
 */

import React from 'react';
import { Table, Input, Select, Popconfirm, Icon, message } from 'antd';
import { $http } from 'containers/config/https';
import { hourFormat } from 'tools/index';
import moment from 'moment';
import './style/index.less';

const Option = Select.Option;

class AddMechanism extends React.Component {
    constructor(props) {
        super(props)
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            dataSource: [],
            data: [],
            bookMethodDetail: [],
            methodDetail: [],
            userData: userData
        }
    }

    componentDidMount() {
        this.props.onRef && this.props.onRef(this);
    }

    //获取切换的渠道参数
    changeSelect(index, e) {
        this.state.data[index]['methodFlag'] = 'insert';
        this.state.data[index]['BookMethodDr'] = e;
        this.state.data[index]['CreateUserDr'] = this.state.userData.userId;
        this.setState({
            methodDetailId: e
        })
    }

    //获取切换的时段ID
    changeTime(index, e) {
        var modelDetail = this.props.modelDetail;
        for (var i = 0; i < modelDetail.length; i++) {
            if (e == modelDetail[i].timeRangId) {
                this.state.data[index]['TimeRangName'] = modelDetail[i].timeRang
            }
        }
        this.state.data[index]['TimeRangeDr'] = e;
    }

    //获取开始时间
    changeStartTime(index, e) {
        this.state.data[index]['StartTime'] = moment(e).format(hourFormat)
    }

    //获取结束时间
    changeEndTime(index, e) {
        this.state.data[index]['StopTime'] = moment(e).format(hourFormat)
    }

    //获取分发号源参数
    onChangeAppintNum(index, e) {
        this.state.data[index]['AppointNum'] = e.target.value
    }

    //删除
    delMechansim(index) {
        if (this.state.data.length === 1) {
            this.state.data = [{}];
        } else {
            this.state.data.splice(index, 1);
            this.setState({})
        }
    }

    //通过渠道ID获取右边列表参数
    getMethodId(id) {
        var params = {
            params: [{
                deptDoctorId: this.props.deptDoctorId,
                regTitleId: this.props.regTitleId,
                bookMethodId: id
            }]
        }
        // var params = []
        $http.post('urlDeault', this, {
            code: "03020022",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        methodDetail: res.methodDetail
                    })
                }
            }
        });
        //获取当前渠道的id，用于删除数据后的页面渲染
        this.setState({
            methId: id
        })
    }

    //删除排版模板
    delMethedList(data) {
        var params = {
            params: [{
                ID: data.id,
                updateUser: this.state.userData.userId,
                className: 'User.BSWorkBookMethod'//应后端要求，写死
            }]
        }
        // var params = []
        $http.post('urlDeault', this, {
            code: "03020024",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    message.success('删除成功！')
                    this.getMethodId(this.state.methId);
                }
            }
        });
    }

    //添加号源分发机制
    addMechansim() {
        this.setState({
            addType: true
        })
        this.state.data.push({});
        this.setState({})
    }

    // 提交
    onSubmit(status) {
        var data = this.state.data;
        var { onSubmit } = this.props;
        onSubmit && onSubmit(data, status);
    }

    setMechanismData = (data) => {
        this.setState({ data });
    }

    // 向外输出分发机制数据
    getMechanismData = () => {
        const { data } = this.state;
        return data;
    }

    render() {
        let timeOption = []//渠道
        let methodOption = []//时段
        //取父级传过来的参数，push到渠道名称中
        this.props.bookMethodDetail && this.props.bookMethodDetail.map((item, index) => {
            timeOption.push(<Option key={index} value={item.id + ''}>{item.descripts}</Option>)
        })
        this.props.modelDetail && this.props.modelDetail.map((item, index) => {
            methodOption.push(<Option key={index} value={(item?.timeDetailID || item?.indexId) + ''}>{item.timeRangDetail}</Option>)
        })
        const columns = [
            {
                title: '渠道名称',
                dataIndex: 'BookMethodDr',
                width: 100,
                align: 'center',
                render: (text, data, index) => {
                    return (data.methodId ?
                        (<span style={{ cursor: 'pointer' }} onClick={this.getMethodId.bind(this, data.methodId)}>{data.descripts}</span>) :
                        <Select value={data?.BookMethodDr || undefined} style={{ width: '90%' }} placeholder="请选择渠道类型" showSearch={true}
                            onChange={this.changeSelect.bind(this, index)}
                            dropdownMatchSelectWidth={false}>
                            {timeOption}
                        </Select>
                    )
                }
            },
            {
                title: '时段',
                dataIndex: 'TimeRangeDr',
                width: 100,
                align: 'center',
                render: (text, data, index) => {
                    return data.id ? <span>{data.timeRange}</span> :
                        <Select style={{ width: '90%' }} placeholder="请选择时段" showSearch={true}
                            onChange={this.changeTime.bind(this, index)}
                            dropdownMatchSelectWidth={false}>
                            {methodOption}
                        </Select>
                }
            },
            {
                title: '分发号数目',
                dataIndex: 'AppointNum',
                width: 100,
                align: 'center',
                render: (text, data, index) => {
                    return data.id ? <span>{data.appointNum}</span> :
                        <Input onChange={this.onChangeAppintNum.bind(this, index)} style={{ width: '90%' }} placeholder='分发号数目' />
                }
            }, {
                title: '操作',
                dataIndex: 'operstion',
                width: 80,
                align: 'center',
                render: (text, data, index) => {
                    return (
                        this.state.methodDetail.length > 0 ?
                            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.delMethedList(data)} >
                                <span className="span">删除</span>
                            </Popconfirm> : <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.delMechansim(index)} >
                                <span className="span">删除</span>
                            </Popconfirm>
                    )
                }
            }
        ];

        return (
            <div className='addDoctorStyle'>
                <div><Icon type='plus' />
                    <span className='addMechanismColor' onClick={this.addMechansim.bind(this)}>添加号源分发机制</span></div>
                <div style={{ marginTop: '10px' }}>
                    <Table
                        scroll={{ x: 380 }}
                        columns={columns}
                        dataSource={this.state.data}
                        pagination={false}
                        style={{ width: '70%', minHeight: '200px' }}
                        rowKey={data => data.id}
                    />
                </div>
                {/* <div>{this.props.showBtn ? null :
                    <Button disabled={!this.props.saveStatus} className={!this.props.saveStatus?'disSaveBtn':'saveTableButton'}
                        onClick={this.onSubmit.bind(this, 'save')}>保存</Button>}</div> */}
            </div>
        )
    }
}

export default AddMechanism;