import React, { Component } from 'react';
import { AmosAlert, Form, Select, Modal, Button, Icon } from 'amos-framework';
import { browserHistory } from 'amos-react-router';
import PropTypes from 'prop-types';
import BootBar from '../../component/toolbar';
import AmosGridTable from '../../component/table/table/AmosGridTable';
import NewRoutePoint from './newRoutePoint';
import { queryRoutePointAction, batchDelRoutePointAction, migrateRoutePointAction, queryAllRouteAction, exchangeOrderNumberAction } from '../../../services/checkService';
import { pathMapping } from './../../../routes/customRoutes';

const FormItem = Form.Item;
const Option = Select.Option;
const routeUrl = () => pathMapping.route;
const getDropnavs = () => {
  return [
    { key: '1', text: '返回', icon: 'fanhui', href: 'jacascript::void(0)' },
    { key: '2', text: '添加', icon: 'edit' , href: 'jacascript::void(0)', permissionCode: 'route', isWriteable: true },
    { key: '3', text: '删除', icon: 'delete', href: 'jacascript::void(0)', permissionCode: 'route', isWriteable: true },
    { key: '4', text: '迁移', icon: 'ccgl-chukucaozuo-13' , href: 'jacascript::void(0)', permissionCode: 'route', isWriteable: true }
  ];
};
const getColumns = (self) =>{

  return [
    {
      title: '巡检点编号',
      dataIndex: 'pointNo',
      key: 'pointNo',
      width: '50%',
      className: 'uant-table-thead'
    },
    {
      title: '巡检点名称',
      dataIndex: 'name',
      key: 'name',
      width: '50%',
      className: 'uant-table-thead',
      render: (text, record, index) =>{
        const divClass = self.state.hover[index] ? 'actionShow' : 'actionHide';
        let html = (<div>{text}
            <div className={divClass}>
              <div className={(index > 0)?'domShow':'domHide'}>
                <Button type="primary" size="small" className="mr-5" onClick={self.handleClickBySortUp.bind(self,index)}><Icon type="caret-up" />上移</Button>
              </div>
              <div className={(index < self.state.data.length - 1)?'domShow':'domHide'}>
                <Button type="primary" size="small" className="mr-5" onClick={self.handleClickBySortDown.bind(self,index)}><Icon type="caret-down" />下移</Button>
              </div>
            </div>
        </div>);
        return html;
      }
    }
  ];
};

/**
 * 巡检项
 *
 * @class RoutePointTable
 * @extends {Component}
 */
class RoutePointTable extends Component {
  constructor(props) {
    super(props);
    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
    this.state = {
      hover: [],
      pagination: true,
      isChecked: true,
      selectedRows: [],
      selectedRowKeys: [],
      pointSelected: [],
      routeData: [],
      selectedRouteRowKeys: [],
      modal: false,
      addModal: false,
      data: [],
      count: 0,
      pageConfig: {
        pageNumber: 0,
        pageSize: 10
      },
      requestParam: []
    };
  }

  /**
   * 组件初始化调用
   */
  componentWillMount = () => {
    this.reloadRoute();
  }
  /**
   * 接受新的属性时回调
   */
  componentWillReceiveProps = (nextProps) => {
    let { changeType, queryParam } = nextProps;
    if ('query' === changeType) {
      let request = new Array();
      if (queryParam) {
        for (let key in queryParam) {
          let obj = new Object();
          obj.name = key;
          obj.type = 'LIKE';
          obj.value = queryParam[key];
          request.push(obj);
        }
      }
      this.setState({ requestParam: request }, () => this.reloadPoint(this.pageConfig));
    }
  }


  onClickBootBar = type => {
    if (type === '1') {
      browserHistory.goBack(routeUrl());
    } else if (type === '2') {
      this.addRoutePoint();
    } else if (type === '3') {
      this.deleteRoutePoint();
    } else if (type === '4') {
      let { selectedRowKeys } = this.state;

      if (selectedRowKeys === undefined || selectedRowKeys.length <= 0 ) {
        AmosAlert.warning('提示', '请选择要迁移的检查项');
        return;
      }
      this.setState({ modal: true });
    }
  };

  onChangeSelect = (e) => {
    this.setState({ selectedRouteRowKeys: e });
  }

  getAddContext = () => {
    const { routeId } = this.props;
    return (<NewRoutePoint callback={this.addCallback} routeId={routeId} />);
  }

  getContext = () => {
    let { routeData } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
        className: 'colspan'
      }
    };

    return (
      <Form>
        <FormItem label={<span>路线名称</span>} {...formItemLayout} >
          <Select
            data={routeData}
            className="input_item_Input"
            renderOption={item => <Option value={item.id}>{item.name}</Option>}
            defaultOption={<Option value="-1">请选择</Option>}
            onChange={(e) => this.onChangeSelect(e)}
          />
        </FormItem>
      </Form>
    );
  }

  /**
   * 分页设置参数
   */
  setPageConfig = ({ pageSize, current }) => {
    if (pageSize !== undefined) {
      this.pageConfig.pageSize = pageSize;
    }
    if (current !== undefined) {
      this.pageConfig.pageNumber = current;
    }
  }

  /**
   * 获取表格所选则的行数据
   */
  getSelectedRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  }

  //鼠标移到内容模块上时触发的事件
  handleMouseEnter(record, index) {
    let arg = this.state.hover;
    arg[index] = true;
    this.setState({
      hover: arg
    });
}

  //鼠标离开内容模块时触发的事件
  handleMouseLeave(record, index) {
    let arg = this.state.hover;
    arg[index] = false;
    this.setState({
      hover: arg
    });
  }
  //点击向上排序按钮事件
  handleClickBySortUp(index, e) {
    e.stopPropagation();
    let arr = this.state.data;
    if (index !== 0) {
      let temp = arr[index - 1];
      arr[index - 1] = arr[index];
      arr[index] = temp;
      exchangeOrderNumberAction(arr[index - 1].routePointId, arr[index].routePointId).then(data => {
        if (!data) {
          this.setState({
            data: this.state.data
          });
        }
      });
    }
  }

  //点击向下排序按钮事件
  handleClickBySortDown(index, e) {
    e.stopPropagation();
    let arr = this.state.data;
    if (index !== arr.length - 1) {
      let temp = arr[index + 1];
      arr[index + 1] = arr[index];
      arr[index] = temp;
      exchangeOrderNumberAction(arr[index + 1].routePointId, arr[index].routePointId).then(data => {
        if (!data) {
          this.setState({
            data: this.state.data
          });
        }
      });
    }
  }

  updatePointOrder = (arr) => {

  }

  addCallback = () => {
    this.cancel('add');
    this.reloadPoint(this.pageConfig);
  }

  cancel = (key) => {
    const { modal, addModal } = this.state;
    if (modal && 'tranf' === key) {
      this.setState({ modal: false });
    } else if (addModal && 'add' === key) {
      this.setState({ addModal: false });
    }
  }

  /**
   *根据条件查询检查项
   */
  reloadPoint = (pageParam) => {
    if (pageParam === undefined) {
      pageParam = this.pageConfig;
    }
    let { requestParam } = this.state;
    let { pageSize } = pageParam;
    let pageNumber = 0;
    this.setState({ selectedRows: [], selectedRowKeys: [] });
    if (pageParam.current !== null && !isNaN(pageParam.current)) {
      pageNumber = pageParam.current;
    }
    let { routeId } = this.props;
    queryRoutePointAction(requestParam, pageNumber, pageSize, routeId).then(data => {
      if (data) {
        this.setState( { data: data.content, count: data.totalElements } );
      }
    });
  }

  reloadRoute = () => {
    queryAllRouteAction().then(data => {
      this.setState({ routeData: data });
    });
  }

  addRoutePoint = () => {
    this.setState({ addModal: true });
  }

  deleteRoutePoint = () => {
    let { routeId } = this.props;
    let { selectedRowKeys } = this.state;

    if (selectedRowKeys === undefined ||  selectedRowKeys.length <= 0 ) {
      AmosAlert.warning('提示', '请选择要删除的检查项');
      return;
    }
    let ids = selectedRowKeys.join(',');

    AmosAlert.confirm('提示', '是否删除?', {
      callback: (flag) => {
        if (flag){
          // 确定删除
          batchDelRoutePointAction(routeId, ids).then(data => {
            AmosAlert.success('提示', '删除成功', {
              callback: () => {
                // this.reloadPoint(this.pageConfig);
                this.state.reload();
              }
            });
          }, err => {
            AmosAlert.error('提示', err);
          });
        }
      }
    });
  }

  transferPoint = () => {
    let { routeId } = this.props;
    let { selectedRowKeys, selectedRouteRowKeys } = this.state;
    let ids = selectedRowKeys.join(',');
    if (!selectedRouteRowKeys || selectedRouteRowKeys.length <= 0 ) {
      return;
    }
    let targetRouteId = selectedRouteRowKeys;
    if ('-1' === targetRouteId) {
      return;
    }

    migrateRoutePointAction(routeId, ids, targetRouteId).then(data => {
      AmosAlert.success('提示', '迁移成功', {
        callback: () => {
          this.reloadPoint();
          this.cancel('tranf');
        }
      });
    }, err => {
      AmosAlert.error('错误', err);
      this.cancel('tranf');
    });
  }

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

  render() {
    let { pagination, isChecked, data, modal, addModal, count, selectedRowKeys } = this.state;
    let defaultPageConfig = this.pageConfig;
    return (
      <div className="patrol-page-table">
        <Modal
          className='route-point-modal'
          header="新增路线巡检点"
          visible={addModal}
          destroyContent
          noDefaultFooter
          onCancel={() => this.cancel('add')}
          content={this.getAddContext()}
        />
        <Modal
          className='route-point-modal'
          header="请选择迁移路线"
          visible={modal}
          content={this.getContext()}
          onCancel={() => this.cancel('tranf')}
          onOk={(e) => this.transferPoint()}
        />
        <BootBar dropnavs={getDropnavs()} callBack={this.onClickBootBar} />
        <AmosGridTable
          rowKey="id"
          columns={getColumns(this)}
          isPageable={pagination}
          isChecked={isChecked}
          dataList={data}
          totals={count}
          selectedRowKeys={selectedRowKeys}
          callBack={this.reload}
          onRowDoubleClick={this.props.onRowDoubleClick}
          onRowMouseEnter={(record, index) => this.handleMouseEnter(record, index)}
          onRowMouseLeave={(record, index) => this.handleMouseLeave(record, index)}
          getTableDataAction={this.reloadPoint}
          getSelectedRows={this.getSelectedRows}
          setPageConfig={this.setPageConfig}
          defaultPageConfig={defaultPageConfig}
        />
      </div>
    );
  }
}

RoutePointTable.propTypes = {
  changeType: PropTypes.string,
  queryParam: PropTypes.object,
  routeId: PropTypes.string,
  onRowDoubleClick: PropTypes.func
};

export default RoutePointTable;
