import React, { Component } from 'react';
import { Form, Input, Select, Button, AmosAlert, MultiSelect, Radio } from 'amos-framework';
import PropTypes from 'amos-react-router/lib/PropTypes';
import BizIcon from '../../../common/icon/BizIcon';
import EditableCell from './../../common/editableCell/EditableCell';
import EditableCellInputNum from './../../common/editableCell/EditableCellInputNum';
import AmosGridTable from './../../common/tableComponent/table/AmosGridTable';
import { getTaskworkDetailAction, deleteTaskworkContentAction, getRiskSourceByTypeAction, getEquipmentOptionsDataAction } from './../../../../services/bizService';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;

const MSOption = MultiSelect.Option;
const floorData = [{ id: '1', name: '1层' }, { id: '2', name: '2层' }, { id: '3', name: '3层' }, { id: '4', name: '4层' }, { id: '5', name: '5层' }];
const riskSourceType = '02';
const getColumns = (self) => {
  let { disabled } = self.state;
  let oper = <Button hidden={disabled} icon={<BizIcon icon="tianjia" />} transparent onClick={() => {self.onAdd();}} />;
  return [
    {
      title: '步骤顺序',
      dataIndex: 'serialNum',
      key: 'serialNum',
      width: '23%',
      render: (text, record) => <EditableCellInputNum disabled={disabled} value={text} onChange={(text) => self.onCellChange(record, text, 'serialNum')} inital={record.inital} />,
      className: 'uant-table-thead'
    },
    {
      title: '作业活动步骤',
      dataIndex: 'content',
      key: 'content',
      width: '74%',
      render: (text, record) => <EditableCell disabled={disabled} value={text} onChange={(text) => self.onCellChange(record, text, 'content')} inital={record.inital} />,
      className: 'uant-table-thead'
    },
    {
      title: oper,
      dataIndex: '',
      key: '',
      width: '3%',
      render: (text, record) => {
        return (
          <Button
            icon={<BizIcon icon="shanchu" />}
            transparent
            onClick={() => self.onDelete(record.key)}
            hidden={disabled}
          />
        );
      },
      className: 'uant-table-thead operation-items'
    }
  ];
};

/**
 * 作业活动新增及编辑
 *
 * @class TaskWorkModel
 * @extends {Component}
 */
class TaskWorkModel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      form: {
        name: '',
        post: '',
        part: '',
        type: '',
        regionId: '',
        departmentId: '',
        groupId: [],
        contentList: [],
        floor3d: '1',
        isIndoor: 1,
        position3d: '',
        workRate:'',
        taskworkSubstance:'',
        workshopSection: '',//工段
        equipmentId: 0,
        equipmentName: '',//设备名称
        equipmentCode: '',//位号
        taskworkAddress: '',
      },
      deptData: [],
      regionData: [],
      groupData: [],
      typeData: [],
      equipData: [],
      positionData: [],
      stepData: [],
      rules: {
        name: [
          { required: true, message: '作业活动名称不能为空' },
          { pattern: new RegExp(/^[^ ]+$/), message: '作业活动名称不能为空或包含空格' }
        ],
        post: [{ required: true, message: '作业活动岗位不能为空' }],
        part: [{ required: true, message: '作业活动部位不能为空' }],
        taskworkAddress: [{ required: true, message: '作业活动地点不能为空' }],
        type: [{ required: true, message: '作业活动类型不能为空' }],
        regionId: [{ required: true, message: '所在分区不能为空' }],
        departmentId: [{ required: true, message: '车间/部门不能为空' }],
        workshopSection: [{ required: true, message: '所属工段不能为空' }],
        equipmentId: [{ required: true, message: '设备名称不能为空' }],
        equipmentCode: [{ required: true, message: '设备位号不能为空' }],
        groupId: [{ required: true, message: '班组不能为空' }],
        isIndoor: [{ required: true, message: '是否室内不能为空' }],
        position3d: [{ validator: this.validPositon3d }]
      },
      param: { regionId: '', departmentId: '', workshopSection: '', controlObjectName: '' }
    };
  }

  componentWillMount() {
    const { taskworkId } = this.props;
    taskworkId && this.setState({ taskworkId });
    this.getRiskSource(riskSourceType);//风险区域
  }

  componentDidMount() {
    const { taskworkId, toolbarFlag } = this.props || {};
    if (toolbarFlag === 1) {
      //编辑
      this.getTaskWorkDetail(taskworkId);
    }
  }


  onInputChange = (key, value) => {
    const { form } = this.state;
    form[key] = value;
    if(key === 'taskworkAddress'){
      this.partContent(form);
    }
    this.setState({ form });
  };

  // onSelectChange(key, value) {
  //   const { form } = this.state;
  //   form[key] = value;
  //   if (key === 'regionId') {
  //     this.getDeptData(value);
  //   }
  //   if (key === 'departmentId') {
  //     this.getTeamData(value);
  //   }
  //   this.setState({ form });
  // }

  onSelectChange = (key, value, item) =>{
    const { form, param } = this.state;
    form[key] = value;
    if (key === 'regionId') {
      this.getDeptData(value);
    }
    if ('departmentId' === key) {
      this.getTeamData(value);
      this.getStepData(value);
      form.workshopSection = '';
      form.equipmentName = '';
      form.equipmentId = '';
      form.equipmentCode = '';
    } else if ('workshopSection' === key) {
      this.getEquipData(value);
      form.equipmentId = '';
      form.equipmentName = '';
      form.equipmentCode = '';
      param.workshopSection = value;
    } else if ('equipmentId' === key) {
      this.getPositionData(item.optionName);
      form.equipmentName = item.optionName;
      form.equipmentCode = '';
    }
    this.partContent(form);
    this.setState({ form });
    // this.setState({ form, param });
  };

  partContent = (form) =>{
    let {workshopSection,equipmentName,equipmentCode,taskworkAddress} = form
    let partContent = (workshopSection + (equipmentName?('/'+equipmentName):'')+ (equipmentCode?('/'+equipmentCode):'')+ (taskworkAddress?('/'+taskworkAddress):''));
    this.state.form.part = partContent;
    // this.setState({ form });
  }


  getStepData = (departmentId) => {
    let { param } = this.state;
    param.departmentId = departmentId;
    param.workshopSection = '';
    getEquipmentOptionsDataAction({ ...param, departmentId }).then(data => {
      this.setState({ stepData: data, param, equipData: [], positionData: [] });
    });
  }
  getEquipData = (workshopSection) => {
    let { param, taskworkId, form } = this.state;
    param.workshopSection = workshopSection;
    getEquipmentOptionsDataAction({ ...param, workshopSection }).then(data => {
      if (taskworkId) {//查看时
        let obj = data.filter(item => item.id === form.equipmentId);
        if (obj.length === 1) {
          this.getPositionData(obj[0].optionName);
          form.equipmentName = obj[0].optionName;
          this.setState({ form });
        }
      }
      this.setState({ equipData: data, param, positionData: [],form });
    });
  };

  getPositionData = (controlObjectName) => {
    let { param, form } = this.state;
    getEquipmentOptionsDataAction({ ...param, controlObjectName }).then(data => {
      this.setState({ positionData: data, form });
    });
  };

  onCellChange = (record, text, type) => {
    const { form } = this.state;
    const target = form.contentList.find(item => item.key === record.key);
    if (target) {
      target[type] = text;
      target['inital'] = false;
      this.setState({ form });
    } else {
      let obj = {};
      obj[type] = text;
      form.contentList.push(obj);
      this.setState({ form });
    }
    console.log(type);
  };

  onDelete = (index) => {
    let { form } = this.state;
    //调用后端接口删除。成功时再删除，失败提示用户
    let content = form.contentList.find(item => item.key === index);
    if (content.id) {//已添加的步骤删除
      deleteTaskworkContentAction(content.id).then(data => {
        this.onAfterDelete(index);
      }, err => {
        AmosAlert.error('删除失败', err);
      });
    } else {//初始化添加的步骤删除
      this.onAfterDelete(index);
    }
  }

  onAfterDelete = (index) => {
    let { form } = this.state;
    form.contentList = form.contentList.filter(item => item.key !== index);
    form.contentList.map(item => {
      if (item.key > index) {
        item.key -= 1;
      }
    });
    this.setState({ form });
  }

  onAdd = () => {
    let { form } = this.state;
    form.contentList.map(item => item.inital = false);
    let key = form.contentList.length + 1;
    let newObj = { key, serialNum: '', content: '', inital: true };
    form.contentList.push(newObj);
    this.setState({ form });
  }

  getRiskSource = type => {
    getRiskSourceByTypeAction(type).then(data => {
      this.setState({ regionData: data });
    });
  }

  //获取部门
  getDeptData = (regionDepartmentTree = {}) => {
    let depatData = regionDepartmentTree.secondDepartments;
    let deptData = [];
    for (let key in depatData ) {
      depatData[key].map(item =>{
        let deptObj = {};
        deptObj.id = item.sequenceNbr;
        deptObj.name = item.departmentName;
        deptData.push(deptObj);
      });
    }
    return deptData;
  };

  //获取班组
  getTeamData = (departmentId) => {
    const { regionDepartmentTree = [] } = this.props;
    let { groupData } = this.state;
    let depatData = regionDepartmentTree.thirdDepartments;
    let dData  = new Map(Object.entries(depatData)).get(String(departmentId));
    groupData = [];
    dData && dData.map(item => {
      let deptObj = {};
      deptObj.id = item.sequenceNbr;
      deptObj.name = item.departmentName;
      groupData.push(deptObj);
    });
    this.setState({ groupData });
  };

  getTaskWorkDetail = taskworkId => {
    getTaskworkDetailAction(taskworkId).then(data => {
      let { disabled = false } = this.state;
      let form = {};
      Object.assign(form, data);
      form.contentList && form.contentList.map((item, index) => item.key = index);
      form.groupId = data.groupId.split(',');
      form.isIndoor = data.isIndoor ? 1 : 0;
      form.status > 1 && (disabled = true);//当作业活动状态=1即未开始时才能编辑，其他情况不能编辑
      this.setState({ form, disabled }, () => this.forEditUse());
    });
  };

  
  forEditUse = () => {
    const { form } = this.state;
    const { toolbarFlag } = this.props;
    if (toolbarFlag === 1) {
      this.getTeamData(form.departmentId);
      this.getStepData(form.departmentId);
      this.getEquipData(form.workshopSection);
    }
  }

  validPositon3d = (rule, value, callback) => {
    let tempArry = value && (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('非法格式');
    }
  }

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

  render() {
    const { form, rules, regionData, groupData, disabled, stepData, equipData, positionData } = this.state;
    const { typeData, regionDepartmentTree } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 9 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 },
        className: 'colspan'
      }
    };

    return (
      <Form model={form} rules={rules} ref={component => this.form = component}>
        <div className='task-work-model'>
          <div style={{ width: '50%' }}>
            <FormItem label={<span>作业活动名称</span>} field="name" {...formItemLayout}>
              <Input style={{ width: '80%' }} disabled={disabled} className="risk_factor_select" required value={form.name} onChange={e => this.onInputChange('name', e.target.value)} />
            </FormItem>
            <FormItem label={<span>作业活动岗位</span>} field="post" {...formItemLayout}>
              <Input style={{ width: '80%' }} disabled={disabled} className="risk_factor_select" required value={form.post} onChange={e => this.onInputChange('post', e.target.value)} />
            </FormItem>
            <FormItem label={<span>作业活动频率</span>} field="workRate" {...formItemLayout}>
              <Input style={{ width: '80%' }} disabled={disabled} className="risk_factor_select" required value={form.workRate} onChange={e => this.onInputChange('workRate', e.target.value)} />
            </FormItem>
            <FormItem label={<span>班组</span>} field="groupId" {...formItemLayout}>
              <MultiSelect
                className="risk_factor_select"
                style={{ width: '80%' }}
                values={form.groupId}
                data={groupData}
                renderOption={item => <MSOption value={item.id}>{item.name}</MSOption>}
                onChange={e => this.onSelectChange('groupId', e)}
                disabled={disabled}
              />
            </FormItem>
            <FormItem label={<span>设备名称</span>} field="equipmentId" {...formItemLayout}>
              <Select
                className="common-long-select"
                data={equipData}
                searchable
                disabled={disabled}
                value={form.equipmentId}
                renderOption={item => <Option value={item.id}>{item.optionName}</Option>}
                onChange={(e, item) => this.onSelectChange('equipmentId', e, item)}
              />
            </FormItem>
            <FormItem label={<span>地点</span>} field="taskworkAddress" {...formItemLayout}>
              <Input style={{ width: '80%' }} disabled={disabled} className="risk_factor_select" required value={form.taskworkAddress} onChange={e => this.onInputChange('taskworkAddress', e.target.value)} />
            </FormItem>
            <FormItem label={<span>作业活动内容</span>} field="taskworkSubstance" {...formItemLayout}>
              <Input style={{ width: '80%' }} disabled={disabled} className="risk_factor_select" required value={form.taskworkSubstance} onChange={e => this.onInputChange('taskworkSubstance', e.target.value)} />
            </FormItem>


            
            <FormItem label={<span>3维楼层</span>} field="floor3d" {...formItemLayout}>
              <Select
                className="risk_factor_select"
                style={{ width: '80%' }}
                data={floorData}
                defaultValue='1'
                value={form.floor3d}
                renderOption={item => <Option value={item.id}>{item.name}</Option>}
                onChange={e => this.onSelectChange('floor3d', e)}
              />
            </FormItem>
          </div>


          <div style={{ width: '50%' }}>
           
            <FormItem label={<span>作业活动类型</span>} field='type' {...formItemLayout}>
              <Select
                className="risk_factor_select"
                style={{ width: '80%' }}
                data={typeData || []}
                renderOption={item => <Option value={item.dictDataKey}>{item.dictDataValue}</Option>}
                value={form.type}
                onChange={e => this.onSelectChange('type', e)}
                disabled={disabled}
              />
            </FormItem>
            <FormItem label={<span>所属风险区域</span>} field="regionId" {...formItemLayout}>
              <Select
                className="risk_factor_select"
                style={{ width: '80%' }}
                data={regionData}
                renderOption={item => <Option value={String(item.id)}>{item.name}</Option>}
                value={form.regionId}
                onChange={e => this.onSelectChange('regionId', e)}
                disabled={disabled}
              />
            </FormItem>
            <FormItem label={<span>车间/部门</span>} field="departmentId" {...formItemLayout}>
              <Select
                className="risk_factor_select"
                style={{ width: '80%' }}
                data={this.getDeptData(regionDepartmentTree)}
                renderOption={item => <Option value={item.id}>{item.name}</Option>}
                value={form.departmentId}
                onChange={e => this.onSelectChange('departmentId', e)}
                disabled={disabled}
              />
            </FormItem>
            <FormItem label={<span>所属工段</span>} field="workshopSection" {...formItemLayout}>
              <Select
                className="common-long-select"
                data={stepData}
                disabled={disabled}
                renderOption={item => <Option value={item.optionName}>{item.optionName}</Option>}
                value={form.workshopSection}
                onChange={e => this.onSelectChange('workshopSection', e)}
              />
            </FormItem>
            <FormItem label={<span>设备位号</span>} field="equipmentCode" {...formItemLayout}>
              <Select
                className="common-long-select"
                data={positionData}
                searchable
                disabled={disabled}
                value={form.equipmentCode}
                renderOption={item => <Option value={item.optionName}>{`${item.optionName}`}</Option>}
                onChange={(e, item) => this.onSelectChange('equipmentCode', e, item)}
              />
            </FormItem>

           
            <FormItem label={<span>作业活动部位</span>} field="part" {...formItemLayout}>
              <Input style={{ width: '80%' }} disabled={true} className="risk_factor_select" required value={form.part} onChange={e => this.onInputChange('part', e.target.value)} />
            </FormItem>
            
            <FormItem label={<span>3维坐标</span>} field="position3d" {...formItemLayout}>
              <Input style={{ width: '80%' }} placeholder="-23.01,45,36" value={form.position3d} onChange={e => this.onSelectChange('position3d', e.target.value)} />
            </FormItem>
            <FormItem label={<span>是否室内</span>} field="isIndoor" {...formItemLayout}>
              <RadioGroup defaultValue={form.isIndoor} value={form.isIndoor} onChange={e => this.onSelectChange('isIndoor', e)}>
                <Radio value={0}>否</Radio>
                <Radio value={1}>是</Radio>
              </RadioGroup>
            </FormItem>
          </div>
        </div>
        
        <FormItem label={<span>作业活动步骤</span>} field="contentList" className='editable-table' >
          <AmosGridTable
            rowKey="key"
            columns={getColumns(this)}
            callBack={this.reload}
            dataList={form.contentList || []}
            getTableDataAction={() => {}}
            isChecked={false}
            isPageable={false}
          />
        </FormItem>
      </Form>
    );
  }
}

TaskWorkModel.propTypes = {
  taskworkId: PropTypes.number,
  toolbarFlag: PropTypes.number,
  typeData: PropTypes.array,
  regionDepartmentTree: PropTypes.obj
};
export default TaskWorkModel;
