/*
*    黄家金  原本文件
**/
import React, {Component} from "react";
import {connect} from "dva";
import moment from "moment";
import {
  Form,
  Input,
  Select,
  Timeline,
  Row,
  Col,
  Button,
  Radio,
  Steps,
  Checkbox,
  Icon,
  Table,
  InputNumber,
  TimePicker,
  Modal
} from "antd";
import Drawer from "react-motion-drawer";
import AddNewShift from "../AddNewShift";
import {enterpriseCompanyComBaseInfoGetComBaseInfoById} from "../../../services/api";

import "../Task.less";

const FormItem = Form.Item;
const {Option} = Select;
const {Step} = Steps;
const format = "HH:mm";

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

const formItemLayout1 = {
  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}
  }
};

const formItemLayout3 = {
  labelCol: {
    xs: {span: 24},
    sm: {span: 14}
  },
  wrapperCol: {
    xs: {span: 24},
    sm: {span: 8},
    md: {span: 8}
  }
};
const formItemLayout4 = {
  labelCol: {
    xs: {span: 24},
    sm: {span: 4}
  },
  wrapperCol: {
    xs: {span: 24},
    sm: {span: 6},
    md: {span: 6}
  }
};

const formItemLayout2 = {
  labelCol: {
    xs: {span: 24},
    sm: {span: 3}
  },
  wrapperCol: {
    xs: {span: 24},
    sm: {span: 21},
    md: {span: 21}
  }
};

/*
固定班制---设置出勤班次 */
const columns1 = [
  {
    title: "工作日",
    dataIndex: "workday",
    key: "2"
  },
  {
    title: "班次详情",
    dataIndex: "detail",
    key: "3"
  },
  {
    title: "操作",
    dataIndex: "option",
    key: "4",
    render: text => {
      return <div style={{color: "rgba(15,113,255,1)"}}>{text}</div>;
    }
  }
];
const dataSource1 = [
  {
    key: "1",
    workday: "周一",
    detail: "休息",
    option: "选择班次"
  },
  {
    key: "2",
    workday: "周二",
    detail: "休息",
    option: "选择班次"
  },
  {
    key: "3",
    workday: "周三",
    detail: "休息",
    option: "选择班次"
  },
  {
    key: "4",
    workday: "周四",
    detail: "休息",
    option: "选择班次"
  },
  {
    key: "5",
    workday: "周五",
    detail: "休息",
    option: "选择班次"
  },
  {
    key: "6",
    workday: "周六",
    detail: "休息",
    option: "选择班次"
  },
  {
    key: "7",
    workday: "周日",
    detail: "休息",
    option: "选择班次"
  }
];

/* 排班制----设置出勤班次 */
const columns2 = [
  {
    title: "列号",
    dataIndex: "list",
    key: "1"
  },
  {
    title: "班次名称",
    dataIndex: "banci",
    key: "2"
  },
  {
    title: "时间安排",
    dataIndex: "time",
    key: "3",
    render: text => {
      return <div style={{color: "rgba(15,113,255,1)"}}>{text}</div>;
    }
  }
];
const dataSource2 = [
  {
    key: "1",
    banci: "班次A",
    time: "09:00-12:00"
  },
  {
    key: "2",
    banci: "一天3班3个次日班",
    time: "09:00-11:00 | 12:00 -14:00 | 15:00-18:00"
  }
];

/* 排班制----周期性排班设置 */
const columns3 = [
  {
    title: "周期名称",
    dataIndex: "list",
    key: "1"
  },
  {
    title: "周期天数",
    dataIndex: "banci",
    key: "2"
  },
  {
    title: "启用班次",
    dataIndex: "time",
    key: "3",
    render: text => {
      return <div style={{color: "rgba(15,113,255,1)"}}>{text}</div>;
    }
  },
  {
    title: "操作",
    dataIndex: "time",
    key: "4",
    render: text => {
      return <div style={{color: "rgba(15,113,255,1)"}}>{text}</div>;
    }
  }
];
const dataSource3 = [
  {
    key: "1",
    list: "1",
    banci: "班次A",
    time: "09:00-12:00"
  },
  {
    key: "2",
    list: "2",
    banci: "一天3班3个次日班",
    time: "09:00-11:00 | 12:00 -14:00 | 15:00-18:00"
  }
];

/* 选择班次--drawer */
const columns4 = [
  {
    title: "班次名称",
    dataIndex: "bc",
    render: text => <a href="#">{text}</a>
  },
  {
    title: "出勤时间",
    dataIndex: "time"
  }
];
const dataSource4 = [
  {
    key: "1",
    bc: "John Brown",
    time: 32
  }
];

/* 考勤地点--drawer */
const columns5 = [
  {
    key: "1",
    title: "考勤地点",
    dataIndex: "a",
    render: text => <span>{text}</span>
  },
  {
    width: 60,
    title: "操作",
    dataIndex: "b",
    render: () => <span style={{color: "#0F71FF"}}>删除</span>
  }
];
const dataSource5 = [
  {
    key: "1",
    a: "01.软件园3期城毅大街2342号",
    b: 32
  }
];

/* 添加wifi--drawer */
const columns6 = [
  {
    key: "1",
    title: "考勤地点",
    dataIndex: "a",
    render: text => <span>{text}</span>
  },
  {
    width: 60,
    title: "操作",
    dataIndex: "b",
    render: () => <span style={{color: "#0F71FF"}}>删除</span>
  }
];
const dataSource6 = [
  {
    key: "1",
    a: "01.00-01-6c-06-0a-60-29",
    b: 32
  }
];

const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(
      `selectedRowKeys: ${selectedRowKeys}`,
      "selectedRows: ",
      selectedRows
    );
  },
  getCheckboxProps: record => ({
    disabled: record.name === "Disabled User" // Column configuration not to be checked
  })
};

const rowSelectionRadio = {
  type: "radio",
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(
      `selectedRowKeys: ${selectedRowKeys}`,
      "selectedRows: ",
      selectedRows
    );
  },
  getCheckboxProps: record => ({
    disabled: record.name === "Disabled User" // Column configuration not to be checked
  })
};

const CustomizedForm = Form.create({
  onFieldsChange(props, changedFields) {
    props.onChange(changedFields);
  },
  mapPropsToFields(props) {
    return {
      username: Form.createFormField({
        ...props.username,
        value: props.username.value
      })
    };
  },
  onValuesChange(_, values) {
    console.log(values);
  }
})(props => {
  const {getFieldDecorator} = props.form;
  return (
    <Form layout="inline">
      <FormItem label="Username">
        {getFieldDecorator("username", {
          rules: [{required: true, message: "Username is required!"}]
        })(<Input/>)}
      </FormItem>
    </Form>
  );
});

@connect(state => ({
  profile: state.profile
}))
@Form.create()
export default class Information extends Component {
  state = {
    open: false, //固定--添加班次
    open1: false, //排班次--添加班次
    open2: false, //添加排班周期
    open3: false, //新增班次
    visible: false, //添加地点
    address: "",
    attendType: "2",
    selectedTags: [],
    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() {
    // window.initialize = this.initializeMap;
    this.loadMapScript();
    enterpriseCompanyComBaseInfoGetComBaseInfoById({comId: "0"}).then(data => {
      console.log(data, "componentDidMount");
    });
  }

  initializeMap = () => {
    const that = this;
    const {BMap} = window;
    const map = new BMap.Map("taskMapContainer");
    map.centerAndZoom(new BMap.Point(116.404, 39.915), 12);
    map.addControl(new BMap.NavigationControl());
    const ac = new BMap.Autocomplete({
      input: "suggestId",
      location: map
    });

    function myFun(result) {
      const cityName = result.name;
      map.setCenter(cityName);
    }

    const myCity = new BMap.LocalCity();
    myCity.get(myFun);

    ac.addEventListener("onhighlight", function a(e) {
      //鼠标放在下拉列表上的事件
      console.log(e);
    });

    let myValue;
    ac.addEventListener("onconfirm", function a(e) {
      //鼠标点击下拉列表后的事件
      const value1 = e.item.value;
      myValue =
        value1.province +
        value1.city +
        value1.district +
        value1.street +
        value1.business;
      console.log(myValue, "myValue");
      setPlace();
    });

    function setPlace() {
      map.clearOverlays(); //清除地图上所有覆盖物
      function myFun1() {
        const pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
        map.centerAndZoom(pp, 18);
        map.addOverlay(new BMap.Marker(pp)); //添加标注
      }

      const local = new BMap.LocalSearch(map, {
        //智能搜索
        onSearchComplete: myFun1,
        renderOptions: {map}
      });
      that.setState({address: myValue});
      local.search(myValue);
    }
  };

  loadMapScript = () => {
    const script = document.createElement("script");
    script.src =
      "http://api.map.baidu.com/api?v=2.0&ak=B3RiZN5ZwDWnFLlzYUlY0G9ety0jiqHr&callback=initialize";
    document.body.appendChild(script);
  };
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.props.dispatch({
          type: "form/submitRegularForm",
          payload: values
        });
      }
    });
  };
  callback = key => {
    console.log(key);
  };

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

  handleChange(tag, checked) {
    const {selectedTags} = this.state;
    const nextSelectedTags = checked
      ? [...selectedTags, tag]
      : selectedTags.filter(t => t !== tag);
    console.log("You are interested in: ", nextSelectedTags);
    this.setState({selectedTags: nextSelectedTags});
  }

  /* 验证手机号码 */
  checkPhone = (rule, value, callback) => {
    if (
      value &&
      !/^1[0-9]{10}$/.test(value)
    ) {
      callback("请输入正确的手机号码！");
    } else {
      callback();
    }
  };

  /* 固定上班次 */
  fixedShiftRender = () => {
    const {getFieldDecorator} = this.props.form;
    return (
      <FormItem {...formItemLayout} label="设置出勤班次">
        {getFieldDecorator("comTaskFixedDtoList", {
          rules: [
            {
              required: true,
              message: "请选择"
            }
          ]
        })(
          <div>
            <Button
              onClick={() => {
                this.setState({open: true});
              }}
              style={{marginBottom: 16}}
              type="primary"
              ghost
            >
              选择默认班次
            </Button>
            <Table
              size="middle"
              pagination={false}
              columns={columns1}
              dataSource={dataSource1}
            />
          </div>
        )}
      </FormItem>
    );
  };

  /* 排班制--出勤班次 */
  scheduleRender = () => {
    const {getFieldDecorator} = this.props.form;

    return (
      <FormItem {...formItemLayout} label="设置出勤班次">
        {getFieldDecorator("shiftIdList", {
          rules: [
            {
              required: true,
              message: "请选择"
            }
          ]
        })(
          <div>
            <Button
              onClick={() => {
                this.setState({open1: true});
              }}
              style={{marginBottom: 16}}
              type="primary"
              ghost
            >
              添加班次
            </Button>
            <Table
              size="middle"
              pagination={false}
              columns={columns2}
              dataSource={dataSource2}
            />
          </div>
        )}
      </FormItem>
    );
  };

  /* 排班制--周期性排班 */
  periodicityRender = () => {
    const {getFieldDecorator} = this.props.form;
    return (
      <FormItem {...formItemLayout} label="周期性排班设置">
        {getFieldDecorator("taskSchedulCycleDtoList", {
          rules: [
            {
              required: true,
              message: "请选择"
            }
          ]
        })(
          <div>
            <Button
              onClick={() => {
                this.setState({open2: true});
              }}
              style={{marginBottom: 16}}
              type="primary"
              ghost
            >
              添加周期
            </Button>
            <Table
              size="middle"
              pagination={false}
              columns={columns3}
              dataSource={dataSource3}
            />
          </div>
        )}
      </FormItem>
    );
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    return (
      <div className="CreateTask">
        <div className="Steps">
          <Steps current={1}>
            <Step title="基本信息"/>
            <Step title="出勤设置"/>
            <Step title="发布设置"/>
          </Steps>
        </div>
        <Form onSubmit={this.handleSubmit} style={{marginTop: 24}}>
          {/* <FormItem
            {...formItemLayout}
            label="驻勤小组名称"
          >
            {getFieldDecorator('address', {
              rules: [{ required: true, message: '请输入' }],
            })(
              <Input />
              )}
          </FormItem> */}
          <FormItem {...formItemLayout} label="选择出勤类型">
            {getFieldDecorator("attendType", {
              initialValue: this.state.attendType,
              onChange: e => {
                const val = e.target.value;
                this.setState({attendType: val});
                this.props.form.setFieldsValue({attendType: val});
              },
              rules: [
                {
                  required: true,
                  message: "请选择"
                }
              ]
            })(
              <Radio.Group>
                <Radio className="radioStyle" value="1">
                  固定班制（每天出勤时间一样）{" "}
                  <span className="exclamation">
                    <Icon type="exclamation-circle"/>适用于：每天固定上下班的驻勤。
                  </span>
                </Radio>
                <Radio className="radioStyle" value="2">
                  排班制（自定义设置出勤时间）<span className="exclamation">
                    <Icon type="exclamation-circle"/>适用于：每天多个班次进行轮流上岗的驻勤。
                  </span>
                </Radio>
                <Radio disabled className="radioStyle" value="3">
                  自由班制（不设置班次，可随时打卡出勤，计算工时）
                </Radio>
              </Radio.Group>
            )}
          </FormItem>
          {/*  <FormItem
            {...formItemLayout}
            label="设置出勤班次"
          >
            {getFieldDecorator('branch', {
              rules: [{
                required: true, message: '请选择',
              }],
            })(
              <Checkbox.Group className="checkbox-group">
                <Row>
                  <Col span={3}><Checkbox value="A">周一</Checkbox></Col>
                  <Col span={3}><Checkbox value="B">周二</Checkbox></Col>
                  <Col span={3}><Checkbox value="C">周三</Checkbox></Col>
                  <Col span={3}><Checkbox value="D">周四</Checkbox></Col>
                  <Col span={3}><Checkbox value="E">周五</Checkbox></Col>
                  <Col span={3}><Checkbox value="E">周六</Checkbox></Col>
                  <Col span={3}><Checkbox value="E">周日</Checkbox></Col>
                </Row>
              </Checkbox.Group>,
            )}
          </FormItem> */}
          {/* 固定班次 */}
          {this.state.attendType === "1" && this.fixedShiftRender()}
          {/* 排班次--出勤班次 */}
          {this.state.attendType === "2" && this.scheduleRender()}
          {/* 排班次--周期性排班 */}
          {this.state.attendType === "2" && this.periodicityRender()}
          {/* <FormItem
            {...formItemLayout}
            label="设置出勤起点"
          >
            {getFieldDecorator('company', {
              rules: [{
                required: true, message: '请输入',
              }],
            })(
              <Row>
                <Col span={12}>
                  <TimePicker style={{ width: "100%" }} />
                </Col>
                <Col span={12}>
                  <span className="exclamation"><Icon type="exclamation-circle" />每日到达起点时间才打卡并计算工时</span>
                </Col>
              </Row>
              )}
          </FormItem> */}
          <Row span={24}>
            <Row className="resetant-row">
              <Col span={12}>
                <FormItem {...formItemLayout3} label="设置出勤地点">
                  {getFieldDecorator("taskAttendAddressDtoList", {
                    rules: [{required: true, message: "设置出勤地点"}]
                  })(
                    <div>
                      <Button
                        type="primary"
                        ghost
                        onClick={() => {
                          this.setState({visible: true});
                          window.setTimeout(() => {
                            this.initializeMap();
                          }, 15);
                        }}
                      >
                        添加地点
                      </Button>
                      <span className="exclamation">
                        <Icon type="exclamation-circle"/>可设置多个考勤地点
                      </span>
                    </div>
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem {...formItemLayout4} label="有效范围">
                  {getFieldDecorator("addressRange", {
                    rules: [{required: true, message: "请选择"}]
                  })(<Input addonAfter="米" placeholder="请输入"/>)}
                </FormItem>
              </Col>
            </Row>
            <FormItem {...formItemLayout} label=" " colon={false}>
              <Table
                style={{marginTop: 16}}
                size="middle"
                pagination={false}
                columns={columns5}
                dataSource={dataSource5}
              />
            </FormItem>
          </Row>
          {/* <FormItem
            {...formItemLayout}
            label="根据wifi出勤"
          >
            {getFieldDecorator('address', {
              rules: [{ required: true, message: '请选择' }],
            })(
              <Row span={24}>
                <Row>
                  <Col span={4}>  <Button
                    type="primary"
                    ghost
                    onClick={() => this.setState({ visible1: true })}
                  >
                    添加WIFI
                    </Button></Col>
                </Row>
                <Row>
                  <Table style={{ marginTop: 16 }} size="middle" pagination={false} columns={columns6} dataSource={dataSource6} />
                </Row>
              </Row>
              )}
          </FormItem> */}
          <FormItem {...submitFormLayout} style={{marginTop: 32}}>
            <Button onClick={() => this.props.switchStep(-1)}>上一步</Button>
            <Button type="primary" style={{marginLeft: 8}} htmlType="submit" onClick={() => this.props.switchStep(1)}>
              下一步
            </Button>
          </FormItem>
        </Form>
        {/* 固定班次--选择班次*/}
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          right
          open={this.state.open}
          noTouchClose
          width={600}
          className="drawer-box"
          onChange={open => {
            this.setState({open});
          }}
        >
          <div className="drawer">
            <div className="drawer-header">
              选择班次{" "}
              <Button
                type="primary"
                onClick={() => this.setState({open3: true, open: false})}
                ghost
              >
                新增班次
              </Button>
            </div>
            <div className="drawer-content">
              <Table
                pagination={false}
                rowSelection={rowSelectionRadio}
                columns={columns4}
                dataSource={dataSource4}
              />
            </div>
            <div className="drawer-footer">
              <Button>取消</Button>
              <Button type="primary">确定</Button>
            </div>
          </div>
        </Drawer>
        {/*  排班次--添加班次 */}
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          right
          open={this.state.open1}
          noTouchClose
          width={600}
          className="drawer-box"
          onChange={open1 => {
            this.setState({open1});
          }}
        >
          <div className="drawer">
            <div className="drawer-header">
              选择班次{" "}
              <Button
                onClick={() => this.setState({open3: true, open1: false})}
                type="primary"
                ghost
              >
                新增班次
              </Button>
            </div>
            <div className="drawer-content">
              <Table
                pagination={false}
                rowSelection={rowSelection}
                columns={columns4}
                dataSource={dataSource4}
              />
            </div>
            <div className="drawer-footer">
              <Button>取消</Button>
              <Button type="primary">确定</Button>
            </div>
          </div>
        </Drawer>

        {/*  排班次--添加排班周期 */}
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          right
          open={this.state.open2}
          noTouchClose
          width={600}
          className="drawer-box"
          onChange={open2 => {
            this.setState({open2});
          }}
        >
          <div className="drawer">
            <div className="drawer-header">选择班次</div>
            <div className="drawer-content">
              <Form onSubmit={this.handleSubmit} style={{marginTop: 24}}>
                <FormItem {...formItemLayout} label="周期名称">
                  {getFieldDecorator("address", {
                    rules: [{required: true, message: "请输入"}]
                  })(<Input/>)}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="周期天数"
                  help="2天为一周期进行循环排班"
                >
                  {getFieldDecorator("address", {
                    rules: [{required: true, message: "请输入"}]
                  })(<Input addonAfter="天"/>)}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="第一天班次"
                  help="09:00-11:00 | 12:00-15:00 | 16:00-18:00 "
                >
                  {getFieldDecorator("address", {
                    rules: [{required: true, message: "请输入"}]
                  })(
                    <Select
                      placeholder="Select a person"
                      optionFilterProp="children"
                      filterOption={(input, option) =>
                        option.props.children
                          .toLowerCase()
                          .indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      <Option value="jack">Jack</Option>
                      <Option value="lucy">Lucy</Option>
                      <Option value="tom">Tom</Option>
                    </Select>
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="第二天班次">
                  {getFieldDecorator("address", {
                    rules: [{required: true, message: "请输入"}]
                  })(
                    <Select
                      placeholder="Select a person"
                      optionFilterProp="children"
                      filterOption={(input, option) =>
                        option.props.children
                          .toLowerCase()
                          .indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      <Option value="jack">Jack</Option>
                      <Option value="lucy">Lucy</Option>
                      <Option value="tom">Tom</Option>
                    </Select>
                  )}
                </FormItem>
              </Form>
            </div>
            <div className="drawer-footer">
              <Button>取消</Button>
              <Button type="primary">确定</Button>
            </div>
          </div>
        </Drawer>

        {/*  选择班次--新增班次 */}
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          right
          open={this.state.open3}
          noTouchClose
          width={600}
          className="drawer-box"
          zIndex={2}
          onChange={open3 => {
            this.setState({open3});
          }}
        >
          <AddNewShift/>
        </Drawer>

        <Modal
          title="添加地点"
          visible={this.state.visible}
          okText="提交"
          cancelText="关闭"
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width={700}
        >
          <div id="taskMapContainer"/>
          <Form onSubmit={this.handleSubmit}>
            <FormItem label="地址名称" {...formItemLayout2}>
              <Input id="suggestId"/>
            </FormItem>
            <FormItem {...formItemLayout2} label="详细地址">
              {this.state.address}
            </FormItem>
          </Form>
        </Modal>

        <Modal
          title="添加出勤WIFI"
          visible={this.state.visible1}
          okText="确认"
          cancelText="取消"
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form onSubmit={this.handleSubmit}>
            <FormItem label="WIFI名称" {...formItemLayout1}>
              {getFieldDecorator("address", {
                rules: [{required: true, message: "请输入"}]
              })(<Input/>)}
            </FormItem>
            <FormItem {...formItemLayout1} label="MAC地址">
              {getFieldDecorator("address", {
                rules: [{required: true, message: "请输入"}]
              })(<Input/>)}
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}
