import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form, Input, AmosAlert, Button, Select } from 'amos-framework';
import AmosGridTable from './../../../common/tableComponent/table/AmosGridTable';
import {
  getMonitorPointListAction,
  saveMonitorPointAction,
  deleteMonitorPointAction,
  editMonitorPointAction,
  queryMonitorPointAction
} from './../../../../../services/ledgerService';
import BizIcon from './../../../../common/icon/BizIcon';

const FormItem = Form.Item;
const Option = Select.Option;

const isNormalEnum = { 1: '正常', 0: '异常' };
const typeEnum = { ANALOGUE: '模拟量', SWITCH: '开关量' };

const monitorPointTableColumns = self => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '编号',
      dataIndex: 'code',
      key: 'code',
      width: '23%'
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: '20%'
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: '20%',
      render: text => typeEnum[text] ? typeEnum[text] : text
    },
    {
      title: '单位',
      dataIndex: 'unit',
      key: 'unit',
      width: '15%'
      // render: (text, record) => {
      //   if (record.type === 'ANALOGUE') {
      //     return text;
      //   } else {
      //     return isNormalEnum[text] ? isNormalEnum[text] : text;
      //   }
      // }
    }
  ];
};

class MonitorPointConfig extends Component {
  constructor(props) {
    super(props);
    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
    this.state = {
      form: {
        code: '',
        name: '',
        type: '',
        unit: ''
      },
      rules: {
        code: [
          { required: true, message: '请输入点位编号' },
          { pattern: new RegExp(/[^\u4e00-\u9fa5]+$/), message: '编号不能包含中文' },
          { pattern: new RegExp(/^[^ ]+$/), message: '编号不能为空或含有空格' },
          { pattern: new RegExp(/^(-?\d+)(\.\d+)?$/), message: '编号只能是数字' },
          {
            // validator: (rule, value, callback) => {

            //   const { pointId } = this.props;
            //   this.queryAllPointNo(pointId);
            //   const { pointNoData } = this.state;
            //   if (!pointNoData.includes(value)) {
            //     callback();
            //   } else {
            //     callback(new Error('该编号已存在！'));
            //   }
            // }
          }
        ],
        name: [
          { required: true, message: '请输入名称' }
        ],
        type: [
          { required: true, message: '请选择类型' }
        ],
        unit: [
          { required: true, message: '请输入单位' }
          // { pattern: new RegExp(/^(-?\d+)(\.\d+)?$/), message: '请输入正确参数' }
        ]
      },
      data: [],
      selectedRowKeys: [],
      selectedRows: [],
      searchParam: [],
      fireEquipmentId: -1,
      monitorPointId: -1,
      totals: 0 //所有数据总和
    };
  }

  componentWillMount() {
    let { fireEquipmentId } = this.props;
    fireEquipmentId && this.getInitMonitorPointListData(fireEquipmentId);
  }

  onChange = (key, e) => {
    const { form } = this.state;
    if (e && e.target) {
      const value = e.target.value;
      form[key] = value;
    }
    this.setState({ form });
  };

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

  };

  getInitMonitorPointListData(fireEquipmentId) {
    let { searchParam } = this.state;
    searchParam.pageNumber = 0;
    searchParam.pageSize = 10;
    searchParam.fireEquipmentId = fireEquipmentId;
    this.setState({
      fireEquipmentId
    }, this.getMonitorPointListData(searchParam));
  }

  getMonitorPointListData = (param) => {
    let { searchParam } = this.state;
    if (param.current != null) {
      //前端的current 即后端的pageNumber
      param.pageNumber = param.current;
    }
    Object.assign(searchParam, { ...param });
    getMonitorPointListAction(searchParam, searchParam.fireEquipmentId, param.pageNumber, param.pageSize).then(data => {
      this.setState({
        dataList: data.content,
        totalCount: data.totalElements
      });
    });
  };

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

  getRowClassName = (record, index) => {
    let highlight = this.highlight;
    if (highlight && record.id === highlight) {
      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.current = current;
    }
  };

  renderParamValueView(formItemLayout) {
    let { form, rules } = this.state;
    let type = form.type;
    // if (type === 'SWITCH') {
    //   return (
    //     <FormItem label={<span>参数</span>} field="value" {...formItemLayout}>
    //       <Select prefixCls="" className="monitor-point-config-form-select" value={form.value.toString()} onChange={e => this.onSelectChange('value', e)}>
    //         <Option value="1">开</Option>
    //         <Option value="0">合</Option>
    //       </Select>
    //     </FormItem>);
    // } else {
    //   return (
    //     <FormItem label={<span>单位</span>} field="value" {...formItemLayout}>
    //       <Input className="monitor-point-config-form-input" value={form.value} placeholder="" onChange={e => this.onChange('value', e)} />
    //     </FormItem>);
    // }
    if (type === 'ANALOGUE') {
      rules.unit = [{ required: true, message: '请输入单位' }];
      return (
        <FormItem label={<span>单位</span>} field="unit" {...formItemLayout}>
          <Input className="monitor-point-config-form-input" value={form.unit} placeholder="" onChange={e => this.onChange('unit', e)} />
        </FormItem>);
    } else {
      rules.unit = [];
    }
  }

  handleSubmit = e => {
    this.form.validate((valid, dataValues) => {
      if (valid) {
        const { form, fireEquipmentId, monitorPointId } = this.state;
        form.fireEquipmentId = fireEquipmentId;
        let MonitorPoint = Object();
        Object.assign(MonitorPoint, form);

        if (monitorPointId) { // 编辑时
          editMonitorPointAction(monitorPointId, MonitorPoint).then(
            data => {
              AmosAlert.success('提示', '配置成功');
              // this.getInitMonitorPointListData(fireEquipmentId);
              this.reloadPage();
            },
            error => {
              AmosAlert.error('错误', '配置失败');
            }
          );
        } else {  // 新增时
          saveMonitorPointAction(MonitorPoint).then(
            data => {
              AmosAlert.success('提示', '配置成功');
              // this.getInitMonitorPointListData(fireEquipmentId);
              this.reloadPage();
            },
            error => {
              AmosAlert.error('错误', '配置失败');
            }
          );
        }
        return true;
      } else {
        return false;
      }
    });
  };

  handleCancel(e, self) {
    self.setState({
      form: {
        code: '',
        name: '',
        type: '',
        unit: ''
      },
      selectedRowKeys: [],
      monitorPointId: undefined
    });
  }

  getOperationBtn() {
    return (
      <div>
        <Button icon={<BizIcon icon="tianjia" />} transparent onClick={() => this.add()} />
        <Button icon={<BizIcon icon="xiugai" />} transparent onClick={() => this.edit()} />
        <Button icon={<BizIcon icon="shanchu" />} transparent onClick={() => this.delete()} />
      </div>
    );
  }

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

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

  add() {
    this.setState({
      form: {
        code: '',
        name: '',
        type: '',
        unit: ''
      },
      selectedRowKeys: [],
      monitorPointId: undefined
    });
  }

  edit() {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要编辑的监测点');
      return;
    }
    let monitorPointId = selectedRowKeys[0];
    this.setState({
      monitorPointId
    });
    queryMonitorPointAction(selectedRowKeys[0]).then(
      data => {
        this.setState({
          form: data
        });
      },
      err => {
        AmosAlert.error('错误', err);
      }
    );
  }

  delete() {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要删除的监测点');
      return;
    }
    AmosAlert.confirm('提示', '确定删除指定监测点?', {
      callback: flag => {
        if (flag) {
          // 确定删除
          let ids = selectedRowKeys.join(',');
          deleteMonitorPointAction(ids).then(
            data => {
              AmosAlert.success('提示', '删除成功');
              this.reloadPage();
              this.setState({
                form: {
                  code: '',
                  name: '',
                  type: '',
                  unit: ''
                },
                selectedRowKeys: []
              });
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }
      }
    });
  }

  render() {
    let { dataList, totalCount, form, rules, selectedRowKeys } = this.state;
    const pagination = { pageSizeOptions: ['10'], defaultPageSize: 10 };//分页：10条每页，默认为10
    const formItemLayout = {
      labelCol: {
        xs: { span: 26 },
        sm: { span: 8 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 26 },
        sm: { span: 14 },
        className: 'colspan'
      }
    };
    let isChecked = true;
    return (
      <div className='monitor-point-config-list' style={{ display: '-webkit-inline-box', width: '100%' }}>
        <div  className='monitor-point-config-list1'>
          <div className='monitor-point-config-list-header' >
            <div className='table-operation-btn'>
              {this.getOperationBtn()}
            </div>
            <div className='monitor-point-config-list-header-title'>已配置点位列表</div>
          </div>
          <AmosGridTable
            rowKey="id"
            columns={monitorPointTableColumns(this)}
            callBack={this.reload}
            dataList={dataList}
            totals={totalCount}
            getTableDataAction={this.getMonitorPointListData}
            pagination={pagination}
            getSelectedRows={this.getSelectedRows}
            rowClassName={this.getRowClassName}
            setPageConfig={this.setPageConfig}
            selectedRowKeys={selectedRowKeys}
            // getPanelHeight={this.getPanelHeight}
            // defaultPageConlHeight={this.getPanelHeight}
            isChecked={isChecked}
          />
        </div>
        <div className='monitor-point-config-list2'>
          <div className='monitor-point-config-form-header'>监测点配置</div>
          <div className='monitor-point-config-form'>
            <Form model={form} rules={rules} ref={component => this.form = component}>
              <FormItem label={<span>点位编号</span>} field="code" {...formItemLayout}>
                <Input className="monitor-point-config-form-input" value={form.code} placeholder="点位编号唯一" onChange={e => this.onChange('code', e)} />
              </FormItem>
              <FormItem label={<span>名称</span>} field="name" {...formItemLayout}>
                <Input className="monitor-point-config-form-input" value={form.name} placeholder="" onChange={e => this.onChange('name', e)} />
              </FormItem>
              <FormItem label={<span>类型</span>} field="type" {...formItemLayout}>
                <Select prefixCls="" className="monitor-point-config-form-select" value={form.type} onChange={e => this.onSelectChange('type', e)}>
                  <Option value="ANALOGUE">模拟量</Option>
                  <Option value="SWITCH">开关量</Option>
                </Select>
              </FormItem>
              <div>{this.renderParamValueView(formItemLayout)}</div>
              <FormItem>
                <div className='operation-button'>
                  <Button onClick={this.handleSubmit}>确定</Button>
                  <Button onClick={e => this.handleCancel(e, this)}>取消</Button>
                </div>
              </FormItem>
            </Form>
          </div>
        </div>
      </div>
    );
  }
}

MonitorPointConfig.propTypes = {
  fireEquipmentId: PropTypes.number
};
export default MonitorPointConfig;
