import React from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Calendar,TimePicker, Badge, Select, Button, Modal, Table } from 'antd';
import styles from './ProductCalendarPage.css';
import {  guid, extendRule, extendOrder,  initQueryFilter,  extendInclude} from "../../../utils/common";
import {message} from "antd/lib/index";
import storage from "../../../utils/storage";
const Option = Select.Option;
class CalendarPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      CurrentMonthFirstDay:moment(new Date()).startOf('month').format("YYYY-MM-DD"),
      CurrentMonthLastDay:moment(new Date()).endOf('month').format("YYYY-MM-DD"),
      CurrentMonthList: [],
      currentData:'',
      CalendarModelList:[],
      WorkStageList:[],
      CurrentWorkStageId:'',
      CurrentCalendarId:null,
      visible: false,
      dataSource: [],
      odlDayListData:[],
      classList:[],
    };
  };

  getClassList=()=>{
    const orgId = storage('lacal').getItem('webOrgId').val;
    let json = initQueryFilter(orgId, 1, 100, "CREATE_TIME", 0);
    extendRule(json, "ENABLE_STATUS", 1, 0);//过滤启用状态

    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'FM/Class/OrderPaged',
      payload: json,
      onComplete: (ret) => {
        this.setState({
          classList:ret
        })
      }
    })
  };
  loadWorkStageData=()=> {//取工作中心
    const orgId = storage('lacal').getItem('webOrgId').val;
    let json= initQueryFilter(orgId, 1, 100, "NAME", 0);
    extendRule(json,"TYPE",1,0);
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'FM/WorkStage/OrderEntities',
      payload: json,
      onComplete: (ret) => {
        this.setState({
            WorkStageList: ret,
            CurrentWorkStageId:ret[0]?ret[0].ID:''
            },
       ()=>
         this.LoadDailyData()
      )}
    });

  };
  LoadDailyData=(callBack)=> { //取每日工作时间数据
    if(!this.state.CurrentWorkStageId)return;
    const orgId = storage('lacal').getItem('webOrgId').val;
    let json = initQueryFilter(orgId, 1, 100, "START_TIME", 0);
    extendOrder(json,"NUM",0);
    extendRule(json, "WORKSTAGE_ID",1,this.state.CurrentWorkStageId);
    extendRule(json, "START_TIME",6,this.state.CurrentMonthFirstDay+' 00:00:00');
    extendRule(json, "START_TIME",4,this.state.CurrentMonthLastDay+' 23:59:59');
    extendInclude(json,"Nav_Class.Nav_ClassDetail");
    //extendRule(json, "IS_DEFAULT_QUERY", 1, true);
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'FM/WorkStageCalendar/OrderEntities',
      payload: json,
      onComplete: (ret) => {
        this.setState({
          CurrentMonthList: ret
        },()=>{
          if(callBack&&typeof callBack=="function"){
            // console.log(this.curDay);
            // callBack(this.curDay);
          }
        });
      }
    });
  }

  LoadCalendarData=()=> { //获取日历模板的数据
    const orgId = storage('lacal').getItem('webOrgId').val;
    let json = initQueryFilter(orgId, 1, 100, "CREATE_TIME", 0);
    extendRule(json, "ENABLE_STATUS", 1, 0);//过滤启用状态
    extendInclude(json,"Nav_CalendarClass.Nav_Class.Nav_ClassDetail");
    //extendInclude(json,"Nav_Class");
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'FM/Calendar/OrderPaged',
      payload: json,
      onComplete: (ret) => {
        if(ret) {
          this.setState({
            CalendarModelList: ret

          });
        }
      }
    });
  }
  componentDidMount() {
    this.loadWorkStageData()
    this.getClassList()
  }

  getListData=(value)=>{
    let listData=[];
    if(this.state.CurrentMonthList) {
      this.state.CurrentMonthList.forEach(v => {
        if (v.DATE.slice(0, 10) == value.format("YYYY-MM-DD")) {
          listData.push({
            type:v.ENABLE_STATUS==1? 'default':'success',
            content: (v.Nav_Class ? v.Nav_Class.NAME : '') + ':' + v.START_TIME.slice(11, 19) + '-' + v.END_TIME.slice(11, 19)
          });
        }
      });
    }

    return listData || [];
  }
  dateCellRender=(value)=>{
    const listData = this.getListData(value);
    return (
      <ul className={styles.events}>
        {
          listData.map(item => (
            <li key={item.content} style={{ listStyle: 'none'}}>
              <Badge status={item.type} text={item.content} />
            </li>
          ))
        }
      </ul>
    );
  }

  getMonthData=({value})=>{
    if (value.month() === 8) {
      return 1394;
    }
  }

  monthCellRender=({value})=>{
    const num = this.getMonthData(value);
    return num ? (
      <div className="notes-month">
        <section>{num}</section>
        <span>Backlog number</span>
      </div>
    ) : null;
  };
  onPanelChange=(date, mode)=>{
    this.setState({
      CurrentMonthFirstDay:moment(date).startOf('month').format("YYYY-MM-DD"),
      CurrentMonthLastDay:moment(date).endOf('month').format("YYYY-MM-DD"),
    }, () => {
      this.LoadDailyData();
    })
  };

  handleChange=(value)=>{
      //console.log(`selected ${value}`);
      this.setState({
        CurrentWorkStageId:value,
      }, () => {
        this.LoadDailyData();
      });
  };
  handleCalendarChange=(value)=>{
    // console.log(value);
    // this.curDay=value;
    // console.log(this.curDay);
    const aArr = [];
    //const obj =this.state.odlDayListData&&this.state.odlDayListData.length? JSON.parse(JSON.stringify(this.state.odlDayListData[0])):{};//复制一份班次对象
   // console.log(`selected ${value}`); //选择的日历模板的数据填充到表格中
    if(this.state.CalendarModelList) {
      this.state.CalendarModelList.forEach(v => {
        if (v.ID == value) {
          v.Nav_CalendarClass.forEach(c => {
            c.Nav_Class.Nav_ClassDetail.forEach(d => {
              //根据选择的模板里面班次的个数 循环复制的班次对象 并修改里面每一份的CLASS_ID、ID
              aArr.push({
                CLASS_ID: c.CLASS_ID,
                ID: guid(),
                WORKSTAGE_ID: this.state.CurrentWorkStageId,
                ORG_ID: storage('lacal').getItem('webOrgId').val,
                DATE: this.state.currentData,
                START_TIME: d.STARTTIME.slice(11, 19),
                END_TIME: d.ENDTIME.slice(11, 19),
                CURR_TIME: d.STARTTIME.slice(11, 19),
                ENABLE_STATUS:c.ENABLE_STATUS,
              })
            })
          })
        }
      })
    }

    const odlDayListData=[...this.state.odlDayListData];
    odlDayListData.forEach((n,i)=>{
      n.IS_DELETED = true;
    });

    this.setState({
      dataSource: aArr,
      odlDayListData,
      CurrentCalendarId:value,
    })
  };
  handleModal = (e) => {
    if(!this.state.CurrentWorkStageId){
      message.error('请设置工作中心');
      return;
    }

    if(!this.state.classList||!this.state.classList.length){
      message.error('请新增班次数据');
      return;
    }

    this.setState({
      visible: true
    }, () => {
      let listData=[];
      let dayListData=[];
      let currentData=e.format("YYYY-MM-DD");
      if(this.state.CurrentMonthList) {
        this.state.CurrentMonthList.forEach(v => {
          if (v.DATE.slice(0, 10) == e.format("YYYY-MM-DD")) {
            dayListData.push(v);
            listData.push({
              ...v,
              key: v.ID,
              CLASS_ID: v.CLASS_ID,
              CLASS_NAME: v.Nav_Class.NAME,
              START_TIME: v.START_TIME.slice(11, 19),
              END_TIME: v.END_TIME.slice(11, 19),
              DATE: v.DATE.toString().substring(0, 10)
            })
          }
        });
      }

      this.setState({
        dataSource: listData,
        odlDayListData:dayListData,
        currentData:currentData,
        CurrentCalendarId:null
      })
      this.LoadCalendarData();
    })
  };
  modalCancel = () => { //保存，退出，刷新
    this.setState({
      visible: false,
      odlDayListData:[]
    })

  };
  modalOk = (e) => {
      this.postData( 'FMWorkStageCalendar/batchUpdate');
  };

  postData=(type)=>{
    let data=[];
    const dataSource=[...this.state.dataSource];
    const odlDayListData=[...this.state.odlDayListData];
    let isError=false;
    if(dataSource&&dataSource.length){
      dataSource.forEach((n,i)=>{
        let isSave=true;
        if(odlDayListData&&odlDayListData.length){
          odlDayListData.forEach((n1,i1)=>{
            if(n1.ID==n.ID){
              if(n1.IS_DELETED){
                isSave=false;
              }
            }
          });
        }
        if(isSave){
          if(!n.START_TIME){
            message.error('请填写开始时间');
            isError=true;
          }

          if(!n.END_TIME){
            message.error('请填写结束时间');
            isError=true;
          }

          if(!n.CLASS_ID){
            message.error('请填写班次');
            isError=true;
          }

          n.START_TIME=(n.DATE?n.DATE:this.state.currentData)+' '+n.START_TIME;
          n.END_TIME=(n.DATE?n.DATE:this.state.currentData)+' '+n.END_TIME;
          n.CURR_TIME=n.START_TIME;
          n.Nav_Class=null;
          data.push(n);
        }
      });
    }
    if(odlDayListData&&odlDayListData.length) {
      odlDayListData.forEach((n1, i1) => {
        if (n1.IS_DELETED) {
          n1.Nav_Class=null;
          data.push(n1);
        }
      });
    }
    if(isError)return;

    const {dispatch} = this.props;
    dispatch({
      type:type,
      payload: {Nav_WorkstageCalendars:data},
      onComplete: (ret) => {
        if(ret) {
          message.success('执行成功');
          this.setState({
            visible: false,
          },()=>{
            this.LoadDailyData();
          });
        }
      }
    });
  }

  applyAll = () => {
    this.postData( 'FMWorkStageCalendar/allUpdate');
  };

  handleAdd = () => {
    const { dataSource } = this.state;
    const newData = {
      ID: guid(),
      WORKSTAGE_ID:this.state.CurrentWorkStageId,
      CLASS_ID:'',
      ORG_ID:storage('lacal').getItem('webOrgId').val,
      START_TIME:moment(new Date()).format( 'HH:mm:ss'),
      END_TIME: moment(new Date()).format( 'HH:mm:ss'),
      DATE:this.state.currentData,
    };
    this.setState({
      dataSource: [...dataSource, newData],
    });
  }

  handleEnable = () => {
    this.changeStatus('FM/WorkStageCalendar/Enable');
  }

  handleDisable = () => {
    this.changeStatus('FM/WorkStageCalendar/Disable');
  }

 changeStatus=(url)=>{
   const orgId = storage('lacal').getItem('webOrgId').val;
   let json = initQueryFilter(orgId);
   json["Keyword"]=this.state.CurrentWorkStageId;
   json["Parameter1"]=this.state.currentData;
   this.props.dispatch({
     type: 'app/getDataByPost',
     url: url,
     payload: json,
     onComplete: (ret) => {
       if(ret) {
         this.LoadDailyData();
       }
     }
   });
 }

  handleCalenderDisabledDate=(currentDate)=> {
    if (!this.state.CurrentMonthFirstDay || !this.state.CurrentMonthLastDay) return false;
    if ((moment(this.state.CurrentMonthFirstDay).isBefore(currentDate, 'day') && currentDate.isBefore(moment(this.state.CurrentMonthLastDay), 'day')) ||
      currentDate.isSame(moment(this.state.CurrentMonthFirstDay), 'day') || currentDate.isSame(moment(this.state.CurrentMonthLastDay), 'day')) {
      return false;
    }
    return true;
  }


  render() {

    const changeClass=(id,field,value)=>{
      if(this.state.dataSource&&this.state.dataSource.length){
        const dataSource=[...this.state.dataSource] ;
        dataSource.forEach((n,i)=>{
          if(n.ID==id){
            n[field]=value;
          }
        })
        this.setState({dataSource});
      }
    }

    const colClass=(text,record,index)=>{
      return <Select
        style={{ width: 100 }}
        placeholder='选择班次'
        optionFilterProp="children"
        value={record.CLASS_ID}
        onChange={(e)=>{changeClass(record.ID,'CLASS_ID',e)}}
        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
      >
        {//map 循环 填充下拉项目
          this.state.classList.map(item => {
            return <Option key={item.ID} value={item.ID}>{item.NAME}</Option>
          })
        }
      </Select>;
    }



    const classColumns=[
      {title: '当前日期', dataIndex: 'DATE', key: 'DATE',render:(text,record,index)=>{if(text)return text.toString().substring(0,10); }},
      {title:<div> <span style={{color:'red'}}>*</span>班次</div> , dataIndex: '', key: '', render: colClass},
      {title:<div> <span style={{color:'red'}}>*</span>开始时间</div>  , dataIndex: '', key: '', render: ( text, record, index)=>{
          return  <TimePicker value={record.START_TIME?moment(record.START_TIME, 'HH:mm:ss'):null}  onChange={(mom, dateString) => changeClass(record.ID, 'START_TIME', dateString)} />;
        }},
      {title: <div> <span style={{color:'red'}}>*</span>结束时间</div> , dataIndex: '', key: '', render: ( text, record, index)=>{
          return  <TimePicker value={record.END_TIME?moment(record.END_TIME, 'HH:mm:ss'):null}  onChange={(mom, dateString) => changeClass(record.ID, 'END_TIME', dateString)} />;
        }},
      {title: '', dataIndex: '', key: '', render: ( text, record, index)=>{
          const deleteRecord=()=>{
            const dataSource=[] ;
            var tempdate=[...this.state.odlDayListData];
            if(this.state.dataSource) {
              this.state.dataSource.forEach((n, i) => {
                if (n.ID != record.ID) {
                  dataSource.push(n);
                }
                else{
                  let isGet=false;
                  tempdate.forEach((n1,i1)=>{
                    if(n1.ID==record.ID){
                      isGet=true;
                      n1.IS_DELETED=true;
                    }
                  })
                  if(!isGet){
                    n.IS_DELETED=true;
                    tempdate.push(n);
                  }
                }
              })
            }
            this.setState({dataSource,odlDayListData:tempdate});
          }
          return <Button type={'danger'} onClick={deleteRecord}  icon={'delete'}></Button>
        }},
      {title: <div> <span style={{color:'red'}}>*</span>状态</div> , dataIndex: '', key: '', render: ( text, record, index)=>{
          return  record.ENABLE_STATUS==1?"未启用":"已启用";
        }},
    ]

    return (
      <div>
        <Modal visible={this.state.visible} maskClosable={false} width={"60%"} onCancel={this.modalCancel} onOk={this.modalOk}>
          <div style={{textAlign:"left"}}>

            <Select
              showSearch
              style={{ width: 200 }}
              placeholder='选择日历模板'
              optionFilterProp="children"
              value={this.state.CurrentCalendarId}
              onChange={this.handleCalendarChange}
              filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
              {//map 循环 填充下拉项目
                this.state.CalendarModelList.map(item => {
                  return <Option key={item.ID} value={item.ID}>{item.NAME}</Option>
                })
              }
            </Select>
          </div>
          <hr/>
          <Button onClick={this.handleAdd} type="primary" icon="plus-circle-o">新增</Button>
          <Button onClick={this.handleEnable} type="default" icon="check-square">启用</Button>
          <Button onClick={this.handleDisable} type="danger" icon="close-square-o">禁用</Button>
          <Button onClick={this.applyAll} type="danger" icon="close-square-o">应用所有中心</Button>
          <Table
            rowKey="ID"
            pagination={false}
            dataSource={this.state.dataSource}
            columns={classColumns}
          />

        </Modal>
        <div style={{textAlign:"right"}}>
          <label >选择工作中心: </label>
          <Select
            showSearch
            style={{ width: 200 }}
            placeholder={'请选择工作中心'}//存在再复制
            optionFilterProp="children"
            value={this.state.CurrentWorkStageId}
            onChange={this.handleChange}
            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >
            {//map 循环 填充下拉项目
              this.state.WorkStageList.map(item => {
                return <Option key={item.ID} value={item.ID}>{item.NAME}</Option>
              })
            }
          </Select>
        </div>
        <Calendar dateCellRender={this.dateCellRender} onSelect={this.handleModal} onPanelChange={this.onPanelChange} disabledDate={this.handleCalenderDisabledDate} />
      </div>
    );
  }
}

export default connect()(CalendarPage);
