import React, { Component } from 'react';
import { Form, Input, AmosAlert, Radio, Select, MultiSelect, Tree, InputNumber, Affix } from 'amos-framework';
import { TreeSelect } from 'amos-antd';
import PropTypes from 'prop-types';
import { browserHistory } from 'amos-react-router';
import {
  queryCatalogTreeAction,
  queryDeptUserTree,
  queryDeptByOrgCodeAction2,
  queryUserByDeptIdAction
} from '../../../services/checkService';
import { addPointAction, queryPointByIdAction, queryAllPointNoAction, gerRiskLevel } from '../../../services/pointService';
import { getRiskSourceSecondLevelAction } from '../../../services/preControlService';
import { utils } from 'amos-tool';
const isIntegrationPreControl = window.isIntegrationPreControl;

const TextArea = Input.TextArea;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const TreeNode = Tree.TreeNode;

class PointBasicInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentPersonData: [],
      form: {
        name: '',
        pointNo: '',
        routeId: '',
        routeName: '',
        saveGps: '0',
        distance: '',
        usuallyShot: '',
        shotMinNumber: 0,
        shotMaxNumber: 10,
        fixedShot: '',
        latitude: '',
        longitude: '',
        address: '',
        offline: false,
        isFixed: '1',
        catalogId: '',
        extendJson: '',
        isScore: '0',
        level: '',
        coordinates: '',
        floor: 1,
        isIndoor: false,
        chargeDeptId: '',
        chargePersonId: '',
        remark: '',
        riskSourceId: 0

      },
      riskLevelList: [],
      inputItemTableData: [],
      pointCatalogJson: {},
      routeData: [],
      catalogData: [],
      userTreeData: [],
      rules: {
        name: [{ required: true, message: '请输入巡检点名称' }],
        pointNo: [
          { required: true, message: '请输入巡检点编号' },
          { pattern: new RegExp(/[^\u4e00-\u9fa5]+$/), message: '编号不能包含中文' },
          { pattern: new RegExp(/^[^ ]+$/), message: '编号不能为空或含有空格' },
          {
            validator: (rule, value, callback) => {

              const { pointId } = this.props;
              this.queryAllPointNo(pointId);
              const { pointNoData } = this.state;
              if (!pointNoData.includes(value)) {
                callback();
              } else {
                callback(new Error('该编号已存在！'));
              }
            }
          }
        ],
        level: [{ required: true, message: '请输入巡检点风险等级' }],
        distance: [{ pattern: new RegExp(/^(0|[1-9]\d*)$/, 'g'), message: '请输入有效数字' }],
        coordinates: [{ validator: this.validPositon3d }]
      },
      treeConfig: {
        expandedKeys: [],
        autoExpandParent: true,
        checkedKeys: [],
        selectedKeys: []
      },
      levelData: [{ 1: '1级' }, { 2: '2级' }, { 3: '3级' }, { 4: '4级' }, { 5: '5级' }],
      executors: [],
      userData: [],
      deptData: [],
      pointNoData: [],
      riskSourceData: []
    };
  }

  componentWillMount() {
    const { pointId } = this.props;
    this.onPointInfoInit(pointId);
    if (isIntegrationPreControl) {
      this.getRiskSourceSecondLevel();
    }
    this.querryRiskLevel();
  }

  onPointInfoInit(pointId) {

    // 根据ID查询点信息
    pointId &&
      queryPointByIdAction(pointId).then(data => {
        let deptId = data.chargeDeptId;

        deptId && this.queryUserByDept(deptId);
        this.setState({
          form: data
        });
      });
    this.loadexecutor();

    // 查询路线
    // queryAllRouteAction().then(data => {
    //   this.setState({
    //     routeData: data
    //   });
    // });

    // 查询分类目录
    this.queryCatalogTree();

    // 查询部门人员
    this.queryDeptByOrgCode();

  }

  getRiskSourceSecondLevel = () => {
    getRiskSourceSecondLevelAction().then(
      data => {
        this.setState({ riskSourceData: data });
      }
    );
  };

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

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

  onRadioChange = (key, e) => {
    const { form } = this.state;
    //  if (e) {
    form[key] = e;
    // }
    this.setState({ form });
    // this.props.onBasicInfoFormChange(form, this.form);
  };

  onChangeSelect = (key, e) => {
    const { form } = this.state;
    if (e && e.id) {
      form.catalogId = e.id;
    }
    this.setState({ form });
    // this.props.onBasicInfoFormChange(form, this.form);
  };

  onRouteSelectChange = key => {
    const { form, routeData } = this.state;
    let routeNameList = [];
    form.routeId = key;
    for (let i in key) {
      for (let j in routeData) {
        if (routeData[j].id === key[i]) {
          routeNameList.push(routeData[j].name);
        }
      }
    }
    form.routeName = routeNameList;
    this.setState({ form });
    // this.props.onBasicInfoFormChange(form, this.form);
  };

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

  onSelectChange = (key, value) => {

    let { form } = this.state;

    if ('chargePersonId' == key) {
      let str;
      for (var i = 0; i < value.length; i++) {
        if (i === 0) {
          str = value[i];
        } else {
          str = str + ',' + value[i];
        }
      }
      form[key] = str;
      console.log('chargePersonId', str);
    } else {
      form[key] = value;

    }

    console.log('chargePersonId', value);

    this.setState(form);
  };

  onTreeExpand = expandedKeys => {
    this.setState({
      treeConfig: {
        expandedKeys,
        autoExpandParent: false
      }
    });
  };

  onTreeNodeCheck = checkedKeys => {
    console.log('onCheck', checkedKeys);
    this.setState({
      treeConfig: {
        checkedKeys
      }
    });
  };

  onTreeNodeSelect = (selectedKeys, info) => {
    console.log('onSelect', info);
    const { form } = this.state;
    form.chargePersonId = selectedKeys;
    this.setState({
      treeConfig: {
        selectedKeys
      },
      form
    });
    // this.props.onBasicInfoFormChange(form, this.form);
  };

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

  getSelectRouteId() {
    const { form } = this.state;
    let selectRouteId = [];
    if (Array.isArray(form.routeId)) {
      selectRouteId = form.routeId;
    } else {
      let temp = form.routeId.split(',');
      for (let i = 0; i < temp.length; i++) {
        if (temp[i] !== '') {
          selectRouteId.push(parseInt(temp[i]));
        }
      }
    }
    return selectRouteId;
  }

  loadexecutor = () => {
    queryDeptUserTree().then(data => {
      let deptPersons = data.filter(item => item.children !== null);
      this.setState({ executors: deptPersons });
    });
  };

  handleExecutorsChange = (executorList, label, extra) => {
    let pro = label.props;
    const { form } = this.state;
    if (pro.children || pro.type === 'department') {
      form.chargePersonId = '';
    } else {
      form.chargePersonId = pro.value;
    }

    this.setState({ form });
  };

  handleSubmit = e => {
    const { form, dataJson } = this.state;

    e.preventDefault();
    this.form.validate((valid, dataValues) => {
      if (valid) {
        let point = Object();
        Object.assign(point, form);
        point.dataJson = JSON.stringify(dataJson);
        addPointAction(point).then(
          data => {
            AmosAlert.success('提示', '新增成功');
            browserHistory.goBack('/main/patrol/point');
          },
          error => {
            AmosAlert.error('错误', '新增点失败');
          }
        );
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  };

  queryCatalogTree = () => {
    queryCatalogTreeAction().then(data => {
      this.setState({ catalogData: data });
    });
  };

  queryDeptByOrgCode = () => {
    queryDeptByOrgCodeAction2().then(data => {
      this.setState({ deptData: data });
    });
  };

  queryUserByDept = deptId => {
    queryUserByDeptIdAction(deptId).then(data => {

      console.log('pointInfo queryUserByDept', data);
      this.setState({ userData: data });
    });
  };

  queryAllPointNo(pointId) {
    if (pointId === undefined) {
      pointId = -1;
    }
    queryAllPointNoAction(pointId).then(data => {
      this.setState({ pointNoData: data });
    });
  }

  validPositon3d = (rule, value, callback) => {
    let tempArry = [];
    if (value) {
      tempArry = value.split(',');
    }
    //    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('非法格式');
    }
  }

  renderTreeNodes = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.label ? item.label : item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.label ? item.label : item.title} key={item.key} {...item} />;
    });
  }

  /**
   * 查询风险等级
   */
  querryRiskLevel = () => {

    gerRiskLevel().then(res => {
      console.log('pointBasicInfos', res);
      const riskLevelList = res;
      this.setState({ riskLevelList });
    })
  }


  /**
   * 渲染风险等级
   */
  rendRiskLevel = () => {
    const { riskLevelList } = this.state;
    console.log('pointBasicInfos pointBasicInfos', riskLevelList);
    if (!utils.isEmpty(riskLevelList) && utils.isArray(riskLevelList)) {
      return (<div>
        {
          riskLevelList.map(e => {
            return <Option key={e.orderNum} value={e.orderNum}>{e.dictDataValue}</Option>
          })
        }
      </div>)
    }
  }
  /**
   * 渲染默认责任人
   */
  renderCurrentPersonData = (data) => {
    console.log('arrayData1', data)
    if (!utils.isEmpty(data)) {
      let array = [];
      let arrayData = data.split(',');
      arrayData.map(e => {
        array.push(e)
      })
      console.log('arrayData', arrayData)
      console.log('array', array)
      return array;
    } else {
      return [];
    }
  }
  render() {
    const { form, rules, catalogData, deptData, userData, riskLevelList, currentPersonData } = this.state;
    console.log('form.chargePersonId', form.chargePersonId);
    console.log('form.userData', userData);

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
        className: 'colspan'
      }
    };
    const def = true;
    const deffalse = false;
    return (
      <div className="point-basic-info-div">
        <Form model={form} rules={rules} ref={component => (this.form = component)}>
          <FormItem label={<span>点编号</span>} field="pointNo" {...formItemLayout}>
            <Input className="point-info-input" value={form.pointNo} maxLength="50" placeholder="" onChange={e => this.onChange('pointNo', e)} />
          </FormItem>
          <FormItem label={<span>点名称</span>} field="name" {...formItemLayout}>
            <Input className="point-info-input" value={form.name} maxLength="50" placeholder="" onChange={e => this.onChange('name', e)} />
          </FormItem>
          <FormItem label={<span>点类型</span>} field="isFixed" {...formItemLayout}>
            <RadioGroup defaultValue="1" value={form.isFixed} onChange={e => this.onRadioChange('isFixed', e)}>
              <Radio value="1">固定点</Radio>
              <Radio value="0">移动点</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label={<span>计划外巡检</span>} field="isScore" {...formItemLayout}>
            <RadioGroup defaultValue="0" value={form.isScore} onChange={e => this.onRadioChange('isScore', e)}>
              <Radio value="1">评分</Radio>
              <Radio value="0">不评分</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label={<span>离线巡检</span>} field="offline" {...formItemLayout}>
            <RadioGroup defaultValue={deffalse} value={form.offline} onChange={e => this.onRadioChange('offline', e)}>
              <Radio value={def}>允许</Radio>
              <Radio value={deffalse}>不允许</Radio>
            </RadioGroup>
          </FormItem>
          {/**
          <FormItem label={<span>地理定位</span>} field="saveGps" {...formItemLayout}>
            <RadioGroup defaultValue="0" value={form.saveGps} onChange={e => this.onRadioChange('saveGps', e)}>
              <Radio value="1">记录</Radio>
              <Radio value="0">不记录</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label={<span>有效巡检距离</span>} field="distance" {...formItemLayout}>
            <Input value={form.distance} className="point-info-input" placeholder="0" onChange={e => this.onChange('distance', e)} />
            <span>米</span>
          </FormItem>
            */}
          {/* {isIntegrationPreControl?<FormItem label={<span>所属区域</span>} field="riskSourceId" {...formItemLayout}>
              <Select
                searchable
                className="fire-equip-select"
                data={riskSourceData}
                renderOption={item => <Option value={parseInt(item.id)}>{item.name}</Option>}
                placeholder = "请选择"
                value={form.riskSourceId}
                onChange={e => this.onSelectChange('riskSourceId', e)} */}
          {/* />
          </FormItem>:''} */}
          <FormItem label={<span>参考位置</span>} field="address" {...formItemLayout}>
            <Input value={form.address} className="point-info-input" placeholder="" onChange={e => this.onChange('address', e)} />
          </FormItem>
          <FormItem label={<span>3维地图坐标</span>} field="coordinates" {...formItemLayout}>
            <Input value={form.coordinates} className="point-info-input" placeholder="" onChange={e => this.onChange('coordinates', e)} />
            <span>(x,y,z)</span>
          </FormItem>
          <FormItem label={<span>3维地图楼层</span>} field="floor" {...formItemLayout}>
            <InputNumber
              value={form.floor}
              className="point-info-input"
              placeholder="1"
              onChange={e => this.onInputNumberChange('floor', e)}
            />
          </FormItem>
          <FormItem label={<span>是否室内</span>} field="isIndoor" {...formItemLayout}>
            <RadioGroup defaultValue={false} value={form.isIndoor} onChange={e => this.onRadioChange('isIndoor', e)}>
              <Radio value={true}>室内</Radio>
              <Radio value={false}>室外</Radio>
            </RadioGroup>
          </FormItem>

          <FormItem label={<span>最少拍照数量</span>} field="shotMinNumber" {...formItemLayout}>
            <InputNumber
              min={0}
              value={form.shotMinNumber}
              className="point-info-input"
              placeholder="0"
              onChange={e => this.onInputNumberChange('shotMinNumber', e)}
            />
          </FormItem>
          <FormItem label={<span>最多拍照数量</span>} field="shotMaxNumber" {...formItemLayout}>
            <InputNumber
              min={0}
              value={form.shotMaxNumber}
              className="point-info-input"
              placeholder="10"
              onChange={e => this.onInputNumberChange('shotMaxNumber', e)}
            />
          </FormItem>
          <FormItem label={<span>风险等级</span>} field="level" {...formItemLayout}>
            <Select prefixCls="" className="point-info-input" value={form.level} onChange={e => this.onSelectChange('level', e)}>
              {/* <Option value="1">1级</Option>
              <Option value="2">2级</Option>
              <Option value="3">3级</Option>
              <Option value="4">4级</Option> */}
              {
                (!utils.isEmpty(riskLevelList) && utils.isArray(riskLevelList)) ? riskLevelList.map(e => (
                  <Option key={e.dictDataKey} value={e.dictDataKey}>{e.dictDataValue}</Option>
                )) : null
              }

            </Select>
          </FormItem>
          <FormItem label={<span>归属区域/部门</span>} field="chargeDeptId" {...formItemLayout}>
            <Select
              className="point-info-input"
              searchable
              data={deptData ? deptData : []}
              renderOption={item => <Option value={item.sequenceNbr}>{item.departmentName}</Option>}
              value={form.chargeDeptId}
              onChange={e => this.onDeptChange('chargeDeptId', e)}
            />
          </FormItem>
          <FormItem label={<span>责任人</span>} field="chargePersonId" {...formItemLayout}>
            {/* <Select
              className="point-info-input"
              searchable
              data={userData}
              renderOption={item => <Option value={item.id}>{item.name}</Option>}
              value={form.chargePersonId}
              onChange={e => this.onSelectChange('chargePersonId', e)}
            /> */}
            <MultiSelect
              className="point-info-input"
              //defaultValues={this.renderCurrentPersonData(form.chargePersonId)}
              //defaultValues={["1569413","1533588","1559667"]}

              data={userData}
              renderOption={item => <Option key={item.id} value={item.id}>{item.name}</Option>}
              onChange={e => this.onSelectChange('chargePersonId', e)}
              values={this.renderCurrentPersonData(form.chargePersonId)}
            />
          </FormItem>

          <FormItem label={<span>所属分类目录</span>} field="catalogId" {...formItemLayout}>
            <TreeSelect
              value={form.catalogId}
              allowClear
              className="point-info-input"
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={catalogData}
              placeholder="请选择"
              treeDefaultExpandAll
              onChange={e => this.onSelectChange('catalogId', e)}
            />
          </FormItem>
          <FormItem label={<span>备注说明</span>} field="remark" {...formItemLayout}>
            <TextArea className="input_item_Input" rows={6} value={form.remark} disableResize onChange={e => this.onChange('remark', e)} />
          </FormItem>
        </Form>
      </div>
    );
  }
}

PointBasicInfo.propTypes = {
  pointId: PropTypes.number
};
export default PointBasicInfo;
