import { Button, Descriptions, Popconfirm, 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 { connect } from 'dva';
import moment from 'moment';
import { message } from "antd/lib/index";
import FormPage from '../../../components/FormPage'
class HM042ShowPrint extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: null,
            BtnSignDisplay: 'none',
            isFinished: 'none',
            isAudit: 'none',
            tmpData: {},
            DEALOPINION: '',
            teamUsers: []
        };
    };
    //审批意见 改变
    DEALOPINIONCHANGE = (val) => {
        this.state.DEALOPINION = val
    }
    componentDidMount() {
        if (this.props.data?.id)
            this.loadData(this.props.data?.id);
    }
    removeDuplicateObj(arr) {
        let obj = {};
        arr = arr.reduce((newArr, next) => {
            obj[next.CHARGE_USER_ID] ? "" : (obj[next.CHARGE_USER_ID] = true && newArr.push(next));
            return newArr;
        }, []);
        return arr;
    }
    componentWillReceiveProps(NextProps) {
        if (NextProps.data?.id && this.props.data?.id != NextProps.data?.id) {
            this.loadData(NextProps.data?.id);
        }
    }

    onChargeUserAgree(agree) {
        this.props.dispatch({
            type: 'app/getDataByPost',
            url: 'HM/HMEvaluationPlan/ChargeUserAgree',
            payload: {
                ID: this.props.data.id,
                TaskID: this.props.data.TaskID,
                CHECK_STATUS: agree,
                AUDIT_OPINION: this.state.DEALOPINION
            },
            onComplete: (ret) => {
                if (ret) {
                    message.success('处理完成！');
                    this.setState({ isAudit: 'none' })
                    this.BtnClose();
                }
            }
        })
    }
    onPersonalAgree() {
        this.props.dispatch({
            type: 'app/getDataByPost',
            url: 'HM/HMEvaluationPlan/UserSignin',
            payload: {
                ID: this.props.data.id,
                TaskID: this.props.data.TaskID,
            },
            onComplete: (ret) => {
                if (ret) {
                    message.success('确认成功！');
                    this.setState({ BtnSignDisplay: 'none' })
                    this.BtnClose();
                }
            }
        })
    }
    BtnClose = () => {
        if (typeof this.props.data.onCancel != "undefined" && typeof this.props.data.onCancel == 'function')
            this.props.data.onCancel();
    }
    removeDuplicateUser(arr) {
        let obj = {};
        arr = arr.reduce((newArr, next) => {
            obj[next.CHARGE_USER_ID] ? "" : (obj[next.CHARGE_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_ReleaseUser');
        extendInclude(json, 'Nav_Details.Nav_ChargeUser');
        extendInclude(json, 'Nav_Details.Nav_Areas.Nav_Area');
        extendInclude(json, 'Nav_Details.Nav_Identifyings.Nav_Identifying');
        extendInclude(json, 'Nav_Files.Nav_ImgFile.Nav_File');
        extendInclude(json, 'Nav_GroupLeader.Nav_UserSignFiles.Nav_ImgFile.Nav_File');
        extendInclude(json, 'Nav_DeputyGroupLeader.Nav_UserSignFiles.Nav_ImgFile.Nav_File');
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'HM/EvaluationPlan/Get',
            onComplete: (ret) => {
                if (ret) {
                    if (this.props.data && this.props.data.loadDataDeal) {
                        this.props.data.loadDataDeal(1);
                    }
                    this.teamUsers = this.removeDuplicateUser(ret.Nav_Details);
                    this.onClickApprove(false);
                    if (ret.STATUS >= 4) {
                        this.state.isFinished = "inline";
                    }
                    this.setState({ data: ret })
                    if (ret.ID) {
                        this.props.dispatch({
                            type: 'app/getDataByPost',
                            url: 'HM/HMEvaluationPlan/GetEvaluationPlan',
                            payload: {
                                ID: this.props.data.id,
                            },
                            onComplete: (result) => {
                                if (this.props.data.tableKey == "2" || this.props.data.tableKey == undefined) {
                                    this.setState({ isAudit: 'none' })
                                } else if (ret.STATUS == 4 && this.props.data.TaskID != null && (ret.DEPUTY_GROUP_LEADER_OPINION == 0 || ret.GROUP_LEADER_OPINION == 0)) {
                                    this.setState({ isAudit: 'inline' })
                                }
                            }
                        })
                        this.props.dispatch({
                            type: 'app/getDataByPost',
                            url: 'HM/HMEvaluationPlan/GetUserDealStatus',
                            payload: {
                                ID: this.props.data.id,
                            },
                            onComplete: (result) => {
                                if (result != null && this.props.data.TaskID != null) {
                                    if (result) {
                                        if (this.props.data.tableKey == "2" || this.props.data.tableKey == undefined) {
                                            this.setState({ BtnSignDisplay: 'none' })
                                        } else {
                                            this.setState({ BtnSignDisplay: 'none' })
                                        }
                                    }
                                }

                            }
                        })
                    }
                }
            }
        });
    }
    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")
    }
    onClickApprove = (appVisible) => {
        const newtmpData = {
            data: { id: this.props.data.id, isShow: true, key: guid(), appVisible: appVisible, BtnAgreeDisplay: 'inline' },
            formCode: "PF123",
        }
        this.setState({
            tmpData: newtmpData,
        });
    }
    joinArea(data) {
        let ret = [];
        for (let it of data) {
            if (it.Nav_Area && it.Nav_Area.NAME) {
                ret.push(it.Nav_Area.NAME);
            }
        }
        return ret.join('、');
    }
    joinIdentifying(data) {
        let ret = [];
        for (let it of data) {
            if (it.Nav_Identifying && it.Nav_Identifying.NAME) {
                ret.push(it.Nav_Identifying.NAME);
            }
        }
        return ret.join('、');
    }
    renderLevel(level) {
        let str = '';
        if (level == undefined) {
            return str;
        }
        if (level.indexOf('0') >= 0) {
            str += '部门 ';
        }
        if (level.indexOf('1') >= 0) {
            str += '车间 ';
        }
        if (level.indexOf('2') >= 0) {
            str += '班组 ';
        }
        if (level.indexOf('3') >= 0) {
            str += '公司 ';
        }
        return str;
    }
    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'} style={{ display: this.state.isFinished }}>打印</Button>}
                    content={() => this.componentRef}
                />
                <Button onClick={() => this.onTableBtnExport()} icon="export" style={{ marginLeft: '8px', display: this.state.isFinished }}>导出</Button>

                <Button type={'primary'} style={{ marginLeft: '8px', display: this.state.BtnSignDisplay }} onClick={() => this.onPersonalAgree()} 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="评价年度">{moment(data.EVALUATION_DATE).format('YYYY')}</Descriptions.Item>
                                <Descriptions.Item label="文件名称">{data.DOCUMENT_NAME}</Descriptions.Item>
                                <Descriptions.Item label="发起时间">{data.CREATE_TIME}</Descriptions.Item>
                                <Descriptions.Item label="发起部门" span={1.5}>{data.Nav_InitiatingDepartment ? data.Nav_InitiatingDepartment.NAME : ''}</Descriptions.Item>
                                <Descriptions.Item label="发起人员" span={1.5}>{data.Nav_ReleaseUser ? data.Nav_ReleaseUser.NAME : ''}</Descriptions.Item>
                                <Descriptions.Item label="风险管理小组副组长" span={1.5}>{data.Nav_DeputyGroupLeader ? data.Nav_DeputyGroupLeader.NAME : ''}</Descriptions.Item>
                                <Descriptions.Item label="风险管理小组组长" span={1.5}>{data.Nav_GroupLeader ? data.Nav_GroupLeader.NAME : ''}</Descriptions.Item>
                                <Descriptions.Item label="风险管理小组成员" span={3}>{
                                    this.teamUsers && this.teamUsers.map((item, i) => {
                                        return item.Nav_ChargeUser ? item.Nav_ChargeUser.NAME+' ' : ''
                                    })
                                }</Descriptions.Item>
                                <Descriptions.Item label="内容要求" span={3}>{data.EVALUATION_CONTENT}</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.Item label="风险管理小组副组长意见" span={1.5}>{
                                    data.DEPUTY_GROUP_LEADER_OPINION != 0 ? this.props.app.enums.HMOpinionEnmu.enums[data.DEPUTY_GROUP_LEADER_OPINION] : ""}
                                    {data.DEPUTY_GROUP_LEADER_OPINION == 1 ? <img width={'200px'} alt={data.Nav_DeputyGroupLeader.NAME} src={data.Nav_DeputyGroupLeader.Nav_UserSignFiles.length > 0 ? config.picServerHost + data.Nav_DeputyGroupLeader.Nav_UserSignFiles[0].Nav_ImgFile?.Nav_File.FILE_PATH : ''} /> : ""}
                                </Descriptions.Item>
                                <Descriptions.Item label="风险管理小组组长意见" span={1.5}>{
                                    data.GROUP_LEADER_OPINION != 0 ? this.props.app.enums.HMOpinionEnmu.enums[data.GROUP_LEADER_OPINION] : ""}
                                    {data.GROUP_LEADER_OPINION == 1 ? <img width={'200px'} alt={data.Nav_GroupLeader.NAME} src={data.Nav_GroupLeader.Nav_UserSignFiles.length > 0 ? config.picServerHost + data.Nav_GroupLeader.Nav_UserSignFiles[0].Nav_ImgFile?.Nav_File.FILE_PATH : ''} /> : ""}
                                </Descriptions.Item>
                            </Descriptions>
                            <table style={{ width: '100%', textAlign: 'center' }} 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>
                                    </tr>
                                    {
                                        data.Nav_Details && data.Nav_Details.map((item, i) => {
                                            return <tr>
                                                <td>{moment(item.START_TIME).format('YYYY-MM-DD')}</td>
                                                <td>{moment(item.END_TIME).format('YYYY-MM-DD')}</td>
                                                <td>{this.renderLevel(item.LEVEL)}</td>
                                                <td>{this.joinArea(item.Nav_Areas)}</td>
                                                <td>{this.joinIdentifying(item.Nav_Identifyings)}</td>
                                                <td>{this.props.app.enums.HMRiskTypeEnmu.enums[item.RISK_TYPE]}</td>
                                                <td>{item.Nav_ChargeUser?.NAME}</td>
                                                <td>{item.REMARK}</td>
                                            </tr>
                                        })
                                    }
                                </tbody>
                            </table>
                            <FormPage {...this.state.tmpData} />
                            <table style={{ width: '90%', lineHeight: '35px' }}>
                                <tbody>
                                    <tr><td colSpan={2}><br></br></td></tr>
                                    <tr>
                                        <th style={{ display: this.state.isAudit }}>意见:</th>
                                        <td>
                                            <Input.TextArea style={{ margin: '0 0 0 15px', display: this.state.isAudit }} onChange={(evt) => this.DEALOPINIONCHANGE(evt.target.value)} />
                                        </td>
                                    </tr>
                                    <tr>
                                        <th></th>
                                        <td >
                                            <Button style={{ width: '120px', height: '38px', margin: '20px 0 20px 15px', display: this.state.isAudit }} type={'primary'} icon={'check'} onClick={() => this.onChargeUserAgree(1)} >同意</Button>
                                            <Button style={{ width: '120px', height: '38px', margin: '20px 0 20px 30px', backgroundColor: "#ED7D31", display: this.state.isAudit }} type="primary" htmlType="submit" icon="close" onClick={() => this.onChargeUserAgree(2)} >驳回</Button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        : null
                }
            </div>

        </div>
    }

}

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