import React, { PureComponent } from 'react';
import moment from 'moment';
import "moment/locale/zh-cn";
import { connect } from 'dva';
import style from 'styled-components';
import {
  Input,
  Button,
  DatePicker,
  Modal,
  Form,
  TreeSelect,
  message,
  Drawer,
  Select
} from 'antd';
// import Drawer from 'react-motion-drawer';
import PTable from '../../../components/Pro/PTable';
import EditGoodDeeds from './EditGoodDeeds';
import {
  deletePerGoodDeedsById,
  addPerGoodDeeds,
  getTreeperBydepart,
  publicCommonDictGetDictByCodeTypes
} from '../../../services/api';
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 { 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 GoodDeeds extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      visible: false,
      forceUpdate: false,
      goodDeedsId: 0,
      open: false, //添加窗口
      openEdit: false, //修改
      showPerId: 0,
      perId: '',
      // treeData: [
      //   //树
      //   { title: '', key: '' }
      // ],
      goodDeedsTypes: [],  //好人好事类型
      idCardValue: '',//选中的时候，对应的身份证号
      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');
    //   }
    // );
    this.__getGoodDeedTypes();
  }
  __getGoodDeedTypes() {
    publicCommonDictGetDictByCodeTypes({ codeTypes: 'goodDeedsType' }).then(res => {
      this.setState({
        goodDeedsTypes: res.data.goodDeedsType
      });
    });
  }
  // 遍历部门人员数据
  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 = goodDeedsId => {
    this.setState({ goodDeedsId });
    this.setState({ openEdit: true });
  };

  //增加
  addDrawer = () => {
    this.setState({ open: true });
  };

  //输入框的书写
  inputSerchGoodDeedsChange = e => {
    console.log(e.target.value.trim());
    this.setState({ keyWords: e.target.value.trim() });
  };

  //报表类型 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]
    });
  };
  //表格渲染
  renderTable = () => {
    const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        width: 120,
        render: (text, record) => (
          <div>
            <p
              style={{
                width: 120,
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                marginTop: '8px',
                marginBottom: '8px'
              }}
            >
              {record.name}
            </p>
          </div>
        )
      },
      {
        title: '身份证号',
        dataIndex: 'idCardNo',
        key: 'idCardNo',
        width: 200,
        render: (text, record) => (
          <div>
            <p
              style={{
                width: 200,
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                marginTop: '8px',
                marginBottom: '8px'
              }}
            >
              {record.idCardNo}
            </p>
          </div>
        )
      },
      {
        title: '日期',
        dataIndex: 'happenDate',
        key: 'happenDate',
        width: 140,
        render: (text, record) => (
          <div>
            <p
              style={{
                width: 140,
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                marginTop: '8px',
                marginBottom: '8px'
              }}
            >
              {record.happenDate}
            </p>
          </div>
        )
      },
      {
        title: '内容',
        dataIndex: 'goodContent',
        key: 'goodContent',
        width: 320,
        render: (text, record) => (
          <div>
            <p
              style={{
                width: 320,
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                marginTop: '8px',
                marginBottom: '8px'
              }}
            >
              {record.goodContent}
            </p>
          </div>
        )
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        width: 90,
        render: (text, record) => (
          <div>
            <Opton
              onClick={this.editDrawer.bind(this, record.goodDeedsId)}
              style={{ color: '#0F71FF', fontSize: '14px' }}
            >
              详情
            </Opton>
            <Opton
              className="delete"
              onClick={this.showDeleteConfirm.bind(this, record.goodDeedsId)}
              style={{ color: '#0F71FF', fontSize: '14px' }}
              s
            >
              删除
            </Opton>
            <p
              style={{
                width: 90,
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                marginTop: '8px',
                marginBottom: '8px'
              }}
            >
              {record.action}
            </p>
          </div>
        )
      }
    ];
    return (
      <PTable
        style={{ marginTop: 20 }}
        columns={columns}
        url="listPerGoodDeeds"
        pageParm={this.state.pageParm}
        forceUpdate={this.state.forceUpdate}
      />
    );
  };

  hideModal = () => {
    // this.setState({
    //   visible: true
    // });
    const values = this.props.form.getFieldsValue();
    console.log(values);
    if (values.goodContent || values.happenDate || values.idCardNo || values.remark !== '' || this.state.perId.length !== 0) {
      this.setState({
        visible: true,
      });
    } else {
      this.handleModalOk();
    }
  };

  handleModalOk = e => {
    console.log(e);
    this.setState({
      visible: false,
      open: false,
      perId: '',
      idCardValue: '',
    });
  };

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

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

  //删除
  orderDelete = goodDeedsId => {
    deletePerGoodDeedsById({ goodDeedsId }).then(
      (response) => {
        message.success(response.msg);
        this.tableUpdate();
      },
      err => {
        console.log(err);
      }
    );
  };
  //树形选择器改编
  handleTreeSelectChange = (value, label, extra) => {
    console.log(value);
    console.log(label);
    console.log(extra.triggerNode.props.idCardNo);

    this.setState({
      showPerId: 0,
      idCardValue: extra.triggerNode.props.idCardNo,
    });
    const lastValue = this.state.perId;
    if (
      extra.triggerNode &&
      extra.triggerNode.props &&
      extra.triggerNode.props.treeType === '1'
    ) {
      console.log('部门');
      this.setState({ perId: lastValue });
    } else {
      this.setState({ perId: value });
    }
  };

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

  //表单提交
  handleAddGoodDeedsSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        Reflect.deleteProperty(values, 'perName');
        const rangeValue = values['happenDate'];
        values.happenDate = rangeValue.format('YYYY-MM-DD');
        addPerGoodDeeds(values).then(
          data => {
            // this.setState({ forceUpdate: true });
            this.setState({ open: false });
            this.setState({ perId: '' });
            this.tableUpdate();
            const { setFieldsValue } = this.props.form;
            setFieldsValue({
              idCardNo: '',
              happenDate: '',
              goodContent: '',
              remark: ''
            });
            this.setState({
              idCardValue: '',
            });
          },
          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>
        {/* 搜索条件面板 */}
        <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.inputSerchGoodDeedsChange}
                placeholder="请输入姓名、身份证号"
                maxLength={20}
              />
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="发生日期:"
              colon={false}
              className="post"
            >
              <RangePicker
                style={{ width: 214 }}
                showTime={{ format: 'HH:mm' }}
                format={dateFormat}
                onChange={this.onChangeTime}
              />
            </FormItem>
            <FormItem {...formItemLayout} label="" colon={false}>
              <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"
          visible={this.state.open}
          title="好人好事详情"
          width={600}
          zIndex={11}
          onChange={open => {
            this.setState({ open });
          }}
          // onClose={()=>{
          //   this.setState({
          //     open:false,
          //     perId: '',
          //     idCardValue: '',
          //   });
          // }}
          onClose={this.hideModal}
          destroyOnClose
        >
          <div>
            {/* <div className="drawer-header"></div> */}
            <div>
              <Form
                style={{ marginTop: 24 }}
                onSubmit={this.handleAddGoodDeedsSubmit}
              >
                <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.state.goodDeedsTypes.map(val => (
                          <Option value={val.codeValue + ''} key={val.codeValue}>
                            {val.label}
                          </Option>
                        ))
                      }
                    </Select>
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="身份证号: ">
                  {getFieldDecorator('idCardNo', {
                    initialValue: this.state.idCardValue,
                    rules: [
                      {
                        transform: (transformeValue) => { return validateTrim(transformeValue); }
                      },
                      {
                        required: true, message: '请输入身份证号',
                      }
                    ]
                  })(<Input style={{ width: 294 }} />)}
                </FormItem>
                <FormItem {...formItemLayout} label="发生日期">
                  {getFieldDecorator(
                    'happenDate',
                    {
                      rules: [
                        {
                          required: true,
                          message: '请选择发生日期'
                        }
                      ]
                    },
                    config
                  )(
                    <DatePicker
                      style={{ width: 294 }}
                      disabledDate={this.disabledStartDate}
                      format="YYYY-MM-DD"
                    />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="好人好事内容">
                  {getFieldDecorator('goodContent', {
                    rules: [
                      {
                        transform: (transformeValue) => { return validateTrim(transformeValue); }
                      },
                      {
                        required: true,
                        message: '请填写好人好事内容'
                      }
                    ]
                  })(
                    <TextArea
                      style={{ width: 294 }}
                      maxLength={500}
                      rows={4}
                      placeholder="请输入"
                    />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="备注">
                  {getFieldDecorator('remark', {
                    initialValue: '',
                    rules: [
                      {
                        transform: (transformeValue) => { return validateTrim(transformeValue); }
                      },
                      {
                        required: false
                      }
                    ]
                  })(
                    <TextArea
                      style={{ width: 294 }}
                      maxLength={500}
                      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.handleAddGoodDeedsSubmit}>
                提交
              </Button>
            </div>
          </div>
        </Drawer>
        <Modal
          title="提示"
          visible={this.state.visible}
          onOk={this.handleModalOk}
          onCancel={this.handleModalCancel}
        >
          <p>当前信息未保存，是否确认返回？</p>
        </Modal>
        <EditGoodDeeds
          onChange={openEdit => {
            this.setState({ openEdit });
          }}
          goodDeedsTypes={this.state.goodDeedsTypes}
          visible={this.state.openEdit}
          goodDeedsId={this.state.goodDeedsId}
          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-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;
}`;
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;
}`;
