import React from 'react';
import { Button, Icon, Modal, message, Checkbox, Pagination } from 'antd';
import { WeaTools, WeaLocaleProvider, WeaUpload } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
import * as _ from 'lodash';

class MaterialLibRight extends React.Component {
    state = { data: [], pageCurrent: 1, pageSize: 10, pageTotal: 0, checkedFiles: [], edit: false, file: {} };

    constructor(props) {
        super(props);
        this.getFiles = this.getFiles.bind(this);
        this.onPageCurrentChange = this.onPageCurrentChange.bind(this);
        this.onPageSizeChange = this.onPageSizeChange.bind(this);
        this.onCheck = this.onCheck.bind(this);
        this.onEdit = this.onEdit.bind(this);
        this.onChange = this.onChange.bind(this);
        this.onSave = this.onSave.bind(this);
        this.onDelete = this.onDelete.bind(this);
        this.onCancel = this.onCancel.bind(this);
        this.getCheckedFiles = this.getCheckedFiles.bind(this);
    }

    componentWillMount() {
        this.getFiles(this.props.dir);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.dir != this.props.dir) {
            this.getFiles(nextProps.dir);
        }
    }

    componentDidUpdate() {
        const input = this.refs.EditInput;
        input && input.focus();
    }

    render() {
        const { hasRight, dir } = this.props;
        const { data = [], pageCurrent, pageSize, pageTotal, checkedFiles, edit, file } = this.state;
        const disabled = !(checkedFiles && checkedFiles.length);

        let row = [],
col = [];
        for (let i = 0, len = data.length; i < len; i++) {
            col.push(data[i]);
            if (i % 5 == 4 || i == len - 1) {
                row.push(col);
                col = [];
            }
        }

        return (
            <div className="portal-p4e-mlr">
                {
                    hasRight ? (
                            <div className="portal-p4e-mlr-top">
                                <div className="portal-p4e-mlr-btns">
                                    <WeaUpload
                                      uploadId="uploadFile"
                                      uploadUrl={`/api/portal/materialLib/uploadFile?dir=${dir}`}
                                      category="string"
                                      multiSelection={true}
                                      maxUploadSize={100}
                                      showClearAll={false}
                                      autoUpload={true}
                                      limitType="jpg,jpeg,gif,ico,bmp,png,flv,mp3,swf,mp4,wmv"
                                      onChange={() => this.getFiles(dir)}
                                      style={{ display: 'inline-block', paddingTop: 0 }}
                                    >
                                        <Button type="primary" className="portal-p4e-mlr-btn" style={{ backgroundColor: '#55a1f8' }}>
                                            <Icon type="plus" />
                                        </Button>
                                    </WeaUpload>
                                    <Button type="primary" disabled={disabled} className="portal-p4e-mlr-btn" style={{ backgroundColor: '#d8d8d8' }} onClick={() => this.onDelete()}>
                                        <Icon type="minus" />
                                    </Button>
                                </div>
                            </div>
                        ) : ''
                }
                <div className="portal-p4e-mlr-middle">
                    {
                        row && row.length ? (
                                <div className="portal-p4e-mlt-table">
                                    {
                                        row.map((row, index) => (
                                                <ul key={index} className="portal-p4e-mlt-tr">
                                                    {
                                                        row.map((col) => {
                                                            const checked = _.findIndex(checkedFiles, item => item.id == col.id) != -1;
                                                            return (
                                                                <li key={col.id} className="portal-p4e-mlt-td">
                                                                    <div className="portal-p4e-mlt-item" style={checked ? { border: '1px solid #408de2' } : {}} onClick={() => this.onCheck(col)}>
                                                                        <div className="portal-p4e-mlt-chk"><Checkbox checked={checked} /></div>
                                                                        <div className="portal-p4e-mlt-preview">
                                                                            <img className="portal-p4e-mlt-img" src={`/weaver/weaver.splitepage.transform.SptmForThumbnail?filerealpath=${col.filepath.substring(1)}`} alt="" />
                                                                        </div>
                                                                        {
                                                                            hasRight ? (
                                                                                    <div className="portal-p4e-mlt-opt">
                                                                                        <span className="portal-p4e-mlt-title">
                                                                                            {
                                                                                                col.id == file.id ? (
                                                                                                        edit ? (
                                                                                                                <input ref="EditInput"
                                                                                                                  defaultValue={col.filename}
                                                                                                                  onClick={e => e.stopPropagation()}
                                                                                                                  onChange={this.onChange}
                                                                                                                  onKeyDown={(e) => {
                                                                                                                           e.stopPropagation();
                                                                                                                           if (e.keyCode == 13) {
                                                                                                                               this.onSave();
                                                                                                                           }
                                                                                                                       }}
                                                                                                                />
                                                                                                            ) : `${file.filename_new}.${col.filetype}`
                                                                                                    ) : `${col.filename}.${col.filetype}`
                                                                                            }
                                                                                        </span>
                                                                                        {
                                                                                            col.id == file.id && edit ? (
                                                                                                    <span className="portal-p4e-mlt-edit"
                                                                                                      onClick={(e) => {
                                                                                                              e.stopPropagation();
                                                                                                              this.onSave();
                                                                                                          }}
                                                                                                    >
                                                                                                        <i className="icon-coms-complete" />
                                                                                                    </span>
                                                                                                ) : (
                                                                                                    <span className="portal-p4e-mlt-edit"
                                                                                                      onClick={(e) => {
                                                                                                              e.stopPropagation();
                                                                                                              this.onEdit(col);
                                                                                                          }}
                                                                                                    >
                                                                                                        <i className="icon-coms-edit" />
                                                                                                    </span>
                                                                                                )
                                                                                        }
                                                                                        {
                                                                                            col.id == file.id && edit ? (
                                                                                                    <span className="portal-p4e-mlt-delete"
                                                                                                      onClick={(e) => {
                                                                                                              e.stopPropagation();
                                                                                                              this.onCancel();
                                                                                                          }}
                                                                                                    >
                                                                                                        <i className="icon-coms-Reset" />
                                                                                                    </span>
                                                                                                ) : (
                                                                                                    <span className="portal-p4e-mlt-delete"
                                                                                                      onClick={(e) => {
                                                                                                              e.stopPropagation();
                                                                                                              this.onDelete(col.id);
                                                                                                          }}
                                                                                                    >
                                                                                                        <i className="icon-coms-delete" />
                                                                                                    </span>
                                                                                                )
                                                                                        }
                                                                                    </div>
                                                                                ) : (
                                                                                    <div className="portal-p4e-mlt-opt">
                                                                                        <span className="portal-p4e-mlt-title2">{`${col.filename}.${col.filetype}`}</span>
                                                                                    </div>
                                                                                )
                                                                        }

                                                                    </div>
                                                                </li>
                                                            );
                                                        })
                                                    }
                                                </ul>
                                            ))
                                    }
                                    <div style={{ clear: 'both' }} />
                                    <div style={{ position: 'absolute', right: 0, margin: '10px' }}>
                                        <Pagination
                                          showSizeChanger
                                          showQuickJumper
                                          current={pageCurrent}
                                          pageSize={pageSize}
                                          total={pageTotal}
                                          showTotal={total => `共 ${total} 条`}
                                          pageSizeOptions={['10', '20', '50', '100']}
                                          onChange={this.onPageCurrentChange}
                                          onShowSizeChange={this.onPageSizeChange}
                                        />
                                    </div>
                                </div>
                            ) : (
                                <div className="ant-table-placeholder">
                                    <i className="anticon anticon-frown" />{getLabel(0, '暂无数据')}
                                </div>
                            )
                    }
                </div>
            </div>
        );
    }

    getFiles(dir, pageCurrent, pageSize) {
        WeaTools.callApi('/api/portal/materialLib/getFiles', 'GET', {
            dir: dir || this.props.dir,
            pageCurrent: pageCurrent || this.state.pageCurrent,
            pageSize: pageSize || this.state.pageSize,
        }).then((result) => {
            this.setState({
                data: result.data,
                pageTotal: result.count,
                checkedFiles: [],
                edit: false,
                file: {},
            });
        });
    }

    onPageCurrentChange(pageCurrent) {
        this.setState({ pageCurrent });

        const { dir } = this.props;
        const { pageSize } = this.state;
        this.getFiles(dir, pageCurrent, pageSize);
    }

    onPageSizeChange(current, pageSize) {
        this.setState({ pageSize });

        const { dir } = this.props;
        const { pageCurrent } = this.state;
        this.getFiles(dir, pageCurrent, pageSize);
    }

    onCheck(file) {
        const { multiCheck = false } = this.props;
        let { checkedFiles } = this.state;

        if (_.findIndex(checkedFiles, item => item.id == file.id) != -1) {
            _.remove(checkedFiles, item => item.id == file.id);
        } else if (multiCheck) {
                checkedFiles.push(file);
            } else {
                checkedFiles = [file];
            }

        this.setState({ checkedFiles });
    }

    onEdit(file = {}) {
        this.setState({ edit: true, file: { ...file, filename_new: file.filename } });
    }

    onChange(e) {
        const { file } = this.state;
        this.setState({ file: { ...file, filename_new: e.target.value } });
    }

    onSave() {
        const { file } = this.state;
        const { filename_new = '' } = file;

        if (filename_new.trim() == '') {
            message.warning(getLabel(0, '必要信息不完整！'));
        } else if (!filename_new.toLowerCase().match(/^[0-9A-Za-z]+$/)) {
            message.warning(getLabel(0, '文件名称只能包含字母和数字'));
        } else {
            this.setState({ edit: false });
            WeaTools.callApi('/api/portal/materialLib/renameFile', 'POST', {
                ...file,
            }).then((result) => {
                if (result.api_status) {
                    message.success(getLabel(0, '操作成功'));
                    this.getFiles();
                } else {
                    message.warning(getLabel(0, '操作失败'));
                }
            });
        }
    }

    onDelete(ids) {
        const { checkedFiles = [] } = this.state;
        const chkIds = checkedFiles.map(item => item.id);
        ids = ids || chkIds.join(',');

        if (ids) {
            Modal.confirm({
                title: getLabel(0, '系统提示'),
                content: getLabel(0, '确定删除吗？'),
                onOk: () => {
                    WeaTools.callApi('/api/portal/materialLib/deleteFile', 'POST', {
                        ids,
                    }).then((result) => {
                        if (result.api_status) {
                            message.success(getLabel(0, '操作成功'));
                            this.getFiles();
                        } else {
                            message.warning(getLabel(0, '操作失败'));
                        }
                    });
                },
            });
        }
    }

    onCancel() {
        this.setState({ edit: false, file: {} });
    }

    getCheckedFiles() {
        return this.state.checkedFiles;
    }
}

export default MaterialLibRight;
