import React, { Component } from 'react';
import { AmosAlert, Form,  Modal, message , Select } from 'amos-framework';
import { TreeSelect } from 'amos-antd';
import { browserHistory } from 'amos-react-router';
import PropTypes from 'prop-types';
import moment from 'moment';
import BootBar from '../../component/toolbar';
import AmosGridTable from '../../component/table/table/AmosGridTable';
import { pathMapping } from './../../../routes/customRoutes';
import { queryTaskAction, batchDelTaskAction, handleTaskAction, queryDeptUserTree, forwardTaskAction,btnAuthAction} from '../../../services/checkService';
const FormItem = Form.Item;
const Option = Select.Option;
const detailTask = pathMapping.detailTask;
const newTask = pathMapping.newTask;



  const dropnavs1 = { key: '1', text: '新增', icon: 'add', href: newTask , permissionCode: 'task', isWriteable: true };
  const dropnavs2 ={ key: '6', text: '转发', icon: 'ccgl-chukucaozuo-13' , href: 'jacascript::void(0)' , permissionCode: 'task', isWriteable: true };
  const dropnavs3 ={ key: '2', text: '明细', icon: 'edit' , href: 'jacascript::void(0)' , permissionCode: 'task', isWriteable: false };
  // { key: '3', text: '办结', icon: 'ccgl-chukucaozuo-13' , href: 'jacascript::void(0)' , permissionCode: 'task', isWriteable: true },
  const dropnavs4 ={ key: '4', text: '取消', icon: 'ccgl-chukucaozuo-13' , href: 'jacascript::void(0)' , permissionCode: 'task', isWriteable: true };
  const dropnavs5 ={ key: '5', text: '删除', icon: 'delete', href: 'jacascript::void(0)' , permissionCode: 'task', isWriteable: true };





const getColumns = () =>{
  return [
    {
      title: '任务名称',
      dataIndex: 'title',
      key: 'title',
      width: 180,
      className: 'uant-table-thead'
    },
    {
      title: '巡检点（检查项）',
      dataIndex: 'pointItemName',
      key: 'pointItemName',
      width: 180,
      className: 'uant-table-thead'
    },
    {
      title: '执行人',
      dataIndex: 'executor',
      key: 'executor',
      width: 130,
      className: 'uant-table-thead'
    },
    {
      title: '发布时间',
      dataIndex: 'publishTime',
      key: 'publishTime',
      width: 150,
      className: 'uant-table-thead',
      render: text =>text === null ? '' : moment(text).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '完成时间',
      dataIndex: 'finishTime',
      key: 'finishTime',
      width: 150,
      className: 'uant-table-thead',
      render: text =>text === null ? '' : moment(text).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '任务状态',
      dataIndex: 'status',
      key: 'status',
      width: 140,
      className: 'uant-table-thead',
      render: (text,record) => {
        if (record.status === 0) {
          return '处理中';
        } else if (record.status === 1) {
          return '已完成';
        }
        else if (record.status === 2) {
          return '已取消';
        }
        else if (record.status === 3) {
          return '已超时';
        }
      }
    },
    {
      title: '执行反馈',
      dataIndex: 'feedbackNum',
      key: 'feedbackNum',
      width: 160,
      className: 'uant-table-thead'
    }
  ];
};

/**
 * 巡检项
 *
 * @class InputItemTable
 * @extends {Component}
 */
class TaskTable extends Component{
  constructor(props) {
    super(props);
    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
    this.state = {
      pagination: true,
      isChecked: true,
      selectedRows: [],
      selectedRowKeys: [],
      data: [],
      userData: [],
      count: 0,
      executor: '',
      pageConfig: {
        pageNumber: 0,
        pageSize: 10
      },
      requestParam: [],
      dropnavs:[]
    };
  }

  /**
   * 组件初始化调用
   */
  componentWillMount = () => {
    this.loadexecutor();
    this.reloadButtonAuth();
  }


reloadButtonAuth = () => {
  // const _path = this.calcRoutes();
  btnAuthAction('/main/patrol/task').then(data => {
    
    let { dropnavs } = this.state;
   if(data){

     if("add" in data&&data.add.hasPermission){
      dropnavs.push( dropnavs1);
     }
     if("zf" in data&&data.zf.hasPermission){
      dropnavs.push( dropnavs2);

    }
    if("mx" in data&&data.mx.hasPermission){
      dropnavs.push( dropnavs3);

    }
    if("qx" in data&&data.qx.hasPermission){
      dropnavs.push( dropnavs4);

    }
    if("delete" in data&&data.delete.hasPermission){
      dropnavs.push( dropnavs5);

    }
   }

    this.setState({ dropnavs});
  });
}
  /**
   * 接受新的属性时回调
   */
  componentWillReceiveProps = (nextProps) => {
    let { changeType, queryParam } = nextProps;
    if ('query' === changeType) {
      let request = new Array();
      if (queryParam) {
        for (let key in queryParam) {
          let obj = queryParam[key];
          request.push(obj);
        }
      }
      this.setState({ requestParam: request }, () => this.reloadTask(this.pageConfig));
    }
  }

  onRowDoubleClick =(record, index, event) => {
    let path = {
      pathname: detailTask,
      state: { taskID: record.id }
    };
    browserHistory.push(path);
  }

  onClickBootBar = type => {
    if (type === '2') {
      this.detailTask();
    } else if (type === '3') {
      this.handleTask(1);
    } else if (type === '4') {
      this.handleTask(2);
    } else if (type === '5') {
      this.deleteTask();
    } if ('6' === type) {
      this.forward();
    }
  };

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

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

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

  // loadexecutor = () => {
  //   queryDeptUserTree().then(data => {
  //     let deptPersons = data.filter(item => item.children !== null);
  //     this.setState({ userData: deptPersons });
  //   });
  // }

  loadexecutor = () => {
    queryDeptUserTree().then(data => {

      
      let deptPersons = data.filter(item => item.children !== null);
      deptPersons.map(item => {
        if (item.children.length > 0) {
          item.children.map(t => {
            t.title = t.label;
          });
        }
      });
      this.setState({ userData: deptPersons });
    });
  };
  /**
   *根据条件查询检查项
   */
  reloadTask = (pageParam) => {
    let { requestParam } = this.state;
    let { pageSize } = pageParam;
    let pageNumber = 0;
    this.setState({ selectedRows: [], selectedRowKeys: [] });
    if (pageParam.current !== null && !isNaN(pageParam.current)) {
      pageNumber = pageParam.current;
    }
    queryTaskAction(requestParam, pageNumber, pageSize).then(data => {
      if (data) {
        this.setState( { data: data.content, count: data.totalElements } );
      }
    });
  }

  /**
   * 删除已经选择的检查项
   */
  deleteTask = () => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined ||  selectedRowKeys.length <= 0 ) {
      AmosAlert.warning('提示', '请先点击选择需要删除的行');
      return;
    }
    let ids = selectedRowKeys.join(',');

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

  /**
   * 跳转到跟新检查项页面
   */
  detailTask = () => {
    const { selectedRows } = this.state;
    if (selectedRows === undefined || selectedRows.length <= 0 ) {
      AmosAlert.warning('提示', '请先点击选择需要编辑的行');
      return;
    }
    let row = selectedRows[0];
    let path = {
      pathname: detailTask,
      state: { taskID: row.id }
    };
    path && browserHistory.push(path);
  }

  forward = () => {
    const { selectedRows } = this.state;
    if (selectedRows === undefined || selectedRows.length <= 0 ) {
      AmosAlert.warning('提示', '请先选择一条需要转发的任务');
      return;
    }
    if ( selectedRows.length > 1 ) {
      AmosAlert.warning('提示', '至多可以选择一条转发的任务');
      return;
    }
    this.setState({ forwardModal: true });
  }

  /**
   * 另存为选中的检查项
   */
  handleTask = (status) => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined ||  selectedRowKeys.length <= 0 ) {
      AmosAlert.warning('提示', '请选择要处理的任务');
      return;
    }
    let ids = selectedRowKeys.join(',');
    AmosAlert.confirm('提示', '是否处理该任务?', {
      callback: (flag) => {
        if (flag){
          // 确定删除
          handleTaskAction(ids, status).then(data => {
            AmosAlert.success('提示', '处理成功', {
              callback: () => {
                // this.reloadTask(this.pageConfig);
                this.state.reload();
              }
            });
          }, err => {
            AmosAlert.error('错误', err);
          });
        }
      }
    });
  }

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




  onSelectChange = (value, item) => {
   
    this.setState({ executorId: value, executor: item.name });
  
  }




  getForwardContext = () => {
    let { userData ,executor } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
        className: 'colspan'
      }
    };
    const conentStyle = {
      height: '200px'
    };
    let def = true;
    return (
      <Form style={conentStyle}>
        <FormItem label={<span>执行人</span>} {...formItemLayout} >
          <TreeSelect
            showSearch
            treeData={userData}
            // className="input_item_select"
            dropdownStyle={{ height: 150, overflow: 'auto' }}
            onSelect={this.handleExecutorsChange1}
            treeIcon={def}
            value={executor}
            treeLine={def}
            style={{ width: 167 }}
            placeholder="执行人选择"
            showCheckedStrategy={TreeSelect.SHOW_CHILD}
            treeNodeFilterProp="title"
            treeNodeLabelProp="title"
            treeDefaultExpandAll
          />

          {/* <Select data={userData}
           renderOption={item => <Option value={item.id}>{item.name}</Option>}
           defaultOption={<Option>执行人选择</Option>}
           onChange={this.onSelectChange}/> */}




        </FormItem>
      </Form>
    );
  }

  handleExecutorsChange1 = (executorList, label, extra) => {
    
    let pro = label.props;
    let userName = '';
    let userId = '';
    if ( pro.children || pro.type === 'department' ) {
      userName = '';
      userId = '';
    } else {
      userName = pro.title;
      userId = parseInt(pro.value);
     // userId = parseInt(pro.userId);
    }
    this.setState({ executorId: userId, executor: userName });
  }

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

  forwardSubmit = () => {
    const { executorId, selectedRows } = this.state;
    
    if (executorId && executorId !== '') {
      forwardTaskAction(executorId, selectedRows[0].id).then(data => {
        if (data) {
          message.danger(data, 3);
        } else {
          this.setState({ forwardModal: false });
          AmosAlert.success('提示', '转发成功');
          this.state.reload();
        }
      }, err => {
        AmosAlert.error(err);
      });
      return;
    }
  }

  render() {
    let { pagination, isChecked, data, count, dropnavs,forwardModal, selectedRowKeys } = this.state;
    let defaultPageConfig = this.pageConfig;
    return (
      <div className="patrol-page-table">
        <Modal
          header="转发任务"
          visible={forwardModal}
          onCancel={() => this.cancel()}
          content={this.getForwardContext()}
          onOk={(e) => this.forwardSubmit()}
        />
        <BootBar dropnavs={dropnavs} callBack={this.onClickBootBar} />
        <AmosGridTable
          rowKey="id"
          columns={getColumns()}
          isPageable={pagination}
          isChecked={isChecked}
          dataList={data}
          totals={count}
          callBack={this.reload}
          selectedRowKeys={selectedRowKeys}
          onRowDoubleClick={this.onRowDoubleClick}
          getTableDataAction={this.reloadTask}
          getSelectedRows={this.getSelectedRows}
          setPageConfig={this.setPageConfig}
          defaultPageConfig={defaultPageConfig}
        />
      </div>
    );
  }
}

TaskTable.propTypes = {
  changeType: PropTypes.string,
  queryParam: PropTypes.object
};

export default TaskTable;
