import React, { PureComponent } from "react";
import { connect } from "dva";
import style from "styled-components";
import moment from "moment";
import {
  Input,
  Button,
  message,
  DatePicker,
  Checkbox,
  Form,
  Modal,
  TreeSelect,
  Drawer
} from "antd";
// import Drawer from "react-motion-drawer";
import PSelect from "../../../components/Pro/PSelect";
import {
  updateComSecurityPpenalty,
  getComSecurityPenaltyById,
  getTreeperBydepart
} from "../../../services/api";
import {
  RegString50,
  RegString500,
} from '../../../constants/regexps';
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: "请选择日期!"
    }
  ]
};
message.config({
  top: 100,
  right: 5,
  duration: 2,
});

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


@connect(state => ({ profile: state.profile }))
@Form.create()
export default class EditPunishment extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      openEdit: this.props.openEdit,
      penaltyId: 0,
      // treeData: [
      //   //树
      //   //{ title: "", key: "" }
      // ],
      showPerId: 0,
      perIdString: [],
      canEditFlag: '', //是否有离职人员
      canEditValue: [], //有离职人员时的被处罚人员
      comSecurityPenalty: {
        penaltyDate: "",
        penaltyType: "",
        penaltyUnit: "",
        isCrime: false,
        penaltyContent: "",
        penaltyReason: "",
        remark: ""
      }
    };
  }

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

  componentWillReceiveProps(nextProps) {
    this.setState({ openEdit: nextProps.visible });
    // if (nextProps.penaltyId !== this.state.penaltyId) {
    //   if (nextProps.penaltyId === 0 || nextProps.penaltyId === undefined) {
    //     return;
    //   }
    //   this.setState({
    //     penaltyId: nextProps.penaltyId
    //   });
    //   this.renderDate(nextProps.penaltyId);
    // }
    if(this.state.openEdit !== nextProps.visible) {
      if (nextProps.penaltyId === 0 || nextProps.penaltyId === undefined) {
        return;
      }
      this.setState({
        penaltyId: nextProps.penaltyId,
        // treeData:nextProps.treeData
      });
      this.renderDate(nextProps.penaltyId);
    }
  }
  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);
    //传一个t时间戳数据，是为了解决ie出现的请求数据缓存
    getComSecurityPenaltyById({ penaltyId: pro, t:new Date().getTime() }).then((data) => {
      console.log('shuju', data.data);
      console.log("comSecurityPenalty", data.data.comSecurityPenalty);
      if (data.data) {
        if (data.data.comSecurityPenalty.isCrime === "1") {
          data.data.comSecurityPenalty.isCrime = true;
          console.log(
            "获取单个处罚信息-checkbox",
            data.data.comSecurityPenalty.isCrime
          );
        } else {
          data.data.comSecurityPenalty.isCrime = false;
          console.log(
            "获取单个处罚信息-checkbox",
            data.data.comSecurityPenalty.isCrime
          );
        }
        const canEditValue = [];
        data.data.canEditFlag === '0' && data.data.perList.map((item)=>{
            canEditValue.push(item.name);
        });
        console.log(canEditValue);
        this.setState({
          canEditValue
        });
      }
      const { setFieldsValue } = this.props.form;
      //人员处理
      const perIdString = [];
      const perName = [];
      data.data.perList && data.data.perList.map((item) => {
        const { perId } = item;
        perIdString.push(perId.toString());
      });
      data.data.perList && data.data.perList.map((item) => {
        const { name } = item;
        perName.push(name.toString());
      });
      console.log(perIdString);
      setFieldsValue({
        perName: perName.join(','),
        perIdString: perIdString.join(','),
        penaltyDate: data.data.comSecurityPenalty.penaltyDate || '',
        penaltyType: data.data.comSecurityPenalty.penaltyType || '',
        penaltyUnit: data.data.comSecurityPenalty.penaltyUnit || '',
        isCrime: data.data.comSecurityPenalty.isCrime || '',
        penaltyContent: data.data.comSecurityPenalty.penaltyContent || '',
        penaltyReason: data.data.comSecurityPenalty.penaltyReason || '',
        remark: data.data.comSecurityPenalty.remark || '',
      });
      this.setState({
        perIdString,
        canEditFlag: data.data.canEditFlag || '',
        comSecurityPenalty: {
          penaltyDate: data.data.comSecurityPenalty.penaltyDate || '',
          penaltyType: data.data.comSecurityPenalty.penaltyType || '',
          penaltyUnit: data.data.comSecurityPenalty.penaltyUnit || '',
          isCrime: data.data.comSecurityPenalty.isCrime || '',
          penaltyContent: data.data.comSecurityPenalty.penaltyContent || '',
          penaltyReason: data.data.comSecurityPenalty.penaltyReason || '',
          remark: data.data.comSecurityPenalty.remark || ''
        },
      });
    }, (err) => {
      console.log(err);
    });
  }

  //表单提交
  handlePunishmentSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values.penaltyId = this.state.penaltyId;
        values.perIdString = [ values.perIdString ];
        const rangeValue = values["penaltyDateSd"];
        Reflect.deleteProperty(values, 'perName');
        values.penaltyDate = rangeValue.format("YYYY-MM-DD");
        const { isCrime } = values;
        if (isCrime) {
          values.isCrime = "1";
        } else {
          values.isCrime = "0";
        }
        console.log('修改表单提交内容');
        console.log(values);
        updateComSecurityPpenalty(values).then(
          data => {
            console.log(data);

            this.setState({ openEdit: false });
            this.props.tableUpdate();
          },
          err1 => {
            console.log(err1);
          }
        );
      }
    });
  };

  hideModal = () => {
    this.setState({
      visible: true,
    });

    const values = this.props.form.getFieldsValue();
    console.log(values);
    const rangeValue = values["penaltyDateSd"];
    values.penaltyDate = rangeValue.format("YYYY-MM-DD");

    if (values.penaltyDate !== this.state.comSecurityPenalty.penaltyDate || values.penaltyType !== this.state.comSecurityPenalty.penaltyType || values.penaltyUnit !== this.state.comSecurityPenalty.penaltyUnit || values.isCrime !== this.state.comSecurityPenalty.isCrime || values.penaltyContent !== this.state.comSecurityPenalty.penaltyContent || values.penaltyReason !== this.state.comSecurityPenalty.penaltyReason || values.remark !== this.state.comSecurityPenalty.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');
  }

  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}
          width={600}
          zIndex={11}
          title="处罚详情"
          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.handlePunishmentSubmit}
              >
                <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(
                    "penaltyDateSd",
                    {
                      initialValue: moment(
                        this.state.comSecurityPenalty.penaltyDate,
                        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("penaltyType", {
                    initialValue: this.state.comSecurityPenalty.penaltyType,
                    rules: [
                      {
                        required: true, message: '请选择处罚类型'
                      }
                    ]
                  })(
                    <PSelect type="penaltyType" style={{ width: 294 }} disabled={this.state.canEditFlag === '0' ? true : false}/>)}
                </FormItem>
                <FormItem {...formItemLayout} label="做出处罚单位">
                  {getFieldDecorator("penaltyUnit", {
                    initialValue: this.state.comSecurityPenalty.penaltyUnit,
                    rules: [
                      {
                        transform:(transformeValue) =>{ return validateTrim(transformeValue); }
                      },
                      RegString50, {
                      required: true, message: RegString50.message,
                    }],
                    // rules: [
                    //   {
                    //     required: true, message: '请填写做出处罚单位'
                    //   }
                    // ]
                  })(
                    <Input
                      maxLength={50}
                      style={{ width: 294 }}
                      placeholder="请输入"
                      disabled={this.state.canEditFlag === '0' ? true : false}
                    />
                  )}
                </FormItem>

                <FormItem {...formItemLayout} label="追究刑事责任">
                  {getFieldDecorator("isCrime", {
                    valuePropName: "checked",
                    initialValue: this.state.comSecurityPenalty.isCrime
                  })(<Checkbox style={{ width: 294 }} disabled={this.state.canEditFlag === '0' ? true : false}/>)}
                </FormItem>

                <FormItem {...formItemLayout} label="处罚内容">
                  {getFieldDecorator("penaltyContent", {
                    initialValue: this.state.comSecurityPenalty.penaltyContent,
                    // rules: [
                    //   {
                    //     required: true, message: '请填写处罚内容'
                    //   }
                    // ]
                    rules: [
                      {
                        transform:(transformeValue) =>{ return validateTrim(transformeValue); }
                      },
                      RegString500, {
                      required: true, message: RegString500.message,
                    }],
                  })(
                    <TextArea
                      style={{ width: 294 }}
                      maxLength={500}
                      rows={4}
                      placeholder="请输入"
                      disabled={this.state.canEditFlag === '0' ? true : false}
                    />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="处罚原因">
                  {getFieldDecorator("penaltyReason", {
                    initialValue: this.state.comSecurityPenalty.penaltyReason,
                    // rules: [
                    //   {
                    //     required: true, message: '请填写处罚原因'
                    //   }
                    // ]
                    rules: [
                      {
                        transform:(transformeValue) =>{ return validateTrim(transformeValue); }
                      },
                      RegString500, {
                      required: true, message: RegString500.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.comSecurityPenalty.remark,
                    rules: [
                      {
                        transform:(transformeValue) =>{ return validateTrim(transformeValue); }
                      },
                      RegString500, {
                      required: false, message: RegString500.message,
                    }],
                  })(
                    <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.handlePunishmentSubmit}>
                提交
              </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;
      margin-bottom: 24px;
      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;
    }`;



