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 ReactToPrint from "react-to-print";
import styles from '../../CustomPages/HI/StepForm.css';
import XLSX from 'xlsx';
import { connect } from 'dva';
import moment from 'moment';
class OG034EditPage extends React.Component {
    constructor(props) {
        super(props);
        let type = 'view';
        switch (this.props.formCode) {
            case 'OG034_EDIT': {
                type = 'edit';
                break;
            }
            case 'OG034_REPORT': {
                type = 'report';
                break;
            }
            case 'OG034_VIEW': {
                type = 'view'
                break;
            }
            default: {
                type = 'view';
                break;
            }
        }
        this.state = {
            ID: this.props.data.id || '',
            data: null,
            type,
            users: null,
            selUids: [],
            reportList: {}
        };
    };

    componentDidMount() {

        this.loadUsers();
        this.loadData();
    }
    loadUsers() {
        let json = initFilter(this.props.login.OrgId, '', null, 'NAME', null);
        extendRule(json, "ENABLE_STATUS", 1, 0);
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'FM/User/Entities',
            onComplete: (ret) => {
                if (!ret)
                    return;
                this.setState({
                    users: ret,
                });
            }
        });
    }
    loadData() {
        let json = initFilter(this.props.login.OrgId, '', null, null, null);
        if (this.state.ID) {
            extendRule(json, 'ID', 1, this.state.ID);
        }
        extendInclude(json, 'Nav_HostUser');
        extendInclude(json, 'Nav_ReviewItemsList.Nav_Item');
        extendInclude(json, 'Nav_ReviewUserList.Nav_User');
        extendInclude(json, 'Nav_ReviewResultList.Nav_Result');
        extendInclude(json, 'Nav_ActionPlanList.Nav_Plan');
        extendInclude(json, 'Nav_ActionPlanList.Nav_User');
        json.IgnoreDataRule = true;
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'OG/OGStanardSysReview/Get',
            onComplete: (ret) => {
                if (!ret)
                    return;
                ret.Nav_ReviewItemsList.sort(function (a, b) {
                    var x = a.Nav_Item.CREATE_TIME;
                    var y = b.Nav_Item.CREATE_TIME;
                    if (x < y) { return -1; }
                    if (x > y) { return 1; }
                    return 0;
                });
                ret.Nav_ReviewResultList.sort(function (a, b) {
                    var x = a.Nav_Result.CREATE_TIME;
                    var y = b.Nav_Result.CREATE_TIME;
                    if (x < y) { return -1; }
                    if (x > y) { return 1; }
                    return 0;
                });
                ret.Nav_ActionPlanList.sort(function (a, b) {
                    var x = a.Nav_Plan.CREATE_TIME;
                    var y = b.Nav_Plan.CREATE_TIME;
                    if (x < y) { return -1; }
                    if (x > y) { return 1; }
                    return 0;
                });
                this.setState({
                    ID: ret.ID,
                    data: ret,
                    selUids: ret.Nav_ReviewUserList.map(it => it.USER_ID),
                });
            }
        });
    }
    fmtEnum(name, value) {
        const enums = this.props.app.enums;
        if (!enums || !enums[name]) return '';
        return enums[name].enums[value] || '';
    }
    onTableBtnExport() {
        let TableWrap = document.getElementById('tableId' + this.props.data.id);
        let Table = TableWrap.getElementsByTagName('table')[0];
        const wb = XLSX.utils.table_to_book(Table);
        let name = '标准化系统评审意见表';
        name += '.xlsx';
        XLSX.writeFile(wb, name)
    }
    BtnClose = () => {
        if (typeof this.props.data.onCancel != "undefined" && typeof this.props.data.onCancel == 'function')
            this.props.data.onCancel();
    }
    onSave = (submit) => {
        if (!this.state.data || this.state.type !== 'edit')
            return;
        let data = JSON.parse(JSON.stringify(this.state.data));
        if (!data.Nav_ReviewUserList) {
            data.Nav_ReviewUserList = [];
        }
        data.Nav_ReviewUserList.forEach(it => {
            if (!this.state.selUids || !this.state.selUids.find(uid => uid == it.USER_ID)) {
                it.IS_DELETED = true;
            }
        })
        this.state.selUids.forEach(uid => {
            if (!data.Nav_ReviewUserList.find(it => it.USER_ID === uid)) {
                data.Nav_ReviewUserList.push({
                    ID: guid(),
                    USER_ID: uid,
                })
            }
        })

        if (submit) {

            if (!data.REVIEW_TIME) {
                message.error("请选择评审时间")
                return;
            }
            if (!data.HOST_ID) {
                message.error("请选择评审主持人")
                return;
            }
            if (!data.Nav_ReviewUserList || data.Nav_ReviewUserList.length == 0) {
                message.error("请选择评审人员")
                return;
            }
            if (!data.Nav_ReviewItemsList || data.Nav_ReviewItemsList.length == 0) {
                message.error("请选择评审项目")
                return;
            }
            if (!data.Nav_ReviewResultList || data.Nav_ReviewResultList.length == 0) {
                message.error("请选择评审结论")
                return;
            }
            if (!data.Nav_ActionPlanList || data.Nav_ActionPlanList.length == 0) {
                message.error("请选择行动计划")
                return;
            }
            let fail = false;
            data.Nav_ActionPlanList.forEach(it => {
                if (!it.USER_ID) {
                    fail = true;
                }
            });
            if (fail) {
                message.error("请选择执行人员")
                return;
            }
        }
        if (submit) {
            data.PUBLISH = 'SaveAndNotify'
        }
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: data,
            url: 'OG/OGStanardSysReview/FullUpdate',
            onComplete: (ret) => {
                message.success("操作成功");
                this.BtnClose();
            }
        });
    }

    onReport() {
        if (this.state.type != 'report')
            return;
        let reportList = this.state.reportList;
        let data = this.state.data;
        let id = ''
        let flag = ''
        let hasError = false
        data && data.Nav_ActionPlanList && data.Nav_ActionPlanList.forEach(it => {
            if (it.IMPLEMENTATION == 0 && !reportList[it.ID] && it.USER_ID === this.props.login.user.ID) {
                hasError = true
            }
            if (reportList[it.ID]) {
                id = id ? id + ',' + it.ID : it.ID
                flag = flag ? flag + ',' + reportList[it.ID] : reportList[it.ID]
            }
        })
        if (hasError) {
            message.error("请选择执行情况")
            return;
        }
        if (!id) {
            message.error("已处理完成!")
            return;
        }
        let json = initFilter(this.props.login.OrgId, '', null, null, null);
        json.Parameter1 = id;
        json.Parameter2 = flag;
        json.Parameter3 = this.props.data.TaskID;
        json.Parameter4 = this.props.data.id;
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'OG/OGStanardSysReview/SubmitUser',
            onComplete: (ret) => {
                if (ret) {
                    message.success("操作成功");
                    this.BtnClose();
                }
            }
        });
    }

    render() {
        const { data, type, users, reportList } = this.state;
        const hasReviewItems = data && data.Nav_ReviewItemsList && data.Nav_ReviewItemsList.length > 0;
        const hasResultList = data && data.Nav_ReviewResultList && data.Nav_ReviewResultList.length > 0;
        const hasPlan = data && data.Nav_ActionPlanList && data.Nav_ActionPlanList.length > 0;
        const isEdit = type === 'edit' && data && data.STATUS === 0 && (!data.USER_ID || data.USER_ID === this.props.login.user.ID);
        const isReprot = type === 'report' && data && data.STATUS === 10;
        const isView = type === 'view';
        return <div>
            <div style={{ padding: '10px' }}>
                {
                    isView && <>
                        <ReactToPrint
                            trigger={() => <Button type={'primary'} icon={'printer'} >打印</Button>}
                            content={() => this.componentRef}
                        />
                        <Button style={{ marginLeft: '8px' }} onClick={() => this.onTableBtnExport()} icon="export" >导出</Button>
                    </>
                }
                {
                    isEdit && <>
                        <Button type='primary' style={{ marginLeft: '8px' }} onClick={() => this.onSave(false)} icon="save" >保存</Button>
                        <Button type='primary' style={{ marginLeft: '8px' }} onClick={() => this.onSave(true)} icon="edit" >提交</Button>
                    </>
                }
                {
                    isReprot && <>
                        <Popconfirm title="是否确定操作?" onConfirm={() => this.onReport()}>
                            <Button type='primary' style={{ marginLeft: '8px' }} icon="edit" >落实</Button>
                        </Popconfirm>
                    </>
                }
            </div>
            <div ref={el => (this.componentRef = el)} id={'tableId' + this.props.data.id} style={{ padding: '20px' }}>
                <h1 style={{ textAlign: 'center' }}>标准化系统评审意见表</h1>
                <table style={{ width: '100%', textAlign: 'center', borderTop: '1px solid #333', borderLeft: '1px solid #333' }} className={styles.PrintForm}>
                    <tbody>
                        <tr>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>评审时间</td>
                            <td colSpan={6} rowSpan={1}>
                                {
                                    data && !isEdit && data.REVIEW_TIME
                                }
                                {
                                    data && isEdit && <DatePicker
                                        format={'YYYY-MM-DD'}
                                        value={data.REVIEW_TIME ? moment(data.REVIEW_TIME) : null}
                                        onChange={(e, datestring) => {
                                            let data = this.state.data;
                                            data.REVIEW_TIME = new Date(datestring);
                                            this.setState({ data })
                                        }}
                                    />
                                }
                            </td>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>评审主持人</td>
                            <td colSpan={6} rowSpan={1}>
                                <Select showSearch={true} style={{ width: "100%" }} disabled={!isEdit} value={data ? data.HOST_ID : null}
                                    onChange={value => {
                                        let data = this.state.data;
                                        data.HOST_ID = value;
                                        this.setState({ data });
                                    }}
                                    filterOption={(input, option) =>
                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {
                                        users && users.map(it => {
                                            return <Select.Option key={it.ID} value={it.ID}>{it.NAME}</Select.Option>
                                        })
                                    }
                                </Select>
                            </td>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>评审人员</td>
                            <td colSpan={6} rowSpan={1}>
                                <Select mode={"multiple"} style={{ width: "100%" }} disabled={!isEdit} value={this.state.selUids}
                                    onChange={value => this.setState({ selUids: value })}
                                    filterOption={(input, option) =>
                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {
                                        users && users.map(it => {
                                            return <Select.Option key={it.ID} value={it.ID}>{it.NAME}</Select.Option>
                                        })
                                    }
                                </Select>
                            </td>
                        </tr>
                        {
                            hasReviewItems && data.Nav_ReviewItemsList.map((it, idx) => {
                                return <tr key={it.ID}>
                                    {
                                        idx == 0 && <td colSpan={2} rowSpan={data.Nav_ReviewItemsList.length} className={styles.fontBold}>评审项目</td>
                                    }
                                    <td colSpan={10} rowSpan={1} style={{ textAlign: 'left' }}>{it.Nav_Item && it.Nav_Item.NAME}</td>
                                    {
                                        idx == 0 && <td colSpan={2} rowSpan={data.Nav_ReviewItemsList.length} className={styles.fontBold}>存在问题</td>
                                    }
                                    <td colSpan={10} rowSpan={1} style={{ textAlign: 'left' }}>
                                        {
                                            isEdit ?
                                                <Input value={it.PROBLEM} onChange={evt => {
                                                    let data = this.state.data;
                                                    data.Nav_ReviewItemsList[idx].PROBLEM = evt.target.value;
                                                    this.setState({ data });
                                                }} />
                                                :
                                                it.PROBLEM
                                        }
                                    </td>
                                </tr>
                            })
                        }
                        {
                            !hasReviewItems && <tr>
                                <td colSpan={2} rowSpan={1} className={styles.fontBold}>评审项目</td>
                                <td colSpan={10} rowSpan={1}></td>
                                <td colSpan={12} rowSpan={1}></td>
                            </tr>
                        }
                        {
                            hasResultList && data.Nav_ReviewResultList.map((it, idx) => {
                                return <tr key={it.ID}>
                                    {
                                        idx == 0 && <td colSpan={2} rowSpan={data.Nav_ReviewResultList.length} className={styles.fontBold}>评审结论</td>
                                    }
                                    <td colSpan={10} rowSpan={1} style={{ textAlign: 'left' }}>{it.Nav_Result && it.Nav_Result.NAME}</td>
                                    <td colSpan={12} rowSpan={1} style={{ textAlign: 'left' }}>
                                        {
                                            !isEdit && it.RESULT
                                        }
                                        {
                                            isEdit && it.Nav_Result && it.Nav_Result.NAME === '标准化系统运行的总体评价' &&
                                            <Select style={{ width: "100%" }} value={it.RESULT} onChange={(value) => {
                                                let data = this.state.data;
                                                data.Nav_ReviewResultList[idx].RESULT = value;
                                                this.setState({ data });
                                            }}>
                                                <Select.Option value={"优"}>优</Select.Option>
                                                <Select.Option value={"良"}>良</Select.Option>
                                                <Select.Option value={"中"}>中</Select.Option>
                                                <Select.Option value={"差"}>差</Select.Option>
                                            </Select>
                                        }
                                        {

                                            isEdit && it.Nav_Result && it.Nav_Result.NAME !== '标准化系统运行的总体评价' &&
                                            <Input value={it.RESULT} onChange={evt => {
                                                let data = this.state.data;
                                                data.Nav_ReviewResultList[idx].RESULT = evt.target.value;
                                                this.setState({ data });
                                            }} />
                                        }
                                    </td>
                                </tr>
                            })
                        }
                        {
                            !hasResultList && <tr>
                                <td colSpan={2} rowSpan={1} className={styles.fontBold}>评审结论</td>
                                <td colSpan={10} rowSpan={1}></td>
                                <td colSpan={12} rowSpan={1}></td>
                            </tr>
                        }
                        {
                            hasPlan && data.Nav_ActionPlanList.map((it, idx) => {
                                return <tr key={it.ID}>
                                    {
                                        idx == 0 && <td colSpan={2} rowSpan={data.Nav_ActionPlanList.length} className={styles.fontBold}>行动计划</td>
                                    }
                                    <td colSpan={2} rowSpan={1} style={{ textAlign: 'left' }}>{it.Nav_Plan && it.Nav_Plan.NAME}</td>
                                    {
                                        data && data.STATUS === 0 &&
                                        <td colSpan={8} rowSpan={1} style={{ textAlign: 'left' }}>
                                            <Input value={it.PLAN_CONTENT} onChange={(e) => {
                                                let d = this.state.data;
                                                d.Nav_ActionPlanList[idx].PLAN_CONTENT = e.target.value;
                                                this.setState({ data: d });
                                            }} />
                                        </td>
                                    }
                                    {
                                        data && data.STATUS !== 0 &&
                                        <td colSpan={8} rowSpan={1} style={{ textAlign: 'left' }}>{it && it.PLAN_CONTENT}</td>
                                    }
                                    {
                                        idx == 0 && <td colSpan={2} rowSpan={data.Nav_ActionPlanList.length} className={styles.fontBold}>执行人员</td>
                                    }
                                    <td colSpan={4} rowSpan={1} style={{ textAlign: 'left' }}>
                                        {
                                            !isEdit && it.Nav_User && it.Nav_User.NAME
                                        }
                                        {
                                            isEdit && <Select style={{ width: "100%" }} value={it.USER_ID} showSearch={true}
                                                onChange={value => {
                                                    let data = this.state.data;
                                                    data.Nav_ActionPlanList[idx].USER_ID = value;
                                                    this.setState({ data });
                                                }}
                                                filterOption={(input, option) =>
                                                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }
                                            >
                                                {
                                                    users && users.map(it => {
                                                        return <Select.Option required key={it.ID} value={it.ID}>{it.NAME}</Select.Option>
                                                    })
                                                }
                                            </Select>
                                        }
                                    </td>
                                    {
                                        idx == 0 && <td colSpan={2} rowSpan={data.Nav_ActionPlanList.length} className={styles.fontBold}>执行情况</td>
                                    }
                                    <td colSpan={4} rowSpan={1}>
                                        {
                                            it.IMPLEMENTATION === 0 && it.USER_ID === this.props.login.user.ID && this.state.type === 'report' ?
                                                <>
                                                    <Select style={{ width: "100%" }} value={reportList[it.ID]} onChange={(value) => {
                                                        let reportList = this.state.reportList;
                                                        reportList[it.ID] = value;
                                                        this.setState({ reportList });
                                                    }}>
                                                        <Select.Option value={"1"}>已执行</Select.Option>
                                                        <Select.Option value={"0"}>未执行</Select.Option>
                                                    </Select>

                                                </>
                                                :
                                                this.fmtEnum('OGStandardizationImplementation', it.IMPLEMENTATION)
                                        }
                                    </td>
                                </tr>
                            })
                        }
                        {
                            !hasPlan && <tr>
                                <td colSpan={2} rowSpan={1} className={styles.fontBold}>行动计划</td>
                                <td colSpan={10} rowSpan={1}></td>
                                <td colSpan={2} rowSpan={1} className={styles.fontBold}>执行人员</td>
                                <td colSpan={4} rowSpan={1}></td>
                                <td colSpan={2} rowSpan={1} className={styles.fontBold}>执行情况</td>
                                <td colSpan={4} rowSpan={1}></td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </div>
    }


}

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