import React from 'react';
import { SearchOption, InspectCommon, Calendar ,Notify,ConfirmModal,Add} from '@commonComp';
import SlideExcel from './SlideExcel';
import SlideSelect from './SlideSelect';
import { deepClone } from '@utils/tools';
import styles from './index.less';
import date1 from './img/date1.png';
import close from './img/close.png';
import slideUp from "@common/images/slide-up.png";
import slideDown from "@common/images/slide-down.png";
import store from '@store';
import $ from 'jquery';
class Inspect extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      showFill: false,
      date: false,
      currentIdx: '',
      dateTime: "",
      currentData: {},
      numPlus: 0,     //判断是否所有的填写单都是空
      num: 0,            //暂存数据，获取一次，不能每次都是新的数据
      toastText: '',
      visible: false,
      type: null,
      id: null,
      tmpIds: [],      //内层外层
    }
    this.handleChangeDate = this.handleChangeDate.bind(this)
    this.handleShowDate = this.handleShowDate.bind(this)
    this.getCurrentDate = this.getCurrentDate.bind(this)
    this.getItemList = this.getItemList.bind(this)
    this.getSearchList = this.getSearchList.bind(this)
    this.getCommonList = this.getCommonList.bind(this)
    this.changeActivePart = this.changeActivePart.bind(this)
    this.showDetails = this.showDetails.bind(this)
    this.delConfirm = this.delConfirm.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.handleSearchShow = this.handleSearchShow.bind(this)
    this.changeShowFill = this.changeShowFill.bind(this)
    this.handleFillShow = this.handleFillShow.bind(this)
    this.handleDelClick = this.handleDelClick.bind(this)
  }
  delConfirm() {//弹窗确定
    const { delPartItem, handleCloseExcel, handlePush } = this.props;
    const { type, id } = this.state;
    if (type == 1) {
      delPartItem(id)
    } else if (type == 2) {
      handleCloseExcel(id)
    }
    this.setState({
      visible: false,
      type: null,
      id: null,
    })
    Notify.success("删除成功");
    handlePush && handlePush();       //右侧推送
  }
  handleDelClick(type, idx) {
    this.setState({
      type: type,
      id: idx,
      visible: true
    })
    if (type == 1) {//单项
      this.setState({
        toastText: '是否删除该化验项？'
      })
    } else if (type == 2) {//导入项
      this.setState({
        toastText: '是否删除导入项？'
      })
    }
  }
  handleCancel() {
    this.setState({
      visible: false,
      type: null,
      id: null,
    })
  }
  componentDidMount() {
    $(document).click((event) => {
      let searchWrap = $('#searchWrap')[0];   // 搜索按钮
      let searchOption = $('#searchOption')[0];   // 搜索列表
      let inspectFill = $('#inspectFill')[0];         // 公共填写单
      if (searchOption) {
        if (searchOption != event.target && searchWrap != event.target && searchWrap != event.target.parentNode && !$.contains(searchOption, event.target)) { // Mark 1
          this.setState({ show: false });
        }
      }
      if (inspectFill) {
        if (event.target.getAttribute('data-flg') != 'current' && inspectFill != event.target && !$.contains(inspectFill, event.target)) { // Mark 1
          this.setState({ showFill: false, date: false });
        }
      }
    });
    this.getCurrentDate();
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.fillActive.name != this.props.fillActive.name) {
      this.setState({ num: 0 })
    }
  }
  changeShowFill() {
    this.setState({ showFill: false })
  }
  handleChangeDate(info) {
    let date = info.year + '-' + (info.month < 10 ? '0' + info.month : info.month) + '-' + (info.day < 10 ? '0' + info.day : info.day);
    this.setState({ dateTime: date, date: false })
  }
  handleSearchShow(e) {
    let tmpShow = this.state.show;
    this.setState({ show: !tmpShow })
    // e.stopPropagation();
  }
  handleFillShow(e, idx) {
    let tmpShow = this.state.showFill;
    let baseList = store.getState().inspect.fillActive;
    this.setState({
      showFill: !tmpShow,
      currentIdx: idx,
      currentData: baseList,
      dateTime: baseList.time ? baseList.time : this.getCurrentDate()
    })
    e.stopPropagation();
  }
  handleShowDate() {
    this.setState({
      date: !this.state.date
    })
  }
  getCurrentDate() {
    let myDate = new Date();
    let year = myDate.getFullYear();       //获取完整的年份(4位,1970-????)
    let mon = myDate.getMonth() - 0 + 1;       //获取当前月份(0-11,0代表1月)
    let day = myDate.getDate();            //获取当前日(1-31)
    let date = year + '-' + (mon < 10 ? '0' + mon : mon) + '-' + (day < 10 ? '0' + day : day);
    this.setState({ dateTime: date })
    return date;
  }
  changeActivePart(idx, val, clear) {
    let nums = this.state.num;
    let fillActive;
    if (nums == 0) {
      fillActive = this.props.fillActive;
    } else {
      fillActive = this.state.currentData;
    }
    ++nums;
    this.setState({ num: nums });
    let tempArr = deepClone(fillActive);

    if (clear) {    //点击清空按钮，至清初输入的数字
      for (let i = 0; i < tempArr.details.length; i++) {
        tempArr.details[i].value = ''
        tempArr.show = false;
      }
      tempArr.time = this.getCurrentDate();
      this.setState({ currentData: tempArr })
      return;
    } else {
      let tempNumPlus = 0;
      for (let i = 0; i < tempArr.details.length; i++) {
        if (i == idx) {
          tempArr.details[i].value = val
        }
        if (tempArr.details[i].value != undefined && tempArr.details[i].value != '') {
          tempArr.show = true;
        } else {
          ++tempNumPlus;
          if (tempNumPlus == tempArr.details.length) {
            tempArr.show = false;
          }
        }
      }
      tempArr.time = this.state.dateTime;
      this.setState({ currentData: tempArr })
    }
  }
  getItemList() {        //填写单展示
    let number = this.state.num;
    let fillActive;
    if (number == 0) {
      fillActive = this.props.fillActive;
    } else {
      fillActive = this.state.currentData;
    }
    return <ul className={styles.searchLis}>
      {
        fillActive && fillActive.details && fillActive.details.map((item, idx) => {
          if (item.controlType == 1) {
            return (
              <li className={`${styles.itemPart} ${fillActive.details.length > 1 ? '' : styles.itemPartOne}`}>
                <span className={styles.itemPartL}>{item.name}</span>
                <select className={styles.itemPartR} onChange={(e) => {
                  if (e.target.value == '请选择') {
                    this.changeActivePart(idx, '')
                    return;
                  }
                  this.changeActivePart(idx, e.target.value);
                }}
                >
                  <option value="请选择">请选择</option>
                  {
                    (item.questionDetailList).map((val) => {
                      return <option value={val.name}
                        selected={val.name == item.value ? true : false}
                      >{val.name}</option>
                    })
                  }
                </select>
              </li>
            )
          } else if (item.controlType == 6) {
            return (
              <li className={`${styles.itemPart} ${fillActive.details.length > 1 ? '' : styles.itemPartOne}`}>
                <span className={styles.itemPartL} title={item.name}>{item.name}</span>
                <span className={styles.itemPartT}>
                  <input type="text"
                    placeholder="(填写)"
                    value={item.value}
                    onKeyUp={(e) => { this.changeActivePart(idx, e.target.value.trim()) }}
                  />
                  <p className={styles.unit} title={item.labelSuffix}>{item.labelSuffix}</p>
                </span>
              </li>
            )
          }
        })
      }
    </ul>
  }
  getSearchList(list) {//搜索列表
    const { handleSign } = this.props;
    return <ul className={styles.searchLiUl}>
      {
        list && list.map((item, idx) => {
          return <li key={idx}
            className={styles.searchLi}
            title={item.name == item.retrievalName ? item.name : item.name + '(' + item.retrievalName + ')'}
            onClick={() => {
              handleSign(item.questionId, idx,'search');
              this.setState({ show: false })
            }}
          >
            {item.name}{item.name == item.retrievalName ? null : '(' + item.retrievalName + ')'}
          </li>
        })
      }
    </ul>
  }
  getCommonList(){//常用列表
    const { handleSign,inspectList } = this.props;
    return <ul className={styles.searchLiUl}>
      {
        inspectList && inspectList.map((item, idx) => {
          return <li key={idx}
            className={styles.searchLi}
            title={item.name}
            onClick={() => {
              handleSign(item.questionId, idx,'common');
              this.setState({ show: false })
            }}
          >
            {item.name}
          </li>
        })
      }
    </ul>
  }
  showDetails(val) {
    if (val.questionDetailList.length > 0) {
      return val.questionDetailList.map((item) => {
        if (val.value == item.name) {
          return <td style={{ width: '20%' }} className={item.abnormal != '0' ? "red" : ''}>{val.value}</td>
        }
      })
    } else {
      return <td style={{ width: '20%' }}><span className={(val.value - 0).toString() == 'NaN' ? "red" : (val.maxValue || val.minValue) ? (val.value > val.maxValue || val.value < val.minValue ? "red" : '') : ''}>{val.value}</span> {val.labelSuffix}</td>
    }
  }
  render() {
    const { getInfomation,handleChangeValue,inspectVal, list, labelList, delPartItem, handleLabelSub, handleClear, handleConfirm, fillActive, getExcelDataList, handleCloseExcel, handlePush } = this.props;
    const { toastText, visible, tmpId, tmpIdx } = this.state;

    return (
      <div className={styles.wrapper}>
        <div className={styles.check}>
          {
            getExcelDataList.length > 0 && getExcelDataList.map((items, id) => {
              return <div style={{ marginTop: '10px' }}>
                {
                  items && items.lisExcelRes.length > 0 ? <ul className={styles.excelDataLists}>
                    <img className={styles.close} src={close} alt="关闭导入excel数据" onClick={() => { this.handleDelClick(2, id) }} />
                    {
                      items.lisExcelRes.map((item, idx) => {
                        return <SlideExcel
                          items={items}
                          item={item}
                          idx={idx}
                          dateTime={this.state.dateTime}
                          getInfomation={getInfomation}
                        ></SlideExcel>
                      })
                    }
                  </ul> : null
                }
              </div>
            })
          }
          <ul className={styles.labelWrap} >
            {
              labelList && labelList.map((item, idx) => {
                return <SlideSelect
                  item={item}
                  idx={idx}
                  showFill={this.state.showFill}
                  handlePush={handlePush}
                  fillActive={fillActive}
                  handleLabelSub={handleLabelSub}
                  date={this.state.date}
                  dateTime={this.state.dateTime}
                  currentIdx={this.state.currentIdx}
                  currentData={this.state.currentData}
                  showDetails={this.showDetails}
                  handleShowDate={this.handleShowDate}
                  handleChangeDate={this.handleChangeDate}
                  changeShowFill={this.changeShowFill}
                  handleFillShow={this.handleFillShow}
                  getItemList={this.getItemList}
                  changeActivePart={this.changeActivePart}
                  handleDelClick={this.handleDelClick}
                  handleConfirm={handleConfirm}
                  getInfomation={getInfomation}
                ></SlideSelect>
              })
            }
          </ul>
        </div>
        <div style={{ position: "relative", clear: "both" }}>
          <Add showText="添加化验项" handleClick={(e) => this.handleSearchShow(e)} id="searchWrap" />
          {this.state.show ? <SearchOption handleChangeValue={handleChangeValue} visible={true}>
            {list && list.length>0?this.getSearchList(list):(inspectVal == ''?'':<p style={{padding:'5px 30px',color:'#bfbfbf'}}>暂无筛选项</p>)}
            {
              list && list.length>0 || (inspectVal != '')?'':<div>
                  <p style={{padding:'5px 30px',color:'#bfbfbf'}}>常用化验项</p>
                  {
                    this.getCommonList()
                  }
                </div>
            }
          </SearchOption> : ''}
        </div>
        <ConfirmModal
          visible={visible}
          confirm={this.delConfirm}
          close={this.handleCancel}
          cancel={this.handleCancel}
          okText="删除"
          cancelText='取消'
          okBorderColor={'#3B9ED0'}
          okColor={'#fff'}
          oKBg={'#3B9ED0'}
        >
          <p className={styles['center']}>{toastText}</p>
        </ConfirmModal>
      </div>
    )
  }
}

export default Inspect;