import { message } from "antd/lib/index";
import { Button, Descriptions, Row, Col, Form, Input, Select, Table } from 'antd';
import React from 'react';
import { initFilter, extendRule, extendInclude, setDataFieldValue, guid, initQueryFilter } from "../../../utils/common";
import ReactToPrint from "react-to-print";
import styles from '../HI/StepForm.css';
import config from "../../../config";
import XLSX from 'xlsx';
import moment from 'moment';
import { connect } from 'dva';
import FormPage from '../../../components/FormPage'
class HM099ShowPrint extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: null,
            tmpData: {},
            BtnAgreeDisplay: 'none',
            areas: [],
            users: [],
        };
    };

    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);
        }
    }
    onTableBtnAgree() {
        this.props.dispatch({
            type: 'app/getDataByPost',
            url: 'HM/HazardRecord/PersonalAgree',
            payload: {
                ID: this.props.data.id,
                TaskID: this.props.data.TaskID,
            },
            onComplete: (ret) => {
                if (ret) {
                    message.success('确认成功');
                    this.setState({ BtnAgreeDisplay: 'none' })
                    this.BtnClose();
                }
            }
        })
    }
    onClickApprove = (appVisible) => {
        const newtmpData = {
            data: { id: this.props.data.id, isShow: true, key: guid(), appVisible: appVisible, BtnAgreeDisplay: 'inline' },
            formCode: "PF123",
        }
        this.setState({
            tmpData: newtmpData,
        });
    }
    BtnClose = () => {
        if (typeof this.props.data.onCancel != "undefined" && typeof this.props.data.onCancel == 'function')
            this.props.data.onCancel();
    }
    removeDuplicateObj(arr) {
        let obj = {};
        arr = arr.reduce((newArr, next) => {
            obj[next.USER_ID] ? "" : (obj[next.USER_ID] = true && newArr.push(next));
            return newArr;
        }, []);
        return arr;
    }
    loadData = (dataId) => {
        let json = initFilter(this.props.login.OrgId);
        extendRule(json, 'ID', 1, dataId);
        extendInclude(json, 'Nav_InitiatingDepartment');
        extendInclude(json, 'Nav_Users.Nav_User');
        extendInclude(json, 'Nav_Details.Nav_Area');
        extendInclude(json, 'Nav_Details.Nav_OccupationalRisk');
        extendInclude(json, 'Nav_Details.Nav_Identifying');
        extendInclude(json, 'Nav_Users.Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File');
        extendInclude(json, 'Nav_Files.Nav_ImgFile.Nav_File');
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'HM/HazardRecord/Get',
            onComplete: (ret) => {
                if (ret) {
                    if (this.props.data && this.props.data.loadDataDeal) {
                        this.props.data.loadDataDeal(1);
                    }
                    this.onClickApprove(false);
                    // let index = ret.Nav_Users.findIndex((item) =>
                    //     item.USER_ID == this.props.login.userId
                    // );
                    // if (index > -1) {
                    //     var areaid = ret.Nav_Users[index].AREA_ID;
                    //     ret.Nav_Users = ret.Nav_Users.filter(item => item.AREA_ID == areaid);
                    // }
                    let areas = [];
                    for (let i = 0; i < ret.Nav_Details.length; i++) {
                        areas.push(ret.Nav_Details[i].Nav_Area?.NAME);
                    };
                    this.state.areas = Array.from(new Set(areas));

                    ret.Nav_Users = this.removeDuplicateObj(ret.Nav_Users);
                    ret.Nav_Details = ret.Nav_Details.filter(item => item.HAZARD_STATUS == 0);
                    this.setState({ data: ret })
                    if (ret.ID) {
                        this.props.dispatch({
                            type: 'app/getDataByPost',
                            url: 'HM/HazardRecord/GetHazardRecord',
                            payload: {
                                ID: this.props.data.id,
                            },
                            onComplete: (result) => {
                                if (result != null) {
                                    if (result) {
                                        this.setState({ BtnAgreeDisplay: 'inline' })
                                    }
                                }
                            }
                        })
                    }
                }
            }
        });
    }
    BtnClose = () => {
        if (typeof this.props.data.onCancel != "undefined" && typeof this.props.data.onCancel == 'function')
            this.props.data.onCancel();
    }
    onTableBtnExport() {
        let TableWrap = document.getElementById('tableId' + this.props.data.id);
        let Table = TableWrap.getElementsByTagName('table')[0];
        const wb = XLSX.utils.table_to_book(Table);
        XLSX.writeFile(wb, "职业危害辨识记录表.xlsx")
    }

    render() {
        const { data } = this.state;
        return <div>
            <div style={{ padding: '10px' }}>
                <Button onClick={() => this.onClickApprove(true)} icon="export">审批详情</Button>
                <ReactToPrint
                    trigger={() => <Button type={'default'} icon={'printer'} >打印</Button>}
                    content={() => this.componentRef}
                />
                <Button onClick={() => this.onTableBtnExport()} icon="export" style={{ marginLeft: '8px' }}>导出</Button>
                <Button type="primary" style={{ display: this.state.BtnAgreeDisplay }} onClick={() => this.onTableBtnAgree()} icon="check" >确认</Button>

            </div>
            <div ref={el => (this.componentRef = el)} id={'tableId' + this.props.data.id} style={{ padding: '20px' }}>
                <h1 style={{ textAlign: 'center' }}>职业危害辨识记录表</h1>
                {
                    data ? <div>

                        <Descriptions size="middle" bordered>
                            <Descriptions.Item label="编号">{data.CODE}</Descriptions.Item>
                            <Descriptions.Item label="任务层级">{this.props.app.enums.FMDepartmentType.enums[data.LEVEL]}</Descriptions.Item>
                            <Descriptions.Item label="执行时间">{moment(data.START_TIME).format('YYYY-MM-DD') + '~' + moment(data.END_TIME).format('YYYY-MM-DD')}</Descriptions.Item>
                            <Descriptions.Item label="辨识区域" span={3}>{
                                this.state.areas && this.state.areas.map((item, i) => {
                                    if (i == (this.state.areas.length - 1)) {
                                        return item
                                    } else {
                                        return item + '  '
                                    }
                                })
                            }</Descriptions.Item>
                            <Descriptions.Item label="辨识人员" span={3}>{
                                data.Nav_Users && data.Nav_Users.map((item, i) => {
                                    if (i == (data.Nav_Users.length - 1)) {
                                        if (item.DEAL_STATUS == 0)
                                            return <label style={{ color: 'red' }} title='未签到'> {item.Nav_User.NAME}</label>
                                        else
                                            return item.Nav_User.NAME
                                    } else {
                                        if (item.DEAL_STATUS == 0)
                                            return <label style={{ color: 'red' }} title='未签到'>{item.Nav_User.NAME + '  '}</label>
                                        else
                                            return item.Nav_User.NAME + '  '
                                    }
                                })
                            }</Descriptions.Item>
                            <Descriptions.Item label="附件" span={3}> {
                                data.Nav_Files && data.Nav_Files.map((item, i) => {
                                    return <a width={'20%'} title={item.Nav_ImgFile.FILE_NAME} target='_blank' href={config.picServerHost + item.Nav_ImgFile.Nav_File.FILE_PATH} >{item.Nav_ImgFile.FILE_NAME} </a>
                                })
                            }</Descriptions.Item>
                        </Descriptions>
                        <table style={{ width: '100%', textAlign: 'center', marginTop: '10px' }} className={styles.PrintForm1}>
                            <tbody>
                                <tr className={styles.fontBold}>
                                    <td className={styles.fontBold}>序号</td>
                                    <td className={styles.fontBold}>区域</td>
                                    <td className={styles.fontBold}>职业危害名称</td>
                                    <td className={styles.fontBold}>职业危害位置</td>
                                    <td className={styles.fontBold}>暴露时间</td>
                                    <td className={styles.fontBold}>暴露限值</td>
                                    <td className={styles.fontBold}>暴露人数</td>
                                    <td className={styles.fontBold}>可能造成的职业风险</td>
                                </tr>
                                {
                                    data.Nav_Details && data.Nav_Details.map((item, index) => {
                                        return <tr>
                                            <td>{index + 1}</td>
                                            <td>{item.Nav_Area?.NAME}</td>
                                            <td>{item.Nav_Identifying.NAME}</td>
                                            <td>{item.HAZARD_POSITION}</td>
                                            <td>{item.EXPOSURE_TIME}</td>
                                            <td>{item.EXPOSURE_LIMIT_VALUE}</td>
                                            <td>{item.EXPOSURE_NUMBER}</td>
                                            <td>{item.Nav_OccupationalRisk ? item.Nav_OccupationalRisk.NAME : ''}</td>
                                        </tr>
                                    })
                                }
                            </tbody>
                        </table>
                        <table style={{ width: '100%', textAlign: 'center' }} className={styles.PrintForm1}>
                            <tbody>
                                <tr>
                                    <td style={{ width: '10%' }} className={styles.fontBold}>辨识人员签字</td>
                                    <td>{
                                        data.Nav_Users && data.Nav_Users.map((item, i) => {
                                            if (item.DEAL_STATUS == 1) {
                                                if (item.Nav_User != null && item.Nav_User.Nav_UserSignFiles[0] != null)
                                                    return <img width={'150px'} alt={item.Nav_User.NAME} src={config.picServerHost + item.Nav_User.Nav_UserSignFiles[0].Nav_ImgFile.Nav_File.FILE_PATH} />
                                                else
                                                    return <img width={'150px'} title={item.Nav_User.NAME} />
                                            }
                                        })
                                    }</td>
                                </tr>
                            </tbody>
                        </table>
                        <FormPage {...this.state.tmpData} />
                    </div> : null
                }
            </div>
        </div>
    }

}

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