import React, { Component } from 'react';
// import { utils } from 'amos-tool';
import {isEmpty} from '../../../utils/validate'
import { Form, Input, AmosAlert, Radio, Button, Select, Checkbox, InputNumber } from 'amos-framework';
import PropTypes from 'prop-types';
import { browserHistory } from 'amos-react-router';
import { TreeSelect } from 'amos-antd';
import './../../../styles/view/patrol/inputItem.scss';
import HasPermission from '../../component/toolbar/hasPermission';

import CommonTablexq from './CommonTablexq';
import { saveInputItemAction, queryInputItemDetailAction, queryCatalogTreeAction, queryAllItemNoAction } from '../../../services/checkService';

const TextArea = Input.TextArea;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const levelData = [{ id:'1' ,name:'1级' }, { id:'2' ,name: '2级' }, { id:'3' ,name:'3级'}, { id:'4' ,name:'4级' }, { id:'5' ,name:'5级'}];

class NumberInputItemxq extends Component {
  constructor(props) {
    super(props);
    this.state = {
      form: {
        name: '',
        defaultValue: '',
        catalogId: '',
        itemType: '数字',
        isMultiline: '是',
        isScore: '是',
        isMust: '是',
        remark: '',
        level:'',
        itemNo: ''
      },
      tableData: [],
      itemNoData: [],
      treeData: [],
      inputItemID: '',
      dataJson: {
        OkScore: 0,
        NoScore: 0,
        ValidUp: '',
        ValidDown: '',
        OkUp: '',
        OkDown: '',
        CheckValidUp: false,
        CheckValidDown: false,
        CheckOkUp: false,
        CheckOkDown: false,
        Precision: 0
      },
      rules: {
        name: [{ required: true, message: '请输入检查项名称' }],
        CheckValidUp: [{ type: 'number', message: '非法参数' }],
        CheckValidDown: [{ type: 'number', message: '非法参数' }],
        CheckOkUp: [{ type: 'number', message: '非法参数' }],
        CheckOkDown: [{ type: 'number', message: '非法参数' }],
        itemNo: [
          { required: true, message: '请输入检查项编号' },
          { pattern: new RegExp(/[^\u4e00-\u9fa5]+$/), message: '编号不能包含中文' },
          { pattern: new RegExp(/^[^ ]+$/), message: '编号不能为空或含有空格' },
          {
            validator: (rule, value, callback) => {

              const { inputItemID } = this.state;
              this.queryAllItemNo(inputItemID); //查询除自己外的所有编号数组
              const { itemNoData } = this.state;
              if (!itemNoData.includes(value)) {
                callback();
              } else {
                callback(new Error('该编号已存在！')); //校验检查项编号是否重复
              }
            }
          }
        ]
      },
      showTips: false,
      errList: new Map()

    };
  }
  /**
   * 组件初始化时调用
   */
  componentWillMount = () => {
    this.queryCatalogTree();
    const { inputItemID } = (this.props.location || {}).state || {};
    inputItemID && this.onInit(inputItemID);
  };

  queryCatalogTree = () => {
    queryCatalogTreeAction().then(data => {
      let treeData = data;
      this.setState({ treeData: treeData });
    });
  };
  /**
   * 编辑页面时初始化数据
   */
  onInit = id => {
    this.setState({ inputItemID: id });
    queryInputItemDetailAction(id).then(data => {
      let detail = new Object();
      detail.name = data.name;
      detail.itemNo = data.itemNo;
      detail.defaultValue = data.defaultValue;
      detail.catalogId = data.catalogId;
      detail.itemType = data.itemType;
      detail.isScore = data.isScore;
      detail.isMust = data.isMust;
      detail.remark = data.remark;
      detail.level = data.level;
      let json = JSON.parse(data.dataJson);
      let pic = JSON.parse(data.pictureJson);
      this.setState({ form: detail, tableData: pic, dataJson: json });
    });
  };

  queryAllItemNo(itemId) {
    if (isEmpty(itemId)) {
      itemId = -1;
    }
    queryAllItemNoAction(itemId).then(data => {
      this.setState({ itemNoData: data });
    });
  }

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

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

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

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

  onChangeTableValues = values => {
    this.setState({ tableData: values });
  };

  /**
   *checkbox点击数据处理
   */
  onChangeCheckBox(record, checked) {
    let { tableData } = this.state;
    record.isMust = checked;
    tableData[record.orderNo - 1] = record;
    this.setState({ tableData });
  }

  onDataJsonCheckBox(key, e) {
    const { dataJson } = this.state;
    dataJson[key] = e;
    this.setState({ dataJson });
  }

  onChangePicInput = (record, e) => {
    const { tableData } = this.state;
    for (let i = 0; i < tableData.length; i++) {
      if (tableData[i].orderNo === record.orderNo) {
        tableData[i].name = e;
      }
    }
    this.setState(tableData);
  };

  onChangePicCheckBox = (record, checked) => {
    const { tableData } = this.state;
    for (let i = 0; i < tableData.length; i++) {
      if (tableData[i].orderNo === record.orderNo) {
        tableData[i].isMust = checked ? '是' : '否';
      }
    }
    this.setState(tableData);
  };

  /**
   * 获取表格表头
   */
  getPicTablecolumns = () => {
    let { errList } = this.state;
    errList.clear();
    return [
      {
        title: '名称',
        dataIndex: 'name',
        width: '50%',
        render: (text, record) => {
          let { showTips, errList } = this.state;
          errList.set(record.orderNo, showTips);
          return !record.edit ? text : <Input style={{ width: '100%', padding: '0px' }} placeholder="名称不能为空" onChange={e => this.onChangePicInput(record, e.target.value)} value={text} />;
        }
      },
      {
        title: '是否拍照',
        dataIndex: 'isMust',
        width: '50%',
        render: (text, record) => {
          return !record.edit ? (
            text ? (
              text
            ) : (
              '否'
            )
          ) : (
            <Checkbox
              onChange={e => this.onChangePicCheckBox(record, e.target.checked)}
              checked={text === undefined || text === '否' ? false : true}
              defaultChecked={text === undefined || text === '否' ? false : true}
            />
          );
        }
      }
    ];
  };

  handleSubmit = e => {
    let { errList } = this.state;
    if ([...errList.values()].includes(true)) {
      return;
    }
    this.form.validate((valid, dataValues) => {
      const { form, tableData, dataJson, inputItemID } = this.state;
      if (valid) {
        let body = Object();
        Object.assign(body, form);
        let pictureJson = tableData.map(item => {
          if (item.name !== undefined && item.name !== ''){
            let obj = new Object();
            obj.isMust = item.isMust;
            obj.name = item.name;
            obj.orderNo = item.orderNo;
            return obj;
          }
        });
        pictureJson = pictureJson.filter(item => item != undefined);
        body.id = inputItemID;
        body.pictureJson = JSON.stringify(pictureJson);
        body.dataJson = JSON.stringify(dataJson);
        saveInputItemAction(body).then(
          data => {
            AmosAlert.success('提示', '保存成功', {
              callback: flag => {
                if (flag) {
                  browserHistory.goBack('/main/patrol/inputitem');
                }
              }
            });
          },
          err => {
            AmosAlert.error('错误', err);
          }
        );
      } else {
        return false;
      }
    });
  };

  handleCancel = e => {
    browserHistory.goBack('/main/patrol/inputitem');
  };

  render() {
    const { form, rules, treeData, dataJson, tableData } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
        className: 'colspan'
      }
    };
    const wrapperCol = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 14, offset: 4 }
      }
    };
    const tableLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 12, offset: 2 }
      }
    };

    return (
      <div className="input_item_div">
        <Form model={form} rules={rules} ref={component => (this.form = component)}>
          <FormItem label={<span>检查项目编号</span>} field="itemNo" {...formItemLayout}>
            <Input className="input_item_Input" value={form.itemNo} disabled maxLength = "50" placeholder="请输入检查项目编号" onChange={e => this.onChange('itemNo', e)} />
          </FormItem>
          <FormItem label={<span>检查项目名称</span>} field="name" {...formItemLayout}>
            <Input className="input_item_Input" value={form.name} disabled maxLength = "50" placeholder="请输入检查项目名称" onChange={e => this.onChange('name', e)} />
          </FormItem>
          <FormItem label={<span>小数点后位数</span>} field="Precision" {...formItemLayout}>
            <InputNumber className="input_item_Input" value={dataJson.Precision} disabled onChange={e => this.onDataJsonCheckBox('Precision', e)} />
          </FormItem>
          <FormItem label={<span>默认输入值</span>} field="defaultValue" {...formItemLayout}>
            <Input className="input_item_Input" value={form.defaultValue} disabled onChange={e => this.onChange('defaultValue', e)} />
          </FormItem>
          <FormItem label={<span>是否为必填项</span>} field="isMust" {...formItemLayout}>
            <RadioGroup defaultValue={form.isMust} value={form.isMust}  onChange={e => this.onChangeRedio('isMust', e)}>
              <Radio value="是">是</Radio>
              <Radio value="否">否</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label={<span>是否计算评分</span>} field="isScore" {...formItemLayout}>
            <RadioGroup defaultValue={form.isScore} value={form.isScore}  onChange={e => this.onChangeRedio('isScore', e)}>
              <Radio value="是">是</Radio>
              <Radio value="否">否</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label={<span>合格评分数</span>} field="OkScore" {...formItemLayout}>
            <InputNumber value={dataJson.OkScore} disabled onChange={e => this.onChangeDataJson('OkScore', e)} />
          </FormItem>
          <FormItem label={<span>不合格评分数</span>} field="NoScore" {...formItemLayout}>
            <InputNumber value={dataJson.NoScore} disabled onChange={e => this.onChangeDataJson('NoScore', e)} />
          </FormItem>
          <FormItem label={<span>有效值上限</span>} field="ValidUp" {...formItemLayout}>
            <InputNumber value={dataJson.ValidUp} disabled onChange={e => this.onChangeDataJson('ValidUp', e)} />
            <Checkbox disabled
              checked={dataJson.CheckValidUp}
              defaultChecked={dataJson.CheckValidUp}
              onChange={e => this.onDataJsonCheckBox('CheckValidUp', e.target.checked)}
            >
              强制校验，输入值不能大于有效值上限。
            </Checkbox>
          </FormItem>
          <FormItem label={<span>有效值下限</span>} field="ValidDown" {...formItemLayout}>
            <InputNumber  disabled value={dataJson.ValidDown} onChange={e => this.onChangeDataJson('ValidDown', e)} />
            <Checkbox disabled
              checked={dataJson.CheckValidDown}
              defaultChecked={dataJson.CheckValidDown}
              onChange={e => this.onDataJsonCheckBox('CheckValidDown', e.target.checked)}
            >
              强制校验，输入值不能小于有效值下限。
            </Checkbox>
          </FormItem>
          <FormItem label={<span>合格值上限</span>} field="OkUp" {...formItemLayout}>
            <InputNumber value={dataJson.OkUp} onChange={e => this.onChangeDataJson('OkUp', e)} disabled />
            <Checkbox disabled checked={dataJson.CheckOkUp} defaultChecked={dataJson.CheckOkUp} onChange={e => this.onDataJsonCheckBox('CheckOkUp', e.target.checked)}>
              合格判断，输入值大于合格值上限时为不合格。
            </Checkbox>
          </FormItem>
          <FormItem label={<span>合格值下限</span>} field="OkDown" {...formItemLayout}>
            <InputNumber value={dataJson.OkDown} disabled  onChange={e => this.onChangeDataJson('OkDown', e)} />
            <Checkbox disabled
              checked={dataJson.CheckOkDown}
              defaultChecked={dataJson.CheckOkDown}
              onChange={e => this.onDataJsonCheckBox('CheckOkDown', e.target.checked)}
            >
              合格判断，输入值小于合格值下限时为不合格。
            </Checkbox>
          </FormItem>
          <FormItem label={<span>所属分类目录</span>} field="catalogId" {...formItemLayout}>
            <TreeSelect disabled
              value={form.catalogId ===0 ?undefined : form.catalogId}
              className="input_item_Input"
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={treeData}
              placeholder="请选择"
              allowClear
              treeDefaultExpandAll
              onChange={e => this.onSelectChange('catalogId', e)}
            />
          </FormItem>
          <FormItem label={<span>检查项等级</span>} field="level" {...formItemLayout}>
          <Select disabled
            data={levelData}
            renderOption={item => <Option value={item.id}>{item.name}</Option>}
            value={form.level}
            // defaultOption={<Option>请选择</Option>}
            className="input_item_Input"
            onChange={e => this. onSelectChange('level', e)}
          />
          </FormItem>
          <FormItem label={<span>检查项目说明</span>} field="remark" {...formItemLayout}>
            <TextArea  disabled className="input_item_Input" rows={6} disableResize value={form.remark} onChange={e => this.onChange('remark', e)} />
          </FormItem>
          <FormItem {...tableLayout}>
            <CommonTablexq  tableData={tableData} onChangeTableValues={this.onChangeTableValues} columns={this.getPicTablecolumns()} />
          </FormItem>
          {/* <FormItem {...wrapperCol}>
            <HasPermission permissionCode="inputitem">
              <Button onClick={this.handleSubmit}>提交</Button>
            </HasPermission>
            <Button onClick={this.handleCancel}>返回</Button>
          </FormItem> */}
        </Form>
      </div>
    );
  }
}
NumberInputItemxq.propTypes = {
  inputItemID: PropTypes.string
};
export default NumberInputItemxq;
