import { message } from "antd/lib/index";
import { Button, Popconfirm, Row, Col, Checkbox, Radio, Form, Input, Select, Table, Upload, Icon } from 'antd';
import React from 'react';
import { initFilter, extendRule, extendInclude, setDataFieldValue, guid, initQueryFilter } from "../../../utils/common";
import { connect } from 'dva';
import config from "../../../config";

const Option = Select.Option;

class SE001EditPage extends React.Component {
    constructor(props) {
        super(props);
        let readonly = false;
        if (props.data.id !== "" && props.data.btnConfig && props.data.btnConfig.customParams) {
            let params = props.data.btnConfig.customParams;
            if (params.indexOf('VIEW=1') != -1) {
                readonly = true;
            }
        }
        this.state = {
            data: {

            },
            TYPE: null,
            NAME: "",
            TRAINNAME: "",
            ANSWER: null,
            USAGE: 0,
            SELECT_POINTS: [],
            SELECT_POSTS: [],
            SELECT_NOTIFYS: [],
            OPTIONS: [
                { label: "[A]", value: "" },
                { label: "[B]", value: "" },
                { label: "[C]", value: "" },
                { label: "[D]", value: "" },
                { label: "[E]", value: "" },
            ],
            FILE_ID: null,
            POINTS: [],
            POSTS: [],
            NOTIFYS: [],
            readonly: readonly,
        };
    };

    componentDidMount() {
        this.loadData();
        this.loadPoints();
        this.loadPosts();
        this.loadNotifys();
    }

    BtnClose = () => {
        if (typeof this.props.data.onCancel != "undefined" && typeof this.props.data.onCancel == 'function')
            this.props.data.onCancel();
    }
    loadPoints = () => {
        let json = initQueryFilter(this.props.login.OrgId, 1, 1000, "NAME", 0);
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'SE/TestEnumPoint/OrderPaged',
            onComplete: (ret) => {
                if (ret) {
                    this.setState({ POINTS: ret })
                }
            }
        });
    }
    loadPosts = () => {
        let json = initQueryFilter(this.props.login.OrgId, 1, 1000, "CODE", 0);
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'FM/UserPost/OrderPaged',
            onComplete: (ret) => {
                if (ret) {
                    this.setState({ POSTS: ret })
                }
            }
        });
    }
    loadNotifys = () => {
        let json = initQueryFilter(this.props.login.OrgId, 1, 1000, "CODE", 0);
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'SE/SETest/getNotifyNames',
            onComplete: (ret) => {
                if (ret) {
                    this.setState({ NOTIFYS: ret })
                }
            }
        });
    }

    loadData = () => {
        if (this.props.data.id == "")
            return;
        let json = initFilter(this.props.login.OrgId);
        extendRule(json, 'ID', 1, this.props.data.id);
        extendInclude(json, 'Nav_Posts');
        extendInclude(json, 'Nav_Posts.Nav_Post');
        extendInclude(json, 'Nav_Points');
        extendInclude(json, 'Nav_Points.Nav_Point');
        json.IgnoreDataRule = true;
        //extendInclude(json, 'Nav_File');
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'SE/Test/Get',
            onComplete: (ret) => {
                if (ret) {
                    let points = [];
                    let posts = [];
                    let notifys = [];
                    if (ret.Nav_Points) {
                        ret.Nav_Points.map(it => {
                            points.push(it.POINT_ID)
                        })
                    }
                    if (ret.Nav_Posts) {
                        ret.Nav_Posts.map(it => {
                            if (it.POST_ID)
                                posts.push(it.POST_ID)
                        })
                    }
                    if (ret.Nav_Posts) {
                        ret.Nav_Posts.map(it => {
                            if (it.POST_ID)
                                posts.push(it.POST_ID)
                        })
                    }
                    if(ret.TRAINNAME!=""){
                        ret.TRAINNAME?.split("、").map(item=>{
                            notifys.push(item)
                        })
                    }
                    let OPTIONS = this.state.OPTIONS;
                    OPTIONS[0].value = ret.OPTION_A;
                    OPTIONS[1].value = ret.OPTION_B;
                    OPTIONS[2].value = ret.OPTION_C;
                    OPTIONS[3].value = ret.OPTION_D;
                    OPTIONS[4].value = ret.OPTION_E;
                    this.setState({
                        data: ret,
                        TYPE: ret.TYPE,
                        NAME: ret.NAME,
                        ANSWER: ret.ANSWER,
                        FILE_ID: ret.FILE_ID,
                        USAGE: ret.USAGE,
                        OPTIONS: OPTIONS,
                        SELECT_POINTS: points,
                        SELECT_POSTS: posts,
                        SELECT_NOTIFYS: notifys,
                    })
                }
            }
        });
    }
    onSave = () => {
        if (-1 === [0, 1, 2].indexOf(this.state.TYPE)) {
            message.error(`请选择题型`);
            return;
        }
        if (!this.state.NAME || this.state.NAME.length == 0) {
            message.error(`请输入题目`);
            return;
        }

        if ((this.state.USAGE & 7) == 0) {
            message.error(`请选择适用表单`);
            return;
        }
        if (this.state.SELECT_POINTS.length == 0) {
            message.error(`请选择知识点`);
            return;
        }

        if (this.state.TYPE == 0) {
            if (this.state.ANSWER !== 1 && this.state.ANSWER !== 2) {
                message.error(`请选择答案`);
                return;
            }
        }
        if (this.state.TYPE == 1) {
            if (-1 == [1, 2, 4, 8, 16].indexOf(this.state.ANSWER)) {
                message.error(`请选择答案`);
                return;
            }
        }
        if (this.state.TYPE == 2) {
            if ((this.state.ANSWER & 0xf) == 0) {
                message.error(`请选择答案`);
                return;
            }
        }
        if (this.state.TYPE == 1 || this.state.TYPE == 2) {
            for (let it of this.state.OPTIONS) {
                if (it.value === '' && it.label != "[E]") {
                    message.error(`选项不可为空`);
                    return;
                }
            }
        }
        let data = JSON.parse(JSON.stringify(this.state.data));
        data.NAME = this.state.NAME;
        data.TYPE = this.state.TYPE;
        data.USAGE = this.state.USAGE;
        data.ANSWER = this.state.ANSWER;
        if (!data.ID) {
            data.ID = guid()
        }
        if (!data.ORG_ID) {
            data.ORG_ID = this.props.login.OrgId
        }

        //处理适用岗位
        if (!data.Nav_Posts) {
            data.Nav_Posts = [];
        }
        let posts = JSON.parse(JSON.stringify(this.state.SELECT_POSTS));
        let map = {};
        for (let it of data.Nav_Posts) {
            map[it.POST_ID] = true;
            if (-1 === posts.indexOf(it.POST_ID)) {
                it.IS_DELETED = true;
            }
        }
        for (let it of posts) {
            if (!map[it]) {
                data.Nav_Posts.push({
                    ID: guid(),
                    TEST_ID: data.ID,
                    POST_ID: it
                })
            }
        }
        //处理知识点
        if (!data.Nav_Points) {
            data.Nav_Points = [];
        }
        let points = JSON.parse(JSON.stringify(this.state.SELECT_POINTS));
        map = {};
        for (let it of data.Nav_Points) {
            map[it.POINT_ID] = true;
            if (-1 === points.indexOf(it.POINT_ID)) {
                it.IS_DELETED = true;
            }
        }
        for (let it of points) {
            if (!map[it]) {
                data.Nav_Points.push({
                    ID: guid(),
                    TEST_ID: data.ID,
                    POINT_ID: it
                })
            }
        }
        //处理培训名称
        data.TRAINNAME=this.state.SELECT_NOTIFYS.join("、");
        if (this.state.updateFileList && this.state.updateFileList.length > 0) {
            let item = this.state.updateFileList[this.state.updateFileList.length - 1];
            if (item.response && item.response.Data) {
                this.state.FILE_ID = item.response.Data
            }
        }
        data.FILE_ID = this.state.FILE_ID
        if (this.state.TYPE == 0) {
            data.OPTION_A = '';
            data.OPTION_B = '';
            data.OPTION_C = '';
            data.OPTION_D = '';
            data.OPTION_E = '';
        } else {
            data.OPTION_A = this.state.OPTIONS[0].value;
            data.OPTION_B = this.state.OPTIONS[1].value;
            data.OPTION_C = this.state.OPTIONS[2].value;
            data.OPTION_D = this.state.OPTIONS[3].value;
            data.OPTION_E = this.state.OPTIONS[4].value;
        }

        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: data,
            url: 'SE/SETest/FullUpdate',
            onComplete: (ret) => {
                if (ret) {
                    message.success('保存成功！');
                    this.state.data = {};
                    this.state.TYPE = null;
                    this.state.NAME = "";
                    this.state.ANSWER = null;
                    this.state.USAGE = 0;
                    this.state.SELECT_POINTS = [];
                    this.state.SELECT_POSTS = [];
                    this.state.SELECT_NOTIFYS = [];
                    this.state.TRAINNAME = "";
                    this.state.OPTIONS = [
                        { label: "[A]", value: "" },
                        { label: "[B]", value: "" },
                        { label: "[C]", value: "" },
                        { label: "[D]", value: "" },
                        { label: "[E]", value: "" },
                    ];
                    this.state.FILE_ID = null;
                    this.BtnClose();
                }
            }
        });
    }
    fmtEnum(name, value) {
        const enums = this.props.app.enums;
        if (!enums || !enums[name]) return '';
        return enums[name].enums[value] || '';
    }
    render() {

        const layout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 16 },
        };
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 14 },
        };
        const btnItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 14 },
            colon: false
        };
        const uploadFilesProps = {
            name: 'file',
            action: config.serviceHost + 'PF/File/UploadFile',
            data: { OrgId: this.props.login.OrgId },
            fileList: this.state.updateFileList,
            onChange: (info) => {
                this.setState({
                    updateFileList: info.fileList,
                });
                if (info.file.status === 'done') {
                    message.success(`${info.file.name} file uploaded successfully`);
                } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} file upload failed.`);
                }
            },
        };
        return (
            <Form {...layout}>
                <Form.Item label={'适用表单'} {...formItemLayout}>
                    <Checkbox disabled={this.state.readonly} checked={(this.state.USAGE & 1) !== 0} onChange={(evt) => {
                        if (!evt.target.checked) {
                            this.setState({ USAGE: this.state.USAGE & (~1) })
                        } else {
                            this.setState({ USAGE: this.state.USAGE | 1 })
                        }
                    }}>安全意识调查
                    </Checkbox>
                    <Checkbox disabled={this.state.readonly} checked={(this.state.USAGE & 2) !== 0} onChange={(evt) => {
                        if (!evt.target.checked) {
                            this.setState({ USAGE: this.state.USAGE & (~2) })
                        } else {
                            this.setState({ USAGE: this.state.USAGE | 2 })
                        }
                    }}>培训
                    </Checkbox>
                    <Checkbox disabled={this.state.readonly} checked={(this.state.USAGE & 4) !== 0} onChange={(evt) => {
                        if (!evt.target.checked) {
                            this.setState({ USAGE: this.state.USAGE & (~4) })
                        } else {
                            this.setState({ USAGE: this.state.USAGE | 4 })
                        }
                    }}>事故事件
                    </Checkbox>
                </Form.Item>
                <Form.Item label={'适用岗位'} {...formItemLayout}>
                    <Select disabled={this.state.readonly} value={this.state.SELECT_POSTS} mode="multiple" style={{ width: '100%' }}
                        onChange={(value) => {
                            this.setState({
                                SELECT_POSTS: value
                            });
                        }}
                        filterOption={(input, option) =>
                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                    >
                        {
                            this.state.POSTS.map(it => {
                                return <Option value={it.ID}>{it.NAME}</Option>
                            })
                        }
                    </Select>
                </Form.Item>
                <Form.Item label={'知识点'} {...formItemLayout}>
                    <Select disabled={this.state.readonly} value={this.state.SELECT_POINTS} mode="multiple" style={{ width: '100%' }} onChange={(value) => {
                        this.setState({
                            SELECT_POINTS: value
                        });
                    }}>
                        {
                            (this.state.USAGE & 1) !== 0 && (
                                <Select.OptGroup label="安全意识调查">
                                    {
                                        this.state.POINTS.filter(it => (it.TYPE & 1) === 1).map(it => {
                                            return <Option value={it.ID}>{it.NAME}</Option>
                                        })
                                    }
                                </Select.OptGroup>
                            )

                        }
                        {
                            (this.state.USAGE & 2) !== 0 && (
                                <Select.OptGroup label="培训">
                                    {
                                        this.state.POINTS.filter(it => (it.TYPE & 2) === 2).map(it => {
                                            return <Option value={it.ID}>{it.NAME}</Option>
                                        })
                                    }
                                </Select.OptGroup>
                            )
                        }
                        {
                            (this.state.USAGE & 4) !== 0 && (
                                <Select.OptGroup label="事故事件">
                                    {
                                        this.state.POINTS.filter(it => (it.TYPE & 4) === 4).map(it => {
                                            return <Option value={it.ID}>{it.NAME}</Option>
                                        })
                                    }
                                </Select.OptGroup>
                            )
                        }
                    </Select>
                </Form.Item>
                <Form.Item label={'培训名称'} {...formItemLayout}>
                    <Select disabled={this.state.readonly} value={this.state.SELECT_NOTIFYS} mode="multiple" style={{ width: '100%' }}
                        onChange={(value) => {
                            this.setState({
                                SELECT_NOTIFYS: value
                            });
                        }}
                        filterOption={(input, option) =>
                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                    >
                        {
                            this.state.NOTIFYS.map(it => {
                                return <Option value={it.NAME}>{it.NAME}</Option>
                            })
                        }
                    </Select>
                </Form.Item>

                <Form.Item label={'题型'} {...formItemLayout}>
                    <Select disabled={this.state.readonly} value={this.state.TYPE} style={{ width: '100%' }} onChange={(value) => {
                        this.setState({
                            TYPE: value
                        });
                    }}>
                        {
                            this.props.app.enums && this.props.app.enums.SETestTypeEnum && this.props.app.enums.SETestTypeEnum.options ?
                                this.props.app.enums.SETestTypeEnum.options.map(t => {
                                    return <Option value={t.value}>{t.label}</Option>
                                }) : null
                        }
                    </Select>
                </Form.Item>

                {
                    [0, 1, 2].indexOf(this.state.TYPE) !== -1 && (
                        <Form.Item label={'题目'} {...formItemLayout}>
                            <Input.TextArea disabled={this.state.readonly} rows={2} value={this.state.NAME} onChange={(e) => {
                                this.setState({
                                    NAME: e.target.value
                                });
                            }} />
                        </Form.Item>
                    )
                }
                {
                    (this.state.TYPE === 1 || this.state.TYPE === 2) && (
                        <Form.Item label={'选项'} {...formItemLayout}>
                            {
                                this.state.OPTIONS.map((it, idx) => {
                                    return (

                                        <Input disabled={this.state.readonly} addonBefore={it.label} value={it.value} onChange={(e) => {
                                            var options = this.state.OPTIONS;
                                            options[idx].value = e.target.value;
                                            this.setState({ OPTIONS: options });
                                        }}>
                                        </Input>
                                    )
                                })
                            }
                        </Form.Item>

                    )
                }
                {
                    [0, 1, 2].indexOf(this.state.TYPE) !== -1 && (
                        <Form.Item label={'答案'} {...formItemLayout}>
                            {
                                this.state.TYPE === 0 && (
                                    <Select disabled={this.state.readonly} value={this.state.ANSWER} style={{ width: '100%' }} onChange={(value) => {
                                        this.setState({
                                            ANSWER: value
                                        });
                                    }}>
                                        <Option value={1}>是</Option>
                                        <Option value={2}>否</Option>
                                    </Select>
                                )
                            }
                            {
                                this.state.TYPE === 1 && (
                                    <Radio.Group disabled={this.state.readonly} value={this.state.ANSWER} onChange={(evt) => {
                                        this.setState({ ANSWER: evt.target.value })
                                    }} >
                                        {
                                            this.state.OPTIONS.map((it, idx) => {
                                                return (<Radio value={1 << idx}>{it.label}</Radio>)
                                            })
                                        }
                                    </Radio.Group>
                                )
                            }
                            {
                                this.state.TYPE === 2 && (
                                    this.state.OPTIONS.map((it, idx) => {
                                        return (
                                            <Checkbox
                                                disabled={this.state.readonly}
                                                checked={(this.state.ANSWER & (1 << idx)) !== 0}
                                                onChange={(evt) => {
                                                    if (!evt.target.checked) {
                                                        this.setState({ ANSWER: this.state.ANSWER & (~(1 << idx)) })
                                                    } else {
                                                        this.setState({ ANSWER: this.state.ANSWER | (1 << idx) })
                                                    }
                                                }}>
                                                {it.label}
                                            </Checkbox>
                                        )
                                    })
                                )
                            }
                        </Form.Item>
                    )
                }
                {/* {
                    !this.state.readonly && (
                        <Form.Item label={'附件'} {...formItemLayout}>
                            <Upload {...uploadFilesProps}>
                                {
                                    <Button>
                                        <Icon type="upload" /> 上传附件
                                    </Button>
                                }
                            </Upload>
                        </Form.Item>
                    )
                } */}

                {
                    !this.state.readonly && (
                        <Form.Item label=' '  {...btnItemLayout}>
                            <Button type="primary" onClick={() => { this.onSave(); }}>
                                保存
                            </Button>
                        </Form.Item>
                    )
                }
            </Form>
        );
    }

}

export default connect(({ login, app }) => ({ login, app }))(SE001EditPage) 