import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button,AmosAlert,Modal } from 'amos-framework';
import AmosGridTable from './../../common/tableComponent/table/AmosGridTable';
import BizIcon from './../../../common/icon/BizIcon';
import CamerasEdit from './CamerasEdit';
import { camerasDeleteAction, camerasSaveAction } from './../../../../services/bizService';


const buttonMap = [
  { key: 'add',icon: 'tianjia',label: '添加' },
  { key: 'edit',icon: 'xiugai',label: '修改' },
  { key: 'delete',icon: 'shanchu',label: '删除' },
  { key: 'filter',icon: 'shaixuan',label: '筛选' }
];
const getColumns = () => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '摄像机编号',
      dataIndex: 'code',
      key: 'code',
      width: '15%'
    },
    {
      title: '摄像机名称',
      dataIndex: 'name',
      key: 'name',
      width: '15%'
    },
    {
      title: '摄像机类型',
      dataIndex: 'type',
      key: 'type',
      width: '10%'
    },
    {
      title: '摄像机IP',
      dataIndex: 'ip',
      key: 'ip',
      width: '10%'
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: '10%'
    },
    {
      title: '密码',
      dataIndex: 'password',
      key: 'password',
      width: '10%'
    },
    {
      title: '端口号',
      dataIndex: 'port',
      key: 'port',
      width: '10%'
    },
    {
      title: '通道',
      dataIndex: 'channel',
      key: 'channel',
      width: '10%'
    }
  ];
};
/**
 *
 * 摄像头列表
 * @class CameraTable
 * @extends {Component}
 */
class CamerasTable extends Component {
  constructor(props) {
    super(props);
    this.pageConfig = {
      current: 1,
      pageSize: 10
    };
    this.state = {
      pagination: true,
      isChecked: true,
      selectedRows: [],
      selectedRowKeys: [],
      dataList: [],
      totalCount: 0
    };
  }

  componentWillMount() {

  }

  componentDidMount() {

  }

  onRowClick = record => {
    let { selectedRowKeys, selectedRows } = this.state;
    let exist = false;
    selectedRows.find(item => {
      if (item.id === record.id) {
        exist = true;
      }
    });
    if (exist) {
      selectedRows.splice(selectedRows.findIndex(item => item.id === record.id), 1);
      selectedRowKeys.splice(selectedRowKeys.findIndex(item => item === record.id), 1);
    } else {
      selectedRows.push(record);
      selectedRowKeys.push(record.id);
    }
    this.setState({
      selectedRows,
      selectedRowKeys
    });
  }

  onOk = (btnType) =>{
    const { form } = this.model.state;
    this.model.form.validate((valid, dataValues) => {
      if (valid) {
        this.editCamerasTable(form);
        this.cancel();
      } else {
        return false;
      }
    });
  }

  onToolBarClick =(key)=>{
    const { selectedRowKeys } = this.state;
    if (key === 'add'){//新增
      this.setState({ modal: true,btnType: key });
    } else if (key === 'edit'){//编辑
      if (selectedRowKeys === undefined || selectedRowKeys.length <= 0){
        AmosAlert.warning('提示', '请先点击选择编辑的行');
        return;
      }
      if (selectedRowKeys.length > 1){
        AmosAlert.warning('提示', '每次只能编辑一行');
        return;
      }
      this.setState({ modal: true,btnType: key });
    } else if (key === 'delete'){//删除
      if (selectedRowKeys === undefined || selectedRowKeys.length <= 0){
        AmosAlert.warning('提示', '请先点击选择删除的行');
        return;
      }
      this.deleteCamersById(selectedRowKeys);
    } else if (key === 'filter') {
      this.props.changeStatus();
    }
  }

  getContext = (btnType) => {
    const { selectedRows } = this.state;
    const { camerasTypeData = [] } = this.props;
    if (btnType === 'add') {
      return <CamerasEdit camerasTypeData={camerasTypeData} ref={component =>this.model = component} /> ;
    } else if (btnType === 'edit'){
      return <CamerasEdit camerasTypeData={camerasTypeData} selectedRow={selectedRows.length > 0 ? selectedRows[0] : {}} ref={component =>this.model = component} /> ;
    }
  }

  getRowClassName = (record, index) => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys.findIndex(item => item === record.id) >= 0) {
      return 'highlight-row';
    } else {
      return 'normal-row';
    }
  }

  getSelectedRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  }

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

  getModelHeader =(btnType)=>{
    switch (btnType){
      case 'add':
        return '添加摄像机';
      case 'edit':
        return '编辑摄像机';
    }
  }

  cancel = () => {
    this.setState({ modal: false });
  }

  reload = r => {
    this.setState(
      {
        reload: () => {
          r();
          this.setState({ selectedRows: [], selectedRowKeys: [] });
        }
      },
      r()
    );
  }

  deleteCamersById =(ids)=>{
    AmosAlert.confirm('提示', '确定要删除么?', {
      callback: flag => {
        if (flag) {
          // 确定
          camerasDeleteAction(ids).then(
            data => {
              AmosAlert.success('提示', '删除成功');
              this.reloadPage();
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }
      }
    });
  }

  editCamerasTable =(cameras)=>{
    camerasSaveAction(cameras).then(data=>{
      AmosAlert.success('提示', '保存成功');
      this.reloadPage();
    },err=>{
      AmosAlert.error('错误', err);
    });
  }

  reloadPage = () => {
    this.clearSelectedRows();
    this.state.reload();
  }

  clearSelectedRows = () => {
    this.setState({ selectedRows: [], selectedRowKeys: [] });
  }
  renderButton =()=>{
    return (<div className='cameras-button'>
      {buttonMap.map(item=>{ return <Button icon={<BizIcon title={item.label} icon={item.icon} />} transparent onClick={()=>this.onToolBarClick(item.key)} />;})}
    </div>);
  }

  render() {
    const { pagination,isChecked, selectedRowKeys,btnType,modal } = this.state;
    const defaultPageConfig = this.pageConfig;
    const { fetchData,totalNum,dataList } = this.props;
    return (
      <div className='cameras-table'>
        <div className='cameras-table-button'>
          <div className='cameras-table-title'>
            监控点位
          </div>
          {this.renderButton()}
        </div>
        <AmosGridTable
          columns={getColumns()}
          callBack={this.reload}
          isPageable={pagination}
          dataList={dataList}
          totals={totalNum}
          getTableDataAction={param => fetchData(param, this)}
          selectedRowKeys={selectedRowKeys}
          getSelectedRows={this.getSelectedRows}
          rowClassName={this.getRowClassName}
          setPageConfig={this.setPageConfig}
          defaultPageConfig={defaultPageConfig}
          onRowClick={this.onRowClick}
          isChecked={isChecked}
        />
        <Modal
          header={this.getModelHeader(btnType)}
          visible={modal}
          className="cameras-modal"
          destroyContent
          width='45%'
          content={this.getContext(btnType)}
          onCancel={() => this.cancel()}
          onOk={() => this.onOk()}
          okText="确定"
          cancelText="取消"
        />
      </div>
    );
  }
}

CamerasTable.propTypes = {
  changeStatus: PropTypes.func,
  fetchData: PropTypes.func,
  totalNum: PropTypes.number,
  dataList: PropTypes.array,
  camerasTypeData: PropTypes.arry
};

export default CamerasTable;
