import React, { Component } from 'react';
import { PropTypes } from 'amos-react-router/lib';
import { Button, Form, Select, Upload, AmosAlert, Input, Modal } from 'amos-framework';
import { browserHistory } from 'amos-react-router';
import AmosGridTable from '../../../common/tableComponent/table/AmosGridTable';
import BizIcon from './../../../../common/icon/BizIcon';
import { getFireTruckDetailAction, addFireTruckAction } from '../../../../../services/ledgerService';
import FireTruckModel from './fireTruckModel';
import { FasSerUrl, baseURI } from '../../../../../consts/urlConsts';
import _amosTool from 'amos-tool';
import SysConsts from 'amos-processor/lib/config/consts';
import　CommonTable　from './../../../common/table/CommonTable';
import { convertImgUrlToFile, getBase64 } from './../../../../../utils/FileUtils';
import { UUID } from 'amos-tool';


const ls = _amosTool.Store.lsTool;
const apiKey = SysConsts.api_key;
const token = SysConsts.token;
const url = FasSerUrl.fireTruckAddUrl;


/**
 * 消防车详情
 */
class FireTruckDetailInfo extends Component {
  constructor(props) {
    super(props);

    this.state = {
      truckInfo: {},
      performanceInfo: [], //车辆性能信息
      dataList: [],
      imgFiles: [],
      previewVisible: false,
      previewImage: '',
      isDisabled: false
    };
  }

  componentDidMount() {
    let { fireCarId } = this.props.location.state || {};
    fireCarId && this.getFireTruckData(fireCarId);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps && nextProps.location.state) {
      let { fireCarId } = nextProps.location.state || {};
      fireCarId && this.getFireTruckData(fireCarId);
    }
  }

  getFireTruckData = fireCarId => {
    getFireTruckDetailAction(fireCarId).then(data => {
      let performanceInfo = data.performanceIndex && this.isJSON(data.performanceIndex) ? JSON.parse(data.performanceIndex) : [];
      this.setState({ truckInfo: data, dataList: performanceInfo });
      this.setHavingFileToState(data);
    });
  };

  setHavingFileToState = truckInfo => {
    let photoArry = truckInfo.photoPath.split(',');
    photoArry.map(e => {
      let fileName = e.substring(e.lastIndexOf('\\') + 1);
      console.log('e=', baseURI + e);
      console.log('filename=', fileName);
      convertImgUrlToFile(baseURI + e, fileName, this.callBack);
    });
  };

  isJSON(str) {
    if (typeof str === 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj ){
          return true;
        } else {
          return false;
        }

      } catch (e) {
        console.log('error：' + str + '!!!' + e);
        return false;
      }
    }
    console.log('It is not a string!');
  }

  callBack = file => {
    let { imgFiles } = this.state;
    this.setState({ imgFiles: [...imgFiles, file] });
  };

  goBack() {
    browserHistory.goBack();
  }

  fireTruckTableColumns = () => {
    return [
      {
        title: '指标名称',
        dataIndex: 'name',
        key: 'name',
        width: '50%',
        render: (text, record) => {
          return !record.edit ? (
            text
          ) : (
            <div>
              <Input onChange={e => this.onChangeInput(record, e.target.value, 'name')} value={text} />
            </div>
          );
        }
      },
      {
        title: '指标量',
        dataIndex: 'value',
        key: 'value',
        width: '20%',
        render: (text, record) => {
          return !record.edit ? (
            text
          ) : (
            <div>
              <Input onChange={e => this.onChangeInput(record, e.target.value, 'value')} value={text} />
            </div>
          );
        }
      }
    ];
  };

  onChangeInput = (record, e, key) => {
    const { dataList } = this.state;
    for (let i = 0; i < dataList.length; i++) {
      if (dataList[i].orderNo === record.orderNo) {
        dataList[i][key] = e;
      }
    }
    this.setState(dataList);
  };

  handSubmit = () => {
    let imgFiles = this.state.imgFiles;
    let orgCode = this.props.currentNode.key;
    let param = {
      imgFiles,
      orgCode
    };
    editOrgImgAction(param).then(data => {
      message.success('操作成功');
      this.setState({ visible: false });
    });
  };

  beforeUpload = file => {
    //1.格式校验
    const pattern = /image\/(gif|jpeg|png|jpg|bmp)$/;
    const isImg = pattern.test(file.type);
    if (!isImg) {
      AmosAlert.warning('请选择符合格式的图片！（gif|jpeg|png|jpg|bmp）');
      return false;
    }
    //2.url转文件对象
    this.changeData(file);
    return false;
  };

  changeData = async file => {
    file.url = await getBase64(file);
    let { imgFiles } = this.state;
    this.setState({ imgFiles: [...imgFiles, file] });
  };

  submitData = e => {
    let { form } = this.model;
    let { dataList, imgFiles } = this.state;
    form.validate((valid, dataValues) => {
      if (valid) {
        this.setState({ isDisabled: true });
        let formData = new FormData();
        imgFiles.forEach(file => {
          formData.append('file', file);
        });
        delete dataValues.createDate;
        delete dataValues.performanceIndex;
        Object.keys(dataValues).map(item => {
          formData.append(item, dataValues[item]);
        });
        dataList.forEach(item => {
          delete item.edit;
        });
        formData.append('performanceIndex', JSON.stringify(dataList));
        fetch(url, {
          method: 'post',
          headers: {
            Accept: 'application/json;charset=UTF-8',
            'X-Api-Key': _amosTool.Store.getCookieByName(apiKey),
            'X-Access-Token': ls.read(token)
          },
          body: formData
        })
          .then(e => {
            AmosAlert.success('提示', '保存成功');
            this.goBack();
          })
          .catch(e => {
            AmosAlert.error('错误', '保存失败');
          });
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  };

  fileRemove = file => {
    this.setState(({ imgFiles }) => {
      let index = imgFiles.indexOf(file);
      let newFileList = imgFiles.slice();
      newFileList.splice(index, 1);
      return {
        imgFiles: newFileList
      };
    });
  };

  onChangeTableValues = data => {
    this.setState({ dataList: data });
  };

  handlePreview = file => {
    this.setState({
      previewImage: file.url,
      previewVisible: true
    });
  };

  handleCancel = () => this.setState({ previewVisible: false });

  updateFireCarState = (key, value) => {
    let { truckInfo } = this.state;
    truckInfo[key] = value;
    this.setState({ truckInfo });
  };

  render() {
    let { truckInfo, dataList, imgFiles, previewImage, previewVisible, isDisabled } = this.state;
    return (
      <div className="fire-resource-truck-detail-info">
        <div className="fire-resource-truck-detail-button">
          <Button icon={<BizIcon icon="fanhui" />} transparent onClick={() => this.goBack()} />
          <div className="fire-resource-commit-button">
            <Button icon="ok" disabled={isDisabled ? true : false} onClick={() => this.submitData()} transparent>
              提交
            </Button>
          </div>
        </div>
        <div className="fire-resource-truck-detail-info-content">
          <div className="fire-truck-performance1">
            <div className="fire-truck-performance-title">车辆图片</div>
            <div>
              <Upload
                fileList={imgFiles}
                listType="picture-card"
                beforeUpload={this.beforeUpload}
                onPreview={this.handlePreview}
                onRemove={this.fileRemove}
                multiple
              >
                <Button transparent>选择图片</Button>
              </Upload>
              <Modal className='preview-photo-modal' content={<img style={{ width: '100%' }} src={previewImage} />} visible={previewVisible} noDefaultFooter onCancel={this.handleCancel} />
            </div>
          </div>
          <div className="fire-truck-performance2">
            <div className="fire-truck-performance-title">车辆基本信息</div>
            <FireTruckModel truckInfo={truckInfo} updateFireCarState={this.updateFireCarState} ref={model => (this.model = model)} />
          </div>
          <div className="fire-truck-performance3">
            <div className="fire-truck-performance-title">车辆性能信息</div>
            <CommonTable tableData={dataList} onChangeTableValues={this.onChangeTableValues} columns={this.fireTruckTableColumns()} />
          </div>
        </div>
      </div>
    );
  }
}

FireTruckDetailInfo.propTypes = {
  truckInfo: PropTypes.any
};
export default FireTruckDetailInfo;
