// 国家标准数据元值域
import React from 'react';
import { Row, Col, Button, Icon, Divider, Popconfirm, message, Input, Select} from 'antd';
import { $http } from 'containers/config/https';
import store from 'store';
import PubilcTablePagination from '../common/PubilcTablePagination.jsx'; // 公共table组件
import NewRange from './component/NewRange.jsx'; // 新增数据元值域
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import 'assets/css/common.css';
import './style/index.less';

let {Option} = Select;

export default class DataMetadataDomain extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            columns: [],
            tableData: [],
            total: 0,
            page: 1,
            pageSize: 10,
            headerHeight: 0,
            listID: undefined, // 表ID
            code: undefined, // 值域代码
            descripts: undefined, // 值域名称
            dataCatalogueID: undefined, // 数据元目录ID
            standardVersion: undefined, // 国标版本
            value: undefined, // 值域值
            definition: undefined, // 值域定义
            selectData: {},
            loading: false
        };
        this.columns = [
            {
                title: '值域代码',
                dataIndex: 'code',
                align: "center",
                width: '100px'
            },
            {
                title: '值域名称',
                dataIndex: 'descripts',
                align: "center",
                width: '200px'
            },
            {
                title: '值域值',
                dataIndex: 'value',
                align: "center",
                width: '100px',
            },
            {
                title: '值域定义',
                dataIndex: 'definition',
                align: "center",
                width: '200px',
            },
            {
                title: '国标版本',
                dataIndex: 'standardVersion',
                align: "center",
                width: '100px'
            },
            {
                title: '开始日期',
                dataIndex: 'startDate',
                align: "center",
                width: '100px',
            },
            {
                title: '结束日期',
                dataIndex: 'stopDate',
                align: "center",
                width: '100px'
            },
            {
                title: '数据元目录ID',
                dataIndex: 'dataCatalogueID',
                align: "center",
                width: '150px'
            },
            {
                title: '数据元目录名称',
                dataIndex: 'dataCatalogueDesc',
                align: "center",
                width: '150px'
            },
            {
                title: '备注',
                dataIndex: 'remarks',
                align: "center",
                width: '100px',
            },
            {
                title: '创建人',
                dataIndex: 'createdUserDesc',
                align: "center",
                width: '100px'
            },
            {
                title: '创建日期',
                dataIndex: 'createdDateTime',
                align: "center",
                width: '180px',
            },
            {
                title: '最后更新人',
                dataIndex: 'updateUserDesc',
                align: "center",
                width: '100px'
            },
            {
                title: '最后更新日期',
                dataIndex: 'updateDateTime',
                align: "center",
                width: '180px'
            },
            {
                title: '操作',
                key: 10,
                align: "center",
                fixed: 'right',
                width: 130,
                render: (text, record) => (
                    <span>
                        <Icon type="edit" style={{color: '#108EE9'}}></Icon>
                        <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
                        {/* 分割线 */}
                        <Divider type="vertical" />
                        <Icon type="delete" style={{color: 'rgba(240,65,52,1)'}}></Icon>
                        <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
                            <span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
                        </Popconfirm>
                    </span>
                ),
            }
        ]
    }

    componentDidMount() {
        this.getColumnsData(); // 初始化表头数据
        this.handleQuery(); // 初始化列表数据
        this.getSelectData(); // 初始化下拉框数据
        var box = document.querySelector(".domain-header");
		if(box){ //此处在加一层判断，更加严密，如果box存在的情况下获取
			this.setState({headerHeight: box.offsetHeight})
		}
    }

    // 获取下拉框数据
    getSelectData = () => {
        let data = {
			params: [{}]
		}
		$http.post('urlS', this, {
			code: "06010029",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
                    this.setState({selectData: res.result})
				}
			}
		})
    }

    // 获取表头数据
    getColumnsData = () => {
        let data = {
			params: [{
				compontName: "DataMetadataDomain",
				type: "C",
			}]
		}
		$http.post('urlDeault', this, {
			code: "01040073",
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
                    var totalWidth = 0;
                    let obj = {
                        title: '操作',
                        key: 10,
                        align: "center",
                        fixed: 'right',
                        width: 130,
                        widthNum: 130,
                        render: (text, record) => (
                            <span>
                                <Icon type="edit" style={{color: '#108EE9'}}></Icon>
                                <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
                                {/* 分割线 */}
                                <Divider type="vertical" />
                                <Icon type="delete" style={{color: 'rgba(240,65,52,1)'}}></Icon>
                                <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
                                    <span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
                                </Popconfirm>
                            </span>
                        ),
                    }
					let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
						return {
							...item,
							widthNum: parseInt(item.width),
                            title: <div onDoubleClick={!name ? this.columnChild.onOpenModel : this.doctorAdviceHistoryColumnRef.onOpenModel}>{item.title}</div>,
						}
					}) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    filterArr.push(obj);
					for(var i = 0; i < filterArr.length; i++) {
						totalWidth += filterArr[i].widthNum;
                    }
                    this.setState({ columns: filterArr, tableWidth: totalWidth })
				}
			}
		})
    }

	columnRef = (ref) => {
		this.columnChild = ref;
	}
    
    // 查询
    handleQuery = () => {
        this.setState({page: 1, pageSize: 10}, () => {
            this.getTableData();
        })
    }

    // 获取表格数据
    getTableData = () => {
        this.setState({loading: true})
        let {page, pageSize, listID, code, descripts, dataCatalogueID, standardVersion, value, definition} = this.state;
		let data = {
			params: [{
				ID: listID ? listID : undefined, // 表ID
				code, // 值域代码
				descripts, // 值域名称
				dataCatalogueID, // 数据元目录ID
				standardVersion, // 国标版本
                value, // 值域值
                definition, // 值域定义
			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page
			}]
		}
		$http.post('urlS', this, {
			code: "06010009",
			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;
                        res.result.data[i].createdDateTime = res.result.data[i].createdDate + ' ' + res.result.data[i].createdTime;
                        res.result.data[i].updateDateTime = res.result.data[i].updateDate + ' ' + res.result.data[i].updateTime;
					}
					this.setState({ tableData: res.result.data, total: res.result.totalCount, loading: false })
					// 数据加载成功关闭loading
					this.child.handleLoading();
				} else {
					this.setState({ tableData: [], total: 0, loading: false })
					// 数据加载失败关闭loading
					this.child.handleLoading();
				}
			},
			error: function (error) {
				this.setState({ tableData: [], total: 0, loading: false }, () => {
					// 数据加载成功关闭loading
					this.child.handleLoading();
				})
			}
		})
    }

	// 提供修改page和pageSize的回调函数
	compilePage(page, pageSize) {
		// 修改page，或者pageSize
		this.setState({ page: page, pageSize: pageSize }, () => {
			// 重新调用查询方法
			this.getTableData();
		})
	}
    
	// 调用公共组件的连接事件
	onRef = (ref) => {
		this.child = ref
    }

    newOnRef = (ref) => {
		this.newChild = ref
    }

    // 表ID
    // handleListIDOnChange = e => {
    //     this.setState({listID: e.target.value})
    // }

    // 目录代码
    handleCodeOnChange = e => {
        this.setState({code: e.target.value})
    }

    // 目录名称
    handleDescriptsOnChange = e => {
        this.setState({descripts: e.target.value})
    }

    // 数据元目录
    handleDataCatalogueIDOnChange = e => {
        this.setState({dataCatalogueID: e})
    }

    // 国标版本
    handleStandardVersionOnChange = e => {
        this.setState({standardVersion: e.target.value})
    }

    // 值域值
    handleValueOnChange = e => {
        this.setState({value: e.target.value})
    }

    // 值域定义
    handleDefinitionOnChange = e => {
        this.setState({definition: e.target.value})
    }

    // 新目录
    handleAdd = () => {
        let obj = {
            flag: 'add'
        }
        this.newChild.showModal(obj);
    }

    // 编辑
    handleCompile = record => {
        let obj = {
            flag: 'compile',
            userInfo: record
        }
        this.newChild.showModal(obj);
    }

    // 删除
    handleDelete = record => {
        let data = {
			params: [{
				ID: record.ID
			}]
		}
		$http.post('urlADS', this, {
			code: '06010012',
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0) {
					message.success('删除成功');
                    // 刷新列表数据
                    this.getTableData();
				}
			}
		})
    }

    render() {
        let {columns, tableData, total, page, headerHeight, listID, code, descripts, dataCatalogueID, standardVersion, value, definition, selectData,
            loading, totalWidth
        } = this.state;
        // 组件所需参数
		const param = {
			// 表头配置
			columns: columns&&columns.length > 0 ? columns : this.columns,
			// 表格数据
			data: tableData,
			// 数据总条数
			total,
			// 当前页数
			page,
			// 表格的宽度
			x: columns&&columns.length > 0 ? totalWidth : 2020,
			y: store.getState().tableHeight.y + 78 - headerHeight,
            height: store.getState().tableHeight.y + 123 - headerHeight + 'px',
            loading
		}
        
        // 目录ID
        let dataCatalogueIDOption = selectData&&selectData.data&&selectData.data.map((item, index) => {
            return (<Option key={index} value={item.ID} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        return (
            <div>
                <div className="domain-header">
                    <Row style={{ minHeight: '64px', padding: '0 24px' }}>
                        <Col span={20}>
                            {/* 表ID：<Input
                                value={listID}
                                onChange={this.handleListIDOnChange} 
                                style={{width: '100px', margin: '23px 6px 0 0'}} 
                                placeholder="请输入" 
                                onPressEnter={this.handleQuery}
                            /> */}
                            值域代码：<Input 
                                value={code} 
                                onChange={this.handleCodeOnChange} 
                                style={{width: '100px', margin: '23px 6px 0 0'}} 
                                placeholder="请输入" 
                                onPressEnter={this.handleQuery}
                            />
                            值域名称：<Input 
                                value={descripts} 
                                onChange={this.handleDescriptsOnChange} 
                                style={{width: '100px', margin: '23px 6px 0 0'}} 
                                placeholder="请输入" 
                                onPressEnter={this.handleQuery}
                            />
                            数据元目录： <Select
                                showSearch optionFilterProp="seatchprop" allowClear
                                style={{width: '100px', margin: '23px 15px 0 0'}} 
                                placeholder="请选择"
                                value={dataCatalogueID}
                                onChange={this.handleDataCatalogueIDOnChange} 
                            >
                                {dataCatalogueIDOption}
                            </Select>
                            国标版本：<Input 
                                value={standardVersion} 
                                onChange={this.handleStandardVersionOnChange} 
                                style={{width: '100px', margin: '23px 6px 0 0'}} 
                                placeholder="请输入" 
                                onPressEnter={this.handleQuery}
                            />
                            <div style={{display: 'inline-block'}}>
                                值域值：<Input 
                                    value={value} 
                                    onChange={this.handleValueOnChange} 
                                    style={{width: '100px', margin: '23px 15px 0 0'}} 
                                    placeholder="请输入" 
                                    onPressEnter={this.handleQuery}
                                />
                                值域定义：<Input 
                                    value={definition} 
                                    onChange={this.handleDefinitionOnChange} 
                                    style={{width: '100px', margin: '23px 15px 0 0'}} 
                                    placeholder="请输入" 
                                    onPressEnter={this.handleQuery}
                                />
                                <Button onClick={this.handleQuery} style={{ margin: '23px 0 20px 0', background: 'rgba(255,255,255,1)'}}>查询</Button>
                            </div>
                        </Col>
                        <Col span={4} style={{ textAlign: 'right' }}>
                            <Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff', marginTop: '23px'}}>新增值域</Button>
                        </Col>
                    </Row>
                </div>
                <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
                <div style={{ padding: 24 }} className="table-body-height">
                    {/* handelThis将夫组件的属性与方法给子组件访问 */}
                    <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
                </div>
                <NewRange onRef={this.newOnRef} handleQuery={this.getTableData} selectData={selectData} /> 
                <ColumnAuthoritysModel
					clientWidth='800px'
					compontName="DataMetadataDomain"
					configType="C"
					onRef={this.columnRef}
					reloadData={() => this.getColumnsData()}
				/>
            </div>
        )
    }
}