import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Form,
  Button,
  Radio,
  Steps,
  Icon,
  Table,
  Breadcrumb,
  Checkbox,
  Input,
  message,
  Alert,
  Drawer
} from 'antd';
import { Link } from 'dva/router';
import { gup } from '../../utils/utils';

import {
  //taskAttendanceComattendgroupfixedSave, //新增内勤组-选择考勤类型-固定班制-新增
  // taskAttendanceComattendgroupfixedGetAddTemp, //新增内勤组-选择考勤类型-固定班制-获取周一到周日模板
  //taskAttendanceComattendgroupfixedUpdate, //新增内勤组-选择考勤类型-固定班制-修改
  taskAttendanceComAttendGroupInFirstStepAttendGroup, //新增内勤组-选择考勤类型-固定班制-详情
  taskAttendanceComAttendGroupSaveFirstStepAttendGroup, //新增或者修改内勤组-第一步-设置考勤类型和工作安排
  taskComShiftPage //获取班次分页查询
} from '../../services/api';

import './ThiftManagement.less';

const FormItem = Form.Item;
const { Step } = Steps;
const weekend = {
  1: '星期一',
  2: '星期二',
  3: '星期三',
  4: '星期四',
  5: '星期五',
  6: '星期六',
  7: '星期日'
};
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 7 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 10 }
  }
};

const selectedRowKeysall = ['1', '2', '3', '4', '5', '6', '7'];

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

const dataSource1 = [
  {
    key: '1',
    weekDay: '1',
    detail: '休息',
    option: '选择班次',
    shiftId: '',
    isRest: '1'
  },
  {
    key: '2',
    weekDay: '2',
    detail: '休息',
    option: '选择班次',
    shiftId: '',
    isRest: '1'
  },
  {
    key: '3',
    weekDay: '3',
    detail: '休息',
    option: '选择班次',
    shiftId: '',
    isRest: '1'
  },
  {
    key: '4',
    weekDay: '4',
    detail: '休息',
    option: '选择班次',
    shiftId: '',
    isRest: '1'
  },
  {
    key: '5',
    weekDay: '5',
    detail: '休息',
    option: '选择班次',
    shiftId: '',
    isRest: '1'
  },
  {
    key: '6',
    weekDay: '6',
    detail: '休息',
    option: '选择班次',
    shiftId: '',
    isRest: '1'
  },
  {
    key: '7',
    weekDay: '7',
    detail: '休息',
    option: '选择班次',
    shiftId: '',
    isRest: '1'
  }
];

@connect(state => ({
  profile: state.profile
}))
@Form.create()
export default class SelectionAttendanceType extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      open: false, //固定--添加班次
      attendType: '1',
      attendGroupId: gup('attendGroupId') || '',
      midAttendGroupId: gup('midAttendGroupId') || '',
      isFormal: gup('isFormal') || '',
      isFollowLegalHoliday: '0',
      comAttendGroupFixeds: dataSource1.map(val => {
        const obj = { ...val };
        return obj;
      }),
      selectedRowKeys: [],
      radioSelectedRows: {}, //当前选种的班次
      isinit: true, //是否是新增
      taskComShiftPage: [], //所有班次
      currentkey: '', //当前工作日的key
      defaultClick: false, //是否设置默认班次
      // 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
      // }
      //分页配置
      pageParm: {
        //数据请求 分页信息
        pageNumber: '1',
        pageSize: '10',
        current: 1
        // showTotal: total => `总共 ${total} 条`,
      },
      pagination: {
        showQuickJumper: true,
        pageSizeOptions: ['5', '10', '15', '25', '50'],
        showSizeChanger: true,
        onChange: this.onPaginationChange,
        onShowSizeChange: this.onPaginationShowSizeChange
      }
    };
  }

  /*
固定班制---设置出勤班次 */
  columns1 = [
    {
      title: '工作日',
      dataIndex: 'weekDay',
      key: '2',
      render: text => {
        return weekend[text];
      },
      width: 100
    },
    {
      title: '班次详情',
      dataIndex: 'detail',
      key: '3',
      render: text => {
        let val = text;
        if (text === '') {
          val = '休息';
        }
        return <div dangerouslySetInnerHTML={{ __html: val }} />;
      }
    },
    // {
    //   title: '操作',
    //   dataIndex: 'option',
    //   key: '4',
    //   render: (text, record) => {
    //     return (
    //       <div
    //         onClick={() => {
    //           this.setState({
    //             currentkey: record.key,
    //             open: true,
    //             defaultClick: false
    //           });
    //         }}
    //         style={{ color: 'rgba(15,113,255,1)' }}
    //       >
    //         选择班次
    //       </div>
    //     );
    //   },
    //   width: 80
    // }
  ];
  /* 选择班次--drawer */
  columns4 = [
    {
      key: '1',
      title: '班次名称',
      dataIndex: 'shiftName',
      render: text => <span>{text}</span>,
      width: 100
    },
    {
      key: '2',
      title: '出勤时间',
      dataIndex: 'shiftRuleTime',
      render: text => {
        return <div dangerouslySetInnerHTML={{ __html: text }} />;
      }
    }
  ];

  componentDidMount() {
    // window.initialize = this.initializeMap;
    this.taskComShiftPage();
    this.taskAttendanceComAttendGroupInFirstStepAttendGroup();
  }

  //页码改变
  onPaginationChange = (page, pageSize) => {
    const { pageParm, pagination } = {
      ...this.state
    };

    pageParm.pageNumber = page;
    pagination.current = page;

    this.setState({ pageParm, pagination });
    this.taskComShiftPage();
  };

  //pageSize 变化的回调
  onPaginationShowSizeChange = (current, size) => {
    const { pageParm, pagination } = {
      ...this.state
    };
    //切换每页显示多少条记录的时候，重置为第一页。重新排版 table
    pageParm.pageSize = size;
    pageParm.pageNumber = 1;
    pagination.current = 1;
    this.setState({ pageParm, pagination });
    this.taskComShiftPage();
  };

  //提交的时候进行判断
  taskAttendanceComAttendGroupSaveFirstStepAttendGroup = () => {
    let timeArray=[];
    let isSuccent = true;
    const {
      attendType,
      midAttendGroupId,
      isFollowLegalHoliday = '0',
      attendGroupName,
      comAttendGroupFixeds,
      attendGroupId
    } = this.state;
    if (
      !comAttendGroupFixeds.some(val => {
        return val.isRest === '0';
      })
    ) {
      message.error('班次至少要有一次');
      return;
    }

    //班次时间出现冲突
    comAttendGroupFixeds.map((item,index)=>{
      const time = item.time;
      if(item.detail!=='休息' && time !== undefined){
        const length = time.length;
        if(time.indexOf("次日")>0){
          timeArray.push({
            start:Number(time.substring(0,2))*60 + Number(time.substring(3,5)),
            end:Number(time.substring(length-6,length-4))*60 + Number(time.substring(length-3,length-1)),
            next:'次日'
          });
        }else{
            timeArray.push({
            start:Number(time.substring(0,2))*60 + Number(time.substring(3,5)),
            end:Number(time.substring(length-6,length-4))*60 + Number(time.substring(length-3,length-1)),
            next:''
          });
        }
      }else{
        timeArray.push({
          start:''
        });
      }
    });
    timeArray.map((item,index)=>{
      if(index!== 6){//不是周日
        if(item.start!==''&& timeArray[index+1].start!==''){//当前和下一个不是休息时间对比
          if(item.next && item.end > timeArray[index+1].start){
            const weekend = index===0 ?'一':index === 1?'二':index === 2? '三':index === 3? '四': index === 4? '五': index === 5? '六': index === 6? '日':'';
            const weekend1 = index+1 ===1 ?'二':index+1 === 2? '三':index+1 === 3? '四': index+1 === 4 ? '五': index+1 === 5? '六': index+1 === 6? '日':'';
            message.error(`星期${weekend}和星期${weekend1}的排班班次出现冲突，请重新设置`);
            isSuccent = false;
            return;
          }
        }
      } else {
        if(item.start!==''&& timeArray[0].start !==''){//周日跟周一对比
          if(item.next && item.end > timeArray[0].start){
            message.error(`星期日和星期一的排班班次出现冲突，请重新设置`);
            isSuccent = false;
            return;
          }
        }
      }
    });

    if(isSuccent){
       taskAttendanceComAttendGroupSaveFirstStepAttendGroup({
      attendType,
      midAttendGroupId,
      isFollowLegalHoliday,
      attendGroupName,
      attendGroupId,
      comAttendGroupFixeds: JSON.stringify(comAttendGroupFixeds)
    })
      .then(res => {
        this.props.history.push(
          `/attendancemanagement/newattendanceunit/choosewayattendance?attendGroupId=${
            res.data.attendGroupId
          }&midAttendGroupId=${res.data.midAttendGroupId}`
        );
      })
      .catch(err =>
        console.log(err, '新增或者修改内勤组-第一步-设置考勤类型和工作安排-err')
      );
    }
  };

  //新增内勤组-选择考勤类型-固定班制-详情
  taskAttendanceComAttendGroupInFirstStepAttendGroup = () => {
    taskAttendanceComAttendGroupInFirstStepAttendGroup({
      attendGroupId: this.state.attendGroupId,
      isFormal: this.state.isFormal,
      midAttendGroupId: this.state.midAttendGroupId
    }).then(
      response => {
        if (!('comAttendGroupFixeds' in response.data)) {
          return null;
        }
        let comAttendGroupFixeds = JSON.parse(
          response.data.comAttendGroupFixeds
        );

        const {
          attendType,
          midAttendGroupId,
          isFollowLegalHoliday,
          attendGroupName
        } = response.data;
        this.setState({
          attendType,
          midAttendGroupId,
          isFollowLegalHoliday,
          attendGroupName
        });

        const { setFieldsValue } = this.props.form;
        setFieldsValue({
          attendType,
          attendGroupName,
          isFollowLegalHoliday: isFollowLegalHoliday === '1' ? !0 : false
        });

        if (comAttendGroupFixeds.length > 0) {
          const selectedRowKeys = [];
          comAttendGroupFixeds = comAttendGroupFixeds.map(val => {
            val.key = val.weekDay + '';
            if (val.detail) {
              selectedRowKeys.push(val.weekDay + '');
            }
            return val;
          });
          this.setState(
            {
              isinit: false,
              comAttendGroupFixeds,
              selectedRowKeys
            },
            () => {
              this.setcomAttendGroupFixeds();
            }
          );
        } else {
          this.setState({
            isinit: true,
            comAttendGroupFixeds: dataSource1.map(val => {
              const obj = { ...val };
              return obj;
            })
          });
        }
      },
      err => {
        console.log(
          err,
          '新增内勤组-选择考勤类型-固定班制-详情-taskAttendanceComAttendGroupInFirstStepAttendGroup-err'
        );
      }
    );
  };
  //获取班次分页查询
  taskComShiftPage = () => {
    taskComShiftPage({
      // pageSize: 5000,
      // pageNumber: 1,
      ...this.state.pageParm,
      shiftType: this.state.attendType
    }).then(
      response => {
        const taskComShiftPagedata = response.data.data.map((val, i) => {
          val.key = i;
          return val;
        });
        const { pagination } = this.state;
        pagination.total = response.data.total;

        this.setState({
          pagination
        });
        this.setState({ taskComShiftPage: taskComShiftPagedata });
      },
      err => {
        console.log(err, '获取班次分页查询-taskComShiftPage-err');
      }
    );
  };

  //设置班次的值
  setbangchi = () => {
    const { comAttendGroupFixeds, radioSelectedRows, currentkey } = this.state;
    let { selectedRowKeys } = this.state;
    selectedRowKeys.push(currentkey);
    selectedRowKeys = Array.from(new Set(selectedRowKeys));
    comAttendGroupFixeds[currentkey - 1].detail = `${
      radioSelectedRows['shiftName']
    }：${radioSelectedRows['shiftRuleTime']}`;
    comAttendGroupFixeds[currentkey - 1].shiftId = radioSelectedRows['shiftId'];
    comAttendGroupFixeds[currentkey - 1].isRest = '0';

    comAttendGroupFixeds[currentkey - 1].time = `${radioSelectedRows['shiftRuleTime']}`;//只放时间
    this.setState({
      comAttendGroupFixeds,
      open: false,
      selectedRowKeys: selectedRowKeys.sort()
    });
  };
  //设置默认班次的值
  setbangchi1 = () => {
    const { radioSelectedRows } = this.state;
    let { comAttendGroupFixeds } = this.state;

    comAttendGroupFixeds = selectedRowKeysall.map(val => {
      comAttendGroupFixeds[val - 1].detail = `${
        radioSelectedRows['shiftName']
      }：${radioSelectedRows['shiftRuleTime']}`;
      comAttendGroupFixeds[val - 1].shiftId = radioSelectedRows['shiftId'];
      comAttendGroupFixeds[val - 1].isRest = '0';

      comAttendGroupFixeds[val - 1].time = `${radioSelectedRows['shiftRuleTime']}`;//只放时间
 
      return comAttendGroupFixeds[val - 1];
    });
    this.setState({
      comAttendGroupFixeds,
      selectedRowKeys: ['1', '2', '3', '4', '5', '6', '7'],
      open: false
    });
  };

  //设置comAttendGroupFixeds 表单的值
  setcomAttendGroupFixeds = () => {
    const { comAttendGroupFixeds, isinit } = this.state;
    const { setFieldsValue } = this.props.form;
    const comAttendGroupFixeds1 = comAttendGroupFixeds.map(val => {
      const ob = {};
      ob.isRest = val.shiftId === '' ? '1' : '0';
      ob.weekDay = val.weekDay;
      ob.shiftId = val.shiftId;
      if (!isinit) {
        ob.attendGroupFixedId = val.attendGroupFixedId || '';
        ob.attendGroupId = val.attendGroupId || '';
      }
      return ob;
    });
    setFieldsValue({
      comAttendGroupFixeds: JSON.stringify(comAttendGroupFixeds1)
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    this.setcomAttendGroupFixeds();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.taskAttendanceComAttendGroupSaveFirstStepAttendGroup();
      }
    });
  };

  /* 固定上班次 */
  fixedShiftRender = () => {
    const { getFieldDecorator } = this.props.form;
    //编辑页面不显示操作字段，新建时候显示
    let column = [...this.columns1];
    this.state.attendGroupId === '' ? column.push({
      title: '操作',
        dataIndex: 'option',
        key: '4',
        render: (text, record) => {
          return (
            <div
              onClick={() => {
                this.setState({
                  currentkey: record.key,
                  open: true,
                  defaultClick: false
                });
              }}
              style={{ color: 'rgba(15,113,255,1)' }}
            >
              选择班次
            </div>
          );
        },
        width: 80
    }) : column[0].width=200;
    return (
      <FormItem {...formItemLayout} label="工作安排">
        {getFieldDecorator('comAttendGroupFixeds', {
          rules: [
            {
              required: true,
              message: '请选择'
            }
          ]
        })(
          <div>
          {//编辑页面不显示，新建时候显示
            this.state.attendGroupId === '' ?
            <Button
              onClick={() => {
                this.setState({ open: true, defaultClick: true });
              }}
              style={{ marginBottom: 16 }}
              type="primary"
              ghost
            >
              批量安排班次
            </Button>:''
            }
            <Table
              size="middle"
              rowSelection={
                //编辑页面不显示选择项，新建时候显示
                this.state.attendGroupId === '' ?
                {
                onChange: (selectedRowKeys, selectedRows) => {
                  const { comAttendGroupFixeds } = this.state;

                  selectedRowKeysall.forEach(val => {
                    if (selectedRowKeys.indexOf(val) === -1) {
                      comAttendGroupFixeds[val - 1].detail = '休息';
                      comAttendGroupFixeds[val - 1].shiftId = '';
                      comAttendGroupFixeds[val - 1].isRest = '1';
                    }
                  });
                  this.setState({
                    selectedRowKeys: selectedRowKeys.sort(),
                    comAttendGroupFixeds
                  });
                },
                getCheckboxProps: record => {
                  return {
                    disabled: record.isRest === '1' ? !0 : false // Column configuration not to be checked
                  };
                },
                selectedRowKeys: this.state.selectedRowKeys.filter(val => {
                  const { comAttendGroupFixeds } = this.state;
                  if (comAttendGroupFixeds[val - 1]) {
                    return comAttendGroupFixeds[val - 1].isRest === '0';
                  }
                  return false;
                })
              }:null
            }
              pagination={false}
              columns={column}
              dataSource={this.state.comAttendGroupFixeds}
            />
          </div>
        )}
      </FormItem>
    );
  };

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="CreateTask ThiftManagement">
        <div className="card-breadcrumb" style={{ marginRight: 25 }}>
          <Breadcrumb
            style={{ borderBottom: '1px solid #E9E9E9', paddingBottom: '10px' }}
          >
            <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>
                内勤组排班班次规则设置后，不可变更；若需要调整，请新建内勤组。
              </div>
            }
            type="warning"
            showIcon
            style={{ marginBottom: '15px' }}
          />
          <Steps current={0}>
            <Step title="选择考勤类型" />
            <Step title="考勤地点" />
            <Step title="设置考勤人员" />
            <Step title="完成" />
          </Steps>
        </div>
        <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
          <FormItem {...formItemLayout} label="内勤组名称">
            {getFieldDecorator('attendGroupName', {
              initialValue: this.state.attendGroupName,
              rules: [
                {
                  required: true,
                  message: '请输入'
                },
                { max: 25, message: '已超出25个' }
              ]
            })(
              <Input
                onChange={e => {
                  this.setState({ attendGroupName: e.target.value });
                }}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="选择出勤类型">
            {getFieldDecorator('attendType', {
              initialValue: this.state.attendType,
              rules: [
                {
                  required: true,
                  message: '请选择'
                }
              ]
            })(
              <Radio.Group>
                <Radio className="radioStyle" value="1">
                  固定班制（每周考勤模式一致）
                  <span className="exclamation">
                    <Icon type="exclamation-circle" />
                    适用于每周考勤固定的团队和部门。
                  </span>
                </Radio>
              </Radio.Group>
            )}
          </FormItem>
          {/* 固定班次 */}
          {this.fixedShiftRender()}
          <FormItem {...formItemLayout} label=" " colon={false}>
            {getFieldDecorator('isFollowLegalHoliday', {
              valuePropName: 'checked'
            })(
              <Checkbox
                onChange={e => {
                  this.setState({
                    isFollowLegalHoliday: e.target.checked ? '1' : '0'
                  });
                }}
                disabled={this.state.attendGroupId === ''? false : true}
              >
                是否遵循法定假日
              </Checkbox>
            )}
          </FormItem>
          <FormItem {...submitFormLayout} style={{ marginTop: 24 }}>
            <Button
              onClick={() => {
                this.props.history.push(
                  '/attendancemanagement/newattendanceunit'
                );
              }}
              loading={submitting}
            >
              取消
            </Button>
            <Button type="primary" style={{ marginLeft: 8 }} htmlType="submit">
              确认并进行下一步
            </Button>
          </FormItem>
        </Form>
        {/* 固定班次--选择班次*/}
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          placement="right"
          visible={this.state.open}
          zIndex={11}
          title="选择默认班次"
          width={600}
          onChange={open => {
            this.setState({ open });
          }}
          onClose={() => {
            this.setState({
              open: false
            });
          }}
        >
          <div>
            {/* <div className="drawer-header"> */}
              {/* 选择默认班次 */}
              {/* <Button type="primary" onClick={() => this.setState({ open3: true, open: false })} ghost>新增班次</Button> */}
            {/* </div> */}
            <div className="drawer-content">
              <Table
                rowSelection={{
                  type: 'radio',
                  onChange: (selectedRowKeys, radioSelectedRows) => {
                    this.setState({ radioSelectedRows: radioSelectedRows[0] });
                  }
                }}
                // pagination={false}
                pagination={this.state.pagination}
                columns={this.columns4}
                dataSource={this.state.taskComShiftPage}
              />
            </div>
            <div className="drawer-footer">
              <Button
                onClick={() => {
                  this.setState({
                    open: false
                  });
                }}
                style={{ marginRight:'8px' }}
              >
                取消
              </Button>
              <Button
                onClick={() => {
                  if ('shiftTypeName' in this.state.radioSelectedRows) {
                    this.state.defaultClick
                      ? this.setbangchi1()
                      : this.setbangchi();
                  } else {
                    message.error('请选择班次');
                  }
                }}
                type="primary"
              >
                确定
              </Button>
            </div>
          </div>
        </Drawer>
      </div>
    );
  }
}
