// 人员审核弹框
import React from 'react';
import { Select, Input, Row, Col, Button, Divider, Radio, message, Form, Steps, Table, Popover } from 'antd';
import { $http } from '../../../containers/config/https';
import '../style/style.less'
import Moment from 'moment';

// 组件const
const { Option } = Select;
const RadioGroup = Radio.Group;
const Step = Steps.Step;
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 4 },
    wrapperCol: { span: 19 },
};
const { TextArea } = Input;

const customDot = (dot, { status, index }) => (
    <Popover content={<span>step {index} status: {status}</span>}>
        {dot}
    </Popover>
);


class PersAuditModal extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            dataGroup: [],  // 添加分组数据
            userInfo: {}, // 回显用户数据
            auditGroupAry: [],  // 审核数组
            dis: false,  // 不可选
            radioValue: [], // 默认radio
            persAuditDateId: '', //审核弹框主键
            userAuditFlag: '', //审核还是查看
        };
        // 医嘱子类table
        this.columnsGroup = [
            {
                title: '角色名称',
                dataIndex: 'CBGroupDesc',
                align: "center",
                key: '1',
                render: (text, record, index) => (
                    <span>
                        {record.CBGroupDesc ? record.CBGroupDesc : record.auditGroupDesc}
                    </span>
                )
            }, {
                title: '操作',
                dataIndex: 'radioS',
                align: "center",
                key: '2',
                render: (text, record, index) => (
                    <RadioGroup onChange={(event) => { this.RadioGroup(event, record, index) }} defaultValue={this.state.radioValue[index].userAuditStatus ? (this.state.radioValue[index].userAuditStatus === 'N' ? '2' : '1') : ''} >
                        <Radio disabled={this.state.dis} value="1">审核通过</Radio>
                        <Radio disabled={this.state.dis} value="2">审核不通过</Radio>
                    </RadioGroup>
                )
            },
        ]

    }

    componentDidMount() {
        if (this.props.persAuditDateId && this.props.persAuditDateId !== "") {
            let data = this.props.persAuditDateId
            let userAuditFlag = this.props.userAuditFlag

            this.setState({
                userAuditFlag: userAuditFlag,
            })

            this.callbackData(data, userAuditFlag) // 数据回显

        }

    }

    // 实时更新
    componentWillReceiveProps(nextProps) {
        const { persAuditDateId, userAuditFlag } = this.state
        const newdata = nextProps.persAuditDateId
        const newuserAuditFlag = nextProps.userAuditFlag

        if (persAuditDateId !== newdata) {

            this.setState({
                persAuditDateId: newdata,
                userAuditFlag: newuserAuditFlag,
            }, () => {
                this.callbackData(newdata, newuserAuditFlag) // 数据回显
            })
        }

    }

    RadioGroup = (e, record, index) => {
        let { auditGroupAry } = this.state  // 审核数组
        // auditGroupAry.splice(index, 1, e.target.value);
        auditGroupAry[index].CBGroupID = record.auditGroupId
        auditGroupAry[index].userAuditStatus = e.target.value === '1' ? 'Y' : 'N'
        this.setState({
            auditGroupAry: auditGroupAry
        })
    }

    // 数据回显
    callbackData = (id, flag) => {
        let data = {
            "params": [{
                userID: id
            }]
        };
        let code
        if (flag === '1') {
            code = '01040064'
        } else {
            code = '01040054'
        }
        $http.post('urlS', this, {
            code: code,
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {

                    for (var i = 0; i < res.result.userAuditLogAry.length; i++) {
                        res.result.userAuditLogAry[i].key = i;
                    }

                    let auditGroupAry = []  // 审核数组

                    res.result.userAuditLogAry.map((item, i) => {
                        auditGroupAry.push({
                            CBGroupID: '',
                            userAuditStatus: ''
                        })
                    })
                    this.setState({
                        dataGroup: [], // 回显用户数据（避免回显radio不更改）
                    })
                    this.setState({
                        userInfo: res.result, // 回显用户数据
                        dataGroup: res.result.userAuditLogAry, // 回显用户数据
                        dis: this.state.userAuditFlag === '1' ? false : true,
                        auditGroupAry: auditGroupAry,
                        radioValue: res.result.userAuditLogAry
                    }, () => {
                        console.log(this.state.userInfo)
                    })
                }
            }
        });
    }
    // 用户分配科室
    handleLocAllocation = () => {
        let userID = JSON.parse(window.sessionStorage.userData).userID
        var params = {
            params: [{
                deptDocLogID: '', //科室人员主键
                userID: this.state.userInfo.userID || '',   //人员主键
                locID: this.state.userInfo.userApplyLocID || '',        //科室主键
                hospID: this.state.userInfo.userApplyHospID,   //医院主键
                deptDepartmentHead: "N",       //部门领导
                deptInpatient: "N",    //住院病人
                deptOutpatient: "N",   //门诊病人
                deptEmergency: "N",    //急诊病人
                deptOwnPatientsOnly: "N",       //只看本病人可用
                deptDocStartDate: this.state.userInfo.userApplyDate ?
                    Moment(this.state.userInfo.userApplyDate).utcOffset(480).format('YYYY-MM-DD') : "",        // 科室配置生效日期
                deptDocEndDate: "",     //科室配置失效日期
                updateUserID: userID,     //当前用户
                deptPrescriberFlag: "N",   //处方权
                deptNoOrders: "Y",      //无医嘱权
                deptNoEMR: "Y",        //无病历权
                deptNoDiagnosis: "Y",      //无诊断权
                deptNotReadResults: "N",       // 不看检查结果
                herbalPresc: "N",       // 不看检查结果
                deptAnaesthesia: "N",      //毒麻药品处方权
                deptAntibiotic: "N",       //抗生素处方权
                deptTriageNurse: "N",      //是否是分诊护士
                medGrpUserLeaderFlag: "N",      //是否为所属分组组长
                deptSchedule: "Y",      //排班
                // 'active': Util.replaceTrueFalse(values.active) || "",      //激活
                medGroupLogID: "",      //所属分组主键
                beforMedGrpUserID: "",  //所选用户原有人员分组中人员记录主键
                medGrpUserLogID: "", //人员分组中人员记录主键
                removeUserExperAry: [],        //专长数组删除的
                userExperAry: []       //专长数组
            }]
        };
        $http.post('urlADS', this, {
            code: "01040025",
            data: params,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    message.success(res.errorMessage);
                    this.setState({
                        deptLocId: 'relive' // 提交成功 置空
                    })
                }
            }
        });
    }

    // 保存用户信息表单提交
    handleSubmit = (e) => {

        e.preventDefault();

        this.props.form.validateFields((err, values) => {
            if (!err) {  //!err
                let { auditGroupAry, userInfo } = this.state  // 审核数组
                let error = true;

                console.log(auditGroupAry)
                auditGroupAry.some((item, i) => {
                    if (item.userAuditStatus === '') {
                        error = false
                        message.error('尚有关联角色未审核完');
                        return true
                    }
                })

                if (error) {
                    let data = {
                        "params": [{
                            "userID": this.state.userInfo.userID || '',
                            "userApplyHospID": this.state.userInfo.userApplyHospID || '',
                            "userAuditRemarks": values.auditMarks || '',
                            "userAuditLogAry": auditGroupAry,
                            "userAuditLocID": this.state.userInfo.userApplyLocID || '',
                            'userAuditUserID': JSON.parse(window.sessionStorage.userData).userID || '',        //更新人
                            'hospID': JSON.parse(window.sessionStorage.userData).hospID || '',   // 当前医院
                            'userCode': values.userCode || '',
                        }]
                    };
                    $http.post('urlADS', this, {
                        code: "01040028",
                        data: data,
                        success: function (res) {
                            let errorCode = res.errorCode;
                            if (errorCode === '0') {
                                this.props.handleOk();
                                this.setState({
                                    dis: true,  // 不可选
                                })
                                this.handleLocAllocation();
                            }
                        }
                    });
                }


            }

        });
    }




    render() {
        const { getFieldDecorator } = this.props.form;
        const { userInfo } = this.state
        return (
            <div>
                <Row >
                    <Col span={16} offset={4}>
                        <Steps current={1} progressDot={customDot} className="steps" style={{ whiteSpace: 'nowrap' }}>
                            <Step title='发起申请' description={userInfo.userApplyDate || '' + ' ' + userInfo.userApplyTime || ''} />
                            <Step title={userInfo.userAuditResult} description={userInfo.userAuditLogDesc} />
                            {/* {userInfo.groupAuditObj ? (userInfo.groupAuditObj.auditFlag === '0' ? <Step title={userInfo.firstAuditDesc ? userInfo.firstAuditDesc + '审核' : '' + '审核'} /> : <Step description={userInfo.groupAuditObj.auditDateTime} title={userInfo.groupAuditObj.applyResult + ' ' + userInfo.groupAuditObj.secondAuditDesc + userInfo.groupAuditObj.finalAudResult} />) : ''} */}
                        </Steps>
                    </Col>
                </Row>
                <Form layout="vertical" className="depart-form" onSubmit={this.handleSubmit}  >
                    <Divider orientation="left">基本资料</Divider>
                    <Row style={{ lineHeight: '30px' }}>
                        <Col span={6}>
                            <span>姓名：{userInfo.userDesc}</span>
                        </Col>
                        <Col span={6}>
                            <span>性别：{userInfo.userSexDesc}</span>
                        </Col>
                        <Col span={6}>
                            <span>证件类型：{userInfo.userCredTypeDesc}</span>
                        </Col>
                        <Col span={6}>
                            <span>证件号码：{userInfo.userCredNo}</span>
                        </Col>
                    </Row>
                    <Row style={{ lineHeight: '30px' }} >
                        <Col span={6}>
                            <span>出生日期：{userInfo.userDOB}</span>
                        </Col>
                        <Col span={6}>
                            <span>手机号码：{userInfo.userMobile}</span>
                        </Col>
                        <Col span={6}>
                            <span>职称：{userInfo.userTitleDesc}</span>
                        </Col>
                    </Row>
                    <Divider orientation="left">医院岗位</Divider>
                    <Row style={{ lineHeight: '30px' }}>
                        <Col span={6}>
                            <span>所属医院：{userInfo.userApplyHospDesc}</span>
                        </Col>
                        <Col span={6}>
                            <span>所属科室：{userInfo.userApplyLocDesc}</span>
                        </Col>
                        <Col span={6}>
                            <span>申请岗位：{userInfo.userPostDesc}</span>
                        </Col>
                    </Row>
                    <Divider orientation="left">关联角色</Divider>
                    <Row className="mB30">
                        <Col span={24} >
                            <Table bordered dataSource={this.state.dataGroup} columns={this.columnsGroup} pagination={false} style={{ maxHeight: '215px', overflow: 'auto' }} />
                        </Col>
                    </Row>
                    <Row>
                        <Col span={24} >
                            <Form.Item label="人员工号："  {...formItemLayout} >
                                {getFieldDecorator('userCode', {
                                    initialValue: '',
                                    rules: [],
                                })(
                                    <Input allowClear placeholder="人员工号" className='input' disabled={this.state.dis} />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={24} >
                            <Form.Item label="拒绝原因："  {...formItemLayout} >
                                {getFieldDecorator('auditMarks', {
                                    initialValue: userInfo.userAuditRemarks,
                                    rules: [],
                                })(
                                    <TextArea rows={3} maxLength="30" placeholder="请输入拒绝原因" disabled={this.state.dis} />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row >
                        <Col span={24} style={{ display: this.state.dis === true ? 'none' : 'block' }}>
                            <Row style={{ width: '100%', textAlign: 'center', marginBottom: '10px' }}>
                                <Button onClick={this.handleSubmit} style={{ marginRight: '15px', background: 'rgba(66,185,131,1)', color: '#fff' }}>确定</Button>
                            </Row>
                        </Col>
                    </Row>


                </Form>
            </div>

        )
    }
}

const PersAuditModalFrom = Form.create()(PersAuditModal);

export default PersAuditModalFrom