import React from 'react';
import { connect } from 'dva';
import { Button, Icon, Upload, Form } from 'antd';
import config from "../../../config.js";
import storage from '../../../utils/storage';
import styles from '../HI/StepForm.css';
import { initFilter, extendRule, downLoad, extendInclude, setDataFieldValue, guid, initQueryFilter, showFiles, showApprove, showUserSign, showUsersSign } from "../../../utils/common";

class OH017Import extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            fileName: props.data.fileName,
            data: null,
            Msg: '',
            isMsgShow: false,
            url: props.data.url,
            isOk: true,
            id: props.data.id,
            TaskID: props.data.TaskID,
            dataBack: []
        }
    }

    getRequestHeaders = () => {
        // 请求参数
        const addHeader = 'Bearer ' + storage('lacal').getItem('accessToken').val
        const userId = storage('lacal').getItem('userid').val
        const user = storage('lacal').getItem('loginUserVerify').val
        const RootOrgId = storage('lacal').getItem('RootOrgId').val
        const orgId = storage('lacal').getItem('webOrgId').val
        const Tenant = storage('lacal').getItem('Tenant').val
        const headers = {
            // 'Content-Type': type === 'post' ? 'application/json' : 'application/x-www-form-urlencoded',
            Authorization: addHeader,
            userid: userId,
            username: user ? user.username : '',
            RootOrgId,
            orgId,
            Tenant: Tenant
        }
        return headers
    }

    fillImportData = (ret) => {
        if (!ret) {
            this.setState({
                data: [],
                selectedRowKeys: [],
                messages: '',
            })
            return;
        }
        if (ret.ErrorMessage) {
            this.setState({
                messages: ('错误：' + ret.ErrorMessage)
            });
        }
        let messages = '';
        if (ret.Data && ret.Data.MessageList && ret.Data.MessageList.length) {
            var tmps = [];
            ret.Data.MessageList.forEach((n, i) => {
                tmps.push(n);
            });
            messages = tmps.join('\n');
        }
        const selectedRowKeys = [];
        if (ret.Data && ret.Data.Data) {
            ret.Data.Data.forEach((n, i) => {
                selectedRowKeys.push(n.ID);
            });
        }
        this.setState({
            data: (ret.Data && ret.Data.Data ? ret.Data.Data : []),
            selectedRowKeys,
            messages
        });
    }

    componentDidMount() {
        if (this.props.data?.id)
            this.loadData(this.props.data?.id);
    }

    componentWillReceiveProps(NextProps) {
        if (NextProps.data?.id && this.props.data?.id != NextProps.data?.id) {
            this.loadData(NextProps.data?.id);
        }
    }
    loadData = (id) => {
        var orgId = this.props.login ? this.props.login.OrgId : '';   //登录后有存储登录信息
        let json = initFilter(orgId);
        extendRule(json, 'ID', 1, id);    //ID=‘’，字段，等于，条件值， 1代表=，2代表不等于，3小于，4小于等于，5大于，6大于等于，7以开始的Like,8以结束的Like，9包含 
        let that = this;
        let btndisplay = 'none';
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'OH/OHHealthExamResult/GetImportIni',
            onComplete: (ret) => {    //返回查询结果ret
                if (ret) {    //判断是否有记录
                    this.setState({   //设置setState全局变量
                        data: ret,      //将ret对象赋值给data, data供页面调用
                        isMsgShow: true,
                        dataBack: ret.Nav_ListResult
                    })
                }
            }
        });
    }

    // downLoad = (fileName) => {
    //     let link = document.createElement('a')
    //     // link.style.display=nonWhiteSpace
    //     link.href = config.picServerHost + '/' + fileName,
    //         document.body.appendChild(link)
    //     link.click()
    // }

    //渲染页面
    render() {
        const { data, Msg, fileName, isMsgShow, url, urlDown, isOk, dataBack, id, TaskID } = this.state;
        const enums = this.props.data.enums ? this.props.data.enums : this.props.app.enums;
        const that = this;
        const uploadProps = {
            name: 'file',
            action: config.serviceHost(url),
            data: { OrgId: this.props.login.OrgId, id: id, TaskID: TaskID },//, ImportConfigCode: configCode, delFlag: delFlag
            fileList: this.state.updateLoadFileList,
            accept: '.xls,.xlsx',
            headers: this.getRequestHeaders(),
            onChange(info) {
                var Msg = ''
                var isOk = true
                var dataBack = []
                if (info.file.status === 'done') {
                    if (info.file.response.IsSuccessful) {
                        // Msg = "【" + info.file.name + '】' + info.file.response.Data.Data
                        // message.info(`${info.file.name} 导入并保存成功`);
                        dataBack = info.file.response.Data

                    } else {
                        //失败
                        Msg = info.file.response.ErrorMessage
                        isOk = false
                        // message.error(`${info.file.response.ErrorMessage} `);
                    }
                } else if (info.file.status === 'error') {
                    isOk = false
                    if (info.file.response && info.file.response.ErrorMessage) {
                        Msg = "【" + info.file.name + '】导入错误，详情：' + info.file.response.ErrorMessage
                        // message.error(`${info.file.name} 导入错误，详情：${info.file.response.ErrorMessage}`);
                    }
                    else {
                        Msg = "【" + info.file.name + '】导入错误'
                    }
                }
                that.setState({
                    updateLoadFileList: info.fileList,
                    data: info,
                    Msg: '导入说明：' + Msg,
                    isMsgShow: true,
                    isOk: isOk,
                    dataBack: dataBack
                });
            },
        };

        return <div>
            <div style={{ padding: '10px' }}>
                <Form>
                    <table>
                        <tr >
                            <td>
                                <Upload  {...uploadProps}>
                                    <Button>
                                        <Icon type="upload" /> 选择数据
                                    </Button>
                                </Upload>
                            </td>
                            <td>
                                <Button onClick={() => { downLoad(config.picServerHost, fileName) }}>
                                    <Icon type="vertical-align-bottom" /> 下载模板  
                                </Button>
                            </td>
                        </tr>
                        {
                            isMsgShow ? (
                                isOk ? <tr >
                                    <td colSpan={2}>
                                        <div>{Msg}</div>
                                    </td>
                                </tr>
                                    :
                                    <tr style={{ color: 'red' }}>
                                        <td colSpan={2}>
                                            <div>{Msg}</div>
                                        </td>
                                    </tr>
                            )
                                : null
                        }
                    </table>
                </Form>
            </div>


            <div ref={el => (this.componentRef = el)} style={{ padding: '20px', paddingTop: '20px' }} id={'tableId' + this.props.data.id}>
                <h1 className={styles.showPrintHead}>体检结果导入</h1>
                {
                    <table className={styles.PrintFormLight}>
                        <tbody>
                            <tr className={styles.PrintFormLightTh}>
                                <td>体检批次</td>
                                <td>体检人员</td>
                                <td>身份证号</td>
                                <td>体检结论</td>
                                <td>结果描述</td>
                                <td>处理意见</td>
                            </tr>
                            {dataBack?.map((item, i) => {
                                return <tr>
                                    <td>{item.Nav_NoticeRegister?.Nav_ExamBatch?.BATCH}</td>
                                    <td>{item.Nav_User?.NAME}</td>
                                    <td>{item.Nav_User?.ID_CARD} </td>
                                    <td>{item.RESULT_ENUM == 0 ? '' : enums.OHHealthExamResult.enums[item.RESULT_ENUM]} </td>
                                    <td>{item.DESCRIPTION} </td>
                                    <td>{item.SUGGESTION} </td>
                                </tr>
                            })}
                        </tbody>
                    </table>
                }
            </div>


        </div>
    }
}
export default connect(({ login, app }) => ({ login, app }))(OH017Import) 