import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { Form, AmosAlert, Input, Button } from 'amos-framework';
import { evaluateCriteriaSaveAction } from '../../../../../services/bizService';
import EditableCell from './../../../common/editableCell/EditableCell';
import AmosGridTable from './../../../common/tableComponent/table/AmosGridTable';
import BizIcon from '../../../../common/icon/BizIcon';

const FormItem = Form.Item;
const getColumns = (self) => {
  let oper = <Button icon={<BizIcon icon="tianjia" />} transparent onClick={() => {self.onAdd();}} />;
  return [
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: '30%',
      render: (text, record) => <EditableCell value={text} onChange={(text) => self.onCellChange(record, text, 'description')} inital={record.inital} />,
      className: 'uant-table-thead'
    },
    {
      title: '评分标准',
      dataIndex: 'standard',
      key: 'standard',
      width: '50%',
      render: (text, record) => <EditableCell value={text} onChange={(text) => self.onCellChange(record, text, 'standard')} inital={record.inital} />,
      className: 'uant-table-thead'
    },
    {
      title: '分值',
      dataIndex: 'score',
      key: 'score',
      width: '17%',
      render: (text, record) => <EditableCell value={text} onChange={(text) => self.onCellChange(record, text, 'score')} inital={record.inital} />,
      className: 'uant-table-thead'
    },
    {
      title: oper,
      dataIndex: 'score',
      key: 'score',
      width: '3%',
      render: (text, record) => {
        return (
          <Button
            icon={<BizIcon icon="shanchu" />}
            transparent
            onClick={() => self.onDelete(record.key)}
          />
        );
      },
      className: 'uant-table-thead operation-items'
    }
  ];
};

/**
 * 风险评价准则新增及编辑
 */
class EvaluationCriteria extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchParam: [],
      maintenances: [],
      last: false,
      form: {
        name: '',
        evaluateModelId: -1,
        criteriation: []
      },
      rules: {
        name: [{ required: true, message: '风险评价准则名称不能为空' },{ max: 50, message: '长度不能大于50个字符',}]
      }
    };
  }

  componentWillMount = () => {
    const { selectRowData } = this.props || {};
    if (selectRowData) {
      let form = {};
      Object.assign(form, selectRowData);
      form.criteriation = JSON.parse(selectRowData.content);
      this.setState({ form });
    }
  };

  onCellChange = (record, text, type) => {
    const { form } = this.state;
    const target = form.criteriation.find(item => item.key === record.key);
    if (target) {
      target[type] = text;
      target['inital'] = false;
      this.setState({ form });
    } else {
      let obj = {};
      obj[type] = text;
      form.criteriation.push(obj);
      this.setState({ form });
    }
    console.log(type);
  };

  onDelete = (index) => {
    let { form } = this.state;
    form.criteriation = form.criteriation.filter(item => item.key !== index);
    form.criteriation.map(item => {
      if (item.key > index) {
        item.key -= 1;
      }
    });
    this.setState({ form });
  }

  onAdd = () => {
    let { form } = this.state;
    form.criteriation.map(item => item.inital = false);
    let key = form.criteriation.length + 1;
    let newObj = { key, description: '', standard: '', score: '', inital: true };
    form.criteriation.push(newObj);
    this.setState({ form });
  }

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

  handleSubmit = evaModelId => {
    this.form.validate((valid, dataValues) => {
      if (valid) {
        let { form } = this.state;
        form.evaluateModelId = evaModelId;
        this.evaluateCriteriaEdit(form);
      } else {
        return false;
      }
    });
  };

  evaluateCriteriaEdit = body => {
    body.content = JSON.stringify(body.criteriation);
    evaluateCriteriaSaveAction(body).then(
      data => {
        AmosAlert.success('提示', '操作成功');
        this.props.reloadPage();
      },
      err => {
        AmosAlert.error('提示', err);
      }
    );
  };

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

  render() {
    const { form, rules } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
        className: 'colspan'
      }
    };

    return (
      <div>
        <Form model={form} rules={rules} ref={component => this.form = component}>
          <FormItem label={<span>准则名称</span>} field="name" {...formItemLayout}>
            <Input className="risk_factor_input" required value={form.name} onChange={e => this.onInputChange('name', e.target.value)} />
          </FormItem>
          <FormItem label={<span>准则</span>} field="criterion" className='editable-table' >
            <AmosGridTable
              rowKey="key"
              columns={getColumns(this)}
              callBack={this.reload}
              dataList={form.criteriation || []}
              getTableDataAction={() => {}}
              isChecked={false}
              isPageable={false}
            />
          </FormItem>
        </Form>
      </div>
    );
  }
}

EvaluationCriteria.propTypes = {
  reloadPage: PropTypes.func
};
export default EvaluationCriteria;
