import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button } from 'amos-framework';
import dt2react from 'dt2react';
import { browserHistory } from 'amos-react-router/lib';
// import { Store } from 'amos-tool';
import { fetchCheckDetailById, fetchCheckInputById, fetchShortByCheckIdAndCheckInputId } from './../../../../services/patrolService';
import CheckDetailTable from './CheckDetailTable';
import CheckInputTable from './CheckInputTable';
// import './../../../../styles/view/biz/checkDetail/checkDetail.scss';
// import './../../../../styles/view/biz/checkDetail/pointsDetails.scss';
import { patrolURI } from './../../../../consts/urlConsts';
import { tool } from './../../../../utils/processor';
import Picture from './Picture';
import { pathMapping } from './../../../../routes/customRoutes';
import BizIcon from './../../../common/icon/BizIcon';

const CheckListPath = () => pathMapping.checkRecordList;

const { renderLongTime } = tool;

const checkDetailHeaderResult = checkDetail => {
  let checkTime;
  let pointName;
  let pointNo;

  if (checkDetail) {
    if (checkDetail.pointName) {
      checkTime = renderLongTime(checkDetail.checkTime);
      pointName = checkDetail.pointName;
      pointNo = checkDetail.pointNo;
      return `${checkTime} ${pointName} (${pointNo})`;
    } else {
      return '巡检时间 巡检点名称 (巡检点编号)';
    }
  } else {
    return '巡检时间 巡检点名称 (巡检点编号)';
  }
};

const checkInputColumns = (_this) => {
  return [
    {
      title: '扩展分类',
      dataIndex: 'classifyName',
      key: 'classifyName',
      width: '10%',
      query: true,
      required: true, //是否是默认显示的
      primary: true, //是否出现在模糊搜索文本框中
      st: 'text' //搜索的类型
    },
    {
      title: '检查项名称',
      dataIndex: 'inputItemName',
      key: 'inputItemName',
      width: '9%',
      query: true,
      required: true, //是否是默认显示的
      primary: true, //是否出现在模糊搜索文本框中
      st: 'text' //搜索的类型
    },
    {
      title: '检查结果',
      dataIndex: 'inputValue',
      key: 'inputValue',
      width: '8%',
      query: true,
      required: true, //是否是默认显示的
      primary: true, //是否出现在模糊搜索文本框中
      st: 'text' //搜索的类型
    },
    {
      title: '备注说明',
      dataIndex: 'remark',
      key: 'remark',
      width: '10%',
      query: true,
      required: true, //是否是默认显示的
      primary: true, //是否出现在模糊搜索文本框中
      st: 'text' //搜索的类型
    },
    {
      title: '是否正常',
      dataIndex: 'isOK',
      key: 'isOK',
      query: true,
      required: true, //是否是默认显示的
      primary: true, //是否出现在模糊搜索文本框中
      st: 'text', //搜索的类型
      width: '6%',
      render: (text, record) => {

           if(text==='合格'){
            text='正常';
           }else if(text==='不合格'){
            text='异常';
           }
           return  text;




      }
    },
    {
      title: '上报时间',
      dataIndex: 'uploadTime',
      key: 'uploadTime',
      width: '8%',
      render: text => renderLongTime(text)
    },
    {
      title: '检查评分',
      dataIndex: 'inputItemScore',
      key: 'inputItemScore',
      width: '6%'
    },
    {
      title: '照片',
      dataIndex: 'checkInputId',
      key: 'checkInputId',
      width: '5%',
      render: (text, record) => {
        let imgCount = record.imgCount;
        return (
          <span>
            {imgCount === 0 ? '无图片上传' : (<a href="javascript:;" onClick={_this.showPic.bind(this, record)}>查看</a>)}
          </span>
        );
      }
    }
  ];
};

//偏移110px
const offsetHeight = 110;
const defaultHeight = 450;

/**
 * 巡检记录详情
 */
class CheckDetail extends Component {
  constructor(props) {
    super(props);

    this.state = {
      dataList: [], //表格数据集合
      size: 'small', //表格大小
      current: props.defaultPageConfig ? props.defaultPageConfig.current : 1, //当前页初始索引0
      pageSize: props.defaultPageConfig ? props.defaultPageConfig.pageSize : 2, //当前页数据量
      totals: 0, //所有数据总和
      reload() {},
      maxHeight: 650,
      nav1: null,
      nav2: null
    };
  }

  componentWillMount() {
    // if (this.props.location.state) {
     // let { checkID, pointID } = this.props.location.state;
      let { checkID, pointID } = this.props
      let param = { checkID, pointID };
      this.fillCheckInputTable(param);
      this.fillCheckDetailTable(param);
      this.setState({
        pointID
      });
    // }
  }

  componentDidMount() {
    this.setState({
      nav1: this.slider1,
      nav2: this.slider2
    });
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps) {
      // if (nextProps.location.state) {
       // let { checkID, pointID } = nextProps.location.state;
        let { checkID, pointID } = nextProps;
        let param = { checkID, pointID };
        this.fillCheckInputTable(param);
        this.fillCheckDetailTable(param);
      }
    // }
  }

  setPageConfig = ({ pageSize, current }) => {
    if (pageSize !== undefined) {
      this.pageConfig.pageSize = pageSize;
    }
    if (current !== undefined) {
      this.pageConfig.current = current;
    }
  };

  /**
   * @memberof CheckDetail
   */
  getImageView = (checkDetail, type) => {
    let view = [];
    if (checkDetail === undefined) {
      return;
    }
    let dataList = checkDetail.photosUrl;
    if (dataList === undefined) {
      return;
    }

    dataList.map((imgUrl, i) => {
      // const key = `dpn-${i}`;
      view.push(
        <div>
          <a href={patrolURI + imgUrl} target="_blank" rel="noopener noreferrer">
            <img className="check-detail-image" src={patrolURI + imgUrl} alt="图片" />
          </a>
        </div>
      );
    });

    return view;
  };

  /**
   *
   *
   * @memberof CheckDetail
   */
  getSmallImageView = checkDetail => {
    let view = [];
    if (checkDetail === undefined) {
      return;
    }
    let dataList = checkDetail.photosUrl;
    if (dataList === undefined) {
      return;
    }

    dataList.map(imgUrl => {
      view.push(
        <div>
          <img className="check-detail-image" src={patrolURI + imgUrl} alt="" />
        </div>
      );
    });
    return view;
  };

  getPanelHeight = () => {
    let checkDetailTablePanel = this.checkDetailTablePanel;
    let tableLocation = dt2react.getOffset(checkDetailTablePanel) || {};
    return tableLocation !== undefined ? tableLocation.height - offsetHeight : defaultHeight;
  };

  generateRowkey = (record, index) => {
    return record.id ? record.id : index + (this.state.current - 1) * this.state.pageSize;
  };

  showTotal = total => {
    return `共 ${total} 条`;
  };

  /**
   * 获取表格刷新方法
   */
  reload = r => {
    this.setState(
      {
        reload: () => {
          r();
        }
      },
      r()
    );
  };

  fillCheckDetailTable = param => {
    if (param) {
      fetchCheckDetailById(param).then(data => {
        this.setState({
          checkDetail: data === null ? {} : data
        });
      });
    }
  };

  fillCheckInputTable = param => {
    if (param) {
      fetchCheckInputById(param).then(data => {
        if (data && data.result === 'SUCCESS') {
          this.setState({
            dataList: data.content || [],
            // dataList,
            totals: data.totalElements,
            // totals: 18,
            pageSize: data.size
            // pageSize: 10
          });
        } else {
          this.setState({
            dataList: [],
            totals: 0,
            pageSize: 10
          });
        }
      });
    }
  };

  goBackAction = () => {
    let path = {
      pathname: '/biz/checkRecordList',
      state: { pointID: this.state.pointID }
    };
    browserHistory.push(path);
  };

  getPhotoUrl = (checkDetail) => {
    let markerData;
    if (checkDetail) {
      let dataList;
      if (checkDetail.inputItemPicShow) {
        dataList = checkDetail.inputItemPhotosUrl;
      } else {
        dataList = checkDetail.photosUrl;
      }
      markerData = { photosUrl: dataList };
      return markerData;
    }
  }


  showPic = (record, e) => {
   // let { checkID } = this.props.location.state;
    let { checkID } = this.props;
    const { checkDetail } = this.state;
    let inputItemPicShow = record.inputId ? true : false;
    inputItemPicShow && fetchShortByCheckIdAndCheckInputId(checkID, record.inputId ? record.inputId : 0,record.classifyId? record.classifyId : 0).then( data => {
      let photosUrl = new Array();
      if (data && data.length > 0) {
        photosUrl = data;
      }
      if (inputItemPicShow) {
        checkDetail.inputItemPhotosUrl = photosUrl;
      }
      this.setState({ checkDetail });
    });
    checkDetail.inputItemPicShow = inputItemPicShow;
    this.setState({ checkDetail });
  }

  render() {
    const { totals, maxHeight, dataList, checkDetail } = this.state;
    const parentStyle = { width: '100%' };
    return (
      <div className="checkDetail-root">

        <div className="header" style={{ padding: '0px', background: '#f2f2f2' }}>
          <div className="check-detail-header">{checkDetailHeaderResult(checkDetail)}</div>
          <div
            className="check-detail-header-goback"
            // onClick={() => {
            //   this.goBackAction();
            // }}
          >
            {/* <img src={require('./../../../assets/fsc/check/back.png')} alt="" />
            <Button icon={<BizIcon icon="fanhui" />} transparent onClick={() => this.goBackAction()}  /> */}
          </div>
        </div>
        <div className="content-parent" style={parentStyle}>
          <div className="content">
            <div className="check-detail-content-table">
              <CheckDetailTable showPic={this.showPic} checkDetail={checkDetail} />
            </div>
            <div className="check-detail-content-input" ref={node => this.checkDetailTablePanel = node}>
              <div className="check-detail-content1" style={{ padding: '0px', background: '#f2f2f2' }}>检查项目</div>
              <div className="check-detail-content2">
                <CheckInputTable
                  columns={checkInputColumns(this)}
                  callBack={this.reload}
                  dataSource={dataList}
                  totals={totals}
                  getTableDataAction={this.fillCheckInputTable}
                  maxHeight={maxHeight}
                  getPanelHeight={this.getPanelHeight}
                />
              </div>
            </div>
          </div>
          <div className="sider">
            <div className="check-detail-imge">
              <div className="check-detail-imge-text">现场照片/视频</div>
              <Picture markerData={this.getPhotoUrl(checkDetail)} />
            </div>
          </div>
        </div>

      </div>
    );
  }
}

CheckDetail.propTypes = {
  columns: PropTypes.array, //表格列模型
  isChecked: PropTypes.bool, //表格是否包含复选框
  operateCol: PropTypes.func, //表格内部操作按钮，如'查看详情'等
  callBack: PropTypes.func, //获取表格刷新方法，用于各个具体的表格回调获取，方便各种操作后进行表格刷新。
  otherFilter: PropTypes.string, //其他查询条件
  dataList: PropTypes.array,
  getTableDataAction: PropTypes.func,
  selectedRowKeys: PropTypes.array,
  totals: PropTypes.number,
  pagination: PropTypes.any, // 分页props, false时无分页
  isPageable: PropTypes.bool, // 是否分页: true 分页, false 不分页, 当为undefined时默认有分页
  isTreeTable: PropTypes.bool, // 是否是treeTable 默认非
  rowClassName: PropTypes.func,
  setPageConfig: PropTypes.func, //把分页参数给父类
  defaultPageConfig: PropTypes.object, //父类默认分页参数
  checkID: PropTypes.number //巡检记录ID
};

export default CheckDetail;
