import { message } from "antd/lib/index";
import { Button, Popconfirm, Row, Col, DatePicker, Checkbox, Radio, Form, Input, Select, Table, Upload, Icon, PageHeader, Modal } 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';
import config from "../../../config";

const Option = Select.Option;

//   /// <summary>
//   /// 员工意见汇总表状态
//   /// </summary>
//   public enum OGEmployeeOpinionStatus
//   {
//     草稿 = 0,
//     意见征集中 = 1,
//     汇总中 = 2,
//     负责人审阅中 = 3,
//     安环部审阅中 = 4,
//     完成 = 5,
//   }

//   /// <summary>
//   /// 员工意见征集表状态
//   /// </summary>
//   public enum OGEmployeeOpinionFeedbackStatus
//   {
//     未填写 = 0,
//     反馈中 = 1,
//     完成 = 2,
//   }

class OG059ShowPrint extends React.Component {
    constructor(props) {
        super(props);
        let type = '';
        switch (this.props.formCode) {
            case 'OG059_REPORT': {
                type = 'report';
                break;
            }
            case 'OG059_CHECK': {
                type = 'check';
                break;
            }
            case 'OG059_SHOWPRINT': {
                type = 'view'
                break;
            }
        }
        this.state = {
            data: null,
            opinions: [],
            opinion_user_map: {},
            type,
        }
    };

    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);
        }
    }
    BtnClose = () => {
        if (typeof this.props.data.onCancel != "undefined" && typeof this.props.data.onCancel == 'function')
            this.props.data.onCancel();
    }
    loadData = (dataId) => {
        let json = initFilter(this.props.login.OrgId, '', null, null, null);
        extendRule(json, 'ID', 1, dataId);
        json.OrgType = 2;
        extendInclude(json, 'Nav_User');
        extendInclude(json, 'Nav_Department');
        extendInclude(json, 'Nav_Users.Nav_User');
        extendInclude(json, 'Nav_Users.Nav_Files.Nav_ImgFile.Nav_File');
        extendInclude(json, 'Nav_Users.Nav_Opinions');
        extendInclude(json, 'Nav_ChargeUser.Nav_UserSignFiles.Nav_ImgFile.Nav_File');
        extendInclude(json, 'Nav_AHChargeUser.Nav_UserSignFiles.Nav_ImgFile.Nav_File');
        json.IgnoreDataRule = true;
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'OG/EmployeeOpinionCollection/Get',
            onComplete: (ret) => {
                if (!ret)
                    return;
                let map = {};
                let opinions = [];
                let opinion_user_map = {};
                ret.Nav_Users.forEach((it, idx) => {
                    map[it.ID] = idx;
                })
                ret.Nav_Users.filter(t => t.STATUS !== 0).forEach((it, idx) => {
                    it.Nav_Opinions.forEach((op, idx) => {
                        opinions.push(op);
                        opinion_user_map[op.ID] = op;
                    })
                })
                this.setState({
                    data: ret,
                    opinions: opinions,
                    opinion_user_map: opinion_user_map,
                    map,
                });
            }
        });
    }

    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)
    }
    fmtEnum(name, value) {
        const enums = this.props.app.enums;
        if (!enums || !enums[name]) return '';
        return enums[name].enums[value] || '';
    }
    renderUserFeed(it, idx) {
        return <tr key={it.ID}>
            <td colSpan={2} rowSpan={1} >{idx + 1}</td>
            <td colSpan={12} rowSpan={1} >{ }</td>
            <td colSpan={2} rowSpan={1} >{it.Nav_User.NAME}</td>
            <td colSpan={2} rowSpan={1} >受理意见</td>
            <td colSpan={6} rowSpan={1} >不认可解释</td>
        </tr>
    }
    onSave() {
        const curuid = this.props.login.user.ID;
        const editable = this.state.type == 'report' && this.state.data && this.state.data.STATUS === 2 && this.state.data.USER_ID === curuid;
        if (!editable) {
            message.error("当前状态不可保存")
            return;
        }
        let data = JSON.parse(JSON.stringify(this.state.data));
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: data,
            url: 'OG/OGEmployeeOpinionCollection/FullUpdate',
            onComplete: (ret) => {
                if (ret) {
                    message.success("保存成功");
                    this.BtnClose();
                }
            }
        });
    }
    onSubmit() {
        const curuid = this.props.login.user.ID;
        const editable = (this.state.type == 'report' || this.state.type == 'view') && this.state.data && this.state.data.STATUS === 2 && this.state.data.USER_ID === curuid;
        if (!editable) {
            message.error("当前状态不可提交")
            return;
        }
        this.state.data.PUBLISH = "SaveAndNotify";
        this.state.data.TaskID = this.props.data.TaskID;
        let data = JSON.parse(JSON.stringify(this.state.data));
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: data,
            url: 'OG/OGEmployeeOpinionCollection/FullUpdate',
            onComplete: (ret) => {
                if (ret) {
                    message.success("提交成功");
                    this.BtnClose();
                }
            }
        });
    }
    onAgree() {
        const curuid = this.props.login.user.ID;
        const checkable = this.state.type == 'check' && this.state.data &&
            ((this.state.data.STATUS === 3 && this.state.data.CHARGE_USER_ID == curuid) || (this.state.data.STATUS === 4 && this.state.data.AH_CHARGE_USER_ID == curuid));
        if (!checkable) {
            message.error("当前状态不可审阅")
            return;
        }
        let json = initFilter(this.props.login.OrgId, this.props.data.id, null, null, null);
        json.Parameter1 = this.props.data.TaskID;
        this.props.dispatch({
            type: 'app/getDataByPost',
            payload: json,
            url: 'OG/OGEmployeeOpinionCollection/Agree',
            onComplete: (ret) => {
                message.success("提交成功");
                this.BtnClose();
            }
        });
    }
    getUserName(it) {
        if (!it || !this.state.data)
            return "";
        let id = it.COLLECTION_USER_ID;
        let idx = this.state.map[id];
        let t = this.state.data.Nav_Users[idx];
        return t && t.Nav_User && t.Nav_User.NAME;
    }
    render() {
        const curuid = this.props.login.user.ID;
        const { data, opinions, opinion_user_map } = this.state;
        const editable = (this.state.type == 'report') && data && data.STATUS === 2 && data.USER_ID === curuid;
        const checkable = this.state.type == 'check' && data &&
            ((data.STATUS === 3 && data.CHARGE_USER_ID == curuid) || (data.STATUS === 4 && data.AH_CHARGE_USER_ID == curuid));
        const count = data && data.Nav_Users ? data.Nav_Users.length : 0;
        const feedback = data && data.Nav_Users ? data.Nav_Users.filter(t => t.STATUS !== 0).length : 0;
        const rate = count !== 0 ? `${Math.round(feedback * 100 / count)}%` : '';
        return <div>
            {
                this.state.type === 'view' &&
                <div style={{ padding: '10px' }}>
                    <ReactToPrint
                        trigger={() => <Button type={'primary'} icon={'printer'} >打印</Button>}
                        content={() => this.componentRef}
                    />
                    <Button style={{ marginLeft: '8px' }} onClick={() => this.onTableBtnExport()} icon="export" >导出</Button>
                </div>
            }
            {
                editable &&
                <div style={{ padding: '10px' }}>
                    <Button type={"primary"} style={{ marginLeft: '8px' }} onClick={() => this.onSave()}><Icon type="save" />保存</Button>
                    <Button type={"primary"} style={{ marginLeft: '8px' }} onClick={() => this.onSubmit()} ><Icon type="edit" />保存并提交</Button>
                </div>
            }
            {
                checkable &&
                <div style={{ padding: '10px' }}>
                    <Button type={"primary"} style={{ marginLeft: '8px' }} onClick={() => this.onAgree()} icon="check" >确定</Button>
                </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={22} rowSpan={1}>{data && data.NAME}</td>
                        </tr>
                        <tr>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>征集起止时间</td>
                            <td colSpan={6} rowSpan={1}>{data && `${data.START_TIME}-${data.END_TIME}`}</td>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>征集部门</td>
                            <td colSpan={2} rowSpan={1}>{data && data.Nav_Department && data.Nav_Department.NAME}</td>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>征集份数</td>
                            <td colSpan={2} rowSpan={1}>{count}</td>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>回收份数</td>
                            <td colSpan={2} rowSpan={1}>{feedback}</td>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>回收比例</td>
                            <td colSpan={2} rowSpan={1}>{rate}</td>
                        </tr>
                        <tr>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>参与人员</td>
                            <td colSpan={22} rowSpan={1}>
                                {
                                    data && data.Nav_Users && data.Nav_Users.map((item, i) => {
                                        if (item.STATUS == 0)
                                            return <label style={{ color: 'red' }} title='未签到'>{item.Nav_User.NAME + '  '}</label>
                                        else
                                            return item.Nav_User.NAME + '  '
                                    })
                                }
                            </td>
                        </tr>
                        <tr>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>序号</td>
                            <td colSpan={12} rowSpan={1} className={styles.fontBold}>意见反馈</td>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>反馈人员</td>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>受理意见</td>
                            <td colSpan={6} rowSpan={1} className={styles.fontBold}>不认可解释</td>
                        </tr>
                        {
                            opinions.map((it, idx) => {
                                return <tr key={it.ID}>
                                    <td colSpan={2} rowSpan={1} >{idx + 1}</td>
                                    <td colSpan={12} rowSpan={1} >{it.OPINION_CONTENT}</td>
                                    <td colSpan={2} rowSpan={1} >{this.getUserName(it)}</td>
                                    <td colSpan={2} rowSpan={1} >{
                                        !editable ? (data && data.STATUS > 1 ? this.fmtEnum('OGOpinionResultEnum', it.RESULT) : '')
                                            :
                                            <Select value={it.RESULT} onChange={value => {
                                                it.RESULT = value
                                                let opinions = this.state.opinions;
                                                if (opinion_user_map[it.ID]) {
                                                    opinion_user_map[it.ID].RESULT = value
                                                }
                                                this.setState({ opinions })
                                            }}>
                                                <Select.Option value={0}>不认可</Select.Option>
                                                <Select.Option value={1}>认可</Select.Option>
                                            </Select>
                                    }</td>
                                    <td colSpan={6} rowSpan={1} >{
                                        !editable ?
                                            it.REFUSE_DESCRIPTION
                                            :
                                            <Input value={it.REFUSE_DESCRIPTION} onChange={e => {
                                                let opinions = this.state.opinions;
                                                if (opinion_user_map[it.ID]) {
                                                    opinion_user_map[it.ID].REFUSE_DESCRIPTION = e.target.value
                                                }
                                                this.setState({ opinions })
                                            }} />
                                    }</td>
                                </tr>
                            })
                        }
                        <tr>
                            <td colSpan={2} rowSpan={1} className={styles.fontBold}>附件</td>
                            <td colSpan={22} rowSpan={1}>
                                {
                                    data && data.Nav_Users && data.Nav_Users.filter(t => t.STATUS !== 0).map(it => {
                                        return it.Nav_Files.map(item => {
                                            return <a width={'20%'} title={item.Nav_ImgFile.FILE_NAME} target='_blank' href={config.picServerHost + item.Nav_ImgFile.Nav_File.FILE_PATH} >{item.Nav_ImgFile.FILE_NAME} </a>
                                        });
                                    })
                                }
                            </td>
                        </tr>
                        <tr>
                            <td colSpan={2} rowSpan={2} className={styles.fontBold}>审阅意见</td>
                            <td colSpan={2} rowSpan={1}>部门负责人</td>
                            <td colSpan={20} rowSpan={1}>
                                {
                                    data && data.Nav_ChargeUser && data.STATUS > 3 ? <img width={'150px'} alt={data.Nav_ChargeUser.NAME} src={config.picServerHost + data.Nav_ChargeUser.Nav_UserSignFiles[0].Nav_ImgFile.Nav_File.FILE_PATH}></img> : ""
                                }
                            </td>
                        </tr>
                        <tr>
                            <td colSpan={2} rowSpan={1}>安环部负责人</td>
                            <td colSpan={20} rowSpan={1}>
                                {
                                    data && data.Nav_AHChargeUser && data.STATUS > 4 ? <img width={'150px'} alt={data.Nav_AHChargeUser.NAME} src={config.picServerHost + data.Nav_AHChargeUser.Nav_UserSignFiles[0].Nav_ImgFile.Nav_File.FILE_PATH}></img> : ""
                                }
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    }
}

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