import React from 'react';
import { connect } from 'dva';
import MultiSelectPagination from '../../common/MultiSelectPagination';
import { Button, Row, Col, Form, Input, Select, Modal, Transfer, Spin, Tooltip, Table, DatePicker, InputNumber, message, Upload, Icon } from 'antd';
import {
    getDataFieldValue,
    setDataFieldValue,
    initQueryFilter,
    guid,
    initFilter,
    extendRule, extendInclude, extendIgnoreDataRule
} from "../../../utils/common";

const { Option } = Select;
const { TextArea } = Input;

class CM026Edit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {},
            abilityProjectList: [],
            abilityUserNameList: [],
            abilityUserList: []
        };
    };
    isEditing = (record) => {
        return record.key === this.state.editingKey;
    };
    componentDidMount() {
        this.loadData();

    };
    loadUsers() {
        const orgId = this.props.login.OrgId;
        let jsonUser = initFilter(orgId, 1, 100, "CODE", 0);
        // 参会人员基础表数据
        this.props.dispatch({
            type: 'app/getDataByPost',
            url: 'FM/User/Entities',
            payload: jsonUser,
            onComplete: (ret) => {
                if (ret) {
                    this.setState({ abilityUserList: ret })
                }
            }
        });
    }
    loadData = () => {
        var id = this.props.data.id
        this.loadUsers();
        const orgId = this.props.login.OrgId;
        let json = initFilter(orgId);
        // 编辑页面
        if (id && id.length > 0) {
            extendRule(json, 'ID', 1, id);
            extendInclude(json, 'Nav_Users');
            extendInclude(json, 'Nav_Users.Nav_User');
            extendInclude(json, 'Nav_ListProject');
            extendInclude(json, 'Nav_ListProject.Nav_EvaluateProject');
        }
        extendIgnoreDataRule(json)
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: (id && id.length > 0) ? 'CM/AbilityEvaluate/Get' : 'CM/CMAbilityEvaluate/GetNew',
            onComplete: (ret) => {
                if (ret) {
                    this.state.data = ret
                    var abilityEvaluateProjectList = [];
                    for (let i = 0; i < ret.Nav_ListProject.length; i++) {
                        var p = {};
                        p.NUM = i;
                        p.NAME = ret.Nav_ListProject[i].Nav_EvaluateProject.NAME;
                        p.CODE = ret.Nav_ListProject[i].Nav_EvaluateProject.CODE;
                        p.EVALUATE_CONTENT = ret.Nav_ListProject[i].Nav_EvaluateProject.EVALUATE_CONTENT;
                        p.EVALUATE_PROJECT_ID = ret.Nav_ListProject[i].EVALUATE_PROJECT_ID;
                        p.PLATFORM_TYPE = ret.Nav_ListProject[i].PLATFORM_TYPE;
                        p.REMARK = ret.Nav_ListProject[i].REMARK;
                        p.ID = ret.Nav_ListProject[i].ID;
                        abilityEvaluateProjectList.push(p);
                    }

                    abilityEvaluateProjectList.sort(function (a, b) {
                        var x = a.CODE.toLowerCase();
                        var y = b.CODE.toLowerCase();
                        if (x < y) { return -1; }
                        if (x > y) { return 1; }
                        return 0;
                    });
                    let span = [];
                    let idx = 0;
                    for (let i = 0; i < abilityEvaluateProjectList.length; i++) {
                        span[i] = 1;
                        if (i > 0) {
                            if (abilityEvaluateProjectList[i].NAME === abilityEvaluateProjectList[i - 1].NAME) {
                                span[idx]++;
                                span[i] = 0;
                            } else {
                                idx = i;
                            }
                        }
                    }


                    this.setState({
                        abilityProjectList: abilityEvaluateProjectList,
                        span: span
                    })

                    var userNameList = []
                    for (let i = 0; i < ret.Nav_Users.length; i++) {
                        userNameList.push(ret.Nav_Users[i].Nav_User.ID)
                    }
                    this.setState({ abilityUserNameList: userNameList })

                }
            }
        });

    };
    GetTypeCount = () => {
        const dataSource = this.state.abilityProjectList;
        let id = '';
        if (dataSource && dataSource.length > 0) {
            for (let m = 0; m < dataSource.length - 1; m++) {
                if (m == 0) {
                    id = dataSource[m].CODE.substr(0, 2)
                }
                if (id != dataSource[m].CODE.substr(0, 2)) {
                    return m;
                }
            }
        }
    }
    // 下拉选择
    onSelectChange = (v, r, filed, index) => {
        if (filed == 'PLATFORM_TYPE') {
            let data = this.state.abilityProjectList;
            data[index][filed] = v;
            this.setState({ abilityProjectList: data })
        }
    }

    // 输入框输入
    onInputChange = (v, r, filed, index) => {
        let data = this.state.abilityProjectList;
        data[index][filed] = v.target.value;
        this.setState({ abilityProjectList: data })
    }

    BtnClose = () => {
        // debugger
        // if (typeof this.props.closeFn != "undefined")
        //     this.props.closeFn();
        // else if (typeof this.props.data.closeTab == 'function') {
        //     this.props.data.closeTab(this.props.data.id)
        // } else if (typeof this.props.onCancel === "function") {
        //     this.props.onCancel();
        // }
        if (typeof this.props.data.onCancel != "undefined" && typeof this.props.data.onCancel == 'function')
            this.props.data.onCancel();
    }


    //保存
    onSave = (state) => {
        let data = this.state.data, flag = true;
        data.STATUS = state
        let project = this.state.abilityProjectList
        if (!this.state.abilityUserNameList || this.state.abilityUserNameList.length == 0) {
            message.warn('请选择评估人员！');
            flag = false;
            return false;
        }
        if (data.STATUS != 0) {
            for (let i = 0; i < project.length; i++) {
                if (project[i].PLATFORM_TYPE == undefined || project[i].PLATFORM_TYPE == -1) {
                    message.warn('请选择评估情况，行：' + (i + 1) + '！');
                    flag = false;
                    return false;
                }
            }
        }
        if (!flag) {
            return false;
        }
        data.NAME = '应急能力评估'

        //更新评估用户数据
        if (!data.Nav_Users) {
            data.Nav_Users = [];
        }
        data.Nav_Users.forEach(it => {
            if (this.state.abilityUserNameList.indexOf(it.USER_ID) == -1) {
                it.IS_DELETED = true;
            }
        })
        this.state.abilityUserNameList.forEach(uid => {
            let it = data.Nav_Users.find(it => it.USER_ID === uid);
            if (!it) {
                data.Nav_Users.push({
                    ID: guid(),
                    ORG_ID: this.props.login.OrgId,
                    ABILITY_EVALUATE_ID: data.ID,
                    USER_ID: uid,
                })
            }
        })

        //回写评价数据
        data.Nav_ListProject.forEach(it => {
            var newData = project.find(i => i.ID === it.ID);
            if (newData) {
                it.PLATFORM_TYPE = newData.PLATFORM_TYPE;
                it.REMARK = newData.REMARK;
            }
        })
        if (this.props.data && this.props.data.TaskID) {
            data.TaskID = this.props.data.TaskID
        }
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: data,
            url: 'CM/CMAbilityEvaluate/FullUpdate',
            onComplete: (ret) => {
                if (ret) {
                    message.success('保存成功！');
                    this.BtnClose();
                }

            }
        });
    }

    syncClick = () => {
        const { abilityProjectList } = this.state;
        let arr = [];
        abilityProjectList.map((item, index) => {
            let obj = {
                ...item,
                PLATFORM_TYPE: abilityProjectList[0].PLATFORM_TYPE,
            };
            arr.push(obj)
        });
        this.setState({ abilityProjectList: arr })
    }

    render() {
        const { form, location, match, loading, formCode, data } = this.props;
        const enums = this.props.app.enums;
        const formItemLayout = {
            labelCol: { span: 2 },
            wrapperCol: { span: 22 },
        };
        const onChangeConclusion = (e) => {
            let data = this.state.data;
            if (data) {
                data.OVERALL_EVALUATE_CONCLUSION = e.target.value;
                this.setState(data);
            }
        }
        const columns = [
            {
                width: 200, title: '评估项目', dataIndex: 'NAME', key: 'NAME', render: (t, r, i) => {
                    const obj = {
                        children: t,
                        props: {},
                    };
                    obj.props.rowSpan = this.state.span[i];
                    return obj;
                }
            },
            { width: 200, title: '评估内容', dataIndex: 'EVALUATE_CONTENT', key: 'EVALUATE_CONTENT' },
            {
                width: 100,
                title: (<div>评估情况<Tooltip title="同步第一行数据">
                    <Icon type="sync" onClick={this.syncClick} style={{
                        fontSize: '12px',
                        marginLeft: '8px'
                    }} />
                </Tooltip></div>),
                dataIndex: 'PLATFORM_TYPE', key: 'PLATFORM_TYPE', render: (text, record, index) => {
                    return <Select value={text != "-1" ? text : ""} optionFilterProp='name' onChange={(e) => this.onSelectChange(e, record, 'PLATFORM_TYPE', index)}>
                        {
                            enums && enums.CMEvaluateStatusEnum && enums.CMEvaluateStatusEnum.options ? enums.CMEvaluateStatusEnum.options.map(t => {
                                return <Option value={t.value}>{t.label}</Option>
                            }) : null
                        }
                    </Select>;
                }
            },
            {
                width: 300, title: '备注', dataIndex: 'REMARK', key: 'REMARK', render: (text, record, index) => {
                    return <Input value={text} onChange={(e) => { this.onInputChange(e, record, 'REMARK', index) }} />
                }
            }
        ];

        const tableColumns = columns.map((col) => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    inputType: col.dataIndex === 'PLATFORM_TYPE' ? 'Select' : 'text',
                    dataIndex: col.dataIndex,
                    title: col.title,
                    editing: this.isEditing(record),
                }),
            };
        });

        return (
            <div>
                <Form style={{ margin: "0 25px 0 25px" }}>
                    <Row style={{ marginTop: 10, lineHeight: '60px', borderBottom: '1px solid #1890ff' }}>
                        <Button type='primary' icon='save' onClick={() => this.onSave(0)}>保存</Button>
                        <Button style={{ margin: "0 0 0 25px" }} icon='save' type='primary' onClick={() => this.onSave(10)}>保存并发送</Button>
                    </Row>
                    <Row style={{ margin: "10px 0 0 0" }}>
                        <Col span={24}>
                            <Form.Item label={'评估人员'} {...formItemLayout}>
                                <Select value={this.state.abilityUserNameList} style={{ width: '100%' }} mode="multiple"
                                    onChange={value => this.setState({ abilityUserNameList: value })}
                                    filterOption={(input, option) =>
                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {
                                        this.state.abilityUserList ? this.state.abilityUserList.map(d => (
                                            <Option key={d.ID} value={d.ID} label={d.NAME}>
                                                {d.NAME}
                                            </Option>
                                        )) : ''
                                    }
                                </Select>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Table
                            rowKey="ID"
                            pagination={false}
                            dataSource={this.state.abilityProjectList}
                            columns={tableColumns}
                            rowClassName="editable-row"
                            bordered
                        />
                    </Row>
                    <Row style={{ marginTop: 24 }}>
                        <Col span={24}>
                            <Form.Item label={'总体评估结论'} {...formItemLayout} >
                                <TextArea value={this.state.data.OVERALL_EVALUATE_CONCLUSION != null ? this.state.data.OVERALL_EVALUATE_CONCLUSION : ''} rows={2} onChange={onChangeConclusion} />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>
        );
    }
}
export default connect(({ login, loading, custom, app }) => ({ login, loading, custom, app }))(Form.create()(CM026Edit));
