import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { Form, Select, Checkbox } from 'amos-framework';
import { Select as SelectAntd, DatePicker } from 'amos-antd';
import { queryPlanDetByIdAction, queryPlanByOrgNoPageAction } from '../../../../services/checkService';
import '../../../../styles/view/patrol/planTaskReGenTable.scss';
import YearPicker from '../../../common/YearPicker';

const FormItem = Form.Item;
const Option = Select.Option;
const OptionAntd = SelectAntd.Option;
const CheckboxGroup = Checkbox.Group;

const { WeekPicker, MonthPicker } = DatePicker;

/**
 * 重做计划执行
 */

class PlanTaskReGenTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchParam: [],
      cicleArry: [],
      form: {
        planId: '',
        changeFlag: '0',
        interval: null,
        repeatYear: moment().format('YYYY'),
        beginDate: moment().format('YYYY-MM-DD'),
        endDate: moment().format('YYYY-MM-DD')
      },
      plan: {},
      planData: [],
      rules: {
        planId: [{ required: true, message: '请选择重做计划名称' }],
        beginDate: [{ required: true, message: '请选择重做开始日期' }],
        endDate: [{ required: true, message: '请选择重做结束日期' }]
      }
    };
  }

  componentWillMount = () => {
    let { searchParam , form } = this.state;
    let { planId } = this.props;
    form.planId = planId;
    this.queryPlanByOrgNoPage(searchParam);
    this.setState({ form });
    this.queryPlanDetail(planId);
  }

  componentDidMount() {

  }

  componentWillUnmount() {

  }

  onDateChange = (key, date) => {
    const { form } = this.state;
    let { callBack } = this.props;
    form[key] = moment(date).format('YYYY-MM-DD');
    this.setState({ form });
    if (void 0 !== callBack) {
      callBack(form);
    }
  }

  onYearChange =(key,date) =>{
    const { form, plan } = this.state;
    form[key] = date;
    let cicleArry = this.calueCicleData(form[key],plan);
    form.beginDate = moment(date + '0101').startOf('year').format('YYYY-MM-DD');
    form.endDate =  moment(date + '0101').endOf('year').format('YYYY-MM-DD');
    form.interval = 0;
    this.setState({ cicleArry,form });
  }

  onWeekDateChange = (key, date) => {
    const { form } = this.state;
    let { callBack } = this.props;
    if (key === 'beginDate') {
      form[key] = moment(date).startOf('week').format('YYYY-MM-DD');
    } else {
      form[key] = moment(date).endOf('week') > moment().endOf('day') ? moment().endOf('day').format('YYYY-MM-DD') : moment(date).endOf('week').format('YYYY-MM-DD');
    }
    this.setState({ form });
    if (void 0 !== callBack) {
      callBack(form);
    }
  }

  onMonthDateChange = (key, date) => {
    const { form } = this.state;
    let { callBack } = this.props;
    if (key === 'beginDate') {
      form[key] = moment(date).startOf('month').format('YYYY-MM-DD');
    } else {
      form[key] = moment(date).endOf('month') > moment().endOf('day') ? moment().endOf('day').format('YYYY-MM-DD') : moment(date).endOf('month').format('YYYY-MM-DD');
    }
    this.setState({ form });
    if (void 0 !== callBack) {
      callBack(form);
    }
  };

  onSelectChange = (key, value) => {
    const { form } = this.state;
    let { callBack } = this.props;
    form[key] = value;
    this.setState({ form });
    if (void 0 !== callBack) {
      callBack(form);
    }
  }

  onIntervalChange = (key, option) => {
    const { form } = this.state;
    let { callBack } = this.props;
    let { item } = option.props;
    form.beginDate = item.beginDate;
    form.endDate = item.endDate;
    form[key] = item.key;
    this.setState({ form });
    if (void 0 !== callBack) {
      callBack(form);
    }
  }

  onCheckboxChange = selects => {
    const { form } = this.state;
    let { callBack } = this.props;
    form.changeFlag = selects.join(',');
    this.setState({ form });
    if (void 0 !== callBack) {
      callBack(form);
    }
  }

  calueCicleData =(year,plan)=>{
    let cicleArry = [];
    const interval = 12/parseInt(plan.executeRate);
    cicleArry.push({
      key: 0,
      label: '全年',
      disabled: false,
      beginDate: moment(year + '0101').startOf('year').format('YYYY-MM-DD'),
      endDate: moment(year + '0101').endOf('year').format('YYYY-MM-DD')
    });
    if ( plan.executeRate > 1){
      for (let i = 1 ; i <= parseInt(plan.executeRate); i++) {
        let beginNum = interval*i-interval + 1;
        let endNum = interval*i;
        cicleArry.push({
          key: i,
          label: `${beginNum}月到${endNum}月`,
          disabled: false,
          beginDate: moment(year + ('0' + beginNum ).substring(('0' + beginNum).length - 2) + '01').startOf('month').format('YYYY-MM-DD'),
          endDate: moment(year + ('0' + endNum).substring(('0' + endNum).length - 2) + '01').endOf('month').format('YYYY-MM-DD')
        }
        );
      }
    }
    const today = moment().format('YYYY-MM-DD');
    let newArry = [];
    if (year < moment().get('year')) {
      return cicleArry;
    } else {
      newArry = cicleArry.map(item=>  {
        if (today < item.beginDate && item.key > 0 ) {
          item.disabled = true;
        }
        return item;
      });
    }
    if (cicleArry[cicleArry.length - 1].beginDate >= today) {
      cicleArry[0].disabled = true;
    }
    return newArry;
  }

  queryPlanByOrgNoPage = searchParam => {
    queryPlanByOrgNoPageAction(searchParam).then(data => {
      this.setState({ planData: data });
    });
  }

  queryPlanDetail = (planId) => {
    queryPlanDetByIdAction(planId).then(data => {
      if (void 0 !== data) {
        const { form } = this.state;
        let { callBack } = this.props;
        let cicleArry = [];
        if (void 0 !== data && data.planType && parseInt(data.planType) > 1) {
          if (parseInt(data.planType) === 2) {
            form.beginDate = moment(form.beginDate).startOf('week').format('YYYY-MM-DD');
            form.endDate = moment(form.endDate).endOf('week') > moment().endOf('day') ? moment().endOf('day').format('YYYY-MM-DD') : moment(form.endDate).endOf('week').format('YYYY-MM-DD');
          } else if (parseInt(data.planType) === 3) {
            form.beginDate = moment(form.beginDate).startOf('month').format('YYYY-MM-DD');
            form.endDate = moment(form.endDate).endOf('month') > moment().endOf('day') ? moment().endOf('day').format('YYYY-MM-DD') : moment(form.endDate).endOf('month').format('YYYY-MM-DD');
          } else if (parseInt(data.planType) === 4) {
            cicleArry = this.calueCicleData(form.repeatYear,data);
            let firstChecked = cicleArry.find(e=>e.disabled === false);
            form.beginDate = firstChecked.beginDate || '';
            form.endDate =  firstChecked.endDate || '';
            form.interval = firstChecked.key;
          }
        }
        this.setState({ plan: data, form, cicleArry });
        if (void 0 !== callBack) {
          callBack(form);
        }
      }
    });
  }

  disabledDate =(current)=> {
    return current && current >= moment().endOf('day');
  }

  disabledYear =(current)=> {
    return current && current > moment().year();
  }

  renderStartTime =()=> {
    const { plan, form } = this.state;
    if (void 0 !== plan && plan.planType && parseInt(plan.planType) > 1) {
      if (parseInt(plan.planType) === 2) {
        return <WeekPicker disabledDate={this.disabledDate}  value={moment(form.beginDate)} allowClear={false} onChange={e => this.onWeekDateChange('beginDate', e)} />;
      } else if (parseInt(plan.planType) === 3) {
        return <MonthPicker disabledDate={this.disabledDate}  value={moment(form.beginDate)} format="YYYY-MM" allowClear={false} onChange={e => this.onMonthDateChange('beginDate', e)} />;
      } else {
        return <DatePicker disabledDate={this.disabledDate}  value={moment(form.beginDate)} allowClear={false} onChange={e => this.onDateChange('beginDate', e)} />;
      }
    } else {
      return <DatePicker disabledDate={this.disabledDate}  value={moment(form.beginDate)} allowClear={false} onChange={e => this.onDateChange('beginDate', e)} />;
    }
  }

  renderRepeatYear =()=>{
    const { form } = this.state;
    return <YearPicker disabledDate={this.disabledYear}  value={form.repeatYear}  onChange={e => this.onYearChange('repeatYear', e)} ref={node =>this.yearPicker = node} />;
  }

  renderEndTime() {
    const { plan, form } = this.state;
    if (void 0 !== plan && plan.planType && parseInt(plan.planType) > 1) {
      if (parseInt(plan.planType) === 2) {
        return <WeekPicker disabledDate={this.disabledDate}  value={moment(form.endDate)} allowClear={false} onChange={e => this.onWeekDateChange('endDate', e)} />;
      } else if (parseInt(plan.planType) === 3) {
        return <MonthPicker disabledDate={this.disabledDate}  value={moment(form.endDate)} format="YYYY-MM" allowClear={false} onChange={e => this.onMonthDateChange('endDate', e)} />;
      } else {
        return <DatePicker disabledDate={this.disabledDate}  value={moment(form.endDate)} allowClear={false} onChange={e => this.onDateChange('endDate', e)} />;
      }
    } else {
      return <DatePicker disabledDate={this.disabledDate}  value={moment(form.endDate)} allowClear={false} onChange={e => this.onDateChange('endDate', e)} />;
    }
  }

  renderPlanType() {
    const { plan } = this.state;
    if (void 0 !== plan && plan.planType) {
      if (parseInt(plan.planType) === 1) {
        return <span>日任务</span>;
      } else if (parseInt(plan.planType) === 2) {
        return <span>周任务</span>;
      } else if (parseInt(plan.planType) === 3) {
        return <span>月任务</span>;
      } else if (parseInt(plan.planType) === 4) {
        return <span>年任务</span>;
      }
    }
  }

  render() {
    const { form, rules, planData, plan,cicleArry } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
        className: 'colspan'
      }
    };

    return (
      <div>
        <Form model={form} rules={rules} ref={component => (this.form = component)}>
          <FormItem label={<span>重做计划名称</span>} field="planId" {...formItemLayout}>
            <Select
              searchable
              disabled
              className="plan_task_gen_select"
              data={planData}
              renderOption={item => <Option value={item.id}>{item.name}</Option>}
              value={form.planId}
              onChange={e => this.onSelectChange('planId', e)}
            />
          </FormItem>
          <FormItem label={<span>任务类型</span>} field="planType" {...formItemLayout}>
            {this.renderPlanType()}
          </FormItem>
          {
            plan  && plan.planType && parseInt(plan.planType) < 4  ? (<FormItem label={<span>重做开始日期</span>} field="beginDate" {...formItemLayout}>
              {this.renderStartTime()}
            </FormItem>) : <FormItem label={<span>重做年份</span>} field="repeatYear" {...formItemLayout}> {this.renderRepeatYear()} </FormItem>
          }
          {
            plan && plan.planType && parseInt(plan.planType)  < 4  ?
            (<FormItem label={<span>重做结束日期</span>} field="endDate" {...formItemLayout}>
              {this.renderEndTime()}
            </FormItem>) : (<FormItem label={<span>重做区间</span>} field="interval" {...formItemLayout}>
              <SelectAntd
                className="plan_task_gen_select"
                value={form.interval ? form.interval : form.interval === 0 ? form.interval : undefined}
                placeholder='请选择重做区间'
                onSelect={(e,item) => this.onIntervalChange('interval', item)}
              >
                {cicleArry.map(d => (
                  <OptionAntd key={d.key} value={d.key} item={d} disabled={d.disabled}>{d.label}</OptionAntd>
                ))}
              </SelectAntd>
            </FormItem>)
          }
          <FormItem label={<span>全部计为合格</span>} field="changeFlag" {...formItemLayout}>
            <CheckboxGroup onChange={selects => this.onCheckboxChange(selects)}>
              <Checkbox value="1">是</Checkbox>
            </CheckboxGroup>
          </FormItem>
        </Form>
        <br />
        <strong style={{ color: '#ff0000' }}>您确定要重做计划执行么？</strong>
        <br />
        <p>1、计划的具体执行数据，是系统在前一日的23点自动生成的，计划调整后，如果不重做，当日及以前的执行数据不受任何影响。</p>
        <br />
        <p>2、重做后，系统将删除指定计划在指定时间段内的执行数据，巡检记录信息是保持不变的。</p>
        <br />
        <p>3、然后按照当前计划的设置参数，重新生成新的巡检计划执行数据，并重新统计漏检情况。</p>
        <br />
        <p>4、只能重做最近30天的计划执行数据。</p>
      </div>
    );
  }
}

PlanTaskReGenTable.propTypes = {
  callBack: PropTypes.func,
  planId: PropTypes.number
};

export default PlanTaskReGenTable;
