/*
 * Creater:     YQL
 * CreateDate:  2022/11/15
 * Describe：   公共医保对账模块
 * */
import React, { Component } from 'react';
import { message, Input, Button, Col, Form, Row, DatePicker, Spin, Select, Drawer } from 'antd';
import moment from 'moment';
import { Util, dayFormat } from 'tools/index';
import PubilcTablePagination from '../common/PubilcTablePagination';
import fetchJsonp from "fetch-jsonp";
import store from "../../store";
const FormItem = Form.Item;
const { TextArea } = Input;
class PublicMedInsuRecord extends Component {
    constructor(props) {
        super(props);
        this.state = {
            page: 1,
            pageSize: 20,
            total: 0,
            loading: false,
            startDate: '',
            endDate: '',
            status: '', //状态  ''全部,0队列中,1对账中,2对账成功,99对账失败
            columns: [],
            insuToRecordData: [],
            insuToParams: '',  //当前功能模块传参
            typeResultOBJ: {},    //当前功能模型配置详情
            modalFunType: '',    //当前功能模块调用类型，取决于核心功能配置的reqType: 'code'/'dll'
            formData: {},    //Table组件表单数据
            maskStatus: false, //整体遮罩
            drawerVisible: false, //抽屉显示-隐藏
            insuValue: '',    //抽屉内富文本内容
            drawerItemsRecord: ''    //展开详情时选中的行元素内容
        }
    }

    componentDidMount() {
        let params = '';
        if (this.props.location) {
            if (this.props.location.state) { params = this.props.location.state?.params || ''; }
        } else {
            if (this.props.paras) {
                params = this.props.paras?.params || '';
            } else {
                params = this.props?.params || '';
            }
        }
        params !== '' ? sessionStorage.setItem('insuToParams', params) : '';
        let insuToParams = sessionStorage.getItem('insuToParams');
        this.setState({
            insuToParams: params ? params : insuToParams
        }, function () {
            this.getColumn();
            this.getDrawColumn();
            this.getTypeInfo();
        });
    }

    // 获取表头信息
    getColumn = async () => {
        let data = {
            params: [{
                compontName: Util.getValueByUrlStr(this.state.insuToParams, 'componentName'),
                type: 'C',
                reactCode: [Util.getValueByUrlStr(this.state.insuToParams, 'componentName')]
            }]
        };
        const resObj = await React.$asyncPost(this, '01040073', data);
        if (resObj) {
            let errorCode = resObj.errorCode;
            if (+errorCode === 0) {
                let columns = resObj.result && resObj.result.C.length > 0 ? JSON.parse(JSON.stringify(resObj.result.C)).map(item => {
                    if (item.code === 'action') {
                        return {
                            align: item.align,
                            widthNum: parseInt(item.width),
                            width: item.width,
                            dataIndex: item.dataIndex,
                            title: item.title,
                            display: item.display,
                            key: item.seqNo,
                            render: (text, record) => (
                                <span>
                                    {this.state.typeResultOBJ?.detail?.visible === 'Y' ?
                                        <span style={{ color: 'rgba(1,6,0,0.57)', marginRight: '15px', cursor: 'pointer' }} onClick={() => this.insuToRecordItemDetail(record)}>详情</span> : ''}

                                    {this.state.typeResultOBJ?.reconciliation?.visible === 'Y' ?
                                        +record.ledgerResult === 0 || +record.ledgerResult === 3 ?
                                            <span style={{ color: '#2e41ff', cursor: 'pointer' }} onClick={() => this.insuToRecordItemAct(record)}>对账</span> :
                                            +record.ledgerResult === 2 ? <span style={{ color: '#2e41ff', cursor: 'pointer' }} onClick={() => this.insuToRecordItemAct(record)}>重新对账</span> : ''
                                        : ''}
                                </span>
                            )
                        }
                    } else {
                        return {
                            align: item.align,
                            widthNum: parseInt(item.width),
                            width: item.width,
                            dataIndex: item.dataIndex,
                            title: item.title,
                            display: item.display,
                            key: item.seqNo
                        }
                    }
                }) : '';
                this.renderList(columns);//对指定的列进行渲染操作
                this.setState({
                    columns: columns,
                    formData: resObj.result?.formData
                });
                this.getFormDictData(resObj.result?.formData);//获取表单内的字典数据
            } else {
                message.error(resObj.errorMessage)
            }
        }
    };

    //获取表单内的字典数据
    getFormDictData = async (formData) => {
        if (!formData || formData.length < 1) {
            return
        }
        for (let i = 0; i < formData.length; i++) {
            //linkCode 有值，说明需要通过请求获取该表单类型下的字典
            if (formData[i].linkCode) {
                let data = {
                    params: [{
                        modularType: Util.getValueByUrlStr(this.state.insuToParams, 'modularType')
                    }]
                };
                const resObj = await React.$asyncPost(this, formData[i].linkCode, data);
                if (resObj) {
                    let errorCode = resObj.errorCode;
                    if (+errorCode === 0) {
                        this.setState({
                            [formData[i].code + "Dict"]: Util.addKeyValueToDataSource(resObj.result.Data)
                        })
                    } else {
                        message.error(resObj.errorMessage)
                    }
                }
            }
        }
    };

    //对表头列进行渲染操作
    renderList = (columnsValue) => {
        for (let i = 0; i < columnsValue.length; i++) {
            //状态渲染
            if (columnsValue[i].dataIndex === 'ledgerResult') {
                columnsValue[i].render = (text) => {
                    if (+text === 0) {
                        return (<span style={{ color: '#c8c8c8' }}>未对账</span>)
                    } else if (+text === 1) {
                        return (<span style={{ color: '#45B38E' }}>对账中</span>)
                    } else if (+text === 2) {
                        return (<span style={{ color: '#0c74ee' }}>对账成功</span>)
                    } else if (+text === 3) {
                        return (<span style={{ color: '#EE3F3F' }}>对账失败</span>)
                    }
                }
            }
        }
    };

    // 获取抽屉组件表头信息
    getDrawColumn = async () => {
        let data = {
            params: [{
                compontName: Util.getValueByUrlStr(this.state.insuToParams, 'componentDrawerName'),
                type: 'C',
                reactCode: [Util.getValueByUrlStr(this.state.insuToParams, 'componentDrawerName')]
            }]
        };
        const resObj = await React.$asyncPost(this, '01040073', data);
        if (resObj) {
            let errorCode = resObj.errorCode;
            if (+errorCode === 0) {
                let drawColumns = resObj.result && resObj.result.C.length > 0 ? JSON.parse(JSON.stringify(resObj.result.C)).map(item => {
                    return {
                        align: item.align,
                        widthNum: parseInt(item.width),
                        width: item.width,
                        dataIndex: item.dataIndex,
                        title: item.title,
                        display: item.display,
                        key: item.seqNo
                    }
                }) : '';
                this.setState({
                    drawColumns
                });
            } else {
                message.error(resObj.errorMessage)
            }
        }
    };

    //获取功能类型配置详情
    getTypeInfo = async () => {
        let data = {
            params: [{
                modularType: Util.getValueByUrlStr(this.state.insuToParams, 'modularType')
            }]
        };
        const resObj = await React.$asyncPost(this, '15010100', data);
        if (resObj) {
            let errorCode = resObj.errorCode;
            if (+errorCode === 0) {
                this.setState({
                    typeResultOBJ: resObj?.result,
                    modalFunType: resObj?.result?.reconciliation?.reqType
                }, function () {
                    this.insuToRecordListQuery();
                });
            } else {
                message.error(resObj.errorMessage)
            }
        }
    };

    //查询
    insuToRecordListQuery = async () => {
        let { page, pageSize } = this.state;
        let formValuesOBJ = this.getFormValues();
        let data = {
            params: [{
                modularType: Util.getValueByUrlStr(this.state.insuToParams, 'modularType'),
                componentName: Util.getValueByUrlStr(this.state.insuToParams, 'componentName'),
                ...formValuesOBJ
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page
            }]
        };
        let resObj = await this.requestWayPackage('query', data);
        if (resObj) {
            let errorCode = resObj.errorCode;
            if (+errorCode === 0) {
                let resListData = resObj.result && resObj.result.Data;
                if (!resListData || resListData.length === 0) {
                    message.warning('查询数据为空！');
                    this.setState({
                        insuToRecordData: [],
                        total: 0
                    });
                    return
                }
                for (let i = 0; i < resListData.length; i++) {
                    resListData[i].key = i;
                }
                this.setState({
                    insuToRecordData: Util.addKeyValueToDataSource(resListData),
                    total: resObj.result.TotalCount
                }, function () {
                    this.setState({
                        maskStatus: false
                    });
                })
            } else {
                message.error(resObj.errorMessage)
            }
        }
    };

    //刷新
    insuToRecordRefresh = async () => {
        let formValuesOBJ = this.getFormValues();
        let data = {
            params: [{
                modularType: Util.getValueByUrlStr(this.state.insuToParams, 'modularType'),
                componentName: Util.getValueByUrlStr(this.state.insuToParams, 'componentName'),
                ...formValuesOBJ
            }]
        };
        let resObj = await this.requestWayPackage('refresh', data);
        if (resObj) {
            let errorCode = resObj.errorCode;
            if (+errorCode === 0) {
                this.insuToRecordListQuery();
            } else {
                message.error(resObj.errorMessage)
            }
        }
    };

    //全量对账
    insuToRecordALLAct = async () => {
        let { insuToRecordData } = this.state;
        let that = this;
        if (!insuToRecordData || insuToRecordData.length < 1) {
            message.warning('没有可对账数据！');
            return
        }
        for (let i = 0; i < insuToRecordData.length; i++) {
            //批量时，未对账跟对账失败的才允许调用对账
            if (+insuToRecordData[i].ledgerResult === 0 || +insuToRecordData[i].ledgerResult === 3) {
                if (i === insuToRecordData.length - 1) {
                    await that.insuToRecordItemAct(insuToRecordData[i])
                } else {
                    await that.insuToRecordItemAct(insuToRecordData[i], 'ing')
                }
            }
        }
    };

    //详情
    insuToRecordItemDetail = async (record) => {
        let data = {
            params: [{
                modularType: Util.getValueByUrlStr(this.state.insuToParams, 'modularType'),
                items: { ...record }
            }]
        };
        let resObj = await this.requestWayPackage('detail', data);
        if (resObj) {
            let errorCode = resObj.errorCode;
            if (+errorCode === 0) {
                this.setState({
                    drawerVisible: true,
                    insuToDrwaRecordData: resObj?.result?.Data,
                    insuValue: resObj?.result?.TextValue,
                    drawerItemsRecord: record
                });
            } else {
                message.error(resObj.errorMessage)
            }
        }
    };

    //对账
    insuToRecordItemAct = async (record, state, newitems) => {
        let formValuesOBJ = this.getFormValues();
        let data = {
            params: [{
                modularType: Util.getValueByUrlStr(this.state.insuToParams, 'modularType'),
                ...formValuesOBJ,
                items: { ...record },
                newitems
            }]
        };
        //显示遮罩
        this.setState({
            maskStatus: true
        });
        let resObj = await this.requestWayPackage('reconciliation', data);
        if (resObj) {
            let errorCode = resObj.errorCode;
            if (+errorCode === 0) {
                this.setState({ maskStatus: false });
                if (state !== 'ing') {
                    this.insuToRecordListQuery();
                }
            } else {
                this.setState({ maskStatus: false });
                message.error(resObj.errorMessage)
            }
            //保存记录
            let markData = {
                params: [{
                    modularType: Util.getValueByUrlStr(this.state.insuToParams, 'modularType'),
                    items: { ...record },
                    result: resObj
                }]
            };
            if (this.state.modalFunType === 'dll') {
                const markResObj = await this.requestWayPackage('mark', markData);
            }
        }
    };

    //获取Form表单键值，处理日期值的格式
    getFormValues = () => {
        let formValues = this.props.form.getFieldsValue();
        formValues.startDate = moment(formValues?.startDate).format(dayFormat);
        formValues.endDate = moment(formValues?.endDate).format(dayFormat);
        return formValues
    };

    // 提供修改page和pageSize的回调函数
    compilePage = (page, pageSize) => {
        this.setState({ page, pageSize }, () => {
            this.insuToRecordListQuery();
        })
    };

    //公共对账组件请求方式封装  CODE/DLL
    requestWayPackage = async (type, data) => {
        let { typeResultOBJ } = this.state;
        let requestParams = typeResultOBJ[type];
        if (requestParams?.reqType === 'dll') {
            const resObj = await React.$asyncPost(this, requestParams?.reqCode, data);
            if (resObj) {
                let errorCode = resObj.errorCode;
                if (+errorCode === 0) {
                    let dllParams = "{'inputDir':'" + requestParams?.reqDllRoute + "','clsName':'" + requestParams?.reqDllClsName + "','funcName':'" + requestParams?.reqDllFunName + "','dllInput':'" + JSON.stringify(resObj?.result) + "'}";
                    if (typeof (CefSharp) != "undefined") {   // 新元素定制浏览器
                        CefSharp.BindObjectAsync("xysCefToJavaScripts");
                        return new Promise((resolve, reject) => {
                            xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
                                console.log('公共对账组件DLL反参', returnVale);
                                resolve(JSON.parse(returnVale))
                            })
                        })
                    } else {
                        const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
                        if (frame) {
                            frame.DynamicLoadingDLL(dllParams)
                                .then(
                                    data => {
                                        console.log('公共对账组件DLL反参', data);
                                        resolve(JSON.parse(data));
                                    },
                                    err => {
                                        console.log(err);
                                        reject(err);
                                    }
                                )
                        } else {
                            let data = 'input={"inputDir":"' + requestParams?.reqDllRoute + '","clsName":"' + requestParams?.reqDllClsName + '","funcName":"' + requestParams?.reqDllFunName + '","dllInput":' + JSON.stringify(resObj?.result) + '}';
                            return new Promise((resolve, reject) => {
                                fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
                                    jsonpCallback: 'JsonCallback',
                                    timeout: 500000,
                                }).then(function (response) {
                                    return response.json()
                                }).then(function (json) {
                                    resolve(json);
                                }).catch(function (err) {
                                    reject(err);
                                })
                            })
                        }
                    }
                } else { message.error(resObj.errorMessage) }
            }
        } else if (requestParams?.reqType === 'code') {
            return new Promise((resolve, reject) => {
                const resObj = React.$asyncPost(this, requestParams?.reqCode, data);
                resolve(resObj);
            })
        } else {
            message.warning('无效请求方式，请检查医保基础配置');
        }
    };

    //富文本监听事件
    textAreaChange = (e) => {
        this.setState({
            insuValue: e.target.value
        })
    };

    //抽屉关闭事件
    drawerOnClose = () => {
        this.setState({
            drawerVisible: false,
        });
    };

    render() {
        let { page, pageSize, total, loading, columns, drawColumns, insuToRecordData, insuToDrwaRecordData, modalFunType } = this.state;
        const { getFieldDecorator } = this.props.form;
        const params = {
            page,
            pageSize,
            total,
            loading,
            columns,
            data: insuToRecordData,
            x: 900,
            y: store.getState().tableHeight.y + 81 - this.state.headerHeight,
            height: store.getState().tableHeight.y + 50 - this.state.headerHeight + 'px',
            rowKey: 'insuToId',
            componentName: Util.getValueByUrlStr(this.state.insuToParams, 'componentName')
        };
        const drawParams = {
            columns: drawColumns,
            data: insuToDrwaRecordData,
            x: 900,
            y: store.getState().tableHeight.y + 81 - this.state.headerHeight,
            height: store.getState().tableHeight.y + 50 - this.state.headerHeight + 'px',
            rowKey: 'insuToDrawId',
            componentName: Util.getValueByUrlStr(this.state.insuToParams, 'componentDrawerName')
        };

        return (
            <div>
                <Spin spinning={this.state.maskStatus} tip="对账中，请勿离开...">
                    <Row justify='space-between' style={{ paddingTop: '10px' }}>
                        <Col span={18} style={{ paddingLeft: '20px' }}>
                            <Form>
                                {
                                    this.state.formData && this.state.formData.length > 0 ?
                                        this.state.formData.map((item, index) => {
                                            if (item?.typeCode === 'Date') {
                                                return (
                                                    <Col span={item?.col}>
                                                        <FormItem {...{ labelCol: { span: item?.labelCol }, wrapperCol: { span: item?.wrapperCol } }} label={item?.descripts}>
                                                            {getFieldDecorator(item?.code, {
                                                                initialValue: moment(new Date, dayFormat).subtract(item?.default, 'days'),
                                                                rules: [{ required: false, message: item?.placeholder }],
                                                            })(
                                                                <DatePicker
                                                                    allowClear={false}
                                                                    placeholder={item?.placeholder}
                                                                    format={dayFormat} />
                                                            )}
                                                        </FormItem>
                                                    </Col>
                                                )
                                            } else if (item?.typeCode === 'Input') {
                                                return (
                                                    <Col span={item?.col}>
                                                        <FormItem {...{ labelCol: { span: item?.labelCol }, wrapperCol: { span: item?.wrapperCol } }} label={item?.descripts}>
                                                            {getFieldDecorator(item?.code, {
                                                                initialValue: item?.default,
                                                                rules: [{ required: false, message: item?.placeholder }],
                                                            })(
                                                                <Input placeholder={item?.placeholder} />
                                                            )}
                                                        </FormItem>
                                                    </Col>
                                                )
                                            } else if (item?.typeCode === 'Select') {
                                                return (
                                                    <Col span={item?.col}>
                                                        <FormItem {...{ labelCol: { span: item?.labelCol }, wrapperCol: { span: item?.wrapperCol } }} label={item?.descripts}>
                                                            {getFieldDecorator(item?.code, {
                                                                initialValue: item?.default,
                                                                rules: [{ required: false, message: item?.placeholder }],
                                                            })(
                                                                <Select allowClear showSearch>{
                                                                    this.state[item?.code + "Dict"] && this.state[item?.code + "Dict"].map(data => {
                                                                        return (<Select.Option value={data?.code} key={data?.id}>{data?.desc}</Select.Option>)
                                                                    })
                                                                }
                                                                </Select>
                                                            )}
                                                        </FormItem>
                                                    </Col>
                                                )
                                            } else {

                                            }
                                        })
                                        : ''
                                }
                            </Form>
                        </Col>
                        <Col span={6} style={{ textAlign: 'right', paddingRight: '20px' }}>
                            <Button type='primary' onClick={() => this.insuToRecordListQuery()}>查询</Button>
                            <Button type='primary' style={{ marginLeft: '10px' }} onClick={() => this.insuToRecordRefresh()}>刷新</Button>
                            {modalFunType === 'dll' && this.state.typeResultOBJ?.reconciliation?.visible === 'Y' ? <Button type='primary' style={{ marginLeft: '10px' }} onClick={() => this.insuToRecordALLAct()}>全量对账</Button> : ''}
                        </Col>
                    </Row>
                    <Row style={{ marginTop: 20 }}>
                        <PubilcTablePagination param={params} compilePage={this.compilePage} getColumns={this.getColumn} />
                    </Row>

                    <Drawer style={{ paddingTop: '50px' }}
                        title="汇总信息" placement="right" closable={true} width='50%' onClose={this.drawerOnClose} visible={this.state.drawerVisible}>
                        <Row gutter={10} style={{ marginBottom: '15px' }}>
                            <Col span={this.state.typeResultOBJ?.detail?.recVisible === 'Y' ? 22 : 24}>
                                <TextArea rows={4} value={this.state.insuValue} onChange={(e) => this.textAreaChange(e)} />
                            </Col>
                            {this.state.typeResultOBJ?.detail?.recVisible === 'Y' ?
                                <Col span={2}>
                                    <Button style={{ width: '90px', height: '90px' }} type='primary' onClick={() => this.insuToRecordItemAct(this.state.drawerItemsRecord, '', this.state.insuValue)}>发起对账</Button>
                                </Col> : ''
                            }
                        </Row>
                        <PubilcTablePagination param={drawParams} getColumns={this.getDrawColumn} />
                    </Drawer>
                </Spin>
            </div>
        );
    }
}
const PublicMedInsuRecordForm = Form.create()(PublicMedInsuRecord);
export default PublicMedInsuRecordForm;
