import React, { PureComponent } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import style from 'styled-components';
import {
  Input,
  Button,
  message,
  DatePicker,
  Checkbox,
  Modal,
  Form,
  Drawer
} from 'antd';
import { RegString500, RegString50 } from '../../../constants/regexps';
// import Drawer from "react-motion-drawer";
import PTable from '../../../components/Pro/PTable';
import EditPunishment from './EditPunishment';
import {
  addComSecurityPenalty,
  deleteComSecurityPenaltyById,
  getTreeperBydepart
} 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 { confirm } = Modal;
const { RangePicker } = DatePicker;
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 Punishment extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      visible: false,
      open: false, //窗口
      openEdit: false, //修改
      penaltyId: 0,
      forceUpdate: false,
      showPerId: 0,
      perIdString: [],
      // treeData: [
      //   //树
      //   { title: '', key: '' }
      // ],
      pageParm: {
        keyWords: '',
        startDate: '',
        endDate: '',
        pageSize: '10',
        pageNumber: '1'
      },
      keyWords: '',
      startDate: '',
      endDate: ''
    };
  }

  componentDidMount() {
    // getTreeperBydepart({}).then(
    //   response => {
    //     console.log(response, 'getTreeperBydepart-response');
    //     response.data = this.checkMember(response.data);
    //     this.setState({ treeData: response.data });
    //   },
    //   err => {
    //     console.log(err, 'getTreeperBydepart-err');
    //   }
    // );
  }
  // 遍历部门人员数据
  checkMember(data) {
    data = data.map(item => {
      if (item.children && item.children.length) {
        let needDisable = true;
        const temp = subItem => {
          subItem.filter(tempItem => {
            if (tempItem.children && tempItem.children.length) {
              temp(tempItem.children);
              return tempItem;
            } else {
              if (tempItem.treeType === '2') {
                needDisable = false;
              }
              return tempItem;
            }
          });
        };
        temp(item.children);
        needDisable ? (item.disableCheckbox = true) : null;
        this.checkMember(item.children);
        return item;
      } else {
        if (item.treeType !== '2') {
          item.disableCheckbox = true;
          item.disabled = true;
          item.isLeaf = true;
        }
        return item;
      }
    });

    return data;
  }

  //修改
  editDrawer = penaltyId => {
    this.setState({ penaltyId });
    this.setState({ openEdit: true });
  };

  //增加
  addDrawer = () => {
    this.setState({ open: true });
  };
  hideModal = () => {
    this.setState({
      visible: true
    });
    const values = this.props.form.getFieldsValue();
    if (
      values.penaltyContent ||
      values.penaltyDate ||
      values.penaltyReason ||
      values.penaltyType ||
      values.penaltyUnit ||
      values.remark !== '' ||
      this.state.perIdString.length !== 0
    ) {
      console.log(values);
      this.setState({
        visible: true
      });
    } else {
      this.handleModalOk();
    }
  };

  handleModalOk = e => {
    console.log(e);
    this.setState({
      visible: false,
      open: false,
      perIdString: []
    });
  };

  handleModalCancel = e => {
    console.log(e);
    this.setState({
      visible: false
    });
  };

  //输入框的书写
  inputSerchPunishmentChange = e => {
    console.log(e.target.value.trim());
    this.setState({ keyWords: e.target.value.trim() });
    // //正则用//包起来
    // const regex = /^[\u4e00-\u9fa5]{1,20}$/;
    //   if (e.target.value.trim()) {
    //     //react使用正则表达式变量的test方法进行校验，直接使用value.match(regex)显示match未定义
    //     if (regex.test(e.target.value.trim())) {
    //     this.setState({ keyWords: e.target.value.trim() });
    //       return;
    //     } else {
    //       // callback('请输汉字最大20位！');
    //     }
    //   } else {
    //     //这里的callback函数会报错
    //   }
  };

  //报表类型 change
  pSelectChange = (value, type) => {
    this.setState({ [type]: value });
  };

  //刷新方法
  tableUpdate = () => {
    this.setState({ forceUpdate: true }, () => {
      this.setState({ forceUpdate: false });
    });
  };

  //点击搜索
  search = () => {
    const pageParm = { ...this.state.pageParm };
    const { keyWords, startDate, endDate } = this.state;
    pageParm.keyWords = keyWords;
    pageParm.startDate = startDate;
    pageParm.endDate = endDate;
    this.setState({ pageParm });
  };
  //时间选择
  onChangeTime = (date, dateString) => {
    this.setState({
      startDate: dateString[0],
      endDate: dateString[1]
    });
  };

  showDeleteConfirm = penaltyId => {
    console.log(penaltyId);
    const that = this;
    confirm({
      title: '是否删除所选信息，删除后无法找回。是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        console.log('ok');
        that.orderDelete(penaltyId);
      },
      onCancel() {
        console.log('Cancel');
      }
    });
  };

  //删除
  orderDelete = penaltyId => {
    deleteComSecurityPenaltyById({ penaltyId }).then(
      response => {
        message.success(response.msg);
        this.tableUpdate();
      },
      err => {
        console.log(err);
      }
    );
  };
  //表单提交
  handlePunishmentSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      console.log('表单提交......', values);
      values.perIdString = [ values.perIdString ];
      Reflect.deleteProperty(values, 'perName');
      values.perIdString.length === 0 && this.setState({ showPerId: 1 });

      if (!err && values.perIdString) {
        const rangeValue = values['penaltyDate'];
        values.penaltyDate = rangeValue.format('YYYY-MM-DD');
        const { isCrime } = values;
        if (isCrime) {
          values.isCrime = '1';
        } else {
          values.isCrime = '0';
        }
        addComSecurityPenalty(values).then(
          data => {
            console.log(data);
            // this.setState({ forceUpdate: true });
            this.setState({ open: false });
            this.setState({ perIdString: [] });
            this.tableUpdate();
            const { setFieldsValue } = this.props.form;
            setFieldsValue({
              penaltyDate: '',
              penaltyType: '',
              penaltyUnit: '',
              isCrime: false,
              penaltyContent: '',
              penaltyReason: '',
              remark: ''
            });
          },
          err1 => {
            console.log(err1);
          }
        );
      }
    });
  };

  //关键字输入框设置长度
  check = (rule, value, callback) => {
    // debugger;
    //与表单数据进行关联
    // const form = this.props.form;
    //正则用//包起来
    const regex = /^[\u4e00-\u9fa5]{1,20}$/;
    if (value) {
      //react使用正则表达式变量的test方法进行校验，直接使用value.match(regex)显示match未定义
      if (regex.test(value)) {
        callback();
      } else {
        callback('请输汉字最大20位！');
      }
    } else {
      //这里的callback函数会报错
    }
  };

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

  //表格渲染
  renderTable = () => {
    const columns = [
      {
        title: '处罚日期',
        dataIndex: 'penaltyDate',
        key: 'penaltyDate',
        // fixed: 'left',
        render: (text, record) => (
          <div>
            <p
              style={{
                maxWidth: 150,
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                marginTop: '8px',
                marginBottom: '8px'
              }}
            >
              {record.penaltyDate}
            </p>
          </div>
        )
      },
      {
        title: '处罚单位',
        dataIndex: 'penaltyUnit',
        key: 'penaltyUnit',
        render: (text, record) => (
          <div>
            <p
              style={{
                maxWidth: 150,
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                marginTop: '8px',
                marginBottom: '8px'
              }}
            >
              {record.penaltyUnit}
            </p>
          </div>
        )
      },
      {
        title: '处罚内容',
        dataIndex: 'penaltyContent',
        key: 'penaltyContent',
        render: (text, record) => (
          <div>
            <p
              style={{
                maxWidth: 350,
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                marginTop: '8px',
                marginBottom: '8px'
              }}
            >
              {record.penaltyContent}
            </p>
          </div>
        )
      },
      {
        title: '处罚原因',
        dataIndex: 'penaltyReason',
        key: 'penaltyReason',
        render: (text, record) => (
          <div>
            <p
              style={{
                maxWidth: 350,
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                marginTop: '8px',
                marginBottom: '8px'
              }}
            >
              {record.penaltyReason}
            </p>
          </div>
        )
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (text, record) => (
          //render: () => (
          <div>
            <Opton
              onClick={this.editDrawer.bind(this, record.penaltyId)}
              style={{ color: '#0F71FF', fontSize: '14px' }}
            >
              详情
            </Opton>
            <Opton
              onClick={this.showDeleteConfirm.bind(this, record.penaltyId)}
              style={{ color: '#0F71FF', fontSize: '14px' }}
            >
              删除
            </Opton>
            <p
              style={{
                maxWidth: 90,
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                overflow: 'hidden'
              }}
            >
              {record.action}
            </p>
          </div>
        )
      }
    ];
    return (
      <PTable
        style={{ marginTop: 20 }}
        columns={columns}
        url="listComSecurityPenalty"
        pageParm={this.state.pageParm}
        forceUpdate={this.state.forceUpdate}
      // scroll={{ x: 1000 }}
      />
    );
  };

  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>
        {/* 搜索条件面板 */}
        <div className="searchpanel">
          <Form
            className="Wrapper-form"
            layout="inline"
            onSubmit={this.handleSubmit}
          >
            <FormItem
              {...formItemLayout}
              label="关键字："
              colon={false}
              style={{ marginTop: 0 }}
            >
              <Input
                style={{ width: 214 }}
                onChange={this.inputSerchPunishmentChange}
                placeholder="搜索处罚内容、原因、单位"
                maxLength={20}
              />
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="处罚日期:"
              colon={false}
              className="post"
            >
              {/* <RangePicker
                style={{ width: 214 }}
                format={dateFormat}
                onChange={this.onChangeTime}
              /> */}
              <RangePicker
                style={{
                  width: 214
                }}
                showTime={{
                  format: 'HH:mm'
                }}
                format={dateFormat}
                onChange={this.onChangeTime}
              />
            </FormItem>
            <FormItem
              {...formItemLayout}
              label=""
              colon={false}
              style={{ marginTop: 0 }}
            >
              <Button
                type="primary"
                style={{ marginLeft: 17 }}
                onClick={this.search}
              >
                搜索
              </Button>
            </FormItem>
            <br />
            <FormItem {...formItemLayout} label="" colon={false}>
              <div className="btns">
                <Button type="primary" onClick={this.addDrawer}>
                  新增处罚
                </Button>
              </div>
            </FormItem>
          </Form>
        </div>
        {this.renderTable()}
        <Modal
          title="删除的处罚信息不可恢复"
          visible={this.state.visible}
          onOk={this.handleModalOk}
          onCancel={this.handleModalCancel}
        >
          <p>确认删除“处罚信息”？</p>
        </Modal>

        {/*新增处罚*/}
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          placement="right"
          title="新增处罚"
          visible={this.state.open}
          width={600}
          zIndex={11}
          onChange={open => {
            this.setState({ open });
          }}
          // onClose={()=>{
          //   this.setState({
          //     open:false,
          //     perIdString: []
          //   });
          // }}
          onClose={this.hideModal}
          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(
                    'penaltyDate',
                    {
                      rules: [
                        {
                          required: true,
                          message: '请选择处罚日期'
                        }
                      ]
                    },
                    config
                  )(
                    <DatePicker
                      style={{ width: 294 }}
                      disabledDate={this.disabledStartDate}
                      format="YYYY-MM-DD"
                    />)}
                </FormItem>
                <FormItem {...formItemLayout} label="处罚类型">
                  {getFieldDecorator('penaltyType', {
                    rules: [
                      {
                        required: true,
                        message: '请选择处罚类型'
                      }
                    ]
                  })(
                    <PSelect
                      type="penaltyType"
                      onChange={this.pSelectChange}
                      style={{ width: 294 }}
                    />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="做出处罚单位">
                  {getFieldDecorator('penaltyUnit', {
                    rules: [
                      {
                        transform: transformeValue => {
                          return validateTrim(transformeValue);
                        }
                      },
                      RegString50,
                      {
                        required: true,
                        message: RegString50.message
                      }
                    ]
                  })(
                    <TextArea
                      style={{ width: 294 }}
                      maxLength={50}
                      rows={2}
                      placeholder="请输入"
                    />
                  )}
                </FormItem>

                <FormItem {...formItemLayout} label="追究刑事责任">
                  <div style={{ width: 294 }}>
                    {getFieldDecorator('isCrime', {
                      valuePropName: 'checked',
                      initialValue: false,
                      rules: [
                        {
                          required: false,
                          message: '请填写是否追究刑事责任'
                        }
                      ]
                    })(<Checkbox style={{ width: 294 }} />)}
                  </div>
                </FormItem>

                <FormItem {...formItemLayout} label="处罚内容">
                  {getFieldDecorator('penaltyContent', {
                    rules: [
                      {
                        transform: transformeValue => {
                          return validateTrim(transformeValue);
                        }
                      },
                      RegString500,
                      {
                        required: true,
                        message: RegString500.message
                      }
                    ]
                  })(
                    <TextArea
                      style={{ width: 294 }}
                      maxLength={500}
                      rows={4}
                      placeholder="请输入"
                    />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="处罚原因">
                  {getFieldDecorator('penaltyReason', {
                    rules: [
                      {
                        transform: transformeValue => {
                          return validateTrim(transformeValue);
                        }
                      },
                      RegString500,
                      {
                        required: true,
                        message: RegString500.message
                      }
                    ]
                  })(
                    <TextArea
                      style={{ width: 294 }}
                      maxLength={500}
                      rows={4}
                      placeholder="请输入"
                    />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="备注">
                  {getFieldDecorator('remark', {
                    initialValue: '',
                    rules: [
                      {
                        transform: transformeValue => {
                          return validateTrim(transformeValue);
                        }
                      },
                      RegString500,
                      {
                        required: false,
                        message: RegString500.message
                      }
                    ]
                  })(
                    <TextArea
                      maxLength={500}
                      style={{ width: 294 }}
                      rows={4}
                      placeholder="请输入"
                    />
                  )}
                </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>
        {/* {(this.state.open || this.state.openEdit) && (
          <PZhezhao top={"2px"}/>
        )} */}
        <EditPunishment
          onChange={openEdit => {
            this.setState({ openEdit });
          }}
          visible={this.state.openEdit}
          penaltyId={this.state.penaltyId}
          tableUpdate={this.tableUpdate}
          // treeData={this.state.treeData}
        />
      </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 Opton = style.span`{
  font-size: 12px;
  color: #0F71FF;
  cursor:pointer;
  margin-right:8px;
}`;
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;
}`;
