import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Form,
  Select,
  Button,
  Radio,
  Steps,
  DatePicker,
  InputNumber,
  Icon,
  TreeSelect,
  Input,
  message,
  Modal,
  Alert,
  Table
} from 'antd';
import st from 'styled-components';
import $nModal from '../../../utils/modal/nModal';
import $perModal from '../../../utils/modal/perModal';
import '../Task.less';
import {
  taskGetStepThreeDetail,
  taskSaveStepThreeDetail
  // getTaskGetTaskUnInsPerInfoList //获取驻勤未进行投保人员列
} from '../../../services/api';
import bcx_utils from '../../../common/bcx_utils';
import { checkMember, gup } from '../../../utils/utils';
import Result from '../../../components/Result';
import './less/style.less';

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

@connect(state => ({
  profile: state.profile
}))
@Form.create()
export default class Information extends Component {
  state = {
    taskPerArray: [], //所有人员的数组
    taskPerArrayList: [], //不包含没有权限的人员的id
    taskPerArrayNoIdList: [], //只有没有权限的人员的id
    visibleuser: false,
    selectedTags: [],
    arrayObj: [],
    treeData: [],
    comTaskId: this.props.dataSource.comTaskId || '',
    perNum: '', //驻勤所需人数
    pagenav: {
      checkedkeys: [],
      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
    },
    taskStatus: '-2', // 默认值，不显示暂存按钮
    // personName: '' // 需要投保人员列表
    publishSuccessVisible: false, //成功发布提示Modal
    tableHtml: ''
  };

  componentWillMount() {
    let dataSource = this.props.dataSource;
    if (dataSource.comTaskId != undefined) {
      this.setState(
        {
          comId: dataSource.comTaskId
        },
        () => {
          this.taskGetStepThreeDetail();
        }
      );
    }
  }

  componentWillUnmount() {
    // 清除定时器
    this.timer && clearTimeout(this.timer);
  }

  _renderConflictPerList = (conflictPerList, tableId) => {
    conflictPerList = conflictPerList.map((item, index) => {
      item.number = index + 1;
      return item;
    });
    const columns = [
      {
        title: '序号',
        dataIndex: 'number',
        key: 'number',
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '手机号',
        dataIndex: 'mobilePhone',
        key: 'mobilePhone',
      },
      {
        title: '已安排的驻勤点名称及负责人信息',
        dataIndex: 'taskInfos',
        key: 'taskInfos',
      },
    ];
    return (
      // <TableCon>
      <Table
        dataSource={conflictPerList}
        columns={columns}
        pagination={{ pageSize: 10 }}
      />
      // </TableCon>
    );
  }
  handleSubmit = (e, type) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // if(values.taskPerInsMode === '1'){//需要投保
        // getTaskGetTaskUnInsPerInfoList({comTaskId:this.state.comTaskId}).then(response =>{
        //   this.setState({
        //     personName: response.data
        //   });
        //   this.taskSaveStepThreeDetail(values);
        // });
        // }

        if (this.state.taskPerArrayNoIdList.length > 0) {
          values.taskPerArray = values.taskPerArray.concat(
            this.state.taskPerArrayNoIdList
          );
        }
        if (values.taskPerArray.length === 0) {
          message.error('请选择参与人员');
          return;
        }
        if (values.taskPerArray.length > 1000) {
          message.error('参与人数不得大于1000，请重新选择！');
          return;
        }
        values.taskPerArray = this.state.taskPerArray.map(item => item.perId);
        values.perNum = 0;
        // if (values.taskPerArray.length > values.perNum) {
        //   bcx_utils.preventRA(resolve => {
        //     message.error('参与人员数不能大于所需人数', 1.5, () => resolve());
        //   });
        //   return;
        // }
        //是否暂存， isFB 为 0 时候暂存。
        values.isFB = type || '1';
        if (!this.state.comTaskId) {
          message.warning('驻勤ID不能为空');
          return;
        }
        if (!this.state.chargePerName) {
          message.warning('驻勤负责人姓名不能为空');
          return;
        }
        values.comTaskId = this.state.comTaskId;
        values.chargePerName = this.state.chargePerName;
        // let newTaskPerArray = values.taskPerArray.reduce(
        //   (acc, item) => acc.concat(item.replace(/(dept)/, '')),
        //   []
        // );

        // const ajaxData = { ...values, ...{ newTaskPerArray } };
        this.taskSaveStepThreeDetail(values);
      }
    });
  };

  //获取详情
  taskGetStepThreeDetail = () => {
    taskGetStepThreeDetail({ comTaskId: this.state.comTaskId }).then(
      response => {
        if (response.data) {
          const {
            chargePerId,
            chargePerName,
            taskPerArray, //这里的id包含没有权限的人员
            taskPerInsMode,
            perNum,
            taskStatus
          } = response.data;

          this.setState({
            chargePerId,
            checkedkeys: chargePerId,
            chargePerName,
            taskPerArray,
            taskPerInsMode,
            perNum,
            taskStatus,
            taskPerArrayNoIdList: taskPerArray //先把所有数据给他，之后在删除
          });
          if (!response.data.taskStatus) {
            // -1表示是新建驻勤或者暂存驻勤status的值为空时，允许暂存，将暂存按钮显示出来
            this.setState({ taskStatus: '-1' });
          }
          if (this.state.treeData.length > 0) {
            //如果是组织机构先加载完，就在这里处理删除没有权限人员的id
            const perIdList = this.removeNOpowerId(
              taskPerArray,
              this.state.treeData
            );
            const { setFieldsValue } = this.props.form;
            setFieldsValue({
              taskPerArray: perIdList
            });
          }
        } else {
          // -1表示是新建驻勤或者暂存驻勤status的值为空时，允许暂存，将暂存按钮显示出来
          this.setState({ taskStatus: '-1' });
        }
      },
      err => {
        console.log(err, 'err-获取详情-taskGetStepThreeDetail');
      }
    );
  };

  //删掉没有权限的人员id
  removeNOpowerId = (taskPerArray, treeData) => {
    treeData.map(item => {
      if (item.children && item.children.length > 0) {
        item.children = this.removeNOpowerId(taskPerArray, item.children);
      }
    });
    if (treeData.length > 0) {
      treeData.map(tdata => {
        taskPerArray.filter((item, i) => {
          if (item === tdata.key) {
            //给的人员id有在树结构里面
            this.state.taskPerArrayList.push(item);
            this.state.taskPerArrayNoIdList.splice(i, 1);
          }
        });
      });
    }
    console.log(this.state.taskPerArrayNoIdList);
    return this.state.taskPerArrayList;
  };

  //提交表单第三步
  taskSaveStepThreeDetail = values => {
    taskSaveStepThreeDetail(values).then(
      response => {
        const conflictPerList = JSON.parse(response.data.conflictPerList);
        Modal.success({
          title: '驻勤值守发布成功！',
          content: '请返回驻勤列表，为该驻勤值守关联合同、管理驻勤人员、为人员进行考勤排班。',
          okText: '返回驻勤列表',
          onOk: () => {
            if (conflictPerList.length == 0) {
              this.props.history.push('/taskmanager/tasklist');
            } else {
              $nModal({
                width: 650,
                title: '存在重复安排驻勤点人员',
                footer: null,
                content: (
                  <div>
                    <p style={{ color: 'orange' }}>
                      以下人员已被安排在其他驻勤点中，无法再被安排；若需要调整，请先到其他驻勤点移除该人员。
                    </p>
                    {/* <ExcelButton 
                      table={this.state.tableHtml}
                      fileName={'重复安排人员列表'}>
                      导出  
                    </ExcelButton> */}
                    {this._renderConflictPerList(conflictPerList)}
                    {/* {this.setState({tableHtml: document.getElementById(tableId)})} */}
                  </div>
                ),
                onCancel: () => {
                  this.props.history.push('/taskmanager/tasklist');
                },
              });
              // setTimeout(() => {
              //   this.setState({tableHtml: document.getElementById(tableId)});
              // }, 500);
            }
          }
        });

      }
    );
  };
  callback = key => {
    console.log(key);
  };

  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();
    }
  };
  handleCancel = () => {
    console.log('cancle');
    this.setState({
      visibleuser: false
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;

    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 }
      }
    };

    return (
      <div className="CreateTask">
        <div className="Steps">
          <Steps current={2}>
            <Step title="基本信息" />
            <Step title="出勤设置" />
            <Step title="发布设置" />
          </Steps>
        </div>
        <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
          <FormItem {...formItemLayout} label="驻勤负责人">
            {getFieldDecorator('chargePerId', {
              initialValue: this.state.chargePerId,
              rules: [
                {
                  required: true,
                  message: '请输入驻勤负责人'
                }
              ]
            })(
              <div className="fjr">
                <div className="row">
                  <Button
                    type="primary"
                    onClick={() => {
                      // this.setState({ visibleuser: true });
                      $perModal({
                        value: this.state.chargePerId,
                        type: 'radio',
                        fetchType: 'task',
                        onOk: (values, close) => {
                          close();
                          if(values[0]) {
                            this.props.form.setFieldsValue({chargePerId:  values[0].perId});
                            this.setState({
                              chargePerName: values[0].name
                            });
                          }
                        }
                      });
                    }}
                    ghost
                  >
                    选择人员
                  </Button>
                  <span className="exclamation">
                    <Icon type="exclamation-circle" />
                    人数限制：1人
                  </span>
                </div>

                <div className="fjr-list">
                  <span>
                    负责人:
                    <Icon type="user" />
                    {this.state.chargePerName}
                  </span>
                </div>
              </div>
            )}
          </FormItem>
          {/*  <div className="card">全网推送规则</div>
          <FormItem
            {...formItemLayout}
            label="设置共享区域"
          >
            {getFieldDecorator('address', {
              rules: [{ required: true, message: '请选择' }],
            })(
              <Select placeholder="请选择">
                <Option value="xiao">付晓晓</Option>
                <Option value="mao">周毛毛</Option>
              </Select>
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="设置共享人数"
          >
            {getFieldDecorator('address', {
              rules: [{ required: true, message: '请选择' }],
            })(
              <InputNumber min={1} max={10} />
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="中心扩散范围"
          >
            {getFieldDecorator('address', {
              rules: [{ required: true, message: '请选择' }],
            })(
              <Input />
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="共享起止时间"
          >
            {getFieldDecorator('dateRange', {
              rules: [{ required: true, message: '请选择生效日期' }],
            })(
              <RangePicker placeholder={['开始日期', '结束日期']} style={{ width: '100%' }} />
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="驻勤性质"
            style={{ marginBottom: 0 }}
          >
            {getFieldDecorator('branch', {
              rules: [{
                required: true, message: '请选择',
              }],
            })(
              <Radio.Group>
                <Radio className="radioStyle" value="1">固定价位(元/人) <Input style={{ display: "block" }} placeholder="请输入" /> </Radio>
                <Radio className="radioStyle" value="2">时长计价(元/小时) <Input style={{ display: "block" }} placeholder="请输入" /> </Radio>
              </Radio.Group>
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="驻勤投保"
          >
            {getFieldDecorator('branch', {
              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">企业赠送保险</Radio>
                <Radio className="radioStyle" value="3">无需投保</Radio>
              </Radio.Group>
              )}
          </FormItem> */}
          <div className="card">推送给内部员工</div>
          <FormItem
            {...formItemLayout}
            label="选择参与人员"
            style={{ marginBottom: 0 }}
          >
            {getFieldDecorator('taskPerArray', {
              // initialValue: this.state.treeData.length ? this.state.taskPerArray : [],
              rules: [
                {
                  required: true,
                  message: '请选择参与人员'
                }
              ]
            })(
              <InputWrap>
                <Input
                type="text"
                value={this.state.taskPerArray.map(item => item.name).join(',')}
                readOnly
                placeholder="请选择参与人员"
                onClick={() => {
                  const { setFieldsValue } = this.props.form;
                  $perModal({
                    title: '选择参与人员',
                    fetchType: 'task',
                    value: this.state.taskPerArray,
                    onOk: (taskPerArray, close) => {
                      this.setState({ taskPerArray }, () => {
                        setFieldsValue({ 'taskPerArray': this.state.taskPerArray.map(item => item.perId) })
                        close();
                      });
                    }
                  });
                }} />
                {
                  this.state.taskPerArray.length>0 &&
                  <span className="count_wrap">已选（{this.state.taskPerArray.length}）人</span>
                }
              </InputWrap>
              // <TreeSelect
              //   maxTagCount={6}
              //   treeData={this.state.treeData}
              //   treeCheckable
              //   onChange={perIdStr => {
              //     console.log(perIdStr, 'perIdStr-onChange');
              //   }}
              //   showCheckedStrategy={TreeSelect.SHOW_CHILD}
              //   searchPlaceholder={'选择部门或人员'}
              // />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label=" " colon={false}>
            <div style={{ position: 'relative' }}>
              <Alert
                message={
                  <div>
                    <p style={{ marginBottom: 0 }}>
                      最多选择1000人，更多请另建驻勤组设置。
                    </p>
                  </div>
                }
                type="warning"
                showIcon
              />
            </div>
          </FormItem>
          {/* <FormItem {...formItemLayout} label="所需人数">
            {getFieldDecorator('perNum', {
              initialValue: this.state.perNum,
              rules: [
                {
                  pattern: /^[1-9][0-9]*$/,
                  required: true,
                  message: '请选择所需人数'
                }
              ]
            })(<InputNumber min={1} max={1000000000} />)}
          </FormItem> */}
          {/* <FormItem {...formItemLayout} label="投保情况">
            {getFieldDecorator('taskPerInsMode', {
              initialValue: this.state.taskPerInsMode,
              rules: [
                {
                  required: true,
                  message: '请选择投保情况'
                }
              ]
            })(
              <Radio.Group>
                <Radio className="radioStyle" value="1">
                  企业赠送保险{' '}
                </Radio>
                <Radio className="radioStyle" value="2">
                  无需投保
                </Radio>
              </Radio.Group>
            )}
          </FormItem> */}
          {/*  <FormItem
            {...formItemLayout}
            label="开关控制"
          >
            <div className="Switch-box">
              <div>驻勤实名啐证:<Switch checkedChildren="开" unCheckedChildren="关" defaultChecked /></div>
              <div>参与人员上报:<Switch checkedChildren="开" unCheckedChildren="关" defaultChecked /></div>
              <div>驻勤轨迹上报:<Switch checkedChildren="开" unCheckedChildren="关" defaultChecked /></div>
              <div>热力图呈现:<Switch checkedChildren="开" unCheckedChildren="关" defaultChecked /></div>
              <div>驻勤步数记录:<Switch checkedChildren="开" unCheckedChildren="关" defaultChecked /></div>
            </div>
          </FormItem> */}
          <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
            <Button
              onClick={() => {
                this.props.switchStep(-1);
              }}
            >
              上一步
            </Button>
            {/* {this.state.taskStatus === '-1' || this.state.taskStatus === '6' ? (
              <Button
                style={{ marginLeft: 8 }}
                onClick={e => {
                  this.handleSubmit(e, '0');
                }}
              >
                暂存
              </Button>
            ) : null} */}
            <Button type="primary" style={{ marginLeft: 8 }} htmlType="submit">
              发布
            </Button>
          </FormItem>
        </Form>

        {/* 成功发布驻勤后弹窗提示，三秒后消失 */}
        <Modal
          title={null}
          visible={this.state.publishSuccessVisible}
          footer={null}
          closable={false}
        >
          <Result
            type="success"
            title="发布成功"
            description="驻勤已发布成功，并已通知给相关人员，快去排班吧"
          />
        </Modal>
      </div>
    );
  }
}


const TableCon = st.div`
  .ant-table-pagination.ant-pagination {
    display: none;
  }
`;
const InputWrap = st.div`
  display: flex;
  align-items: center;
  .count_wrap{
    flex-shrink: 0;
    margin-left: 8px;
  }
`;
