import React, { PureComponent } from 'react';
import { connect } from 'dva';
import style from "styled-components";
import moment from 'moment';
import "moment/locale/zh-cn";
import { Input, Button, DatePicker, Checkbox, Form, Modal, TreeSelect, Drawer } from 'antd';
// import Drawer from 'react-motion-drawer';
import { updateComSecurityAward, getComSecurityAwardById } from "../../../services/api";
import PSelect from "../../../components/Pro/PSelect";
import $perModal from '../../../utils/modal/perModal';
const FormItem = Form.Item;
const dateFormat = 'YYYY-MM-DD';
const { TextArea } = Input;

const config = {
    rules: [
        {
            type: 'object',
            required: false,
            message: '请选择日期!'
        }
    ]
};

//首次验证trim()
function validateTrim(v) {
    return v === undefined ? v : v.trim();
}

@connect(state => ({ profile: state.profile }))
@Form.create()

export default class EditIncentive extends PureComponent {
    constructor(props, context) {
        super(props, context);
        this.state = {
            openEdit: this.props.visible,
            awardId: 0,
            // treeData: [
            //     //树
            //     { title: "", key: "" }
            // ],
            showPerId: 0,
            perIdArray: [],
            canEditFlag: '', //是否有离职人员
            canEditValue: [], //有离职人员时的表彰奖励人员
            comSecurityAward: {
                awardDate: "",
                awardType: "",
                awardUnit: "",
                isPoliceAward: false,
                awardContent: "",
                awardReason: "",
                remark: "",
            },
        };
    }

    /******************************生命周期******************************/

    componentWillReceiveProps(nextProps) {
        this.setState({ openEdit: nextProps.visible });
        // if (nextProps.awardId !== this.state.awardId) {
        //     if (nextProps.awardId === 0 || nextProps.awardId === undefined) {
        //         return;
        //     }
        //     this.setState({
        //         awardId: nextProps.awardId
        //     });
        //     this.renderDate(nextProps.awardId);
        // }
        if (this.state.openEdit !== nextProps.visible) {
            if (nextProps.awardId === 0 || nextProps.awardId === undefined) {
                return;
            }
            this.setState({
                awardId: nextProps.awardId,
                // treeData: nextProps.treeData
            });
            this.renderDate(nextProps.awardId);
        }
    }
    componentDidMount() {
        // getTreeperBydepart({}).then(
        //     response => {
        //         console.log(response, "getTreeperBydepart-response");
        //         this.setState({ treeData: response.data });
        //     },
        //     err => {
        //         console.log(err, "getTreeperBydepart-err");
        //     }
        // );
    }

    //树形选择器改编
    handleTreeSelectChange = (value, label, extra) => {
        console.log(value, label, extra, 'value, label, extravalue, label, extra')
        const lastValue = this.state.perIdArray;
        if (extra.triggerNode && extra.triggerNode.props && extra.triggerNode.props.treeType === "1") {
            console.log("部门");
            this.setState({ perIdArray: lastValue });
        } else {
            this.setState({ perIdArray: value });
        }
    }
    renderDate = (pro) => {
        //传一个t时间戳数据，是为了解决ie出现的请求数据缓存
        getComSecurityAwardById({ awardId: pro, t: new Date().getTime() }).then((data) => {
            if (data.data) {
                if (data.data.comSecurityAward.isPoliceAward === "1") {
                    data.data.comSecurityAward.isPoliceAward = true;
                    console.log('获取单个奖励信息TRUE', data.data.comSecurityAward.isPoliceAward);
                } else {
                    data.data.comSecurityAward.isPoliceAward = false;
                    console.log('获取单个奖励信息FALSE', data.data.comSecurityAward.isPoliceAward);
                }
                const canEditValue = [];
                data.data.canEditFlag === '0' && data.data.perList.map((item) => {
                    canEditValue.push(item.name);
                });
                this.setState({
                    canEditValue
                });
            }
            const { setFieldsValue } = this.props.form;
            const perList = data.data.perList || [];
            setFieldsValue({
                perName: data.data.perList[0]?data.data.perList[0].name: '',
                perIdString: data.data.perList[0]?data.data.perList[0].perId: '',
                awardDate: data.data.comSecurityAward.awardDate || '',
                awardType: data.data.comSecurityAward.awardType || '',
                awardUnit: data.data.comSecurityAward.awardUnit || '',
                isPoliceAward: data.data.comSecurityAward.isPoliceAward || '',
                awardContent: data.data.comSecurityAward.awardContent || '',
                awardReason: data.data.comSecurityAward.awardReason || '',
                remark: data.data.comSecurityAward.remark || '',
            });
            this.setState({
                canEditFlag: data.data.canEditFlag || '',
                comSecurityAward: {
                    awardDate: data.data.comSecurityAward.awardDate || '',
                    awardType: data.data.comSecurityAward.awardType || '',
                    awardUnit: data.data.comSecurityAward.awardUnit || '',
                    isPoliceAward: data.data.comSecurityAward.isPoliceAward || '',
                    awardContent: data.data.comSecurityAward.awardContent || '',
                    awardReason: data.data.comSecurityAward.awardReason || '',
                    remark: data.data.comSecurityAward.remark || '',
                },
            });
        }, (err) => {
            console.log(err);
        });
    }

    hideModal = () => {
        // this.setState({
        //     visible: true,
        // });
        const values = this.props.form.getFieldsValue();
        console.log(values);
        const rangeValue = values['awardDateSd'];
        values.awardDate = rangeValue.format('YYYY-MM-DD');

        if (values.awardDate !== this.state.comSecurityAward.awardDate || values.awardType !== this.state.comSecurityAward.awardType || values.awardUnit !== this.state.comSecurityAward.awardUnit || values.isPoliceAward !== this.state.comSecurityAward.isPoliceAward || values.awardContent !== this.state.comSecurityAward.awardContent || values.awardReason !== this.state.comSecurityAward.awardReason || values.remark !== this.state.comSecurityAward.remark) {
            this.setState({
                visible: true,
            });
        } else {
            this.handleModalOk();
        }

    }
    handleModalOk = (e) => {
        console.log(e);
        this.setState({
            visible: false,
            openEdit: false,
        });
    }
    handleModalCancel = (e) => {
        console.log(e);
        this.setState({
            visible: false,
        });
    }
    // 判断日期
    disabledStartDate = (currentDate) => {
        return currentDate && currentDate > moment(parseInt(sessionStorage.getItem('requestDate'))).endOf('day');
    }
    //表单提交
    handleIncentiveSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.awardId = this.state.awardId;
                values.perIdString = [values.perIdString];
                Reflect.deleteProperty(values, 'perName');
                const rangeValue = values['awardDateSd'];
                values.awardDate = rangeValue.format('YYYY-MM-DD');
                const { isPoliceAward } = values;
                if (isPoliceAward) {
                    values.isPoliceAward = '1';
                } else {
                    values.isPoliceAward = '0';
                }
                console.log(values);
                updateComSecurityAward(values).then((data) => {
                    this.setState({ openEdit: false });
                    this.props.tableUpdate();
                }, (err1) => {
                    console.log(err1);
                });
            }
        });
    }

    render() {
        const formItemLayout = {
            labelCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 7
                }
            },
            wrapperCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 17
                },
                md: {
                    span: 17
                }
            }
        };
        const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form;
        return (
            <Content>
                {/*奖励详情*/}
                < Drawer
                    overlayColor="rgba(0, 0, 0,0)"
                    placement="right"
                    visible={this.state.openEdit}
                    // noTouchClose
                    title="奖励详情"
                    width={600}
                    zIndex={11}
                    onChange={(openEdit) => {
                        this.props.onChange(openEdit);
                        this.setState({ openEdit });
                    }}
                    onClose={() => {
                        this.setState({
                            openEdit: false
                        });
                    }}
                    destroyOnClose
                >
                    <div>
                        {/* <div className="drawer-header">奖励详情</div> */}
                        <div>
                            <Form style={{ marginTop: 24 }} onSubmit={this.handleIncentiveSubmit}>
                                <FormItem {...formItemLayout} label="表彰奖励人员">
                                    {getFieldDecorator('perIdString', {
                                        rules: [
                                            {
                                                required: true, message: '请选择表彰奖励人员'
                                            }
                                        ]
                                    })(<Input style={{ display: 'none' }} />)}
                                    {getFieldDecorator('perName', {
                                        rules: [
                                            {
                                                required: true, message: '请选择表彰奖励人员'
                                            }
                                        ]
                                    })(<Input readOnly style={{ width: 294 }} onClick={() => {
                                        $perModal({
                                            value: getFieldValue('perIdString'),
                                            type: 'radio',
                                            onOk: (values, close) => {
                                                setFieldsValue({ perIdString: values[0].perId, perName: values[0].name });
                                                close();
                                            }
                                        });
                                    }} />)}

                                </FormItem>
                                
                                <FormItem {...formItemLayout} label="表彰奖励日期">
                                    {getFieldDecorator('awardDateSd', {
                                        initialValue: moment(this.state.comSecurityAward.awardDate, dateFormat),
                                        rules: [
                                            {
                                                required: true, message: '请选择表彰奖励日期'
                                            }
                                        ]
                                    }, config)(
                                        <DatePicker
                                            style={{ width: 294 }}
                                            disabled={this.state.canEditFlag === '0' ? true : false}
                                            disabledDate={this.disabledStartDate}
                                            format="YYYY-MM-DD"
                                        />
                                    )}
                                </FormItem>
                                <FormItem {...formItemLayout} label="表彰奖励类型">
                                    {getFieldDecorator('awardType', {
                                        initialValue: this.state.comSecurityAward.awardType,
                                        rules: [
                                            {
                                                required: true, message: '请选择表彰奖励类型'
                                            }
                                        ]
                                    })(<PSelect type="awardType" style={{ width: 294 }} disabled={this.state.canEditFlag === '0' ? true : false} />)}
                                </FormItem>
                                <FormItem {...formItemLayout} label="颁发单位">
                                    {getFieldDecorator('awardUnit', {
                                        initialValue: this.state.comSecurityAward.awardUnit,
                                        rules: [
                                            {
                                                transform: (transformeValue) => { return validateTrim(transformeValue); }
                                            },
                                            {
                                                required: true, message: '请填写颁发单位'
                                            }
                                        ]
                                    })(<Input style={{ width: 294 }} maxLength={50} placeholder="请输入" disabled={this.state.canEditFlag === '0' ? true : false} />)}
                                </FormItem>

                                <FormItem {...formItemLayout} label="公安机关给予表彰奖励">
                                    {getFieldDecorator('isPoliceAward', {
                                        valuePropName: 'checked',
                                        initialValue: this.state.comSecurityAward.isPoliceAward,
                                    })(<Checkbox
                                        style={{ width: 294 }}
                                        disabled={this.state.canEditFlag === '0' ? true : false}
                                    />
                                    )}
                                </FormItem>
                                <FormItem {...formItemLayout} label="表彰奖励内容">
                                    {getFieldDecorator('awardContent', {
                                        initialValue: this.state.comSecurityAward.awardContent,
                                        rules: [
                                            {
                                                transform: (transformeValue) => { return validateTrim(transformeValue); }
                                            },
                                            {
                                                required: true, message: '请填写表彰奖励内容'
                                            }
                                        ]
                                    })(<TextArea style={{ width: 294 }} maxLength={500} rows={4} placeholder="请输入" disabled={this.state.canEditFlag === '0' ? true : false} />)}
                                </FormItem>
                                <FormItem {...formItemLayout} label="表彰奖励原因">
                                    {getFieldDecorator('awardReason', {
                                        initialValue: this.state.comSecurityAward.awardReason,
                                        rules: [
                                            {
                                                transform: (transformeValue) => { return validateTrim(transformeValue); }
                                            },
                                            {
                                                required: true, message: '请填写表彰奖励原因'
                                            }
                                        ]
                                    })(<TextArea style={{ width: 294 }} maxLength={500} rows={4} placeholder="请输入" disabled={this.state.canEditFlag === '0' ? true : false} />)}
                                </FormItem>
                                <FormItem {...formItemLayout} label="备注">
                                    {getFieldDecorator('remark', {
                                        initialValue: this.state.comSecurityAward.remark,
                                        rules: [
                                            {
                                                transform: (transformeValue) => { return validateTrim(transformeValue); }
                                            },
                                            {
                                                required: false
                                            }
                                        ]
                                    })(<TextArea style={{ width: 294 }} maxLength={500} rows={4} placeholder="请输入" disabled={this.state.canEditFlag === '0' ? true : false} />)}
                                </FormItem>
                            </Form>
                        </div>
                        <div style={{
                            position: 'absolute',
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e8e8e8',
                            padding: '10px 16px',
                            textAlign: 'right',
                            left: 0,
                            background: '#fff',
                            borderRadius: '0 0 4px 4px',
                        }}>
                            <Button onClick={this.hideModal} style={{ marginRight: 8 }}>返回</Button>
                            <Button type="primary" onClick={this.handleIncentiveSubmit}>提交</Button>
                        </div>
                    </div>
                </Drawer >
                <Modal
                    title="提示"
                    visible={this.state.visible}
                    onOk={this.handleModalOk}
                    onCancel={this.handleModalCancel}
                >
                    <p>返回会取消您已填写的内容，确定返回？</p>
                </Modal>
            </Content >
        );
    }
}

/************************样式************************/

const Content = style.div`{
  font-size: 14px;
  color: rgba(0,0,0,0.65);
  .searchpanel{
     margin-bottom:16px;
    .post{
      margin:0 8px 0 16px;
    }
  }
  .btns{
    margin-top:16px;
  }
}`;
const Formitem = style.label`{

    font-family: "Monospaced Number", "Chinese Quote", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 14px;
    line-height: 1.5;
    color: rgba(0, 0, 0, 0.65);
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    list-style: none;
    vertical-align: top;
    -webkit-transition: margin 0.15s steps(1);
    transition: margin 0.15s steps(1);
  }`;
const Formlable = style.span`{
    text-align: right;
    vertical-align: middle;
    line-height: 39.9999px;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
    margin-right:8px;

  }`;

