import React, { Component } from 'react';
import { connect } from 'dva';
import vd from 'validator';
import {
  Form,
  Input,
  Row,
  Col,
  Button,
  Steps,
  Icon,
  Table,
  Modal,
  Notification,
  Breadcrumb,
  message,
  Alert
} from 'antd';
import { Link } from 'dva/router';
import { gup } from '../../utils/utils';
import PMap from '../../components/Pro/PMap';
import bcx_utils from '../../common/bcx_utils';

import {
  taskAttendanceComAttendGroupInSecondStepAttendGroup, //进入内勤组设置-第二步页面
  taskAttendanceComAttendGroupSaveSecondStepAttendGroup //新增或者修改内勤组-第二步-设置考勤地址
} from '../../services/api';

import './ThiftManagement.less';

const FormItem = Form.Item;
const { Step } = Steps;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 7 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 10 }
  }
};

const submitFormLayout = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 10, offset: 7 }
  }
};

@connect(state => ({
  profile: state.profile
}))
@Form.create()
export default class Information extends Component {
  state = {
    point: [],
    address: '',
    visible: false, //添加地点
    attendGroupId: gup('attendGroupId') || '',
    midAttendGroupId: gup('midAttendGroupId') + '' || '',
    addressRange: '300',
    comAttendAddressJson: [],
    pagenav: {
      current: 1,
      pageSize: 10,
      showQuickJumper: true,
      showSizeChanger: true,
      showTotal: total => `总共 ${total} 条`,
      onShowSizeChange: (current, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.current = current;
        pagenav.pageSize = pageSize;
        this.setState({ pagenav });
        setTimeout(() => {
          this.bbdExampersonPage();
        });
      },
      onChange: (page, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.current = page;
        pagenav.pageSize = pageSize;
        this.setState({ pagenav });
        setTimeout(() => {
          this.bbdExampersonPage();
        });
      },
      total: 0
    }
  };

  componentDidMount() {
    this.taskAttendanceComAttendGroupInSecondStepAttendGroup();
  }

  taskAttendanceComAttendGroupSaveSecondStepAttendGroup = () => {
    const {
      midAttendGroupId,
      comAttendAddressJson,
      addressRange,
      attendGroupId
    } = this.state;
    taskAttendanceComAttendGroupSaveSecondStepAttendGroup({
      midAttendGroupId,
      attendGroupId,
      comAttendAddressJson: JSON.stringify(comAttendAddressJson),
      addressRange
    })
      .then(res => {
        this.props.history.push(
          `/attendancemanagement/newattendanceunit/settingupattendance?attendGroupId=${
            res.data.attendGroupId
          }&midAttendGroupId=${res.data.midAttendGroupId}`
        );
      })
      .catch(err =>
        console.log(err, '新增或者修改内勤组-第二步-设置考勤地址-err')
      );
  };

  taskAttendanceComAttendGroupInSecondStepAttendGroup = () => {
    taskAttendanceComAttendGroupInSecondStepAttendGroup({
      midAttendGroupId: this.state.midAttendGroupId,
      attendGroupId: this.state.attendGroupId
    })
      .then(res => {
        if (res.data) {
          const { addressRange, attendGroupId, midAttendGroupId } = res.data;
          let comAttendAddressJson = JSON.parse(res.data.comAttendAddressJson);
          comAttendAddressJson = comAttendAddressJson.map((val, i) => {
            const obj = { ...val };
            obj.key = i;
            return obj;
          });
          this.setState({
            attendGroupId,
            midAttendGroupId,
            addressRange: addressRange || 300,
            comAttendAddressJson
          });
        }
      })
      .catch(err => console.log(err, '进入内勤组设置-第二步页面-err'));
  };
  /* 考勤地点--drawer */
  columns = [
    {
      key: '1',
      title: '考勤地点',
      dataIndex: 'address',
      render: text => <span>{text}</span>
    },
    {
      width: 60,
      title: '操作',
      dataIndex: 'b',
      render: (rext, record) => (
        <span
          onClick={() => {
            const { comAttendAddressJson } = this.state;
            const newarr = comAttendAddressJson.filter(val => {
              return val.key !== record.key;
            });
            this.setState({ comAttendAddressJson: newarr });
          }}
          style={{ color: '#0F71FF' }}
        >
          删除
        </span>
      )
    }
  ];

  handleSubmit = e => {
    e.preventDefault();
    if (this.state.comAttendAddressJson.length === 0) {
      Notification.error({
        message: '请选择考勤地点'
      });
      return;
    }
    this.props.form.validateFieldsAndScroll(err => {
      if (!err) {
        this.taskAttendanceComAttendGroupSaveSecondStepAttendGroup();
      }
    });
  };

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="CreateTask ThiftManagement">
        <div
          className="card-breadcrumb"
          style={{
            borderBottom: '1px solid rgb(233, 233, 233)',
            marginRight: 25,
            paddingBottom: 10
          }}
        >
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/attendancemanagement/newattendanceunit">
                内勤组管理
              </Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>考勤方式</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <div className="Steps" style={{ marginTop: 15 }}>
          <Alert
            message={
              <div>
                内勤组考勤地点，支持多个考勤地点，可点击“添加地点”进行新增；内勤组创建后，可再次编辑考勤地点。
              </div>
            }
            type="warning"
            showIcon
            style={{ marginBottom: '15px' }}
          />
          <Steps current={1}>
            <Step title="选择考勤类型" />
            <Step title="考勤地点" />
            <Step title="设置考勤人员" />
            <Step title="完成" />
          </Steps>
        </div>
        <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
          <FormItem
            className="addressRange-className"
            {...formItemLayout}
            label="设置出勤地点"
            style={{ marginBottom: 5 }}
          >
            <Row span={24}>
              <Row>
                <Col span={10}>
                  <Button
                    type="primary"
                    ghost
                    onClick={() => {
                      this.setState({ visible: true });
                    }}
                  >
                    添加地点
                  </Button>
                  <span className="exclamation">
                    <Icon type="exclamation-circle" />
                    可设置多个考勤地点
                  </span>
                </Col>
                <Col style={{ textAlign: 'right' }} span={4}>
                  有效范围：
                </Col>
                <Col span={10}>
                  {getFieldDecorator('addressRange', {
                    initialValue: this.state.addressRange,
                    rules: [
                      { required: true, message: '请输入' },
                      {
                        validator: (rule, value, cb) => {
                          if (
                            !vd.isNumeric(value + '') ||
                            value <= 0 ||
                            (value + '').length > 10
                          ) {
                            cb('只能是正整数最长10位');
                          }

                          // Note: 必须总是返回一个 callback，否则 validateFieldsAndScroll 无法响应
                          cb();
                        }
                      }
                    ]
                  })(
                    <Input
                      onChange={e => {
                        this.setState({ addressRange: e.target.value });
                      }}
                      addonAfter="米"
                      placeholder="请输入"
                    />
                  )}
                </Col>
              </Row>
            </Row>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label=" "
            colon={false}
            className="small-tips"
            style={{ marginBottom: 0 }}
          >
            <Alert
              message={
                <div>
                  提示：有效范围请勿设置过小，手机定位会受信号等因素影响偏移，造成无法打卡。
                </div>
              }
              type="warning"
              showIcon
            />
          </FormItem>
          <FormItem {...submitFormLayout} style={{ marginTop: 12 }}>
            <Table
              style={{ marginTop: 16 }}
              size="middle"
              pagination={false}
              columns={this.columns}
              dataSource={this.state.comAttendAddressJson}
            />
          </FormItem>

          <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
            <Button
              onClick={() => {
                this.props.history.replace(
                  `/attendancemanagement/newattendanceunit/selectionattendancetype?attendGroupId=${
                    this.state.attendGroupId
                  }&midAttendGroupId=${this.state.midAttendGroupId}`
                );
              }}
              loading={submitting}
            >
              返回
            </Button>
            <Button type="primary" style={{ marginLeft: 8 }} htmlType="submit">
              确认并进行下一步
            </Button>
          </FormItem>
        </Form>

        <Modal
          title="添加地点"
          visible={this.state.visible}
          okText="提交"
          cancelText="关闭"
          onOk={() => {
            let { comAttendAddressJson } = this.state;
            const { point, address } = this.state;
            if (address === '' || point.length === 0) {
              bcx_utils.preventRepeatAsync(callback =>
                callback(resolve => {
                  message.warning(
                    '请填写详细的考勤地点信息，点击查询，并在地图上选择准确的地点',
                    1.5,
                    () => {
                      window.setTimeout(() => {
                        resolve();
                      }, 500);
                    }
                  );
                })
              );
              return;
            }
            comAttendAddressJson.push({
              address,
              addressLongitude: point[0],
              addressLatitude: point[1]
            });
            comAttendAddressJson = comAttendAddressJson.map((val, i) => {
              val.key = i;
              return val;
            });
            this.setState({ comAttendAddressJson });
            this.setState({ visible: false });
          }}
          onCancel={() => {
            this.setState({ visible: false });
          }}
          width={700}
        >
          {
            <PMap
              areaChange={(point, address) => {
                console.log(point, address, 'point,address');
                this.setState({ point, address });
              }}
              ifProvince={false}
              taskCityName="" //添加当前任务城市名称，9-29,公用组件，暂时传空解决冲突
            />
          }
        </Modal>
      </div>
    );
  }
}
