import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import style from 'styled-components';
import {
  Input,
  Button,
  message,
  DatePicker,
  Form,
  Modal,
  TreeSelect,
  Drawer,
  Select 
} from 'antd';
// import Drawer from 'react-motion-drawer';
import {
  getPerGoodDeedsById,
  updatePerGoodDeeds,
  getTreeperBydepart,
  selectPerIdCardNum
} from '../../../services/api';
import $perModal from '../../../utils/modal/perModal';
const FormItem = Form.Item;
const dateFormat = 'YYYY-MM-DD';
const { TextArea } = Input;
const { Option } = Select;
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.visiable,
      goodDeedsId: 0,
      // treeData: [
      //   //树
      //   { title: '', key: '' }
      // ],
      showPerId: 0,
      perId: '',
      canEditFlag: '', //是否有离职人员
      goodDeeds: {
        idCardNo: '',
        name: '',
        happenDate: '',
        goodContent: '',
        remark: ''
      }
    };
  }

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

  componentWillReceiveProps(nextProps) {
    this.setState({ openEdit: nextProps.visible });
    // if (nextProps.goodDeedsId !== this.state.goodDeedsId) {
    //   if (nextProps.goodDeedsId === 0 || nextProps.goodDeedsId === undefined) {
    //     return;
    //   }
    //   this.setState({
    //     goodDeedsId: nextProps.goodDeedsId
    //   });
    //   this.renderDate(nextProps.goodDeedsId);
    // }
    if(this.state.openEdit !== nextProps.visible) {
      if (nextProps.goodDeedsId === 0 || nextProps.goodDeedsId === undefined) {
        return;
      }
      this.setState({
        goodDeedsId: nextProps.goodDeedsId,
        // treeData:nextProps.treeData
      });
      this.renderDate(nextProps.goodDeedsId);
    }
  }
  componentDidMount() {
    // getTreeperBydepart({}).then(
    //   response => {
    //     console.log(response, 'getTreeperBydepart-response');
    //     this.setState({ treeData: response.data });
    //   },
    //   err => {
    //     console.log(err, 'getTreeperBydepart-err');
    //   }
    // );
  }
  renderDate = pro => {
    console.log('id的值', pro);
    getPerGoodDeedsById({ goodDeedsId: pro }).then(
      data => {
        //人员处理
        if (data.data) {
          const { setFieldsValue } = this.props.form;
          setFieldsValue({
            perId: data.data[0].perId,
            perName: data.data[0].name,
            idCardNo: data.data[0].idCardNo || '',
            happenDate: data.data[0].happenDate || '',
            goodContent: data.data[0].goodContent || '',
            remark: data.data[0].remark || ''
          });
          this.setState({
            goodDeedsType: data.data[0].goodDeedsType,
            canEditFlag: data.data[0].canEditFlag || '',
            goodDeeds: {
              idCardNo: data.data[0].idCardNo || '',
              happenDate: data.data[0].happenDate || '',
              goodContent: data.data[0].goodContent || '',
              remark: data.data[0].remark || ''
            }
          });
        }
      },
      err => {
        console.log(err);
      }
    );
  };

  hideModal = () => {
    this.setState({
      visible: true
    });
    const values = this.props.form.getFieldsValue();
    const rangeValue = values['happenDateDs'];
    values.happenDate = rangeValue.format('YYYY-MM-DD');
    console.log(values);
    console.log(this.state.goodDeeds);
    if(values.idCardNo !== this.state.goodDeeds.idCardNo || values.happenDate!== this.state.goodDeeds.happenDate || values.goodContent!== this.state.goodDeeds.goodContent || values.remark!== this.state.goodDeeds.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
    });
  };
  //树形选择器改编
  handleTreeSelectChange = (value, label, extra) => {
    const lastValue = this.state.perId;
    if (
      extra.triggerNode &&
      extra.triggerNode.props &&
      extra.triggerNode.props.treeType === '1'
    ) {
      console.log('部门');
      this.setState({ perId: lastValue }, this.selectPerIdCardNum());
    } else {
      this.setState({ perId: value }, this.selectPerIdCardNum());
    }
  };
  selectPerIdCardNum = () => {
    selectPerIdCardNum({ perId: this.state.perId }).then(
      response => {
        console.log(response, 'selectPerIdCardNum-response');
        const { setFieldsValue } = this.props.form;
        setFieldsValue({ idCardNo: response.data });
      },
      err => {
        console.log(err, 'selectPerIdCardNum-err');
      }
    );
  };

  // 判断日期
  disabledStartDate = (currentDate) =>{
    return currentDate && currentDate > moment(parseInt(sessionStorage.getItem('requestDate'))).endOf('day');
  }

  //表单提交
  handleGoodDeedsSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const rangeValue = values['happenDateDs'];
        values.happenDate = rangeValue.format('YYYY-MM-DD');
        values.goodDeedsId = this.state.goodDeedsId;
        updatePerGoodDeeds(values).then(
          data => {
            console.log(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, setFieldsValue, getFieldValue } = this.props.form;
    console.log(this.state.openEdit)
    return (
      <Content>
        {/*好人好事详情*/}
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          placement="right"
          visible={!!this.state.openEdit}
          // noTouchClose
          width={600}
          zIndex={11}
          title="好人好事详情"
          onChange={openEdit => {
            this.props.onChange(openEdit);
            this.setState({ openEdit });
          }}
          onClose={()=>{
            this.setState({
              openEdit:false
            });
          }}
          destroyOnClose
        >
          <div>
            <div>
              <Form
                style={{ marginTop: 24 }}
                onSubmit={this.handleGoodDeedsSubmit}
              >
                <FormItem {...formItemLayout} label="被表彰奖励人员">
                  {getFieldDecorator('perId', {
                    rules: [
                      {
                        required: true, message: '请选择被表彰奖励人员'
                      }
                    ]
                  })(<Input style={{ display: 'none' }} />)}
                  {getFieldDecorator('perName', {
                    rules: [
                      {
                        required: true, message: '请选择被表彰奖励人员'
                      }
                    ]
                  })(<Input readOnly style={{ width: 294 }} onClick={() => {
                    $perModal({
                      value: getFieldValue('perId'),
                      type: 'radio',
                      onOk: (values, close) => {
                        const { perId, name, idCardNo } = values[0];
                        setFieldsValue({ perId, perName: name, idCardNo });
                        close();
                      }
                    });
                  }} />)}

                </FormItem>
                <FormItem {...formItemLayout} label="好人好事类型: ">
                  {getFieldDecorator('goodDeedsType', {
                    initialValue: this.state.goodDeedsType,
                    rules: [
                      {
                        transform: (transformeValue) => { return validateTrim(transformeValue); }
                      },
                      {
                        required: true, message: '请选择',
                      }
                    ]
                  })(
                    <Select style={{width: 290}}>
                      {
                        this.props.goodDeedsTypes.map(val => (
                          <Option value={val.codeValue + ''} key={val.codeValue}>
                            {val.label}
                          </Option>
                        ))
                      }
                    </Select>
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="身份证号: ">
                  {getFieldDecorator('idCardNo', {
                    initialValue: this.state.goodDeeds.idCardNo,
                    rules: [
                      {
                        required: true,message:"请输入身份证号"
                      }
                    ]
                  })(<Input style={{ width: 294 }} disabled />)}
                </FormItem>
                <FormItem {...formItemLayout} label="发生日期">
                  {getFieldDecorator(
                    'happenDateDs',
                    {
                      initialValue: moment(
                        this.state.goodDeeds.happenDate,
                        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('goodContent', {
                    initialValue: this.state.goodDeeds.goodContent,
                    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.goodDeeds.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.handleGoodDeedsSubmit}>
                提交
              </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;
  }`;
