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 HM063ShowPrint extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: null,
            tmpData: {},
            BtnAgreeDisplay: 'none',
            areas: null
        };
    };

    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/HMRiskRecord/PersonalAgree',
            payload: {
                ID: this.props.data.id,
                TaskID: this.props.data.TaskID,
                LEVEL: this.state.data.LEVEL,
            },
            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();
    }
    renderLevel(level) {
        var str = "";
        if (level == 0) {
            str = '部门级';
        }
        if (level == 1) {
            str = '车间级';
        }
        if (level == 2) {
            str = '班组级';
        }
        if (level == 3) {
            str = '公司级';
        }
        return str;
    }
    loadData = (dataId) => {
        let json = initFilter(this.props.login.OrgId);
        extendRule(json, 'ID', 1, dataId);
        extendInclude(json, 'Nav_Request');
        extendInclude(json, 'Nav_Users.Nav_User');
        extendInclude(json, 'Nav_Identifyings.Nav_Identifying');
        extendInclude(json, 'Nav_Details.Nav_Area');
        extendInclude(json, 'Nav_Details.Nav_Identifying');
        extendInclude(json, 'Nav_Details.Nav_Type');
        extendInclude(json, 'Nav_Details.Nav_EvaluateRiskRecordWorkduty.Nav_Workduty');
        extendInclude(json, 'Nav_Details.Nav_EvaluateRiskRecordEquipment.Nav_Equipment');
        extendInclude(json, 'Nav_Details.Nav_EvaluateRiskRecordFacilities.Nav_Facilities');
        extendInclude(json, 'Nav_Users.Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File');
        extendInclude(json, 'Nav_Details.Nav_OperationStep');
        extendInclude(json, 'Nav_Files.Nav_ImgFile.Nav_File');
        extendInclude(json, 'Nav_NoteTaker');
        extendInclude(json, 'Nav_Details.Nav_DepartmentLiable');
        extendInclude(json, 'Nav_Details.Nav_LiableUser');
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'HM/HMRiskRecord/FullGet',
            onComplete: (ret) => {
                if (ret) {
                    if (this.props.data && this.props.data.loadDataDeal) {
                        this.props.data.loadDataDeal(1);
                    }
                    this.state.areas = this.removeDuplicateArea(ret.Nav_Details);
                    this.onClickApprove(false);
                    let index = ret.Nav_Users.findIndex((item) =>
                        item.USER_ID == this.props.login.userId
                    );
                    ret.Nav_Users = this.removeDuplicateUser(ret.Nav_Users);
                    ret.Nav_Details = ret.Nav_Details.filter(item => item.RISK_STATUS == 0);
                    if (index > -1) {
                        var areaid = ret?.Nav_Users[index]?.AREA_ID;
                        ret.Nav_Details = ret.Nav_Details.filter(item => item.AREA_ID == areaid);
                        ret.Nav_Users = ret.Nav_Users.filter(item => item.AREA_ID == areaid);
                    }
                    this.setState({ data: ret })
                    if (ret.ID) {
                        this.props.dispatch({
                            type: 'app/getDataByPost',
                            url: 'HM/HMRiskRecord/GetRiskRecord',
                            payload: {
                                ID: this.props.data.id,
                            },
                            onComplete: (result) => {
                                if (result != null) {
                                    if (result) {
                                        if (this.props.data.tableKey == "2" || this.props.data.tableKey == undefined) {
                                            this.setState({ BtnAgreeDisplay: 'none' })
                                        } else {
                                            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")
    }
    removeDuplicateArea(arr) {
        let obj = {};
        arr = arr.reduce((newArr, next) => {
            obj[next.AREA_ID] ? "" : (obj[next.AREA_ID] = true && newArr.push(next));
            return newArr;
        }, []);
        return arr;
    }
    removeDuplicateUser(arr) {
        let obj = {};
        arr = arr.reduce((newArr, next) => {
            obj[next.USER_ID] ? "" : (obj[next.USER_ID] = true && newArr.push(next));
            return newArr;
        }, []);
        return arr;
    }
    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.renderLevel(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.Nav_Area.NAME
                                    } else {
                                        return item.Nav_Area.NAME + '  '
                                    }
                                })
                            }</Descriptions.Item>
                            <Descriptions.Item label="辨识要求" span={3}>{
                                data.Nav_Request ? data.Nav_Request.NAME : ''
                            }</Descriptions.Item>
                            <Descriptions.Item label="记录人" span={1.5}>{data.Nav_NoteTaker?.NAME}</Descriptions.Item>
                            <Descriptions.Item label="辨识人员" span={1.5}>{
                                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={1.5}>{
                                data.Nav_Identifyings && data.Nav_Identifyings.map((item, i) => {
                                    if (i == (data.Nav_Identifyings.length - 1)) {
                                        return item.Nav_Identifying.NAME
                                    } else {
                                        return item.Nav_Identifying.NAME + '  '
                                    }
                                })
                            }</Descriptions.Item>
                            <Descriptions.Item label="附件" span={1.5}> {
                                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>
                                    <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>
                                    {/* <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>
                            </tbody>
                            {data.Nav_Details && data.Nav_Details.map((item, index) => {
                                return (
                                    <tbody>
                                        <tr>
                                            <td>{index + 1}</td>
                                            <td>{item.Nav_Area ? item.Nav_Area.NAME : ''}</td>
                                            <td>{item.Nav_Identifying ? item.Nav_Identifying.NAME : ''}</td>
                                            <td>{item.Nav_Type ? item.Nav_Type.NAME : ''}</td>
                                            <td>{item.RISK_NAME}</td>
                                            <td>{item.RISK_PLACE}</td>
                                            <td>{item.Nav_EvaluateRiskRecordWorkduty && item.Nav_EvaluateRiskRecordWorkduty.map((ite, i) => {
                                                if (i == (item.Nav_EvaluateRiskRecordWorkduty.length - 1)) {
                                                    return ite.Nav_Workduty ? ite.Nav_Workduty.NAME : ''
                                                } else {
                                                    return ite.Nav_Workduty ? ite.Nav_Workduty.NAME + '  ' : ''
                                                }
                                            })}</td>
                                            <td>{item.Nav_EvaluateRiskRecordEquipment && item.Nav_EvaluateRiskRecordEquipment.map((ite, i) => {
                                                if (i == (item.Nav_EvaluateRiskRecordEquipment.length - 1)) {
                                                    return ite.Nav_Equipment ? ite.Nav_Equipment.NAME : ''
                                                } else {
                                                    return ite.Nav_Equipment ? ite.Nav_Equipment.NAME + '  ' : ''
                                                }
                                            })}</td>
                                            {/* <td>{item.Nav_EvaluateRiskRecordFacilities && item.Nav_EvaluateRiskRecordFacilities.map((ite, i) => {
                                                if (i == (item.Nav_EvaluateRiskRecordFacilities.length - 1)) {
                                                    return ite.Nav_Facilities ? ite.Nav_Facilities.NAME : ''
                                                } else {
                                                    return ite.Nav_Facilities ? ite.Nav_Facilities.NAME + '  ' : ''
                                                }
                                            })}</td> */}
                                            <td>{item.Nav_OperationStep ? item.Nav_OperationStep.NAME : ''}</td>
                                            <td>{item.Nav_DepartmentLiable ? item.Nav_DepartmentLiable.NAME : ''}</td>
                                            <td>{item.Nav_PostLiable ? item.Nav_PostLiable.NAME : ''}</td>
                                            <td>{item.Nav_LiableUser ? item.Nav_LiableUser.NAME : ''}</td>
                                            {/* <td>{item.RISK_STATUS == 1 ? '作废' : '有效'}</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 }))(HM063ShowPrint) 