import React from 'react'
import { connect } from 'dva'
import moment from 'moment'
import { Calendar, Badge, Select, Button, Modal, Table, InputNumber } from 'antd'
import styles from './EDProRecordSchedulingPage.css'
import { LayoutCard } from '@woowalker/feui'
import { guid, extendRule, 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: [],
      WorkTeamList: [],
      WorkClassList: [],
      CurrentWorkStageId: '',
      CurrentWorkStageName: '',
      CurrentTeamId: '',
      CurrentTeamName: '',
      CurrentClassId: '',
      CurrentClassName: '',
      CurrentCalendarId: null,
      visible: false,
      dataSource: [],
      odlDayListData: [],
      classList: [],
      productList: [],
      nodeId: '',
      nodeName: ''
    }
  };


  loadWorkStageData = () => {//取生产单元
    const orgId = storage('lacal').getItem('webOrgId').val
    let json = initQueryFilter(orgId, 1, 1000, "NAME", 0)
    //  extendRule(json,"IS_PLAN",1,1);
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'BD/MeterNode/OrderEntities',
      payload: json,
      onComplete: (ret) => {
        this.setState({
          WorkStageList: ret,
          CurrentWorkStageId: ret[0] ? ret[0].ID : '',
          CurrentWorkStageName: ret[0] ? ret[0].NAME : ''
        },
          () =>
            this.LoadDailyData()
        )
      }
    })

  };
  loadWorkTeamData = () => {//取班组
    const orgId = storage('lacal').getItem('webOrgId').val
    let json = initQueryFilter(orgId, 1, 1000, "NAME", 0)
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'FM/Team/OrderPaged',
      payload: json,
      onComplete: (ret) => {
        this.setState({
          WorkTeamList: ret,
          CurrentTeamId: ret[0] ? ret[0].ID : '',
          CurrentTeamName: ret[0] ? ret[0].NAME : ''
        },
          () =>
            this.LoadDailyData()
        )
      }
    })

  };
  loadWorkClassData = () => {//取班别
    const orgId = storage('lacal').getItem('webOrgId').val
    let json = initQueryFilter(orgId, 1, 1000, "NAME", 0)
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'FM/Class/OrderPaged',
      payload: json,
      onComplete: (ret) => {
        this.setState({
          WorkClassList: ret,
          CurrentClassId: ret[0] ? ret[0].ID : '',
          CurrentClassName: ret[0] ? ret[0].NAME : ''
        },
          () =>
            this.LoadDailyData()
        )
      }
    })

  };
  loadProductData = () => {//取产品
    const orgId = storage('lacal').getItem('webOrgId').val
    let json = initQueryFilter(orgId, 1, 1000, "NAME", 0)
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'FM/Product/OrderPaged',
      payload: json,
      onComplete: (ret) => {
        this.setState({
          productList: ret
        }
        )
      }
    })

  };

  LoadDailyData = (callBack) => { //取每日工作时间数据
    this.setState({ nodeId: this.props.data.selectedNodes[0].node.id, nodeName: this.props.data.selectedNodes[0].node.name })
    if (!this.state.CurrentWorkStageId) return
    const orgId = storage('lacal').getItem('webOrgId').val
    let json = initQueryFilter(orgId, 1, 100, "START_TIME", 0)
    extendRule(json, "METER_NODE_ID", 1, this.props.data.selectedNodes[0].node.id)
    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_MeterNode")
    extendInclude(json, "Nav_Class")
    extendInclude(json, "Nav_Team")
    extendInclude(json, "Nav_Product")
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'ED/ProdRecord/OrderEntities',
      payload: json,
      onComplete: (ret) => {
        this.setState({
          CurrentMonthList: ret
        }, () => {
          if (callBack && typeof callBack == "function") {
          }
        })
      }
    })
  }



  componentDidMount() {
    this.loadWorkStageData()
    this.loadWorkTeamData()
    this.loadWorkClassData()
    this.loadProductData()
  }

  getListData = (value) => {
    let listData = []
    let listSumData = []
    let listResult = []
    if (this.state.CurrentMonthList) {
      this.state.CurrentMonthList.forEach(v => {
        if (v.START_TIME.slice(0, 10) == value.format("YYYY-MM-DD")) {
          if (v.Nav_Class != null) {
            listData.push({
              type: v.ENABLE_STATUS == 1 ? 'default' : 'success',
              content: (v.Nav_Class ? v.Nav_Class.NAME : '') + ':' + v.QTY + '-' + (v.Nav_Team ? v.Nav_Team.NAME : '')
            })
            var find = listSumData.find(item => item.name === v.Nav_Class.NAME)
            if (find) {
              find.qty = find.qty + v.QTY
            }
            else {
              listSumData.push({
                type: v.ENABLE_STATUS == 1 ? 'default' : 'success',
                name: v.Nav_Class.NAME,
                qty: v.QTY,
                teamName: (v.Nav_Team ? v.Nav_Team.NAME : '')
              })
            }
          }
        }
      })
    }
    listSumData.forEach(v => {
      listResult.push({
        type: v.ENABLE_STATUS == 1 ? 'default' : 'success',
        content: (v.name + ':' + v.qty + '-' + v.teamName)
      })
    })
    return listResult || []
  }
  dateCellRender = (value) => {
    const listData = this.getListData(value)
    return (
      <ul key={guid()} 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()
    })
  };
  //删除记录
  deleteRecordInfo = (id) => {
    this.props.dispatch({
      type: 'app/getDataByGet',
      url: 'ED/ProdRecord/Delete',
      payload: { 'id': id },
      onComplete: (ret) => {
        if (ret) {
          message.success('执行成功')
          this.LoadDailyData()
        }
      }
    })
  };
  handleChange = (value) => {
    this.setState({
      CurrentWorkStageId: value,
    }, () => {
      if (this.state.WorkStageList && this.state.WorkStageList.length) {
        const WorkStageList = [...this.state.WorkStageList]
        WorkStageList.forEach((n, i) => {
          if (n.ID == value) {
            this.setState({
              CurrentWorkStageName: n.NAME
            })
          }
        })
      }
      this.LoadDailyData()
    })
  };

  onChange = (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 })
    }
  }

  handleTeamChange = (value) => {
    this.setState({
      CurrentTeamId: value,
    }, () => {
      if (this.state.WorkTeamList && this.state.WorkTeamList.length) {
        const WorkTeamList = [...this.state.WorkTeamList]
        WorkTeamList.forEach((n, i) => {
          if (n.ID == value) {
            this.setState({
              CurrentTeamName: n.NAME
            })
          }
        })
      }
      this.LoadDailyData()
    })
  };
  handleClassChange = (value) => {
    this.setState({
      CurrentClassId: value,
    }, () => {
      if (this.state.WorkClassList && this.state.WorkClassList.length) {
        const WorkClassList = [...this.state.WorkClassList]
        WorkClassList.forEach((n, i) => {
          if (n.ID == value) {
            this.setState({
              CurrentClassName: n.NAME
            })
          }
        })
      }
      this.LoadDailyData()
    })
  };

  handleModal = (e) => {
    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.START_TIME.slice(0, 10) == e.format("YYYY-MM-DD")) {
            dayListData.push(v)
            listData.push({
              ...v,
              key: v.ID,
              PRODUCT_ID: v.PRODUCT_ID,
              CLASS_NAME: v.Nav_Class.NAME,
              DATE: v.START_TIME.toString().substring(0, 10),
              WORKSTAGE_NAME: v.Nav_MeterNode.NAME,
              TEAM_NAME: v.Nav_Team.NAME,
              QTY: v.QTY
            })
          }
        })
      }

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

  };

  //提交
  modalOk = (e) => {
    this.postData('ED/EDProdRecord/CalendarUpdate')
  };

  postData = (url) => {
    const orgId = storage('lacal').getItem('webOrgId').val
    const dataSource = [...this.state.dataSource]
    const { dispatch } = this.props
    dispatch({
      type: 'app/getDataByPost',
      url: url,
      payload: { Prod_Record: dataSource, ORG_ID: orgId },
      onComplete: (ret) => {
        if (ret) {
          message.success('执行成功')
          this.setState({
            visible: false,
          }, () => {
            this.LoadDailyData()
          })
        }
      }
    })
  }

  //新增
  handleAdd = () => {
    const { dataSource, nodeId, nodeName, WorkClassList, WorkTeamList } = this.state
    var newDatas = []
    for (var i = 0, len = WorkClassList.length; i < len; i++) {
      let newData = {
        ID: guid(),
        CLASS_ID: WorkClassList[i].ID,
        CLASS_NAME: WorkClassList[i].NAME,
        TEAM_NAME: WorkTeamList[0].NAME,
        TEAM_ID: WorkTeamList[0].ID,
        METER_NODE_ID: nodeId,
        WORKSTAGE_NAME: nodeName,
        ORG_ID: storage('lacal').getItem('webOrgId').val,
        START_TIME: this.state.currentData,
        ENABLE_STATUS: 0
      }
      newDatas.push(newData)
    }
    this.setState({
      dataSource: [...dataSource, ...newDatas],
    })
  }

  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 changeTeam = (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 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 changeProduct = (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 colTeam = (text, record, index) => {
      return <Select
        style={{ width: 200 }}
        placeholder='选择班组'
        optionFilterProp="children"
        value={record.TEAM_ID}
        onChange={(e) => { changeTeam(record.ID, 'TEAM_ID', e) }}
        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
      >
        {//map 循环 填充下拉项目
          this.state.WorkTeamList.map(item => {
            return <Option key={item.ID} value={item.ID}>{item.NAME}</Option>
          })
        }
      </Select>
    }
    const colClass = (text, record, index) => {
      return <Select
        style={{ width: 200 }}
        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.WorkClassList.map(item => {
            return <Option key={item.ID} value={item.ID}>{item.NAME}</Option>
          })
        }
      </Select>
    }
    const colProduct = (text, record, index) => {
      return <Select
        style={{ width: 200 }}
        placeholder='选择产品'
        optionFilterProp="children"
        value={record.PRODUCT_ID}
        onChange={(e) => { changeProduct(record.ID, 'PRODUCT_ID', e) }}
        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
      >
        {//map 循环 填充下拉项目
          this.state.productList.map(item => {
            return <Option key={item.ID} value={item.ID}>{item.CODE + "-" + item.NAME}</Option>
          })
        }
      </Select>
    }

    const classColumns = [
      { title: '当前日期', dataIndex: 'START_TIME', key: 'START_TIME', render: (text, record, index) => { if (text) return text.toString().substring(0, 10) } },
      { title: '生产单元', dataIndex: 'WORKSTAGE_NAME', key: 'WORKSTAGE_NAME', render: (text, record, index) => { if (text) return text.toString() } },
      { title: <div> <span style={{ color: 'red' }}>*</span>班组</div>, dataIndex: 'TEAM_NAME', key: 'TEAM_NAME', render: colTeam },
      { title: <div> <span style={{ color: 'red' }}>*</span>班别</div>, dataIndex: 'CLASS_NAME', key: 'CLASS_NAME', render: colClass },
      { title: <div> 产品</div>, dataIndex: 'PRODUCT', key: 'PRODUCT', render: colProduct },
      { title: '数量', dataIndex: 'QTY', key: 'QTY', render: (text, record, index) => { return <InputNumber maxLength={12} defaultValue={text} onChange={(e) => { this.onChange(record.ID, 'QTY', e) }} ></InputNumber> } },
      {
        title: '操作', dataIndex: 'DELETE', key: 'DELETE', render: (text, record, index) => {
          const deleteRecord = () => {
            const dataSource = []
            var deleteId = ''
            if (this.state.dataSource) {
              this.state.dataSource.forEach((n, i) => {
                if (n.ID != record.ID) {
                  dataSource.push(n)
                }
                else {
                  deleteId = record.ID
                }
              })
            }
            this.setState({ dataSource }, () => {
              this.deleteRecordInfo(deleteId)
            })
          }
          return <Button type={'danger'} onClick={deleteRecord} icon={'delete'}></Button>
        }
      },

    ]

    return (
      <div className='scroll_page'>
        <LayoutCard className={styles.calendarWrap}>
          <Calendar
            dateCellRender={this.dateCellRender}
            onSelect={this.handleModal}
            onPanelChange={this.onPanelChange}
            disabledDate={this.handleCalenderDisabledDate}
          />
        </LayoutCard>
        <Modal
          visible={this.state.visible}
          maskClosable={false}
          width={"60%"}
          onCancel={this.modalCancel}
          onOk={this.modalOk}
        >
          <Button onClick={this.handleAdd} type="primary" icon="plus-circle-o">新增</Button>
          <Table
            rowKey="ID"
            pagination={false}
            dataSource={this.state.dataSource}
            columns={classColumns}
          />
        </Modal>
      </div>
    )
  }
}

export default connect()(CalendarPage)
