import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form, AmosAlert, Input, Select, Button } from 'amos-framework';
import { controlMeasureSaveAction,controlMeasureDetailAction,getCatalogEumAction, getTypeEumAction, deleteMeasureContentAction } from '../../../../../services/bizService';
import EditableTextAreaCell from './../../../common/editableCell/EditableTextAreaCell';
import AmosGridTable from './../../../common/tableComponent/table/AmosGridTable';
import BizIcon from '../../../../common/icon/BizIcon';

const FormItem = Form.Item;
const Option = Select.Option;
const getColumns = (self) => {
  let oper = <Button icon={<BizIcon icon="tianjia" />} transparent onClick={() => {self.onAdd();}} />;
  return [
    {
      title: '控制措施内容',
      dataIndex: 'content',
      key: 'content',
      width: '50%',
      render: (text, record) => <EditableTextAreaCell value={text} onChange={(text,editable) => self.onCellChange(record, text, 'content',editable)} inital={record.inital} />,
      className: 'uant-table-thead'
    },
    {
      title: '标准依据',
      dataIndex: 'basis',
      key: 'basis',
      width: '47%',
      render: (text, record, index) => {
        let { isEdit } = self.state;
        if (Object.prototype.toString.apply(text) !== '[object Array]') {
          text = text ? JSON.parse(text) : [];
        }
        let basisItem = text[0] || '';
        let basisItemName = isEdit ? '' : basisItem.name;
        return (
          <div className="control-model-measure-content">
            <Input className='danger-long-input' value={basisItemName || ''} onChange={(e) => self.onBasisInputChange(basisItem.id, e.target.value, record)} />
            <Button icon={<BizIcon icon="tianjia" />} onClick={() => self.onBasisButtonClick('add', basisItem.id, record)} transparent />
            {self.renderBasisInputValues(basisItem.id, record)}
          </div>
        );
      },
      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)}
          />
        );
      },
      className: 'uant-table-thead operation-items'
    }
  ];
};

/**
 * 控制措施模型
 *
 * @class ControlModel
 * @extends {Component}
 */
class ControlModel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchParam: [],
      form: {
        name: '',
        category: '',
        type: '',
        detailCxt: []
      },
      rules: {
        name: [{ required: true, message: '控制措施名称不能为空' },{ max: 30, message: '长度不能大于30个字符',}],
        category: [{ required: true, message: '控制措施类别不能为空' }],
        type: [{ required: true, message: '所属类型不能为空' }],
        // criterion: [{ validator: this.validCriterion }]
        criterion: [{ max: 50, message: '长度不能大于50个字符',}]
      },
      deletedCxt: [],
      catalogData: [],
      typeData: [],
      basisValues: {},
      isEdit: props.mesId === undefined ? false : true
    };
  }

  componentWillMount = () => {
    const { mesId } = this.props || {};
    mesId && this.getMeaSuresDetailById(mesId);
    this.getCatalogEumData();
    this.getTypeEumData();
  };

  onCellChange = (record, text, type,editable) => {
    const { form } = this.state;
    const target = form.detailCxt.find(item => item.key === record.key);
    if (editable){
      target[type] = text;
    } else {
      target['inital'] = false;
    }
    this.setState({ form });
  };

  onDelete = (record) => {
    let { form,deletedCxt } = this.state;
    const { oprate } = this.props;
    let index = record.id ? form.detailCxt.findIndex(item => item.id === record.id) : form.detailCxt.findIndex(item=>item.key === record.key);//有id按照id删除
    if (oprate === 'edit') {
      form.detailCxt[index].id ? deletedCxt.push(form.detailCxt[index]) : '';
    }
    if (record.id) {
      deleteMeasureContentAction(record.id).then(
        data => {
          form.detailCxt.splice(index,1);
          form.detailCxt.forEach((item,index) => item.key = index);//修改key与index 相同
          this.setState({ form,deletedCxt });
        },
        err => {
          AmosAlert.error('错误', err);
        });
    } else {
      form.detailCxt.splice(index,1);
      form.detailCxt.forEach((item,index) => item.key = index);//修改key与index 相同
      this.setState({ form,deletedCxt });
    }
  }

  onAdd = () => {
    let { form } = this.state;
    form.detailCxt.map(item => item.inital = false);
    let newObj = { detailCxt: '', basis: [], inital: true, isDelete: false };
    form.detailCxt.push(newObj);
    form.detailCxt.forEach((item,index) => item.key = index);//设置key与index 相同
    this.setState({ form });
  }

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

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

  onBasisInputChange = (key, value, record) => {

    let { form, basisValues } = this.state;
    let recordIndex = record.key;
    let basis = form.detailCxt[recordIndex].basis[0];
    let basisItemValues = basisValues[record.key] || [];
    if (basis) {
      basis.name = value;
    } else {
      basis = {};
      basis.id = basisItemValues ? basisItemValues.length : 0;
      basis.name = value;
      form.detailCxt[recordIndex].basis.push(basis);
    }
    this.setState({ form, isEdit: false });
  }

  onBasisInputEditChange = (key, value, record) => {

    let { form, basisValues } = this.state;
    let recordIndex = record.key;
    let basisItemValues = basisValues[record.key] || [];
    let basis = basisItemValues[key];
    let formBasis = form.detailCxt[recordIndex].basis;
    if (basis) {
      basis.name = value;
      formBasis && (formBasis[basis.id + 1].name = value);
    } else {
      basis = {};
      basis.key = basisItemValues.length;
      basis.name = value;
      (basisValues[record.key] = []).push(basis);
      formBasis && formBasis.push(basis);
    }
    this.setState({ form });
  }

  onBasisButtonClick = (bthType, key, record) => {
    let { basisValues, form } =  this.state;
    let recordIndex = record.key;
    let basis = form.detailCxt[recordIndex].basis;
    let basisItemValues = basisValues[record.key] || [];
    if (bthType === 'delete') {
      let targetName = '';
      basisItemValues.map(item => {
        if (item.id === key) {
          targetName = item.name;
        }
      });
      basisItemValues.splice(basisItemValues.findIndex(item => item.id === key), 1);
      basisItemValues.forEach((item, index) => item.id = index);//修改key与index 相同
      let formBasis = form.detailCxt[record.key].basis;
      formBasis.splice(formBasis.findIndex(item => item.name === targetName), 1);
      formBasis.forEach((item, index) => item.id = index);
    } else {
      if (basis[0].name === '') {
        return;
      }
      if (basis[0]) {
        basisItemValues.push({ id: basisItemValues.length , name: basis[0].name });//设置key与index 相同
        basis.push({ id: basis.length, name: basis[0].name });
      }
      basisValues[record.key] = basisItemValues;
    }
    basis[0] && (basis[0].name = '');
    this.setState({ basisValues,form });
  }

  getMeaSuresDetailById = (id) => {
    controlMeasureDetailAction(id).then(data => {

      let { basisValues } = this.state;
      data.detailCxt && data.detailCxt.map((item, index) => {
        basisValues[index] = JSON.parse(item.basis);
        item.key = index;
        item.basis = JSON.parse(item.basis);
        for (let i = item.basis.length; i >= 0; i--) {
          item.basis[i] = item.basis[i - 1];
          (i > 0) && (item.basis[i].id = i);
        }
        item.basis[0] = { id: 0, name: '' };
      });
      this.setState({ form: data, basisValues });
    });
  }

  getCatalogEumData =()=>{
    getCatalogEumAction().then(data=>{
      this.setState({ catalogData: data });
    });
  }

  getTypeEumData =()=>{
    getTypeEumAction().then(data=>{
      this.setState({ typeData: data });
    });
  }

  handleSubmit = e => {
    this.form.validate((valid, dataValues) => {
      if (valid) {
        let { form, deletedCxt } = this.state;
        deletedCxt.forEach(item => item.isDelete = true);
        form.detailCxt = [...form.detailCxt, ...deletedCxt];
        form.detailCxt.forEach(item => {
          if (item.basis === undefined) {
            item.basis = [];
          }
          item.detailCxt = item.content;
        });
        form.detailCxt = form.detailCxt.filter(item => item.content !== undefined && item.content !== '');
        this.controlMeasureSave(form);
      } else {
        return false;
      }
    });
  };

  controlMeasureSave = body => {
    body.detailCxt.map(item => {
      let t = item.basis[0];
      let len = item.basis.length;
      if (len > 1) {
        for (let i = 1; i < len; i++) {
          item.basis[i - 1] = item.basis[i];
          item.basis[i - 1].id = i - 1;
        }
        item.basis[len - 1] = t;
        item.basis[len - 1].id = len - 1;
      }
      item.basis = item.basis.filter(o => o.name !== '');
      if (Object.prototype.toString.apply(item.basis) === '[object Array]') {
        item.basis = JSON.stringify(item.basis);
      }
      item.basis = item.basis ? item.basis : '[]';
    });
    controlMeasureSaveAction(body).then(
      data => {
        AmosAlert.success('提示', '操作成功');
        this.props.reloadPage();
      },
      err => {
        AmosAlert.error('提示', err);
      }
    );
  };

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

  renderBasisInputValues = (key, record) => {

    let { basisValues } = this.state;
    let basisItemValues = basisValues[record.key];
    return basisItemValues && basisItemValues.map(item=>{
      return (
        <div className="control-model-measure-content">
          <Input value={item.name}  className='danger-long-input' onChange={(e) => this.onBasisInputEditChange(item.id, e.target.value, record)} />
          <Button icon={<BizIcon icon="shanchu" />} onClick={() => this.onBasisButtonClick('delete', item.id, record)} value={item.id} transparent />
        </div>
      );
    });
  }

  validCriterion = (rule, value, callback) => {
    // debugger
    // let tempArry = value.split(',') || [];
    // if ( tempArry && tempArry.length === 3 ){
    //   const patt = /(^([-]?)[1-9]([0-9]+)?(\.[0-9]+)?$)|(^([-]?)(0){1}$)|(^([-]?)[0-9]\.[0-9]+?$)/;
    //   let i = 0;
    //   for (let key of tempArry){
    //     if (!patt.test(key)){
    //       i = i + 1;
    //       callback('非法格式');
    //       break;
    //     }
    //   }
    //   i === 0 ? callback() : '';
    // } else if (!value) {
    //   callback();
    // } else {
    //   callback('非法格式');
    // }
  }

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

    return (
      <div>
        <Form model={form} rules={rules} ref={component => this.form = component}>
          <div className="control-model-line1" >
            <div>
              <FormItem label={<span>控制措施名称</span>} field="name" {...formItemLayout}>
                <Input required className="risk_factor_input" onChange={e => this.onChange('name', e)} value={form.name} />
              </FormItem>
              <FormItem label={<span>所属类型</span>} field="type" {...formItemLayout}>
                <Select
                  className="risk_factor_input"
                  data={typeData}
                  renderOption={item => <Option value={item.dictDataKey}>{item.dictDataValue}</Option>}
                  value={form.type}
                  onChange={value => this.onSelectChange('type', value)}
                />
              </FormItem>
            </div>
            <div>
              <FormItem label={<span>控制措施类别</span>} field="category" {...formItemLayout}>
                <Select
                  className="risk_factor_input"
                  data={catalogData}
                  renderOption={item => <Option value={item.dictDataKey}>{item.dictDataValue}</Option>}
                  value={form.category}
                  onChange={value => this.onSelectChange('category', value)}
                />
              </FormItem>
            </div>
          </div>
          <FormItem label={<span>控制措施内容</span>} field="criterion" className='editable-table' >
            <AmosGridTable
              rowKey="key"
              columns={getColumns(this)}
              callBack={this.reload}
              dataList={form.detailCxt || []}
              getTableDataAction={() => {}}
              isChecked={false}
              isPageable={false}
            />
          </FormItem>
        </Form>
      </div>
    );
  }
}

ControlModel.propTypes = {
  reloadPage: PropTypes.func,
  oprate: PropTypes.string
};
export default ControlModel;
