import { message } from "antd/lib/index";
import { Layout,Descriptions, Tabs, Steps, Button, Popconfirm, Row, Col, Form, Input, Select, Table, Drawer ,Icon} from 'antd';
import React from 'react';
import { PlusOutlined } from '@ant-design/icons';
import ReactToPrint from "react-to-print";
import styles from '../HI/StepForm.css';
import config from "../../../config";
import XLSX from 'xlsx';
import { connect } from 'dva';
const { Header, Footer, Sider, Content } = Layout;
const TabPane = Tabs.TabPane;
const { TextArea } = Input;
const { Step } = Steps;
import {
    extend,
    extendRule,
    initFilter,
    initQueryFilter,
    getOnlyPropertyData,
    extendInclude,
    empty,
    getDataFieldValue, guid, initFilterGroup, extendGroupRule
} from "../../../utils/common";
import FormPage from '../../../components/FormPage'
class PFCommonApproveView extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            title: '流程审核',
            data: {},
            approveCode: '',
            isCurrent: false,
            tmpData: {},
            visible: false,
            userData: [],
            selectUserId: '',
            appVisible:false,
            BtnAgreeDisplay:'none'
        }
    };
    componentDidMount() {
        if (this.props.data?.id)
        {
            this.loadData(this.props.data?.id,false);
            this.setState({
                appVisible: this.props.data.appVisible?this.props.data.appVisible:false,
                BtnAgreeDisplay:this.props.data.BtnAgreeDisplay?this.props.data.BtnAgreeDisplay:'none',
            })
        }
    }

    componentWillReceiveProps(NextProps) {
        // if (NextProps.data?.id && this.props.data?.id != NextProps.data?.id) {
        //     this.loadData(NextProps.data?.id);
        // }
        if(NextProps.data?.key && this.props.data?.key != NextProps.data?.key)
        {
            if (NextProps.data?.id) {
                this.loadData(NextProps.data?.id,true);
                this.setState({
                    appVisible: NextProps.data.appVisible?NextProps.data.appVisible:false,
                    BtnAgreeDisplay:NextProps.data.BtnAgreeDisplay?NextProps.data.BtnAgreeDisplay:'none',
                })
            }
        }
    }

    compare = (val1, val2) => {
        return val1.NUM - val2.NUM;
    };

    onchange = (e) => {
        let tmpData = { ...this.state.data };
        tmpData.CurrentNode.NODE_APPROVE_STATUS = e;
        this.setState({
            data: tmpData
        })
    }
    selectChange = (e) => {
        const jsonUser = initFilter(this.props.login.OrgId, '', '', 0, 1)
        extendRule(jsonUser, "NAME", 1, e);
        this.props.dispatch({
            type: 'app/getDataByPost',
            url: 'FM/User/OrderEntities',
            payload: jsonUser,
            onlyData: false,
            onComplete: (ret) => {
                this.setState({
                    userData: ret.Data
                });
            }
        });
        this.setState({
            selectUserId: e
        })
    }
    BtnClose = () => {
        if (typeof this.props.data.onCancel != "undefined" && typeof this.props.data.onCancel == 'function')
            this.props.data.onCancel();
    }

    onClick = (e) => {
        this.props.form.validateFields((err, values) => {
            //console.log('Received values of form: ', values);
            if (err) {
                return;
            }
            this.props.dispatch({
                type: 'app/getDataByPost',
                url: 'PF/Approve/Submit',
                payload: this.state.data,
                onlyData: false,
                onComplete: (re) => {
                    if (re && re.IsSuccessful) {

                        if (re.Data) {
                            //回调函数

                            this.props.dispatch({
                                type: 'app/getDataByGet',
                                url: re.Data + "?id=" + this.state.data.DATA_ID,
                                onlyData: false,
                                onComplete: (callbak) => {
                                    if (callbak && callbak.IsSuccessful) {
                                        message.success("提交审批成功");
                                        this.BtnClose();
                                    } else {
                                        message.success("提交审批成功，回调失败");
                                    }
                                }
                            });

                        } else {
                            message.success("提交审批成功");
                            this.BtnClose();
                        }

                    } else {
                        message.error("提交审批失败");
                    }
                }
            })


        });

    }
    loadDataOld(dataid,appVisibleTemp) {
        const json = initFilter(this.props.login.OrgId, this.props.data.id, '', 0, 1, this.props.data.PARAM ?? null, this.props.data.PARAM2);
        this.setState({
            appVisible:appVisibleTemp,
            BtnAgreeDisplay:this.props.data.BtnAgreeDisplay?this.props.data.BtnAgreeDisplay:'inline'
        });
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'PF/Approve/GetDataId',
            onComplete: (ret) => {
                if (ret) {
                    const jsonApp = initFilter(this.props.login.OrgId)
                    extendRule(jsonApp, 'ID', 1, ret);
                    extendInclude(jsonApp, "Nav_ApproveDetails")
                    extendInclude(jsonApp, "Nav_ApproveDetails.Nav_ApproveUser")
                    extendInclude(jsonApp, "Nav_ApproveDetails.Nav_ApproveUser.Nav_UserSignFiles")
                    extendInclude(jsonApp, "Nav_ApproveDetails.Nav_ApproveUser.Nav_UserSignFiles.Nav_ImgFile.Nav_File")
                    this.props.dispatch({
                        type: 'app/getDataByPost',
                        url: 'PF/PFApprove/FullGet',
                        payload: jsonApp,
                        onlyData: false,
                        onComplete: (re) => {
                            
                            if (re && re.IsSuccessful && re.Data && re.Data.Nav_ApproveDetails.length > 0) {
                                const newtmpData = {
                                    data: {
                                        id: re.Data.DATA_ID, isShow: true,
                                        enums: this.props.app.enums,
                                    },
                                    formCode: re.Data.APPROVE_CODE,
                                }
                                re.Data.Nav_ApproveDetails.sort(this.compare);
                                let currentNodes = re.Data.Nav_ApproveDetails?.filter(v => v.IS_CURRENT == true);
                                let isCurrent = false;
                                if (currentNodes && currentNodes.length > 0) {
                                    let currentUserNode = currentNodes.filter(v => v.APPROVE_USER_ID == this.props.login.userId);
                                    if (currentUserNode != null) {
                                        isCurrent = true;
                                        re.Data.CurrentNode = currentUserNode[0];
                                    } else {
                                        re.Data.CurrentNode = currentNodes[0];
                                    }
                                    // re.Data.CurrentNode.NODE_APPROVE_STATUS = 10;
                                }
                                this.setState({
                                    //editData,
                                    //isCurrent,
                                    tmpData: newtmpData,
                                    title: re.Data.NAME,
                                    data: re.Data,
                                    visible: true,
                                });
                            } else {
                                const newtmpData = {
                                    data: { id: this.props.data.id, isShow: true },
                                    formCode: this.props.data.viewCode,
                                }
                                this.setState({
                                    //editData,
                                    //isCurrent,
                                    tmpData: newtmpData,
                                    title: this.props.login.currActivatedMenu?.NAME,
                                    //data: re.Data,
                                    visible: false
                                });
                                // message.error("没有审批记录");
                            }
                        }
                    })
                }
                else {
                    const newtmpData = {
                        data: { id: this.props.data.id, isShow: true },
                        formCode: this.props.data.viewCode,
                    }
                    this.setState({
                        //editData,
                        //isCurrent,
                        tmpData: newtmpData,
                        title: this.props.login.currActivatedMenu?.NAME,
                        //data: re.Data,
                        visible: false
                    });
                }
            }
        });
    }
    loadData(dataid,appVisibleTemp) {
        const json = initFilter(this.props.login.OrgId, this.props.data.id, '', 0, 1, this.props.data.PARAM ?? null, this.props.data.PARAM2);
        this.setState({
            appVisible:appVisibleTemp,
            BtnAgreeDisplay:this.props.data.BtnAgreeDisplay?this.props.data.BtnAgreeDisplay:'inline'
        });
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'PF/Approve/GetApproveInfo',
            onComplete: (re) => {
                if (re) {
                    // re = re.map(t=>t.Nav_ApproveDetails.sort(this.compare))
                    if (re && re[0].Nav_ApproveDetails.length > 0) {
                        const newtmpData = {
                            data: {
                                id: re[0].DATA_ID, isShow: true,
                                enums: this.props.app.enums,
                            },
                            formCode: re[0].APPROVE_CODE,
                        }
                        re[0].Nav_ApproveDetails.sort(this.compare);
                        let currentNodes = re[0].Nav_ApproveDetails?.filter(v => v.IS_CURRENT == true);
                        let isCurrent = false;
                        if (currentNodes && currentNodes.length > 0) {
                            let currentUserNode = currentNodes.filter(v => v.APPROVE_USER_ID == this.props.login.userId);
                            if (currentUserNode != null) {
                                isCurrent = true;
                                re[0].CurrentNode = currentUserNode[0];
                            } else {
                                re[0].CurrentNode = currentNodes[0];
                            }
                            // re.Data.CurrentNode.NODE_APPROVE_STATUS = 10;
                        }
                        this.setState({
                            //editData,
                            //isCurrent,
                            tmpData: newtmpData,
                            title: re[0].NAME,
                            data: re,
                            visible: true,
                        });
                    } else {
                        const newtmpData = {
                            data: { id: this.props.data.id, isShow: true },
                            formCode: this.props.data.viewCode,
                        }
                        this.setState({
                            //editData,
                            //isCurrent,
                            tmpData: newtmpData,
                            title: this.props.login.currActivatedMenu?.NAME,
                            //data: re.Data,
                            visible: false
                        });
                        // message.error("没有审批记录");
                    }
                }
                else {
                    const newtmpData = {
                        data: { id: this.props.data.id, isShow: true },
                        formCode: this.props.data.viewCode,
                    }
                    this.setState({
                        //editData,
                        //isCurrent,
                        tmpData: newtmpData,
                        title: this.props.login.currActivatedMenu?.NAME,
                        //data: re.Data,
                        visible: false
                    });
                }
            }
        });
    }

    showAppDrawer= () => {
        this.setState({
            appVisible: true,
        });
    }
    onClose = () => {
        this.setState({
            appVisible:false,
        });
    };
    render() {
        const enums = this.props.app ? this.props.app.enums : null;
        // const headColumnConfig = this.getEditConfig()
        //const columns = headColumnConfig ? headColumnConfig.columns : []
        const { form, location, dispatch, match, loading } = this.props;
        const { userData } = this.state;
        const { getFieldDecorator, validateFields, validateFieldsAndScroll, setFieldsValue } = form;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 14 },
        };
        const stepStyle = {
            marginBottom: 60,
            boxShadow: '0px -1px 0 0 #e8e8e8 inset',
        };
        return (
            // <FormPage {...this.state.tmpData} />

            <Layout>
                 <Drawer
                    title="审批详情"
                    width={320}
                    onClose={this.onClose}
                    visible={this.state.appVisible}
                    bodyStyle={{ paddingBottom: 80 }}
                    placement ="left"
                >
                    {/* <Sider style={{
                    overflow: 'auto',
                    height: '100vh',
                    position: 'fixed',
                    left: 20,
                    background: '#FFF'
                }}> */}
                {/* {
                    this.state.data && this.state.data.Nav_ApproveDetails? <Steps icon="user" current={0} direction="vertical" type="navigation">
                    {this.state.data?.Nav_ApproveDetails?.map((n) => {
                        let status = 'wait'; let result = '';
                        if (n.NODE_APPROVE_STATUS == 10) {
                            status = 'finish';result='同意';
                        } else if (n.NODE_APPROVE_STATUS == 20) {
                            status = 'error';result='驳回';
                        }
                        if (n.IS_CURRENT) {
                            status = 'process'; 
                        }
                        return <Step title={n.NAME} description={<span> {"审批人："+n.Nav_ApproveUser?.NAME}<br/>{"审批时间："+(n.NODE_APPROVE_TIME == "0001-01-01 00:00:00" ? '' : n.NODE_APPROVE_TIME)}
                        <br/>{"审批结论："+result}
                        <br/>{"审批意见："+(n.CONTEXT ==undefined?'': n.CONTEXT)}
                        </span>} status={status} icon={status=='process'?<Icon type="user" />:null}  />
                        // description={n.Nav_ApproveUser?.NAME + (n.NODE_APPROVE_TIME == "0001-01-01 00:00:00" ? '' : n.NODE_APPROVE_TIME)} 
                    })}
                </Steps> :"暂无审批详情" 
                } */}
                     {
                    this.state.data && this.state.data[0] ?
                     this.state.data.map((m,i)=>{
                        
                        return <Steps icon="user" current={0} direction="vertical" type="navigation">
                        {
                        m.Nav_ApproveDetails?.sort(this.compare).map((n) => {
                            let status = 'wait'; let result = '';
                            if (n.NODE_APPROVE_STATUS == 10) {
                                status = 'finish';result='同意';
                            } else if (n.NODE_APPROVE_STATUS == 20) {
                                status = 'error';result='驳回';
                            }
                            if (n.IS_CURRENT) {
                                status = 'process'; 
                            }
                            return <Step title={n.NAME} description={<span> {"审批人："+n.Nav_ApproveUser?.NAME}<br/>{"审批时间："+(n.NODE_APPROVE_TIME == "0001-01-01 00:00:00" ? '' : n.NODE_APPROVE_TIME)}
                            <br/>{"审批结论："+result}
                            <br/>{"审批意见："+(n.CONTEXT ==undefined?'': n.CONTEXT)}
                            </span>} status={status} icon={status=='process'?<Icon type="user" />:null}  />
                            // description={n.Nav_ApproveUser?.NAME + (n.NODE_APPROVE_TIME == "0001-01-01 00:00:00" ? '' : n.NODE_APPROVE_TIME)} 
                        })}
                        <hr style={{border:'1px dashed #ccc',marginBottom:"15px",display:this.state.data.length-1 == i?'none':'block'}}></hr>
                    </Steps>
                     }) :"暂无审批详情" 
                    
                }
                {/* </Sider> */}
                </Drawer>
                {/* <Layout style={{ marginLeft: 0 }}>
                    <Col span={2}>
                     <Button type="primary" style={{ marginLeft: 10,marginTop: 20 }} size="50px" icon="login" onClick={this.showAppDrawer} >审批详情</Button>
                    </Col>
                    <br></br>
                    <Content style={{ margin: '24px 16px 0', overflow: 'initial', background: '#FFF' }}>
                        <FormPage {...this.state.tmpData} />
                    </Content>
                </Layout > */}
                {/* <Footer style={{
                    background: '#FFF',
                }} visible={this.state.visible}>
                    <Steps current={0} direction="horizontal" type="navigation" visible={this.state.visible}>
                        {this.state.data?.Nav_ApproveDetails?.map((n) => {
                            let status = 'wait';
                            if (n.NODE_APPROVE_STATUS == 10) {
                                status = 'finish';
                            } else if (n.NODE_APPROVE_STATUS == 20) {
                                status = 'error';
                            }
                            if (n.IS_CURRENT) {
                                status = 'process';
                            }
                            return <Step title={n.NAME} description={n.Nav_ApproveUser?.NAME + (n.NODE_APPROVE_TIME == "0001-01-01 00:00:00" ? '' : n.NODE_APPROVE_TIME)} status={status} />
                        })}
                    </Steps>
                </Footer> */}
                  {/* {
                     this.state.data && this.state.data[0]?
                     <div style={{display: this.state.BtnAgreeDisplay,backgroundColor:"#fff"}}>
                        <Descriptions size="middle" bordered className={styles.description}>
                        <Descriptions.Item label="审批详情">
                        <div>{
                                    this.state.data[0].Nav_ApproveDetails && this.state.data[0].Nav_ApproveDetails.map((item, i) => {
                                        if (item.NODE_APPROVE_STATUS != 0) {
                                            if (item.Nav_ApproveUser != null && item.Nav_ApproveUser.Nav_UserSignFiles[0] != null)
                                            {
                                                return <table><tr><td style={{width:'50%'}}><b>{(item.NAME? item.NAME: "")}</b><br/>
                                                {("审批结论："+(item.CONTEXT===undefined?"同意":item.CONTEXT ))}<br/> 
                                                {("审核时间："+item.NODE_APPROVE_TIME)}</td>
                                                <td><br/><img style={{ margin: "0 0 0 15px",width:'150px' }} alt={item.Nav_ApproveUser.NAME} src={config.picServerHost + item.Nav_ApproveUser.Nav_UserSignFiles[0].Nav_ImgFile.Nav_File.FILE_PATH} />
                                                </td></tr>
                                                <tr><td colSpan={2}><hr style={{border:'1px dashed #ccc'}}></hr></td></tr>
                                                </table>
                                            }
                                            else
                                            {
                                                return <table><tr><td style={{width:'50%'}}><b>{(item.NAME? item.NAME: "")}</b><br/>
                                                {("审批结论："+(item.CONTEXT===undefined?"同意":item.CONTEXT ))}<br/> 
                                                {("审核时间："+item.NODE_APPROVE_TIME)}</td>
                                                <td><br/><img style={{ margin: "0 0 0 15px",width:'150px' }} title={item.Nav_ApproveUser.NAME} />
                                                </td></tr>
                                                <tr><td colSpan={2}><hr style={{border:'1px dashed #ccc'}}></hr></td></tr>
                                                </table>
                                            }
                                        }
                                    })
                        }</div></Descriptions.Item>
                        </Descriptions>
                     </div>:null
                    } */}
                     {
                     this.state.data && this.state.data[0]?
                     <div style={{display: this.state.BtnAgreeDisplay,backgroundColor:"#fff"}}>
                       <table style={{ width: '100%', textAlign: 'center', borderTop: '1px solid #333', borderLeft: '1px solid #333' }} className={styles.PrintForm}>
                       <tbody>
                        <tr>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>审批详情</td>
                                <td colSpan={8} rowSpan={1}>{
                                    this.state.data[0].Nav_ApproveDetails && this.state.data[0].Nav_ApproveDetails.map((item, i) => {
                                        if (item.NODE_APPROVE_STATUS != 0) {
                                            if (item.Nav_ApproveUser != null && item.Nav_ApproveUser.Nav_UserSignFiles[0] != null)
                                            {
                                                return <table style={{border:"0",width:'100%', textAlign: 'left'}}><tbody><tr><td style={{border:"0"}}><b>{(item.NAME? item.NAME: "")}</b><br/>
                                                {("审批结论："+(item.CONTEXT===undefined?"同意":item.CONTEXT ))}<br/> 
                                                {("审核时间："+item.NODE_APPROVE_TIME)}</td>
                                                <td style={{border:"0"}}><br/><img style={{ margin: "0 0 0 15px",width:'150px' }} alt={item.Nav_ApproveUser.NAME} src={config.picServerHost + item.Nav_ApproveUser.Nav_UserSignFiles[0].Nav_ImgFile.Nav_File.FILE_PATH} />
                                                </td></tr>
                                                <tr><td colSpan={2} style={{border:"0"}}><hr style={{border:'1px dashed #ccc'}}></hr></td></tr>
                                                </tbody>
                                                </table>
                                            }
                                            else
                                            {
                                                return <table style={{border:"0",width:'100%', textAlign: 'left'}}><tbody><tr><td style={{border:"0"}}><b>{(item.NAME? item.NAME: "")}</b><br/>
                                                {("审批结论："+(item.CONTEXT===undefined?"同意":item.CONTEXT ))}<br/> 
                                                {("审核时间："+item.NODE_APPROVE_TIME)}</td>
                                                <td style={{border:"0"}}><br/><img style={{ margin: "0 0 0 15px",width:'150px' }} title={item.Nav_ApproveUser.NAME} />
                                                </td></tr>
                                                <tr><td colSpan={2} style={{border:"0"}}><hr style={{border:'1px dashed #ccc'}}></hr></td></tr></tbody>
                                                </table>
                                            }
                                        }
                                    })
                        }</td>
                        </tr>
                       </tbody>
                        </table>
                     </div>:null
                    }
            </Layout >

        )
    }
}
export default connect(({ login, app }) => ({ login, app }))(Form.create()(PFCommonApproveView))