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 { TreeSelect } from 'amos-antd';
import { browserHistory } from 'amos-react-router';
import './../../../styles/view/patrol/inputItem.scss';
import HasPermission from './../../component/toolbar/hasPermission';

import CommonTable from './CommonTable';
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 TextInputItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      form: {
        name: '',
        defaultValue: '',
        catalogId: '',
        itemType: '文本',
        isMultiline: '是',
        isScore: '是',
        remark: '',
        level: '',
        itemNo: ''

      },
      itemNoData: [],
      inputItemID: '',
      tableData: [],
      treeData: [],
      dataJson: {
        OkScore: 0,
        NoScore: 0,
        CheckType: '始终合格'
      },
      pic: {},
      rules: {
        name: [{ required: true, 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(),
      errList2: 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.isMultiline = data.isMultiline;
      detail.isScore = data.isScore;
      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 });
  };

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

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


  onChangeDataJson = (key, value) => {
    const { dataJson } = this.state;
    dataJson[key] = value;
    this.setState({ dataJson });
  };
  onChangeDataJsonRedio = (key, e) => {
    const { dataJson } = this.state;
    dataJson[key] = e;
    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 });
  }

  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',
        align: 'center',
        width: '50%',
        render: (text, record) => {
          let { showTips, errList } = this.state;
          if (text === undefined || text === '') {
            showTips = true;
          } else {
            showTips = false;
          }
          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',
        align: 'center',
        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 => {
    e.preventDefault();
    let { errList } = this.state;
    if ([...errList.values()].includes(true)) {
      return;
    }
    this.form.validate((valid, dataValues) => {
      if (valid) {
        const { form, tableData, dataJson, inputItemID } = this.state;
        let body = Object();
        Object.assign(body, form);
        let pic = 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;
          }
        });
        pic = pic.filter(item => item != undefined);
        body.id = parseInt(inputItemID);
        body.pictureJson = JSON.stringify(pic);
        body.dataJson = JSON.stringify(dataJson);
        saveInputItemAction(body).then(
          data => {
            AmosAlert.success('提示', '保存成功');
            browserHistory.goBack('/main/patrol/inputitem');
          },
          err => {
            AmosAlert.error('错误', err);
          }
        );
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  };

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

  render() {
    const { form, rules, dataJson, tableData, treeData } = 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} 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} maxLength = "50" placeholder="请输入检查项目名称" onChange={e => this.onChange('name', e)} />
          </FormItem>
          <FormItem label={<span>默认输入值</span>} field="defaultValue" {...formItemLayout}>
            <Input value={form.defaultValue} className="input_item_Input" onChange={e => this.onChange('defaultValue', e)} />
          </FormItem>
          <FormItem label={<span>是否允许多行</span>} field="isMultiline" {...formItemLayout}>
            <RadioGroup defaultValue={form.isMultiline} value={form.isMultiline} onChange={e => this.onChangeRedio('isMultiline', 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} className="input_item_Input" onChange={e => this.onChangeDataJson('OkScore', e)} />
          </FormItem>
          <FormItem label={<span>不合格评分数</span>} field="NoScore" {...formItemLayout}>
            <InputNumber value={dataJson.NoScore} className="input_item_Input" onChange={e => this.onChangeDataJson('NoScore', e)} />
          </FormItem>
          <FormItem label={<span>合格判断方法</span>} field="CheckType" {...formItemLayout}>
            <RadioGroup defaultValue={dataJson.CheckType} value={dataJson.CheckType} onChange={e => this.onChangeDataJsonRedio('CheckType', e)}>
              <Radio value="始终合格">始终合格</Radio>
              <Radio value="始终不合格">始终不合格</Radio>
              <Radio value="无内容合格">无内容合格</Radio>
              <Radio value="有内容合格">有内容合格</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label={<span>所属分类目录</span>} field="catalogId" {...formItemLayout}>
            <TreeSelect
              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
            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 className="input_item_Input" value={form.remark} rows={6} disableResize onChange={e => this.onChange('remark', e)} />
          </FormItem>
          <FormItem {...tableLayout}>
            <CommonTable 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>
    );
  }
}

TextInputItem.propTypes = {
  inputItemID: PropTypes.string
};

export default TextInputItem;
