import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Form,
  Button,
  Steps,
  Icon,
  Divider,
  TreeSelect,
  Table,
  Breadcrumb,
  Modal,
  Alert,
  message,
  Spin,
  Input
} from 'antd';
import st from 'styled-components';
import { Link } from 'dva/router';
import { gup, checkMember } from '../../utils/utils';
import $perModal from '../../utils/modal/perModal';
import PartmentButton from '../../components/PartmentButton';
import {
  getTreeperBydepart, //部门人员
  taskAttendanceComAttendGroupFindAttendGroupByPerIdStr, //新增内勤组-设置考勤人员-检查多个人员是否存在于其他内勤组
  taskAttendanceComAttendGroupInThirdStepAttendGroup, //进入内勤组设置-第三步页面
  taskAttendanceComAttendGroupSaveThirdStepAttendGroup, //新增或者修改内勤组-第三步-设置考勤人员并保存
  taskAttendanceComAttendGroupCheckAttendPer //新增或者修改内勤组-设置考勤人员-检查人员是否存在于其他内勤组
} from '../../services/api';

import './ThiftManagement.less';

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

@connect(state => ({
  global: state.global,
  currentuser: state.user
}))
@Form.create()
export default class SettingUpAttendance extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      perId: [], // 所有人员的id
      perIdList: [], //不包含没有权限的人员的id
      perNoIdList: [], //只有没有权限的人员的id
      perIdStr: [],
      chargePerIdStr: '',
      chargePerIdList: [],
      attendGroupId: gup('attendGroupId') || '',
      midAttendGroupId: gup('midAttendGroupId') || '',
      chargePerVisible: false,
      treeData: [],
      arrayObj: [],
      loading: false
    };
  }

  componentDidMount() {
    // this.getTreeperBydepart();
    // this.taskAttendanceComAttendGroupInThirdStepAttendGroup();
  }
  componentWillMount() {
    this.taskAttendanceComAttendGroupInThirdStepAttendGroup();
    this.setState({
      loading: true
    });
    this.getTreeperBydepart();
  }

  renderTable = data => {
    if (data) {
      data = JSON.parse(data);
    } else {
      return null;
    }
    const dataSource = data.map((val, i) => {
      val.key = i;
      return val;
    });
    const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        key: '1',
        width: 80
      },
      {
        title: '内勤组',
        dataIndex: 'attendGroupName',
        key: '2'
      }
    ];

    return (
      <div>
        <p style={{ color: '#f00' }}>
          调整后，该人员今日的打卡记录将会删除，需要以新的考勤规则重新打卡。
        </p>
        <Table size="small" dataSource={dataSource} columns={columns} />
      </div>
    );
  };
  //新增内勤组-设置考勤人员-检查多个人员是否存在于其他内勤组
  taskAttendanceComAttendGroupFindAttendGroupByPerIdStr = chargePerIdStr => {
    taskAttendanceComAttendGroupFindAttendGroupByPerIdStr({
      perIdStr: chargePerIdStr.join(',')
    }).then(
      response => {
        if (response.data.length > 0) {
          confirm({
            title: '以下人员都已经有考勤任务了',
            content: this.renderTable(response.data),
            okText: '确认调整',
            cancelText: '保持不变',
            onOk: () => { },
            onCancel: () => {
              this.taskAttendanceComAttendGroupInThirdStepAttendGroup();
            }
          });
        }
      },
      err => {
        console.log(
          err,
          'err-新增内勤组-设置考勤人员-检查多个人员是否存在于其他内勤组-taskAttendanceComAttendGroupFindAttendGroupByPerIdStr'
        );
      }
    );
  };

  //新增或者修改内勤组-设置考勤人员-检查人员是否存在于其他内勤组
  taskAttendanceComAttendGroupCheckAttendPer = perIdStr => {
    const { midAttendGroupId, attendGroupId } = this.state;
    taskAttendanceComAttendGroupCheckAttendPer({
      midAttendGroupId,
      // perIdStr: perIdStr.join(","),
      perIdStr,
      attendGroupId
    })
      .then(res => {
        if (res.data) {
          confirm({
            title: '以下人员都已经有考勤任务了',
            content: this.renderTable(res.data),
            okText: '确认调整',
            cancelText: '保持不变',
            closable: true,
            onOk: () => {
              const modal = confirm({
                title: '请根据需求选择准确的生效时间：',
                content: (
                  <div>
                    <Icon
                      type="close"
                      style={{
                        position: 'absolute',
                        right: '15px',
                        top: '15px',
                        cursor: 'point'
                      }}
                      onClick={() => {
                        modal.destroy();
                      }}
                    />
                    <p />
                    今日生效：考勤人员今日的考勤规则将按照本内勤组设置的进行变更，
                    <span style={{ color: '#f00' }}>
                      若今日已有打卡数据，将会被清除。
                    </span>
                    <p>
                      明日生效：考勤人员今日的考勤规则及打卡数据不变，从明日起以本内勤组设置的规则进行考勤打卡。
                    </p>
                  </div>
                ),
                okText: '明日生效',
                cancelText: '今日生效',
                onCancel: () => {
                  this.taskAttendanceComAttendGroupSaveThirdStepAttendGroup(
                    '1',
                    '1'
                  );
                },
                onOk: () => {
                  this.taskAttendanceComAttendGroupSaveThirdStepAttendGroup(
                    '1',
                    '2'
                  );
                }
              });
            },
            onCancel: () => {
              if (res.data && JSON.parse(res.data).length === perIdStr.length) {
                message.error('所有选中的人员都存在班次冲突，无法提交任务');
                return;
              }
              const modal = confirm({
                title: '选择考勤生效时间',
                content: (
                  <div>
                    <Icon
                      type="close"
                      style={{
                        position: 'absolute',
                        right: '15px',
                        top: '15px',
                        cursor: 'point'
                      }}
                      onClick={() => {
                        modal.destroy();
                      }}
                    />
                    <p />
                    今日生效：考勤人员今日的考勤规则将按照本内勤组设置的进行变更，
                    <span style={{ color: '#f00' }}>
                      若今日已有打卡数据，将会被清除。
                    </span>
                    <p>
                      明日生效：考勤人员今日的考勤规则及打卡数据不变，从明日起以本内勤组设置的规则进行考勤打卡。
                    </p>
                  </div>
                ),
                okText: '明日生效',
                cancelText: '今日生效',
                onCancel: () => {
                  this.taskAttendanceComAttendGroupSaveThirdStepAttendGroup(
                    '0',
                    '1'
                  );
                },
                onOk: () => {
                  this.taskAttendanceComAttendGroupSaveThirdStepAttendGroup(
                    '0',
                    '2'
                  );
                }
              });
            }
          });
        } else {
          const modal = confirm({
            title: '选择考勤生效时间',
            content: (
              <div>
                <Icon
                  type="close"
                  style={{
                    position: 'absolute',
                    right: '15px',
                    top: '15px',
                    cursor: 'point'
                  }}
                  onClick={() => {
                    modal.destroy();
                  }}
                />
                <p />
                今日生效：考勤人员今日的考勤规则将按照本内勤组设置的进行变更，
                <span style={{ color: '#f00' }}>
                  若今日已有打卡数据，将会被清除。
                </span>
                <p>
                  明日生效：考勤人员今日的考勤规则及打卡数据不变，从明日起以本内勤组设置的规则进行考勤打卡。
                </p>
              </div>
            ),
            okText: '明日生效',
            cancelText: '今日生效',
            onCancel: () => {
              this.taskAttendanceComAttendGroupSaveThirdStepAttendGroup(
                '0',
                '1'
              );
            },
            onOk: () => {
              this.taskAttendanceComAttendGroupSaveThirdStepAttendGroup(
                '0',
                '2'
              );
            }
          });
        }
      })
      .catch(err =>
        console.log(
          err,
          '新增或者修改内勤组-设置考勤人员-检查人员是否存在于其他内勤组-err'
        )
      );
  };

  //新增或者修改内勤组-第三步-设置考勤人员并保存
  taskAttendanceComAttendGroupSaveThirdStepAttendGroup = (
    isAdjust,
    effectRule
  ) => {
    const { midAttendGroupId, attendGroupId, chargePerIdList } = this.state;
    const chargePerIdStr = chargePerIdList[0].perId;
    taskAttendanceComAttendGroupSaveThirdStepAttendGroup({
      midAttendGroupId,
      attendGroupId,
      isAdjust,
      effectRule,
      chargePerIdStr
    })
      .then(res => {
        this.props.history.push(
          `/attendancemanagement/newattendanceunit/settingcomplete`
        );
      })
      .catch(err =>
        console.log(err, '新增或者修改内勤组-第三步-设置考勤人员并保存-err')
      );
  };
  //进入内勤组设置-第三步页面
  taskAttendanceComAttendGroupInThirdStepAttendGroup = () => {
    const { midAttendGroupId, attendGroupId } = this.state;
    taskAttendanceComAttendGroupInThirdStepAttendGroup({
      midAttendGroupId,
      attendGroupId
    }).then(
      response => {
        const { setFieldsValue } = this.props.form;
        if (
          !('perList' in response.data) ||
          !('chargePerList' in response.data)
        ) {
          return null;
        }
        const { perList, chargePerList } = response.data;
        const newlist1 = perList.map(val => {
          return val.perId;
        });
        setFieldsValue({
          perIdStr: perList.map(({perId}) => perId).join(','),
          perName: perList.map(({name}) => name).join(',')
        });
        // const newlist = perList.map(val => {
        //   return `${val.perId}::${val.name}`;
        // });
        // if (perList.length) {
        //   setFieldsValue({
        //     perIdStr: newlist
        //   });
        //   this.setState({
        //     perIdStr: newlist1
        //   });
        // }
        this.setState({
          perId: newlist1, //里面包含的数据可能存在没有权限的，即没有在树选择器中（让后端在此加入字段判断有没有权限的进行判断）
          perNoIdList: newlist1 //先给没有权限的人员列表里面是所有值，之后在减去
        });
        if (this.state.treeData.length > 0) {
          //如果这个接口后请求完成，就这里掉用设置
          const perIdList = this.removeNOpowerId(newlist1, this.state.treeData);
          setFieldsValue({
            perIdStr: perIdList.join(',')
          });
        }
        if (chargePerList.length > 0) {
          this.setState({
            chargePerIdStr: chargePerList[0]['perId'],
            chargePerIdList: [{ title: chargePerList[0]['name'] }],
            arrayObj: chargePerList
          });
          setFieldsValue({
            chargePerIdStr: chargePerList[0]
          });
        }
      },
      err => {
        console.log(
          err,
          'err-进入内勤组设置-第三步页面taskAttendanceComAttendGroupInThirdStepAttendGroup'
        );
      }
    );
  };

  gerator = data => {
    return data.map(val => {
      val.value = `${val.key}::${val.label}`;
      if (val.treeType === '1') {
        val.value = `${val.key}::${val.label}::dept`;
      }
      if (val.children.length > 0) {
        val.children = this.gerator(val.children);
      }
      return val;
    });
  };

  //部门人员
  getTreeperBydepart = () => {
    getTreeperBydepart().then(
      response => {
        const responseData = checkMember(response.data);
        // response.data = this.gerator(response.data);
        this.setState({ treeData: responseData });
        if (this.state.perId.length > 0) {
          //如果这个接口后请求完成，就这里掉用设置
          const treeData = JSON.parse(JSON.stringify(responseData));
          const perIdList = this.removeNOpowerId(this.state.perId, treeData);
          const { setFieldsValue } = this.props.form;
          setFieldsValue({
            perIdStr: perIdList.join(',')
          });
        }
        this.setState({
          loading: false
        });
      },
      err => {
        this.setState({
          loading: false
        });
        console.log(err, 'err-部门人员-getTreeperBydepart');
      }
    );
  };

  //删掉没有权限的人员id
  removeNOpowerId = (perId, treeData) => {
    treeData.map(item => {
      if (item.children && item.children.length > 0) {
        item.children = this.removeNOpowerId(perId, item.children);
      }
    });
    if (treeData.length > 0) {
      treeData.map(tdata => {
        perId.filter((item, i) => {
          if (item === tdata.key) {
            //给的人员id有在树结构里面
            this.state.perIdList.push(item);
            this.state.perNoIdList.splice(i, 1);
          }
        });
      });
    }
    return this.state.perIdList;
  };
  // //宣染参与人员
  // perIdListRender = () => {
  //   return this.state.perIdList.map((val, i) => {
  //     return (
  //       <span key={i} className="user">
  //         <Icon type="user" />
  //         {val.title}
  //       </span>
  //     );
  //   });
  // };

  //宣染人员选择器
  renderUserSelect = () => {
    const { setFieldsValue } = this.props.form;
    /* 内勤组负责人: */
    return (
      <PartmentButton
        onCheck={(chargePerIdStr, chargePerIdList) => {
          this.setState({
            chargePerVisible: false,
            chargePerIdStr,
            chargePerIdList
          });
          setFieldsValue({ chargePerIdStr });
        }}
        type="radio"
        handleCancel={() => {
          this.setState({
            chargePerVisible: false
          });
        }}
        value={this.state.chargePerIdStr}
        arrayObj={this.state.arrayObj}
        visible={this.state.chargePerVisible}
      />
    );
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.perIdStr = values.perIdStr.split(',');
        Reflect.deleteProperty(values, 'perName');
        if (values.perIdStr.length > 1000) {
          message.error('参与人数不得大于1000，请重新选择！');
          return;
        }
        this.taskAttendanceComAttendGroupCheckAttendPer(values.perIdStr);
      }
    });
  };

  onChange = value => {
    this.setState({ perIdStr: value });
  };

  findper = perIdStr => {
    clearTimeout(this.timeId);
    this.timeId = window.setTimeout(() => {
      this.taskAttendanceComAttendGroupFindAttendGroupByPerIdStr(perIdStr);
    }, 1000);
  };

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator, setFieldsValue, getFieldValue } = this.props.form;
    const { treeData } = this.state;

    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 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="card">设置考勤人员</div> */}
        <div className="Steps" style={{ marginTop: 15 }}>
          <Alert
            message={
              <div>
                <p style={{ marginBottom: 0 }}>
                  1、考勤人员：一个人员仅限归属一个内勤组，若需要变更人员的考勤规则，请新建一个内勤组，并将此人员从本内勤组中删除，在新内勤组中新增；
                </p>
                <p style={{ marginBottom: 0 }}>
                  2、内勤组提交有<span style={{ color: '#f00' }}>今日生效</span>
                  （今日的排班将以最新的规则安排，若旧排班已有打卡数据将会被清除）、
                  <span style={{ color: '#f00' }}>明日生效</span>
                  （今日的排班及考勤数据不变，从明日以最新的规则安排考勤），请根据需求准确选择；
                </p>
                <p style={{ marginBottom: 0 }}>
                  3、增减人说明：内勤组允许增加/减去人员。
                  <span style={{ color: '#f00' }}>
                    减去人员时，若选择今日生效，则该人员当日的考勤数据将会被删除，请知悉！
                  </span>
                </p>
              </div>
            }
            type="warning"
            showIcon
            style={{ marginBottom: '15px' }}
          />
          <Steps current={2}>
            <Step title="选择考勤类型" />
            <Step title="考勤地点" />
            <Step title="设置考勤人员" />
            <Step title="完成" />
          </Steps>
        </div>
        <Spin spinning={this.state.loading}>
          <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
            <FormItem
              {...formItemLayout}
              label={
                <span>
                  {/* <span style={{ color: '#f5222d' }}>* </span> */}
                  <span>选择需要参与考勤的人员</span>
                </span>
              }
              style={{ marginBottom: 5 }}
            >
              <InputWrap>
                {getFieldDecorator('perName', {
                  rules: [
                    {
                      required: true,
                      message: '请选择参与人员'
                    }
                  ]
                })(
                  <Input 
                    type="text"
                    readOnly
                    placeholder="请选择参与人员"
                    onClick={() => {
                      $perModal({
                        title: '选择参与人员',
                        value: getFieldValue('perIdStr'),
                        onOk: (values, close) => {
                          setFieldsValue({
                            perIdStr: values.map(val => val.perId).join(','),
                            perName: values.map(val => val.name).join(','),
                          });
                          close();
                        }
                      });
                    }}
                  />
                )}
                {
                  getFieldValue('perIdStr') && getFieldValue('perIdStr').split(',').length > 0 && 
                  <span className="count_wrap">已选（{getFieldValue('perIdStr').split(',').length}）人</span>
                }
                {getFieldDecorator('perIdStr', {
                  initialvalue: '',
                })(
                  <Input style={{ display: 'none' }} />
                )}
              </InputWrap>
            </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('chargePerIdStr', {
                rules: [
                  {
                    required: true,
                    message: '选择内勤组负责人'
                  }
                ]
              })(
                <div style={{ position: 'relative' }}>
                  <Button
                    onClick={() => {
                      // this.setState({ chargePerVisible: true });
                      $perModal({
                        type: 'radio',
                        value: getFieldValue('chargePerIdStr'),
                        onOk: (values, close) => {
                          this.setState({
                            chargePerIdList: values
                          }, () => {
                            setFieldsValue({chargePerIdStr: values[0].perId});
                          });
                          close();
                        }
                      });
                    }}
                    type="primary"
                    ghost
                    style={{ marginRight: 10 }}
                  >
                    选择人员
                  </Button>
                  {this.state.chargePerIdList.length > 0 &&
                    this.state.chargePerIdList[0]['name']}
                </div>
              )}
            </FormItem>
            <Divider />
            <FormItem {...submitFormLayout} style={{ marginTop: 24 }}>
              <Button
                onClick={() => {
                  this.props.history.replace(
                    `/attendancemanagement/newattendanceunit/choosewayattendance?attendGroupId=${
                    this.state.attendGroupId
                    }&midAttendGroupId=${this.state.midAttendGroupId}`
                  );
                }}
                loading={submitting}
              >
                返回
              </Button>
              <Button
                type="primary"
                style={{ marginLeft: 8 }}
                htmlType="submit"
              >
                提交
              </Button>
            </FormItem>
          </Form>
        </Spin>
        {/* 由于初始值的赋值过程在constructor这个生命周期中完成，为保证每次能拿到正确的初始值，
        过采用调用后即销毁的方式使用该组件，若采用直接调用的方式则下次进入该组件不会执行到
        constructor这个生命周期 */}
        {this.state.chargePerVisible && this.renderUserSelect()}
      </div>
    );
  }
}

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