import React, { Component } from 'react';
import { AmosAlert, Form, Select, Modal, Button, Icon } from 'amos-framework';
import PropTypes from 'prop-types';
import BootBar from '../../../component/toolbar';
import AmosGridTable from '../../../component/table/table/AmosGridTable';
import PointModal from './PointModal';
import PointIntemModal from './PointIntemModal';
import { queryRoutePointAction, migrateRoutePointAction, queryAllRouteAction } from '../../../../services/checkService';
import '../../../../styles/view/patrol/routePoint.scss';

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

  return [
    {
      title: '巡检点编号',
      dataIndex: 'pointNo',
      key: 'pointNo',
      width: '20%'
    },{
      title: '巡检点名称',
      dataIndex: 'pointName',
      key: 'pointName',
      width: '40%',
      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;
      // }
    },{
      title: '扩展分类',
      dataIndex: 'classifyName',
      key: 'classifyName',
      width: '20%',
      className: 'uant-table-thead'
    }
    // ,{
    //   title: '操作',
    //   key: 'operation',
    //   width: '20%',
    //   render: (text, record, index) => {
    //     return (
    //       <span className="check-input-front">
    //         <Icon prefix="amosicon" icon="jianchaxiang" />&nbsp;&nbsp;
    //         <a href="javascript:;" onClick={() => {self.onItemClick(record);}}>检查项</a>
    //       </span>
    //     );
    //   }
    // }
  ];
};

/**
 * 路线巡检点列表
 *
 * @class RoutePointTable
 * @extends {Component}
 */
class RoutePointTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hover: [],
      pagination: false,
      isChecked: true,
      selectedRows: [],
      selectedRowKeys: [],
      pointSelected: [],
      routeData: [],
      deleteRowData: [],
      selectedRouteRowKeys: [],
      modal: false,
      addModal: false,
      itemModal: false,
      data: [],
      count: 0,
      requestParam: [],
      PointItemArray: []
    };
  }

  componentWillMount = () => {
    this.reloadRoute();
  };

  onItemClick =(record) =>{
    this.setState({ itemModal: true, pointId: record.pointId, routeId: record.routeId });
  }

  onClickBootBar = type => {
    if (type === '1') {
      this.openPointModal();
    } else if (type === '2') {
      this.deleteRoutePoint();
    } else if (type === '3') {
      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 (<PointModal callback={this.addCallback} routeId={routeId} />);
  }

  changePointItemArray = (data) => {
    const {PointItemArray}= this.state;
    this.setState({
      PointItemArray:data,
    });
  }

  getItemContext = () => {
    const { routeId, pointId,PointItemArray } = this.state;
    return <PointIntemModal PointItemArray={PointItemArray} changePointItemArray = {this.changePointItemArray}  routeId={routeId} pointId={pointId} ref={mode=> this.modal = mode} />;
  }

  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>}
            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 });
  }

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

  //鼠标移到内容模块上时触发的事件
  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];
      let upOrderNo = arr[index - 1].orderNo;
      let downOrderNo = arr[index].orderNo;
      arr[index - 1] = arr[index];
      arr[index - 1].orderNo = upOrderNo;
      arr[index] = temp;
      arr[index].orderNo = downOrderNo;
      this.setState({ data: arr });
    }
  }

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

  addCallback = (pointSelected) => {
    this.cancel('add');
    this.addRoutePoint(pointSelected);
  }

  addRoutePoint = (pointSelected)=>{
    let { data } = this.state;
    let { routeId } = this.props;
    let newData = data.slice();
    for (let point of pointSelected){
      point.orderNo = newData.length === 0 ? 0 : parseInt(newData[newData.length - 1].orderNo) + 1;
      point.pointName = point.name;
      point.pointId = point.id;
      point.routePointItem = [];
      routeId ? point.routeId = routeId : '';
      newData.findIndex(item => item.pointId === point.id) < 0 ?  newData.push(point) : '';
      delete point.id;
      delete point.name;
    }
    this.setState({ data: newData });
  }

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

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

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

  deleteRoutePoint = () => {
    let { selectedRowKeys, data , selectedRows } = this.state;
    const { forword } = this.props;
    let newData = data.slice();
    let deleteRowData = [];
    if (selectedRowKeys === undefined ||  selectedRowKeys.length <= 0 ) {
      AmosAlert.warning('提示', '请选择要删除的路线点');
      return;
    }
    AmosAlert.confirm('提示', '是否删除?', {
      callback: (flag) => {
        if (flag){
          selectedRows.map(item =>{
            let index = newData.findIndex(e => e.pointId === item.pointId );
            if (forword === 'edit' && newData[index].id) {
              newData[index].isDelete = true;
              deleteRowData.push(newData[index]);
            }
            newData.splice(index,1);
          });
          this.setState({ data: newData,selectedRows: [], deleteRowData, selectedRowKeys: [] });
        }
      }
    });
  }

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

      migrateRoutePointAction(routeId, ids, targetRouteId).then(data => {
        AmosAlert.success('提示', '迁移成功', {
          callback: () => {
            this.cancel('tranf');
          }
        });
      }, err => {
        AmosAlert.error('错误', err);
        this.cancel('tranf');
      });
    } else {
      AmosAlert.error('提示', '请在提交数据后进行迁移操作');
    }
  }

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

  savaPointItem =()=>{
    this.cancel('item');
    let { data, pointId } = this.state;
    const { forword } = this.props;
    let newData = data.slice();
    const { selectData } = this.modal.state;
    let deleteData = [];
    if (forword === 'edit' && newData.filter(it => it.pointId === pointId).length >= 0 && newData.filter(it => it.pointId === pointId)[0].id) {
      deleteData = this.modal.getDeleteItem();
    }
    let index = newData.findIndex(item => item.pointId === pointId);
    newData[index].routePointItem = [...selectData, ...deleteData];
    this.setState({ data: newData });
  }

  render() {
    let { pagination, isChecked, data, modal, addModal, count, selectedRowKeys, itemModal } = 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()}
        />
        <Modal
          className='route-point-item-modal'
          header="添加检查内容"
          visible={itemModal}
          destroyContent
          onCancel={() => this.cancel('item')}
          content={this.getItemContext()}
          onOk={() => this.savaPointItem()}
        />
        {/* <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}
          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 = {
  routeId: PropTypes.string,
  forword: PropTypes.string
};

export default RoutePointTable;
