import React, { Component } from 'react';
// import { utils } from 'amos-tool';
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 {isEmpty} from '../../../utils/validate'
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 ChoiceInputItemxq extends Component {
  constructor(props) {
    super(props);
    this.state = {
      form: {
        name: '',
        catalogId: '',
        itemType: '选择',
        isMultiline: '否',
        isScore: '否',
        isMust: '否',
        remark: '',
        level:'',
        itemNo: ''
      },
      itemNoData: [],
      inputItemID: '',
      choiceData: [],
      treeData: [],
      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.isMust = data.isMust;
      detail.remark = data.remark;
      detail.level = data.level;
      let json = JSON.parse(data.dataJson);
      let tableData = JSON.parse(data.pictureJson);
      this.setState({ form: detail, pic: tableData, choiceData: 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);
  };

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

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

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

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

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

  onChangeChoiceInput = (record, name, value) => {
    const { choiceData } = this.state;
    for (let i = 0; i < choiceData.length; i++) {
      if (choiceData[i].orderNo === record.orderNo) {
        choiceData[i][name] = value;
      }
    }

    this.setState({ choiceData });
  };

  /**
   * 获取表格表头
   */
  getPicTablecolumns = () => {
    let { errList } = this.state;
    errList.clear();
    return [
      {
        title: '名称',
        dataIndex: 'name',
        width: '50%',
        render: (text, record) => {
          return !record.edit ? text : <Input disabled 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  disabled
              onChange={e => this.onChangePicCheckBox(record, e.target.checked)}
              checked={text === undefined || text === '否' ? false : true}
              defaultChecked={text === undefined || text || text === '否' ? false : true}
            />
          );
        }
      }
    ];
  };

  /**
   * 获取选择项表格表头
   */
  getChoiceTablecolumns = () => {
    let { errList2 } = this.state;
    errList2.clear();
    return [
      {
        title: '选项名称',
        dataIndex: 'name',
        width: '30%',
        render: (text, record) => {
          return !record.edit ? text : <Input  disabled style={{ width: '100%', padding: '0px' }} placeholder="名称不能为空" onChange={e => this.onChangeChoiceInput(record, 'name', e.target.value)} value={text} />;
        }
      },
      {
        title: '选择评分',
        dataIndex: 'score',
        width: '30%',
        render: (text, record) => {
          return !record.edit ? text : <InputNumber disabled style={{ width: '100%', padding: '0px' }} placeholder="请输入分数" onChange={e => this.onChangeChoiceInput(record, 'score', e)} value={text} />;
        }
      },
      {
        title: '选中是否合格',
        dataIndex: 'isOk',
        width: '20%',
        render: (text, record) => {
          return !record.edit ? (
            text ? (
              text
            ) : (
              '否'
            )
          ) : (
            <Checkbox disabled
              onChange={e => this.onChangeChoiceInput(record, 'isOk', e.target.checked ? '是' : '否')}
              checked={text === undefined || text === '否' ? false : true}
              defaultChecked={text === undefined || text || text === '否' ? false : true}
            />
          );
        }
      },
      {
        title: '是否默认选中',
        dataIndex: 'isChecked',
        width: '20%',
        render: (text, record) => {
          return !record.edit ? (
            text ? (
              text
            ) : (
              '否'
            )
          ) : (
            <Checkbox
              onChange={e => this.onChangeChoiceInput(record, 'isChecked', e.target.checked ? '是' : '否')}
              checked={text === undefined || text === '否' ? false : true}
              defaultChecked={text === undefined || text === '否' ? false : true}
            />
          );
        }
      }
    ];
  };

  handleSubmit = e => {
    e.preventDefault();
    let { errList, errList2 } = this.state;
    if ([...errList.values()].includes(true) || [...errList2.values()].includes(true)) {
      return;
    }
    this.form.validate((valid, dataValues) => {
      if (valid) {
        const { form, pic, choiceData, inputItemID } = this.state;
        let body = Object();
        Object.assign(body, form);

        let pictureJson = pic.map(item => {
          if (item.name !== undefined && item.name !== ''){
            let obj = new Object();
            obj.isMust = item.isMust ? item.isMust : '否';
            obj.name = item.name;
            obj.orderNo = item.orderNo;
            return obj;
          }
        });
        pictureJson = pictureJson.filter(item => item != undefined);
        let reqChoiceData = choiceData.map(item => {
          if (item.name !== undefined && item.name !== ''){
            let obj = new Object();
            obj.score = item.score!= undefined?item.score:0;
            obj.name = item.name;
            obj.isOk = item.isOk ? item.isOk : '否';
            obj.isChecked = item.isChecked ? item.isChecked : '否';
            obj.orderNo = item.orderNo;
            return obj;
          }
        });
        reqChoiceData = reqChoiceData.filter(item => item != undefined);
        body.id = inputItemID;
        body.pictureJson = JSON.stringify(pictureJson);
        body.dataJson = JSON.stringify(reqChoiceData);
        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, treeData, choiceData, pic } = this.state;
    let choiceData_ = choiceData.filter(item => item !== null);
    let pic_ = pic.filter(item => item !== null);
    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" disabled 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" disabled value={form.name} maxLength = "50" placeholder="请输入检查项目名称" onChange={e => this.onChange('name', 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="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="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 className="input_item_Input" disabled rows={6} disableResize value={form.remark} onChange={e => this.onChange('remark', e)} />
          </FormItem>
          <FormItem {...tableLayout}>
            <CommonTablexq tableData={choiceData_}  onChangeTableValues={this.onChangeChoiceValues} columns={this.getChoiceTablecolumns()} />
          </FormItem>
          <FormItem {...tableLayout}>
            <CommonTablexq tableData={pic_} 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>
    );
  }
}
ChoiceInputItemxq.propTypes = {
  inputItemID: PropTypes.string
};
export default ChoiceInputItemxq;
