import { Button, Descriptions, Badge, Popconfirm, Row, Col, Form, Input, Select, Table } from 'antd';
import React from 'react';
import { initFilter, extendRule, extendInclude, extendIgnoreDataRule, setDataFieldValue, guid, showApprove, showUsersSign, initQueryFilter } from "../../../utils/common";
import ReactToPrint from "react-to-print";
import { ExportToExcel } from '@woowalker/feui'
import XLSX from 'xlsx';
import { connect } from 'dva';
import moment from 'moment';
import { message } from "antd/lib/index";
import styles from '../HI/StepForm.css';
import config from "../../../config.js";
import FormPage from '../../../components/FormPage'
import { DefsElement } from 'canvg';

class BS032ShowPrint extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: null,
            BtnAgreeDisplay: 'none',
            isCheck: false,
            listView: [],//已经审阅的姓名
            levelNameShow: ''
        };
    };

    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);
        }
    }

    sureCheck = () => {
        let json = initFilter(this.props.login.OrgId, this.props.data.id, null, null, null, this.props.data.TaskID);
        // extendRule(json, 'ID', 1, this.props.data.id);
        // extendRule(json, "Parameter1", 1, this.props.data.TaskID)
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'BS/BSSafeCheck/sendCheck',
            onComplete: (ret) => {
                this.BtnClose()
            }
        });
    }

    BtnClose = () => {
        if (typeof this.props.data.onCancel != "undefined" && typeof this.props.data.onCancel == 'function')
            this.props.data.onCancel();
    }

    onClickApprove = (appVisible) => {
        const newtmpData = {
            // data: { id: this.props.data.id, isShow: true, key: guid(), param: this.props.data.param, appVisible: appVisible, BtnAgreeDisplay: 'none' },
            data: { id: this.props.data.id, isShow: true, key: guid(), PARAM2: this.props.data.PARAM2, appVisible: appVisible, BtnAgreeDisplay: 'none' },
            formCode: "PF123",
        }
        this.setState({
            tmpData: newtmpData,
        });
    }
    loadData = () => {
        var userId = this.props.login.userId
        let json = initFilter(this.props.login.OrgId);
        extendRule(json, 'ID', 1, this.props.data.id);
        extendInclude(json, 'Nav_CheckType');
        extendInclude(json, 'Nav_Department');
        // extendInclude(json, 'Nav_CheckTypeLevel.Nav_CheckType.Nav_ListCheckTypeLevel');
        extendInclude(json, 'Nav_CheckTypeLevel.Nav_Enums');
        extendInclude(json, 'Nav_ListCheckRiskArea.Nav_RiskArea');
        extendInclude(json, 'Nav_ListCheckProject.Nav_CheckProject');
        extendInclude(json, 'Nav_ListCheckProjectCategory.Nav_CheckProjectCategory');
        // extendInclude(json, 'Nav_ListSafeCheckDetail.Nav_CheckProject');
        // extendInclude(json, 'Nav_ListSafeCheckDetail.Nav_ListCheckDetailUser.Nav_User');
        extendInclude(json, 'Nav_Files.Nav_ImgFile.Nav_File');
        extendInclude(json, "Nav_Approve.Nav_ApproveDetails.Nav_ApproveUser.Nav_UserSignFiles.Nav_ImgFile.Nav_File");
        extendIgnoreDataRule(json)
        var that = this
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'BS/BSSafeCheck/GetCheckInfoBS034',//GetCheckInfo
            onComplete: (ret) => {
                if (ret) {
                    // var isCheckTemp = (ret.STATUSPLAN == 20 && ret.STATUCHECK == 5) ? true : false
                    var isCheckTemp = this.props.data.tableKey != undefined && this.props.data.tableKey == "1" ? true : false

                    var isCheck = false
                    var levelNameShow = ret.Nav_CheckTypeLevel.Nav_Enums.NAME
                    if ((levelNameShow == '班组级' || levelNameShow == '车间级') && ret.Nav_Department != undefined) {
                        levelNameShow += "(" + ret.Nav_Department?.NAME + ")"
                    }
                    // let strRiskAreaNAME = ''
                    // if (ret.Nav_ListCheckRiskArea && ret.Nav_ListCheckRiskArea.length > 0) {
                    //     for (let i = 0; i < ret.Nav_ListCheckRiskArea.length; i++) {
                    //         strRiskAreaNAME += (strRiskAreaNAME.length > 0 ? "," : "") + ret.Nav_ListCheckRiskArea[i].Nav_RiskArea.NAME;
                    //     }
                    // }

                    // let strCheckProjectNAME = ''
                    // if (ret.Nav_ListCheckProject && ret.Nav_ListCheckProject.length > 0) {
                    //     for (let i = 0; i < ret.Nav_ListCheckProject.length; i++) {
                    //         strCheckProjectNAME += (strCheckProjectNAME.length > 0 ? "," : "") + ret.Nav_ListCheckProject[i].Nav_CheckProject.NAME;
                    //     }
                    // }

                    // let strProjectCategoryNAME = ''
                    // if (ret.Nav_ListCheckProjectCategory && ret.Nav_ListCheckProjectCategory.length > 0) {
                    //     for (let i = 0; i < ret.Nav_ListCheckProjectCategory.length; i++) {
                    //         strProjectCategoryNAME += (strProjectCategoryNAME.length > 0 ? "," : "") + ret.Nav_ListCheckProjectCategory[i].Nav_CheckProjectCategory.NAME;
                    //     }
                    // }

                    var listView = []
                    var listViewUrl = []
                    var tempUrl = ''
                    for (let i = 0; i < ret.Nav_ListSafeCheckDetail.length; i++) {
                        for (let j = 0; j < ret.Nav_ListSafeCheckDetail[i].Nav_ListCheckDetailUser.length; j++) {
                            if (isCheckTemp && !isCheck) {
                                if (ret.Nav_ListSafeCheckDetail[i].Nav_ListCheckDetailUser[j].USER_ID == userId && ret.Nav_ListSafeCheckDetail[i].Nav_ListCheckDetailUser[j].SAFECHECKSTATE < 60) {
                                    isCheck = true
                                }
                            }

                            if (ret.Nav_ListSafeCheckDetail[i].Nav_ListCheckDetailUser[j].SAFECHECKSTATE >= 60) {
                                // debugger
                                // item.Nav_User.Nav_UserSignFiles[0].Nav_ImgFile.Nav_File.FILE_PATH
                                if (ret.Nav_ListSafeCheckDetail[i].Nav_ListCheckDetailUser[j].Nav_User.Nav_UserSignFiles != null) {
                                    tempUrl = ret.Nav_ListSafeCheckDetail[i].Nav_ListCheckDetailUser[j].Nav_User.Nav_UserSignFiles[0]?.Nav_ImgFile.Nav_File.FILE_PATH
                                    if (listViewUrl.indexOf(tempUrl) == -1) {
                                        listViewUrl.push(tempUrl)
                                        listView.push(ret.Nav_ListSafeCheckDetail[i].Nav_ListCheckDetailUser[j])
                                    }
                                }
                            }
                        }
                    }


                    // ret.RiskAreaNAME = strRiskAreaNAME
                    // ret.CheckProjectNAME = strCheckProjectNAME
                    // ret.ProjectCategoryNAME = strProjectCategoryNAME


                    this.setState({   //设置setState全局变量
                        data: ret,      //将ret对象赋值给data, data供页面调用
                        isCheck: isCheck,// (ret.STATUSPLAN == 20 && ret.STATUCHECK == 5) ? true : false,
                        listView: listView,
                        levelNameShow: levelNameShow
                    })
                }
            }
        });
    }

    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, listView, levelNameShow } = this.state;
        const enums = this.props.data.enums ? this.props.data.enums : this.props.app.enums;
        return <div>
            <div style={{ padding: '10px' }}>
                <table>
                    <tr>
                        <td><Button onClick={() => this.onClickApprove(true)} style={{ marginRight: '8px' }} icon="export">审批详情</Button></td>
                        <td><ReactToPrint trigger={() => <Button type={'default'} icon={'printer'} >打印</Button>} content={() => this.componentRef} pageStyle={"#tableId" + this.props.data.id + " { padding:0 40px;} img{width :120px}"} /></td>
                        <td><ExportToExcel fileName='检查任务表' tableId={'tableId' + this.props.data.id} /></td>

                        {/* 如果是通知 检查人员 需要确认
                         如果是 审批 或者 查看 不需要 确认
                          */}
                        {
                            this.state.isCheck ? <td><Button type={'primary'} icon={'check'} onClick={() => this.sureCheck()} >确认</Button>  </td> : null
                        }
                    </tr>
                </table>
            </div>

            <FormPage {...this.state.tmpData} />
            {/* 检查表制定 */}
            <div ref={el => (this.componentRef = el)} style={{ padding: '20px', paddingTop: '20px' }} id={'tableId' + this.props.data.id}>
                <h1 className={styles.showPrintHead} >{data?.Nav_CheckType?.NAME}任务表</h1>
                {
                    //, paddingLeft: '50px' 
                    data ? <div>
                        <Descriptions title="" size="middle" bordered>
                            <Descriptions.Item span={2} label="安全检查名称">{data.NAME}</Descriptions.Item>
                            <Descriptions.Item span={2} label="安全检查编号">{data.CODE}</Descriptions.Item>
                            <Descriptions.Item span={2} label="检查类型">{data.Nav_CheckType.NAME}</Descriptions.Item>
                            <Descriptions.Item span={2} label="检查范围">{enums.BSMineTypeEnum.enums[data.CHECKOBJECT]}</Descriptions.Item>
                            <Descriptions.Item span={2} label="检查层级">{levelNameShow}</Descriptions.Item>
                            {/* data.Nav_CheckTypeLevel.Nav_Enums.NAME */}
                            <Descriptions.Item span={2} label="检查时间">{data.CHECKTIME}</Descriptions.Item>
                            <Descriptions.Item span={2} label="检查区域">{
                                // data.RiskAreaNAME
                                data?.Nav_ListCheckRiskArea?.map((item, i) => {
                                    return <p className={styles.pLin}> {item.Nav_RiskArea.NAME}</p>
                                })
                            }</Descriptions.Item>
                            <Descriptions.Item span={2} label="检查项目">{
                                //data.CheckProjectNAME
                                data?.Nav_ListCheckProject?.map((item, i) => {
                                    return <p className={styles.pLin}> {item.Nav_CheckProject.NAME}</p>
                                })

                            }</Descriptions.Item>
                            {/* ret.Nav_ListCheckProjectCategory[i].Nav_CheckProjectCategory.NAME */}
                            <Descriptions.Item span={2} label="检查项目分类">{
                                data.Nav_ListCheckProjectCategory && data.Nav_ListCheckProjectCategory.map((item, i) => {
                                    // return (i > 0 ? "," : "") + item.Nav_CheckProjectCategory.NAME
                                    return <p className={styles.pLin}> {item.Nav_CheckProjectCategory.NAME}</p>
                                })
                            }</Descriptions.Item>
                            <Descriptions.Item span={2} label="检查人员">{data.CheckUsers}</Descriptions.Item>
                            <Descriptions.Item span={2} label="附件">{
                                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>
                    </div> : null
                }

                {
                    data ? <table className={styles.PrintFormLight}>
                        <tbody>
                            <tr className={styles.PrintFormLightTh}>
                                <td style={{ width: '100px' }}>序号</td>
                                <td>检查区域</td>
                                <td>检查项目</td>
                                <td>检查内容</td>
                                <td>检查依据</td>
                                {/* <td>问题描述</td> */}
                                <td style={{ width: '120px' }} >检查人员</td>
                            </tr>
                            {data.Nav_ListSafeCheckDetail.map((item, i) => {
                                return <tr>
                                    <td>{item.ROW_NO}</td>
                                    <td >{item.Nav_CheckArea?.NAME}</td>
                                    <td>{item.Nav_CheckProject?.NAME}</td>
                                    <td>{item.CHECKCONTENT}</td>
                                    <td>{item.CHECKPROOF}</td>
                                    {/* <td width="50px">{item.QUESTION_LEVEL_DESCRIPTION}</td> */}
                                    {/* <td width="50px">{item.Nav_CheckMain.Nav_CheckTypeLevel.Nav_Enums.NAME}</td> */}
                                    {/* <td>问题描述</td> */}
                                    <td>{
                                        item.Nav_ListCheckDetailUser.map((user, j) => {
                                            if (user.SAFECHECKSTATE >= 60) {
                                                return <a style={{ color: "rgba(0, 0, 0, 0.65)" }}>{(j > 0 ? "," : "") + user.Nav_User.NAME}</a>
                                            } else {
                                                return <a style={{ color: "red" }}>{(j > 0 ? "," : "") + user.Nav_User.NAME}</a>
                                            }
                                        })
                                    }</td>
                                </tr>

                            })}
                            {/* <tr>
                                <td>附件</td>
                                <td colSpan={4}>检查内容</td>
                            </tr> */}
                            <tr>
                                <td>审核人</td> {/* 审核意见 如果已经审批 显示审批信息 */}
                                <td colSpan={5} style={{ textAlign: "left" }}>
                                    {
                                        showApprove(data.Nav_Approve?.Nav_ApproveDetails, this.props.app.enums.NodeApproveStatus.enums, config.picServerHost, 200)
                                    }
                                </td>
                            </tr>
                            {
                                data.STATUSPLAN == 20 ?
                                    <tr >
                                        <td>检查人员确认</td> {/* 审阅意见 如果已经阅读 显示已经阅读的签名 */}
                                        <td colSpan={5} style={{ textAlign: "left" }}>
                                            {
                                                showUsersSign(listView, config.picServerHost, 200)
                                            }
                                        </td>
                                    </tr>
                                    : null
                            }
                        </tbody>
                    </table> : null
                }
            </div>
        </div>
    }
}

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