import { message } from "antd/lib/index";
import { Layout, Tabs, Steps, Button, Popconfirm, Row, Col, Icon, Form, Input, Select, Table, Drawer } from 'antd';
import React from 'react';
import { PlusOutlined, ArrowRightOutlined, SearchOutlined } 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,
    getIsPC
} from "../../../utils/common";
import FormPage from '../../../components/FormPage'
class PFCommonApprove extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            title: '流程审核',
            data: {},
            approveCode: '',
            isCurrent: false,
            tmpData: {},
            visible: false,
            userData: [],
            selectUserId: '',
            appVisible: false,
            comVisible: true,
            btnDisplay: 'block',
            stepDisplay: 'block',
            isRequired: false,
            isPC: getIsPC(),
            BtnAgreeDisplay: 'none',
            BtnRejectDisplay: 'none',
            isOKLoad: false,
            isRejectLoad: false,
            REJECT_INTERFACE: ''
        }
    };
    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);
        }
    }

    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();
    }
    onsubmit = () => {
        this.props.form.validateFields((err, values) => {
            console.log(this.state.data)
            //console.log('Received values of form: ', values);
            if (err) {
                return;
            }
            var newUrl = ''//新api判断 
            // switch (this.state.data.CALLBACK_INTERFACE) {
            //     case 'BS/BSSafeCheck/CheckPlanAuditEnd':
            //     case 'BS/BSSafeCheck/CheckAuditEnd':
            //     case 'BS/BSRiskSubmit/Notice':
            //     case 'BS/BSRiskSubmit/DealEnd':
            //     case 'BS/BSRiskSubmitDelayApply/DealEnd':
            //     case 'FO/FOCrucialLicenseJob/BackUpdate':
            //     case 'FO/FOCrucialLicenseJobOutsource/BackUpdate':
            //     case 'FO/FOJobEventRecord/BackUpdate':
            //         newUrl = this.state.data.CALLBACK_INTERFACE + 'New'
            //         break;
            //     case 'TL/TLBack/BackUpdate':
            //     case 'TL/TLBackRecord/BackUpdate':
            //     case 'DM/DMDeviceBasePurchase/BackUpdate':
            //     case 'DM/DMDeviceBasePurchase/BackUpdateUser':
            //         newUrl = this.state.data.CALLBACK_INTERFACE
            //         break;
            //     default:
            //         break;
            // }
            if (this.state.data.CALLBACK_INTERFACE && this.state.data.CALLBACK_INTERFACE.indexOf("New") > -1) {
                newUrl = this.state.data.CALLBACK_INTERFACE
            }
            if (newUrl.length > 0) {
                this.props.dispatch({
                    type: 'app/getDataByPost',
                    url: newUrl,
                    payload: this.state.data,
                    onlyData: false,
                    onComplete: (re) => {
                        if (re && re.IsSuccessful) {
                            message.success("提交审批成功");
                            this.BtnClose();
                        } else {
                            this.setState({
                                isRequired: true,
                                isOKLoad: false,
                                isRejectLoad: false
                            })
                            message.error("提交审批失败");
                        }
                    }
                })
            } else {
                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 {
                                            //回调失败记录log
                                            this.props.dispatch({
                                                type: 'app/getDataByPost',
                                                url: 'PF/Approve/AddLog',
                                                payload: this.state.data,
                                                onlyData: false,
                                                onComplete: (ret) => {
                                                    if (ret && ret.IsSuccessful) {

                                                    }
                                                }
                                            })
                                            this.setState({
                                                isRequired: true,
                                                isOKLoad: false,
                                                isRejectLoad: false
                                            })
                                            message.error("提交审批成功，回调失败");
                                        }
                                    }
                                });

                            }
                            else {
                                //     //回调失败记录log
                                //     this.props.dispatch({
                                //         type: 'app/getDataByPost',
                                //         url: 'PF/Approve/AddLog',
                                //         payload: this.state.data,
                                //         onlyData: false,
                                //         onComplete: (ret) => {
                                //             if (ret && ret.IsSuccessful) {

                                //             }
                                //         }
                                //     })
                                message.success("提交审批成功");
                                this.BtnClose();
                            }
                        } else {
                            this.setState({
                                isRequired: true,
                                isOKLoad: false,
                                isRejectLoad: false
                            })
                            message.error("提交审批失败");
                        }
                    }
                })

            }

        });
    }
    onClick = (e) => {
        let tmpData = { ...this.state.data };
        tmpData.TaskID = this.props.data.TaskID
        tmpData.CurrentNode.NODE_APPROVE_STATUS = 10;
        this.setState({
            data: tmpData,
            isRequired: false,
            isRejectLoad: false,
            isOKLoad: true
        }, () => {
            this.onsubmit();
        })
    }
    onComplaint = (e) => {
        if (this.state.selectUserId === '') {
            message.error("请选择转办人");
            return;
        }
        const json = initFilter(this.props.login.OrgId, this.state.data.CurrentNode.ID, '', 0, 1, this.state.selectUserId)
        this.props.dispatch({
            type: 'app/getDataByPost',
            url: 'PF/Approve/Complaint',
            payload: json,
            onlyData: false,
            onComplete: (re) => {
                if (re && re.IsSuccessful) {
                    this.setState({
                        visible: false,
                        userData: [],
                        selectUserId: '',
                    });
                    message.success("转办成功");
                } else {
                    message.error("转办失败");
                }
            }
        })
    }
    showDrawer = () => {
        const jsonUser = initFilter(this.props.login.OrgId, '', '', 0, 1)
        this.props.dispatch({
            type: 'app/getDataByPost',
            url: 'FM/User/OrderEntities',
            payload: jsonUser,
            onlyData: false,
            onComplete: (ret) => {
                if (ret) {
                    this.setState({
                        userData: ret.Data,
                    });
                }
            }
        });
        this.setState({
            visible: true,
            appVisible: false,
        });
    };
    showAppDrawer = () => {
        this.setState({
            visible: false,
            appVisible: true,
        });
    }
    onClose = () => {
        this.setState({
            visible: false,
            appVisible: false,
        });
    };
    onRejectConfirm = () => {
        this.props.form.validateFields((err, values) => {
            console.log(this.state.data)
            //console.log('Received values of form: ', values);
            if (err) {
                return;
            }
            this.state.data.TaskID = this.props.data.TaskID
            if (this.state.REJECT_INTERFACE && this.state.data) {
                this.props.dispatch({
                    type: 'app/getDataByPost',
                    url: this.state.REJECT_INTERFACE,
                    payload: this.state.data,
                    onlyData: false,
                    onComplete: (callbak) => {
                        if (callbak && callbak.IsSuccessful) {
                            message.success("驳回成功");
                            this.BtnClose();
                        } else {
                            this.setState({
                                isRequired: true,
                                isOKLoad: false,
                                isRejectLoad: false
                            })
                            message.error("驳回失败");
                        }
                    }
                });
            }
            else {
                message.success("驳回接口未配置或者未获取到审批数据");

                this.setState({
                    isRequired: true,
                    isOKLoad: false,
                    isRejectLoad: false
                })
                return;
            }
        });
    }
    onReject = () => {
        // message.success("驳回功能完善中,暂无法使用");
        // return;
        let tmpData = { ...this.state.data };

        tmpData.CurrentNode.NODE_APPROVE_STATUS = 20;
        this.setState({
            data: tmpData,
            isRequired: true,
            isOKLoad: false,
            isRejectLoad: true
        }, () => {
            this.onRejectConfirm();
        })
    }
    loadData(dataId) {
        let that = this;
        if (window.navigator.userAgent.indexOf("Windows") < 1) {
            that.setState({
                appVisible: false,
                comVisible: false,
                btnDisplay: 'block',
                stepDisplay: 'none'
            });
        } else {
            that.setState({
                appVisible: false,
                comVisible: true,
                btnDisplay: 'none',
                stepDisplay: 'block'
            });
        }
        const json = initFilter(that.props.login.OrgId)
        extendRule(json, 'ID', 1, dataId);
        extendInclude(json, "Nav_ApproveDetails")
        extendInclude(json, "Nav_ApproveDetails.Nav_ApproveUser")
        that.props.dispatch({
            type: 'app/getDataByPost',
            url: 'PF/PFApprove/FullGet',
            payload: json,
            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: that.props.app.enums,
                            loadDataDeal: this.loadDataDeal,
                            // btnDisplay : 'none'
                        },

                        formCode: re.Data.APPROVE_CODE,

                    }
                    re.Data.Nav_ApproveDetails.sort(that.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 == that.props.login.userId);
                        if (currentUserNode != null) {
                            isCurrent = true;
                            re.Data.CurrentNode = currentUserNode[0];
                        } else {
                            re.Data.CurrentNode = currentNodes[0];
                        }
                        if (re.Data.CurrentNode != undefined) {
                            re.Data.CurrentNode.NODE_APPROVE_STATUS = 10;
                        }
                    }
                    that.setState({
                        //editData,
                        isCurrent,
                        tmpData: newtmpData,
                        title: re.Data.NAME,
                        data: re.Data,
                        BtnRejectDisplay: re.Data.REJECT_INTERFACE && newtmpData ? 'inline' : 'none',
                        REJECT_INTERFACE: re.Data.REJECT_INTERFACE ? re.Data.REJECT_INTERFACE : ''
                    });
                    if (that.props.data.tableKey === "2" || that.props.data.tableKey === undefined) {
                        that.setState({ BtnAgreeDisplay: 'none' })
                    } else {
                        that.setState({ BtnAgreeDisplay: 'inline' })
                    }
                    //如果审批模板有配置驳回接口，才显示驳回按钮
                    // if (re.Data.APPROVE_TEMP_ID) {
                    //     const jsonReject = initFilter(that.props.login.OrgId)
                    //     extendRule(jsonReject, 'ID', 1, re.Data.APPROVE_TEMP_ID);
                    //     this.props.dispatch({
                    //         type: 'app/getDataByPost',
                    //         url: 'PF/ApproveTemp/Get',
                    //         payload: jsonReject,
                    //         onlyData: false,
                    //         onComplete: (ret) => {
                    //             if (ret && ret.IsSuccessful) {

                    //                 if (ret.Data && ret.Data.REJECT_INTERFACE) {
                    //                     that.setState({ BtnRejectDisplay: 'inline', REJECT_INTERFACE: ret.Data.REJECT_INTERFACE })
                    //                 } else {
                    //                     that.setState({ BtnRejectDisplay: 'none', REJECT_INTERFACE: '' })
                    //                 }
                    //             }
                    //         }
                    //     })
                    // }

                    //如果状态为驳回，则修改为已阅，点开一次后列表不再显示
                    // if (re.Data.APPROVE_STATUS === 20) {
                    //     this.props.dispatch({
                    //         type: 'app/getDataByPost',
                    //         url: 'PF/Approve/ChangeStatus',
                    //         payload: re.Data,
                    //         onlyData: false,
                    //         onComplete: (ret) => {
                    //             if (ret && ret.IsSuccessful) {
                    //                 message.success("驳回的表单已阅后将不再显示");
                    //             }
                    //         }
                    //     });
                    // }
                }
            }
        })
    }
    loadDataDeal = (a) => {
        if (a == 1) {
            this.setState({ BtnAgreeDisplay: 'inline' })
        }
    }


    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: 2 },
            // wrapperCol: { span: 20 },
        };
        const stepStyle = {
            marginBottom: 60,
            boxShadow: '0px -1px 0 0 #e8e8e8 inset',
        };
        const onChangeRemark = (e) => {
            let tmpData = { ...this.state.data };
            tmpData.CurrentNode.CONTEXT = e.target.value;
            this.setState({
                data: tmpData
            });
        }
        const LayoutStyle = {
            marginLeft: 200
        }
        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'
                }}> */}
                    <Steps 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} />
                        })}
                    </Steps>
                    {/* </Sider> */}
                </Drawer>
                {/* <Sider 
                    style={{
                    overflow: 'auto',
                    height: '100vh',
                    position: 'fixed',
                    left: 20,
                    background: '#FFF',
                    display:this.state.stepDisplay
                }}>
                    <Steps current={0} direction="vertical" type="navigation" style={{ display: this.state.stepDisplay }}>
                        {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>
                </Sider> */}
                {/* style={this.state.comVisible?LayoutStyle:null} */}
                <Layout style={{ background: '#fff' }}>
                    {/* <Header style={{ background: '#fff', padding: 0 }}>
                  
                    </Header> */}
                    <Content>
                        <FormPage {...this.state.tmpData} loadData={this.loadDataDeal} />
                        <Form>{/*onSubmit={this.onClick}  className="ant-advanced-search-form"*/}
                            <Row style={{ marginTop: '10px' }}>
                                {/* <Col span={12}>
                                    <Form.Item
                                        label={'编码'}
                                        {...formItemLayout}
                                    >
                                        {getFieldDecorator('CODE', {
                                            validateTrigger: 'onBlur',
                                            initialValue: getDataFieldValue(this.state.data, 'CODE'),
                                        })(<Input disabled={true} />)}
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item
                                        label={'名称'}
                                        {...formItemLayout}
                                    >
                                        {getFieldDecorator('NAME', {
                                            validateTrigger: 'onBlur',
                                            initialValue: getDataFieldValue(this.state.data, 'NAME'),
                                        })(<Input disabled={true} />)}
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item
                                        label={'当前节点'}
                                        {...formItemLayout}
                                    >
                                        {getFieldDecorator('CurrentNode.NAME', {
                                            validateTrigger: 'onBlur',
                                            initialValue: getDataFieldValue(this.state.data, 'CurrentNode.NAME'),
                                        })(<Input disabled={true} />)}
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item
                                        label={'审批用户'}
                                        {...formItemLayout}
                                    >
                                        {getFieldDecorator('CurrentNode.Nav_ApproveUser.NAME', {
                                            validateTrigger: 'onBlur',
                                            initialValue: getDataFieldValue(this.state.data, 'CurrentNode.Nav_ApproveUser.NAME'),
                                        })(<Input disabled={true} />)}
                                    </Form.Item>
                                </Col> */}
                                {

                                    this.state.isCurrent ? <row>
                                        {/* <Col span={12}>
                                            <Form.Item
                                                label={'审批结果'}
                                                {...formItemLayout}
                                            >
                                                <Select onChange={this.onchange} defaultValue={10}>
                                                    {
                                                        enums && enums["NodeApproveOption"] && enums["NodeApproveOption"].options
                                                            ? enums["NodeApproveOption"].options.map(t => {
                                                                return <Option value={t.value} key={"NodeApproveOption" + t.value} >{t.label}</Option>
                                                            }) : null
                                                    }
                                                </Select>
                                            </Form.Item>
                                        </Col> */}
                                        {/* <Col span={24}>
                                            <hr style={{margin:"0 20px 20px 20px"}}></hr>
                                        </Col> */}
                                        <Col style={{ display: this.state.BtnAgreeDisplay }}>
                                            <Form.Item style={{ margin: '0 50px 0 65px' }}
                                                label={'审批意见'}
                                                {...formItemLayout}
                                            >
                                                {getFieldDecorator('CurrentNode.CONTEXT', {
                                                    rules: [
                                                        {
                                                            required: this.state.isRequired,
                                                            message: `请输入审批意见!`,
                                                        },
                                                    ],
                                                    validateTrigger: 'onBlur',
                                                    initialValue: getDataFieldValue(this.state.data, 'CurrentNode.CONTEXT'),
                                                })(<TextArea disabled={false} onChange={onChangeRemark} />)}
                                            </Form.Item>
                                        </Col>
                                        <Col style={{ display: this.state.BtnAgreeDisplay }}>
                                            <Form.Item>
                                                {
                                                    this.state.isPC ?
                                                        <Row>
                                                            <Button type="primary" htmlType="submit" icon="check" onClick={this.onClick} loading={this.state.isOKLoad} labelCol={2} wrapperCol={20} className={styles.agreedWeb}>同意</Button>
                                                            <Button type="primary" htmlType="submit" icon="close" onClick={this.onReject} loading={this.state.isRejectLoad} labelCol={2} wrapperCol={20} className={styles.rejectedWeb} style={{ display: this.state.BtnRejectDisplay }}>驳回</Button>
                                                        </Row>
                                                        :
                                                        <Row style={{ textAlign: 'center' }}>
                                                            <Button type="primary" htmlType="submit" icon="check" onClick={this.onClick} loading={this.state.isOKLoad} className={styles.agreedPhone}>同意</Button>
                                                            <Button type="primary" htmlType="submit" icon="close" onClick={this.onReject} loading={this.state.isRejectLoad} className={styles.rejectedPhone} style={{ display: this.state.BtnRejectDisplay }}>驳回</Button>
                                                        </Row>
                                                }
                                            </Form.Item>
                                        </Col>
                                    </row>
                                        : null

                                }
                            </Row>
                        </Form>


                    </Content>
                </Layout >
                {/* <Drawer
                    title="选择转办人"
                    width={300}
                    onClose={this.onClose}
                    visible={this.state.visible}
                    bodyStyle={{ paddingBottom: 80 }}

                >
                    <Form layout="vertical" hideRequiredMark>
                        <Row gutter={16}>
                            <Col span={12}>
                                <Form.Item
                                    label={'转办人'}
                                    {...formItemLayout}
                                >
                                    <Select
                                        showSearch
                                        style={{ width: 200 }}
                                        placeholder='选择人员'
                                        onChange={this.selectChange}
                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                    >

                                        {
                                            userData
                                                ? userData.map(t => {
                                                    return <Option value={t.ID} key={t.ID}>{t.NAME}</Option>
                                                }) : null
                                        }
                                    </Select>
                                </Form.Item>
                            </Col>

                        </Row>
                        <Row gutter={16}>
                            <Col span={2} style={{ textAlign: 'right' }}>
                                <Form.Item span={4}>
                                    <Button type="primary" htmlType="complaint" icon="issues-close" onClick={this.onComplaint}>确认转办</Button>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Drawer> */}
            </Layout >

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