import { message } from "antd/lib/index";
import { Button, Popconfirm, Row, Col, Form, Input, Select, Table, Upload, Icon, DatePicker } from 'antd';
import React from 'react';
import { initFilter, extendRule, extendInclude, setDataFieldValue, guid, initQueryFilter } from "../../../utils/common";
import { connect } from 'dva';
import moment from 'moment'
import config from "../../../config";
import storage from '../../../utils/storage';
import Attachment from "../../common/Attachment"
class OG018Check extends React.Component {
    constructor(props) {
        super(props);
        let data = null;
        if (this.props.data && this.props.data.record && this.props.data.record.Nav_Details) {
            data = JSON.parse(JSON.stringify(this.props.data.record.Nav_Details));
            if (data) {
                data.sort((a, b) => { return a.TYPE - b.TYPE })
            }
        }
        this.state = {
            data,
        };
    };
    componentDidMount() {
        if (window.navigator.userAgent.indexOf("Windows") < 1) {
            this.setState({ isMobile: true })
        }
        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);
        }
    }
    createData(items, type) {
        let data;
        if (type == 1) {
            data = items.map(it => {
                return {
                    QUALIFICATION_ID: this.props.data.id,
                    ORG_ID: this.props.login.OrgId,
                    ID: it.ID,
                    TYPE: it.TYPE,
                    ITEM_ID: it.ITEM_ID,
                    Nav_Item: it.Nav_Item ? it.Nav_Item : it,
                    BUSINESS_SCOPE: it.BUSINESS_SCOPE ? it.BUSINESS_SCOPE : '',
                    VALID_PERIOD: it.VALID_PERIOD ? it.VALID_PERIOD : '',
                    RESULT: it.RESULT ? it.RESULT : 0,
                    Nav_Files: it.Nav_Files,
                }
            })
        } else {
            data = items.map(it => {
                return {
                    QUALIFICATION_ID: this.props.data.id,
                    ORG_ID: this.props.login.OrgId,
                    ID: guid(),
                    TYPE: it.TYPE,
                    ITEM_ID: it.ID,
                    Nav_Item: it.Nav_Item ? it.Nav_Item : it,
                    BUSINESS_SCOPE: it.BUSINESS_SCOPE ? it.BUSINESS_SCOPE : '',
                    VALID_PERIOD: it.VALID_PERIOD ? it.VALID_PERIOD : '',
                    RESULT: it.RESULT ? it.RESULT : 0,
                    Nav_Files: [],
                }
            })
        }

        data.sort((a, b) => { return a.TYPE - b.TYPE })
        this.setState({ data })
    }
    BtnClose = () => {
        if (typeof this.props.data.onCancel != "undefined" && typeof this.props.data.onCancel == 'function')
            this.props.data.onCancel();
    }
    loadData() {
        if (this.state.data && this.state.data.length > 0)
            return;
        let json1 = initFilter(this.props.login.OrgId);
        extendRule(json1, 'QUALIFICATION_ID', 1, this.props.data.id);
        extendInclude(json1, 'Nav_Item');
        extendInclude(json1, 'Nav_Files.Nav_ImgFile.Nav_File');
        let json2 = initFilter(this.props.login.OrgId, '', 'CODE', 0, null);
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json1,
            url: 'OG/RelatedQualificationDetail/Entities',
            onComplete: (ret) => {
                if (ret.length > 0) {
                    this.createData(ret, 1);
                } else {
                    this.props.dispatch({
                        type: 'app/getDataByPost',
                        payload: json2,
                        url: 'OG/RelatedQualificationDetailItem/Entities',
                        onComplete: (ret) => {
                            if (!ret)
                                return;
                            this.createData(ret, 2);
                        }
                    });
                }
            }
        });

    }
    fmtEnum(name, value) {
        const enums = this.props.app.enums;
        if (!enums || !enums[name]) return '';
        return enums[name].enums[value] || '';
    }
    onSave = () => {
        this.props.data.parentRecord.Nav_Details = this.state.data;
        this.BtnClose();
    }
    getRequestHeaders = () => {
        // 请求参数
        const addHeader = 'Bearer ' + storage('lacal').getItem('accessToken').val
        const userId = storage('lacal').getItem('userid').val
        const user = storage('lacal').getItem('loginUserVerify').val
        const RootOrgId = storage('lacal').getItem('RootOrgId').val
        const orgId = storage('lacal').getItem('webOrgId').val
        const Tenant = storage('lacal').getItem('Tenant').val
        const headers = {
            // 'Content-Type': type === 'post' ? 'application/json' : 'application/x-www-form-urlencoded',
            Authorization: addHeader,
            userid: userId,
            username: user ? user.username : '',
            RootOrgId,
            orgId,
            Tenant: Tenant
        }
        return headers
    }
    doFilesChange(index, newfiles) {
        let data = this.state.data;
        if (!data[index].Nav_Files) {
            data[index].Nav_Files = [];
        }
        data[index].Nav_Files.forEach(it => {
            if (!newfiles.find(f => f.ID === it.ID)) {
                if (it.CREATE_TIME) {
                    it.IS_DELETED = true;
                }
            } else {
                it.IS_DELETED = false;
            }
        })
        newfiles.forEach(it => {
            if (!data[index].Nav_Files.find(f => f.ID === it.ID)) {
                data[index].Nav_Files.push(it);
            }
        })
        this.setState({ data })
    }
    render() {
        const OGConclusionType = this.props.app.enums && this.props.app.enums.OGConclusionType && this.props.app.enums.OGConclusionType.options;
        const columns = [
            {
                width: 200, title: '审查类型', dataIndex: 'TYPE', key: 'TYPE', render: (value, row, index) => {
                    const obj = {
                        children: this.fmtEnum('OGQualificationDetailType', value),
                        props: {},
                    };
                    const data = this.state.data;
                    if (index === 0 || data[index].TYPE !== data[index - 1].TYPE) {
                        let span = 1;
                        for (let i = index + 1; i < data.length; i++) {
                            if (data[i].TYPE != data[index].TYPE)
                                break;
                            span++;
                        }
                        if (span > 1)
                            obj.props.rowSpan = span;
                    } else {
                        obj.props.rowSpan = 0;
                    }
                    return obj;
                }
            },
            {
                width: 200, title: '项目', dataIndex: 'ITEM_ID', key: 'ITEM_ID', render: (text, record, index) => {
                    return record.Nav_Item.NAME
                }
            },
            {
                width: 200, title: '业务范围', dataIndex: 'BUSINESS_SCOPE', key: 'BUSINESS_SCOPE', render: (text, record, index) => {
                    return <Input value={record.BUSINESS_SCOPE}
                        onChange={(e) => {
                            let data = this.state.data;
                            data[index].BUSINESS_SCOPE = e.target.value;
                            this.setState({ data })
                        }}
                    />
                }
            },
            {
                width: 200, title: '有效期', dataIndex: 'VALID_PERIOD', key: 'VALID_PERIOD', render: (text, record, index) => {
                    return <DatePicker value={record.VALID_PERIOD == "" ? null : moment(record.VALID_PERIOD, 'YYYY-MM-DD')}
                        onChange={(evt, ds) => {
                            let data = this.state.data;
                            data[index].VALID_PERIOD = ds;
                            this.setState({ data })
                        }}
                    />
                }
            },
            {
                width: 200, title: '符合结论', dataIndex: 'OGConclusionType', key: 'OGConclusionType', render: (text, record, index) => {
                    return <Select value={record.RESULT}
                        onChange={(value) => {
                            let data = this.state.data;
                            data[index].RESULT = value;
                            this.setState({ data })
                        }}
                    >
                        {
                            OGConclusionType && OGConclusionType.map(it => {
                                return <Select.Option key={it.value} value={it.value}>{it.label}</Select.Option>
                            })
                        }
                    </Select>
                }
            },

            {
                width: 300, title: '附件', dataIndex: 'Nav_Files', key: 'Nav_Files', render: (text, record, index) => {
                    const colConfig = {
                        promptInfo: '附件',
                        field: 'Nav_Files',
                        column: {
                            INPUT_ID_FIELD: "DETAIL_ID"
                        }
                    }
                    return <Attachment value={text} colConfig={colConfig} record={record} login={this.props.login} onChange={(files) => {
                        this.doFilesChange(index, files.value);
                    }} />
                }
            }
        ];

        const tableColumns = columns.map((col) => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    inputType: col.dataIndex === 'PLATFORM_TYPE' ? 'Select' : 'text',
                    dataIndex: col.dataIndex,
                    title: col.title,
                    editing: this.isEditing(record),
                }),
            };
        });

        return <>
            <div style={{ marginTop: '10px' }}>
                <Button style={{ marginLeft: '10px' }} type={'primary'} onClick={() => this.onSave()} icon="save" >确定</Button>
            </div>

            <Form>
                <Row>
                    <Table
                        rowKey="ID"
                        pagination={false}
                        dataSource={this.state.data}
                        columns={tableColumns}
                        rowClassName="editable-row"
                        bordered
                    />
                </Row>
            </Form>
        </>
    }


}

export default connect(({ login, app }) => ({ login, app }))(OG018Check) 