// 医保对照
import React from 'react';
import '../../assets/css/system.css';
import '../../assets/css/App.css';
import store from '../../store';
import { Table, Input, Radio, Row, Col, Button, Spin, Modal, Card, Select } from 'antd';
import { $http } from '../../containers/config/https';
import { Util } from 'tools/index';
import MedicalInsurance from './MedicalInsurance'
import StandardClassification from './component/StandardClassification';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

// 主菜单弹框
export default class MedicalInsuranceMain extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            options: [],
            list: [],
            children: '',
            userInfo: {},
            sessionData: {},
            Authoritydata: {},
            // 主菜单列表数据
            data: [],
            // 抽屉显示
            visible: true,
            // 主菜单-代码
            code: '',
            // 主菜单-描述
            describe: '',
            // 主菜单-分类
            FindType: '',
            // 主菜单-分类ID
            TypeID: '',
            // 主菜单-别名
            Alias: '',
            // 主菜单分页数据
            total: 0,
            page: 1,
            pageSize: 200,
            flag: '',
            title: '',
            // 是否显示loading
            showLoading: true,
            // 表格loading
            loading: true,
            selectrowid: '',
            ItemData: {},
            modalTypeVisible: false, // modalTypeVisible
            modalTypeSelectData1: [],
            modalTypeSelectData2: [],
            modalTypeSelectDataArr: [],
            newSelectDataArr: [],
            columns: [],
            languageTable1: {}, // 国际化Table1
            languageTable2: {}, // 国际化Table2
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
            languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
            classificationID: undefined, // 分类
            spec: '',
            isContrast: '', // 对照筛选
            serialID: ''
        };
        this.contrastSelectData = [{
            id: '',
            descripts: '全部',
            descriptsSPCode: 'qb'
        }, {
            id: 'Y',
            descripts: '已对照',
            descriptsSPCode: 'ydz'
        }, {
            id: 'N',
            descripts: '未对照',
            descriptsSPCode: 'wdz'
        }]
    }

    componentDidMount() {
        this.tableList();
        this.setState({
            sessionData: window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {}
        })
        setTimeout(() => {
            this.GetAuthority() //获取权限
        }, 0)
        // 初始化设置table的高度以及表体的高度
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
        // 数据异步请求，请求成功之后setState
        this.setState({
            showLoading: false
        })
        this.modalTypeSelectData1() // 获取子类下拉框数据
    }

    GetAuthority = () => {
        let data = {
            params: [{
                logonGroupID: this.state.sessionData.groupID,
                logonHospID: this.state.sessionData.hospID,
                dataType: "grid",
            }]
        }
        $http.post('urlS', this, {
            code: '01040002',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    this.setState({
                        Authoritydata: res.result
                    })
                    setTimeout(() => {
                        // 初始化列表数据
                        this.handleQuery();
                    }, 0)
                }
            }
        })
    }

    // 新增
    handleAdd = () => {
        // 显示弹框 
        this.child.resetFields()
        this.setState({ ItemData: '' });
        this.child.showModal()
        // 初始化数据  
        this.setState({ flag: 'add', title: '新增' })
    }

    // 查询
    handleQuery = () => {
        this.setState({ loading: true })
        let { code, describe, page, pageSize, classificationID, TypeID, Alias, spec, isContrast, serialID } = this.state;
        let data = {
            params: [{
                code: code,
                descripts: describe,
                FindType: this.state.newSelectDataArr || [], // 分类,
                TypeID: TypeID,
                alias: Alias,
                include: "Hosp",
                groupID: this.state.sessionData.groupID,
                hospID: this.state.sessionData.hospID,
                type: classificationID, // 分类
                specInput: spec,
                /**
                * @ByShizi: 增加筛选已对照-未对照过滤功能
                * 需求 #611
                * Create 2021-05-20
                * */
                flag: isContrast, // 对照情况
                serialID: serialID
                // specInput: '',
                // pprovalNoInput: '', 
                // manfDescInput: ''
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: "Code",
                sortOrder: "asc"
            }]
        }
        $http.post('urlS', this, {
            code: '05100379',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    for (var i = 0; i < res.result.Data.length; i++) {
                        res.result.Data[i].key = i
                    }
                    this.setState({ data: res.result.Data, total: res.result.TotalCount, loading: false, selectrowid: "" })
                } else {
                    setTimeout(() => {
                        this.setState({ data: [], total: 0, loading: false, selectrowid: "" })
                    }, 0)
                }
            }
        })
    }
    //导出
    handleExport = () =>{
        let { code, describe,classificationID, TypeID, Alias, spec, isContrast, serialID } = this.state;
        let data = {
            params: [{
                code: code,
                descripts: describe,
                FindType: this.state.newSelectDataArr || [], // 分类,
                TypeID: TypeID,
                alias: Alias,
                include: "Hosp",
                groupID: this.state.sessionData.groupID,
                hospID: this.state.sessionData.hospID,
                type: classificationID, // 分类
                specInput: spec,
                flag: isContrast, // 对照情况
                serialID: serialID
            }]
        }
        $http.post('urlS', this, {
            code: '05100407',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    document.getElementById("iframe").src= window.location.protocol + "//" + window.location.host + res.result;
                } 
            }
        })
    }
    // 查询条件 --- 代码
    onChangeCode = (e) => {
        this.setState({ code: e.target.value });
    }

    // 查询条件 --- 描述
    onChangeDescribe = (e) => {
        this.setState({ describe: e.target.value });
    }

    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }

    onChangeAlias = (e) => {
        this.setState({ Alias: e.target.value });
    }

    onChangeSpec = (e) => {
        this.setState({ spec: e.target.value });
    }
    onChangeSerialID = (e) => {
        this.setState({ serialID: e.target.value });
    }

    // 设置行属性
    selectRow = (record) => {
        return {
            // 单击行选中
            onClick: () => {
                if (this.state.selectrowid === "") {
                    this.setState({
                        selectrowid: record.tind,
                    });
                    this.child.resetFields()
                    var titleTXT = record.itemDesc + "(" + record.itemCode + ")"
                    this.setState({ ItemData: record, title: titleTXT + '     ----编辑', flag: 'TUpdate', })
                    this.child.showModal()
                } else {
                    if (this.state.selectrowid !== record.tind) {
                        this.setState({
                            selectrowid: record.tind,
                        });
                        this.child.resetFields()
                        var titleTXT = record.itemDesc + "(" + record.itemCode + ")"
                        this.setState({ ItemData: record, title: titleTXT + '     ----编辑', flag: 'TUpdate', })
                        this.child.showModal()
                    } else {
                        this.setState({
                            selectrowid: "",
                        });
                        this.child.resetFields()
                        var titleTXT = record.itemDesc + "(" + record.itemCode + ")"
                        this.setState({ ItemData: record, title: titleTXT + '     ----编辑', flag: 'TUpdate', })
                        this.child.showModal()
                    }
                }
            },
            // 双击行编辑
            // onClick: () => {

            //     this.child.resetFields()
            //     var titleTXT = record.itemDesc + "(" + record.itemCode + ")"
            //     this.setState({ ItemData: record, title: titleTXT + '     ----编辑', flag: 'TUpdate', })
            //     this.child.showModal()
            //     this.setState({
            //         selectrowid: record.Tind,
            //     });
            // },
        }
    }

    setRowClassName = (record) => {
        return record.tind === this.state.selectrowid ? 'clickRowStyle' : '';
    }

    onTypeChange = (value, selectedOptions) => {
        if (selectedOptions.length > 1) {
            this.setState({ FindType: selectedOptions[0].value });
            this.setState({ TypeID: selectedOptions[1].value });

        }
        else {
            this.setState({ FindType: '' });
            this.setState({ TypeID: '' });
        }

    }

    // 弹框打开
    modalType = () => {
        this.setState({
            modalTypeVisible: true
        })
    }

    modalTypeHandleCancel = () => {
        this.setState({
            modalTypeVisible: false
        }, () => {
            this.handleQuery() // 查询
        })
    }

    msg = (data) => {
        this.setState({
            newSelectDataArr: data,
        });
    }

    // 获取子类下拉框数据
    modalTypeSelectData1 = () => {
        let data = {
            params: [{
                hospID: "",
                tartype: 'SUB'
            }]
        }
        $http.post('urlS', this, {
            code: "05100011",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    var arr = []
                    for (let i in res) {
                        let o = {};
                        o[i] = res[i];
                        arr.push(o)
                    }
                    this.setState({ modalTypeSelectData1: arr }, () => {
                        this.modalTypeSelectData2()
                    })
                }
            }
        })
    }

    // 获取子类下拉框数据
    modalTypeSelectData2 = () => {
        let data = {
            params: [{
                hospID: "",
                tartype: ''
            }]
        }
        $http.post('urlS', this, {
            code: "05100011",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    var arr = []
                    for (let i in res) {
                        let o = {};
                        o[i] = res[i];
                        arr.push(o)
                    }
                    this.setState({ modalTypeSelectData2: arr }, () => {
                        let modalTypeSelectDataArr = this.state.modalTypeSelectData1.concat(this.state.modalTypeSelectData2)
                        let arrNew = []
                        modalTypeSelectDataArr.forEach((v, i) => {
                            Object.keys(v).forEach(v => {
                                let o = {}
                                o.name = v //取到了key
                                o.val = modalTypeSelectDataArr[i][v] //取到了值
                                arrNew.push(o)

                            })
                        })

                        let arrNew1 = arrNew.filter((item, i) => {
                            return Object.prototype.toString.call(item.val).indexOf('Array') !== -1    //过滤非数组
                        })
                        arrNew1.map((item, i) => {
                            switch (item.name) {
                                case "ACSUBData":
                                    item.label = '会计子类'
                                    break;
                                case "ECSUBData":
                                    item.label = '核算子类'
                                    break;
                                case "ICSUBData":
                                    item.label = '住院子类'
                                    break;
                                case "MCSUBData":
                                    item.label = '病案子类'
                                    break;
                                case "OCSUBData":
                                    item.label = '门诊子类'
                                    break;
                                case "PCSUBData":
                                    item.label = '物价子类'
                                    break;
                                case "TCSUBData":
                                    item.label = '收费子类'
                                    break;
                                case "ACData":
                                    item.label = '会计科目'
                                    break;
                                case "ECData":
                                    item.label = '核算项目分类'
                                    break;
                                case "ICData":
                                    item.label = '住院收据费用'
                                    break;
                                case "MCData":
                                    item.label = '病案分类'
                                    break;
                                case "OCData":
                                    item.label = '门诊收据费用'
                                    break;
                                case "PCData":
                                    item.label = '物价分类'
                                    break;
                                case "TCData":
                                    item.label = '收费分类'
                                    break;
                                default:
                                    break;
                            }
                        })
                        this.setState({
                            modalTypeSelectDataArr: arrNew1
                        })

                    })
                }
            }
        })
    }

    changeType = (e, index) => {
        let { modalTypeSelectDataArr } = this.state
        modalTypeSelectDataArr[index].id = e
        this.setState({
            modalTypeSelectDataArr: modalTypeSelectDataArr
        })
    }

    onColumnRef = (ref) => {
        // console.log(ref)
        this.columnRef = ref;
    }

    // 获取主列表columns
    tableList = () => {
        var data = {
            params: [{
                "reactCode": ["MenuTaritmmentToIns"],
                "compontName": "MenuTaritmmentToIns",
                "type": "C"
            }]
        }
        // console.log(1, data)
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let resC = res.result.C
                    let { languageCode } = this.state
                    for (var i = 0; i < resC.length; i++) {
                        resC[i].key = i;
                    }
                    if (languageCode === "EN") {
                        resC.map((item, i) => {
                            item.title = item.enDescripts
                        })
                    }

                    if (languageCode === "CN") {
                        resC.map((item, i) => {
                            item.title = item.descripts
                        })
                    }
                    let arr = res.result && resC.length > 0 ? JSON.parse(JSON.stringify(resC)).map(item => {
                        return {
                            align: item.align,
                            widthNum: parseInt(item.width),
                            width: item.width,
                            dataIndex: item.dataIndex,
                            title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>,
                            display: item.display,
                            key: item.seqNo
                        }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    this.setState({
                        columns: filterArr,
                        languageTable1: res.result.B || {},  // 国际化Table1
                        languageTable2: res.result.C || {},  // 国际化Table2
                        languageData: res.result.language || {},  // 国际化语言包
                    }, () => {
                        this.LanCNEN(this.state.languageCode)
                    })
                }
            }
        })
    }

    LanCNEN = (code) => {
        let { languageData } = this.state
        this.setState({
            language: languageData[code]
        })
    }

    // 页码改变的回调，参数是改变后的页码及每页条数
    appPageChange = (page, pageSize) => {
        this.setState({
            page: page,
            pageSize: pageSize,
        }, () => {
            // 重新调用查询方法
            this.handleQuery();
        });
    }

    // 条数改变的回调
    apponShowSizeChange = (current, size) => {
        this.setState({
            page: current,
            pageSize: size,
        }, () => {
            // 重新调用查询方法
            this.handleQuery();
        });
    }

    // 分类
    handleClassificationChange = e => {
        this.setState({ classificationID: e.target.value }, () => {
            this.handleQuery();
        })
    }

    render() {
        let { classificationID, language, languageCode, isContrast } = this.state
        return (
            <div>
                <iframe id="iframe" style={{display:'none'}}></iframe>
                <Spin tip={languageCode === "CN" ? "加载中..." : "Loading..."} spinning={this.state.showLoading}>
                    <div>
                        <Row>
                            <Col span={10}>
                                <Card
                                    size="small"
                                    title={<div className="card-title-left-icon"><div></div>收费项列表</div>}
                                >
                                    <div >
                                        <div >
                                            <Row>
                                                <Col span={24}>
                                                    <Row>
                                                        {/* 代码：<Input placeholder="请输入" value={this.state.code} style={{ width: '100px', marginRight: '10px' }} onChange={this.onChangeCode} /> */}
                                                        {/* 描述：<Input placeholder="请输入" value={this.state.describe} style={{ width: '100px', marginRight: '10px' }} onChange={this.onChangeDescribe} /> */}
                                                        {language.MenuTaritmmentToInsCodeDescAlias && language.MenuTaritmmentToInsCodeDescAlias.descripts}：
                                                        <Input
                                                            placeholder={language.MenuTaritmmentToInsCodeDescAlias && language.MenuTaritmmentToInsCodeDescAlias.message}
                                                            value={this.state.Alias}
                                                            style={{ width: '150px', marginRight: '10px' }}
                                                            onChange={this.onChangeAlias}
                                                            onPressEnter={this.handleQuery} />
                                                        <Radio.Group style={{ marginRight: '90px' }} value={classificationID} onChange={this.handleClassificationChange}>
                                                            <Radio.Button value="drugs">药 品</Radio.Button>
                                                            <Radio.Button value="diagnosi">诊 疗</Radio.Button>
                                                            <Radio.Button value="consumables">耗 材</Radio.Button>
                                                        </Radio.Group>
                                                    </Row>
                                                    <Row style={{ marginTop: '10px' }}>
                                                        规格：
                                                        <Input
                                                            style={{ width: '150px', marginRight: '10px' }}
                                                            placeholder="请输入"
                                                            value={this.state.spec}
                                                            onChange={this.onChangeSpec}
                                                            onPressEnter={this.handleQuery}
                                                        />
                                                        对照：
                                                        <Select
                                                            allowClear
                                                            showSearch
                                                            optionFilterProp="seachprop"
                                                            placeholder="请选择"
                                                            value={isContrast}
                                                            onChange={Util.handleSelectChange.bind(this, 'isContrast')}
                                                            style={{ width: '150px', marginRight: '10px' }}
                                                        >
                                                            {React.$SelectOptions(this.contrastSelectData)}
                                                        </Select>
                                                        晶体ID：
                                                        <Input
                                                            style={{ width: '150px', marginRight: '10px' }}
                                                            placeholder="请输入"
                                                            value={this.state.serialID}
                                                            onChange={this.onChangeSerialID}
                                                            onPressEnter={this.handleQuery}
                                                        />
                                                        <Button
                                                            type="primary"
                                                            className="margiRight16"
                                                            onClick={this.handleQuery}
                                                        >
                                                            {language.MenuTaritmmentToInsquery && language.MenuTaritmmentToInsquery.descripts}
                                                        </Button>

                                                        <Button
                                                            type="primary"
                                                            className="margiRight16"
                                                            onClick={this.handleExport}
                                                        >
                                                            {language.MenuTaritmmentToInsexport && language.MenuTaritmmentToInsexport.descripts}
                                                        </Button>
                                                    </Row>
                                                </Col>
                                                {/* <Col span={24}>
                                                </Col> */}
                                            </Row>
                                        </div>
                                    </div>
                                </Card>
                                {/* <div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%' }}></div> */}
                                <div>
                                    <Table
                                        // style={{ height: store.getState().tableHeight.y + 95 + 'px' }}
                                        dataSource={this.state.data}
                                        columns={this.state.columns}
                                        className='TableA table-body-height'
                                        pagination={false}
                                        scroll={{ x: '5200px', y: store.getState().tableHeight.y }}
                                        bordered
                                        loading={this.state.loading}
                                        onRow={this.selectRow}
                                        rowClassName={this.setRowClassName}
                                    />
                                    <CommonPagination size="large" pageSize="200" current={this.state.page} total={this.state.total} search='search'
                                        onShowSizeChange={this.apponShowSizeChange} complete={true} dataSource={this.state.data}
                                        onChange={this.appPageChange} />
                                    <ColumnAuthoritysModel
                                        clientWidth='900px'
                                        compontName='MenuTaritmmentToIns'
                                        configType="C"
                                        onRef={this.onColumnRef}
                                        reloadData={this.tableList}
                                    />
                                    {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                                    {/* <Pagination
                                    size="small"
                                    showQuickJumper
                                    showSizeChanger
                                    defaultCurrent={1}
                                    total={this.state.total}
                                    onChange={this.onChange}
                                    onShowSizeChange={this.onShowSizeChange}
                                    style={{ textAlign: "right", marginTop: '13px' }}
                                /> */}
                                </div>
                            </Col>
                            <Col span={14}>
                                <div style={{ paddingLeft: '6px', position: 'relative' }}>
                                    <Card
                                        size="small"
                                        title={<div className="card-title-left-icon"><div></div>医保对照</div>}
                                        tabIndex={1}
                                        style={{ outline: 'none' }}
                                    >
                                        <MedicalInsurance
                                            //size="small"
                                            onRef={this.onRef}
                                            ItemData={this.state.ItemData}
                                            ChargeItemID={this.state.ChargeItemID}
                                            flag={this.state.flag}
                                            handelThis={this}
                                            title={this.state.title}
                                            Authoritydata={this.state.Authoritydata}
                                            key={this.state.ChargeItemID}
                                        />
                                    </Card>
                                </div>
                            </Col>
                        </Row>
                    </div>
                </Spin>
                <Modal
                    visible={this.state.modalTypeVisible}
                    title={languageCode === "CN" ? '标准分类' : "Standard Classification"}
                    onCancel={this.modalTypeHandleCancel}
                    onOk={this.modalTypeHandleCancel}
                    width='900px'
                >
                    <StandardClassification msg={this.msg} hospID={true} />
                </Modal>
                {/* 新增弹框 */}
            </div>
        );
    }

}

