import React, { useState, useEffect } from 'react';
import { Form, Input, Modal, Row, Col, Select, InputNumber, Spin, Tabs, DatePicker } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import ReactZmage from 'react-zmage';
import styles from './LimitedSpace.less';

function OperationDetail(props) {
  const {
    loading,
    form,
    dispatch,
    visible,
    selectedSpace,
    currentRecord,
    projectId,
    onOk,
    onCancel,
  } = props;
  const { getFieldDecorator, setFieldsValue, resetFields, validateFields } = form;
  const [spaceDetailList, setSpaceDetailList] = useState([]);
  const [isEdit, setIsEdit] = useState(false);
  const [isEpiboly, setIsEpiboly] = useState(false);
  const [opCode, setOpCode] = useState('');
  const [opTime, setOpTime] = useState('');

  const TIMER_FORMAT = 'YYYY-MM-DD HH:mm';

  const handleOk = () => {
    if (isEdit) {
      validateFields((err, fieldValues) => {
        if (!err) {
          const { op_total, op_time } = fieldValues;
          let payload = {
            ...fieldValues,
            project_id: Number(projectId),
            op_time: opTime,
            op_total: Number(op_total),
            op_time: moment(op_time).format('YYYY-MM-DD HH:mm:ss'),
          };
          //编辑
          if (currentRecord) {
            onEdit(payload);
          }
          //新建
          else {
            onCreate(payload);
          }
          setSpaceDetailList([]);
          setIsEdit(false);
          setIsEpiboly(false);
          setOpCode('');
          setOpTime('');
          resetFields();
          onOk();
        }
      });
    }
    //编辑按钮
    else {
      setIsEdit(true);
    }
  };

  const handleCancel = () => {
    setSpaceDetailList([]);
    setIsEdit(false);
    setIsEpiboly(false);
    setOpCode('');
    setOpTime('');
    resetFields();
    onCancel();
  };

  const onCreate = payload => {
    payload = { ...payload, space_ids: selectedSpace.join(',') };
    dispatch({
      type: 'limitedSpace/createOperation',
      payload,
    });
  };

  const onEdit = payload => {
    payload = { ...payload, space_id: Number(spaceDetailList[0].space_id), id: currentRecord.id };
    dispatch({
      type: 'limitedSpace/updateOperation',
      payload,
    });
  };

  const onChangeForm = value => {
    if (value == 3) setIsEpiboly(true);
    else setIsEpiboly(false);
  };

  useEffect(() => {
    if (!visible) return;
    //详情
    if (currentRecord) {
      setIsEdit(false);
      dispatch({
        type: 'limitedSpace/queryOpDetail',
        payload: {
          id: currentRecord.id,
        },
        callback: data => {
          setSpaceDetailList([{ ...data.space, id: data.op.id, space_id: data.op.space_id }]);
          setOpCode(data.op.code);
          setOpTime(data.op.op_time);
          const {
            dep,
            op_content,
            op_form,
            charge_person,
            guardian,
            check_person,
            op_person,
            other_person,
            op_total,
            other_info,
          } = data.op;
          setFieldsValue({
            dep,
            op_content,
            op_form,
            charge_person,
            guardian,
            check_person,
            op_person,
            other_person,
            op_total,
            other_info,
          });
          if (data.op.epiboly) {
            setIsEpiboly(true);
            setFieldsValue({
              epiboly: data.op.epiboly,
            });
          }
        },
      });
    }
    //新建
    else {
      setIsEdit(true);
      setOpTime(moment().format(TIMER_FORMAT));
      dispatch({
        type: 'limitedSpace/querySpacesDetail',
        payload: { selectedSpace },
        callback: list => setSpaceDetailList(list),
      });
    }
  }, [selectedSpace, currentRecord, visible]);

  const renderForm = () => (
    <Form layout="horizontal" labelCol={{ span: 10 }} wrapperCol={{ span: 12 }}>
      <Row gutter={[20, 20]} justify="space-between">
        <Col span={12}>
          <Form.Item label="制定部门">
            {getFieldDecorator('dep', {
              rules: [{ required: true, message: '请填写部门' }],
            })(<Input disabled={!isEdit} required />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="作业内容">
            {getFieldDecorator('op_content', {
              rules: [{ required: true, message: '请填写作业内容' }],
            })(<Input disabled={!isEdit} required />)}
          </Form.Item>
        </Col>
        <Col span={12} className={styles.selectBlock}>
          <Form.Item label="作业形式">
            {getFieldDecorator('op_form', {
              rules: [{ required: true, message: '请选择作业形式' }],
            })(
              <Select disabled={!isEdit} onChange={value => onChangeForm(value)} required>
                <Select.Option key="1"> 自主作业(无外请劳务人员) </Select.Option>
                <Select.Option key="2"> 自主作业(有外请劳务人员) </Select.Option>
                <Select.Option key="3"> 外包作业 </Select.Option>
              </Select>
            )}
          </Form.Item>
        </Col>
        {isEpiboly && (
          <Col span={12}>
            <Form.Item label="外包作业单位">
              {getFieldDecorator('epiboly', {
                rules: [{ required: true, message: '请输入外包单位' }],
              })(<Input disabled={!isEdit} required />)}
            </Form.Item>
          </Col>
        )}
        <Col span={12}>
          <Form.Item label="作业负责人">
            {getFieldDecorator('charge_person', {
              rules: [{ required: true, message: '请填写负责人' }],
            })(<Input disabled={!isEdit} required />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="作业监护人">
            {getFieldDecorator('guardian', {
              rules: [{ required: true, message: '请填写监护人' }],
            })(<Input disabled={!isEdit} required />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="气体检测人">
            {getFieldDecorator('check_person', {
              rules: [{ required: true, message: '请填写气体检测人' }],
            })(<Input disabled={!isEdit} required />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="作业人">
            {getFieldDecorator('op_person', {
              rules: [{ required: true, message: '请填写作业人' }],
            })(<Input disabled={!isEdit} required />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="其他作业人员">
            {getFieldDecorator('other_person')(<Input disabled={!isEdit} />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="作业人数">
            {getFieldDecorator('op_total', {
              rules: [{ required: true, message: '请填写作业人数' }],
            })(<InputNumber precision={0} min={0} disabled={!isEdit} required />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="其他情况">
            {getFieldDecorator('other_info')(<Input disabled={!isEdit} />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="作业时间">
            {getFieldDecorator('op_time', {
              initialValue: moment(opTime || moment(new Date()), TIMER_FORMAT),
            })(
              <DatePicker
                style={{ minWidth: '230px' }}
                disabled={!isEdit}
                format={TIMER_FORMAT}
                placeholder="请选择作业时间"
                showTime={{ format: 'HH:mm' }}
              />
            )}
          </Form.Item>
        </Col>
      </Row>
    </Form>
  );

  //这部分可以重构
  //利用array.map
  //结构[{pic: bool, title: string, value: string}]
  const renderDetail = (space, op_total) => (
    <div className={styles.operationDetail}>
      <div className={styles.opDetailBlock}>
        <div className={styles.opTitle}>作业地点: </div>
        <div className={styles.opContent}>{`石景山水厂${space.data1}${space.name}`}</div>
      </div>
      <div className={styles.opDetailBlock}>
        <div className={styles.opTitle}>作业安全: </div>
        <div className={styles.opContent}>{`本次作业电压不大于${space.data20 || '-'}`}</div>
      </div>
      <div className={styles.opPicBlock}>
        <div className={styles.opPicDes}>
          <div className={styles.opTitle}>有限空间基本情况: </div>
          <div className={styles.opContent}>
            {`为${space.type || '-'}, 深度${space.data8 || '-'}米, 出入口共有${space.data9 ||
              '-'}个`}
          </div>
        </div>
        {space?.data9_pic?.length != 0 && (
          <div className={styles.opPic}>
            {space.data9_pic.map((item, index) => (
              <ReactZmage key={index} src={item} />
            ))}
          </div>
        )}
      </div>
      <div className={styles.opPicBlock}>
        <div className={styles.opPicDes}>
          <div className={styles.opTitle}>周围情况: </div>
          <div className={styles.opContent}>
            {`${space.data11 || '-'}, 此有限空间为${
              space.data12 ? (space.data12 == '是' ? '道路作业' : '非道路作业') : '-'
            }`}
          </div>
        </div>
        {space?.data11_pic?.length != 0 && (
          <div className={styles.opPic}>
            {space.data11_pic.map((item, index) => (
              <ReactZmage key={index} src={item} />
            ))}
          </div>
        )}
      </div>
      <div className={styles.opPicBlock}>
        <div className={styles.opPicDes}>
          <div className={styles.opTitle}>危险源情况: </div>
          <div className={styles.opContent}>{space.data10}</div>
        </div>
        {space?.data10_pic?.length != 0 && (
          <div className={styles.opPic}>
            {space.data10_pic.map((item, index) => (
              <ReactZmage key={index} src={item} />
            ))}
          </div>
        )}
      </div>
      <div className={styles.opPicBlock}>
        <div className={styles.opPicDes}>
          <div className={styles.opTitle}>内部情况: </div>
          <div className={styles.opContent}>{space.data14}</div>
        </div>
        {space?.data14_pic?.length != 0 && (
          <div className={styles.opPic}>
            {space.data14_pic.map((item, index) => (
              <ReactZmage key={index} src={item} />
            ))}
          </div>
        )}
      </div>
      <div className={styles.opDetailBlock}>
        <div className={styles.opTitle}>照明灯具数量: </div>
        <div className={styles.opContent}>{op_total}</div>
      </div>
      <div className={styles.opDetailBlock}>
        <div className={styles.opTitle}>安全带数量: </div>
        <div className={styles.opContent}>{op_total}</div>
      </div>
      <div className={styles.opDetailBlock}>
        <div className={styles.opTitle}>安全帽数量: </div>
        <div className={styles.opContent}>{op_total ? Number(op_total) + 2 : null}</div>
      </div>
      <div className={styles.opDetailBlock}>
        <div className={styles.opTitle}>安全绳数量: </div>
        <div className={styles.opContent}>{op_total}</div>
      </div>
      <div className={styles.opDetailBlock}>
        <div className={styles.opTitle}>呼吸防护数量: </div>
        <div className={styles.opContent}>{`每人应携带${space.data19 < 10 ? 1 : 2}个`}</div>
      </div>
      {opCode && (
        <div className={styles.opDetailBlock}>
          <div className={styles.opTitle}>审批表编号: </div>
          <div className={styles.opContent}>{opCode}</div>
        </div>
      )}
      <div className={styles.opDetailBlock}>
        <div className={styles.opTitle}>审批人: </div>
        <div className={styles.opContent}>{space.data6}</div>
      </div>
    </div>
  );

  return (
    <Modal
      className={styles.selectModal}
      title={`作业详情`}
      visible={visible}
      onCancel={handleCancel}
      onOk={handleOk}
      width={'95%'}
      okText={isEdit ? '提交' : '编辑'}
    >
      {renderForm()}
      <br />
      <Spin spinning={loading}>
        <Tabs>
          {spaceDetailList?.map((space, index) => {
            let id = selectedSpace[index] || space.space_id;
            const { op_total } = form.getFieldsValue();
            return (
              <Tabs.TabPane tab={space.name} key={id}>
                {renderDetail(space, op_total)}
              </Tabs.TabPane>
            );
          })}
        </Tabs>
      </Spin>
    </Modal>
  );
}

export default connect()(Form.create()(OperationDetail));
