/**
 * 编辑项目的弹窗表单
 */
import React, { Component } from 'react';
import { Form, Input, Select, Field, Dialog, Feedback } from '@icedesign/base';
import IceEvents from '@ali/ice-events';
import axios from 'axios';
import { apiList } from '../utils';

@IceEvents
export default class EditProjectForm extends Component {
  field = new Field(this);

  componentWillReceiveProps(nextProps) {
    if (nextProps.formData) {
      this.field.setValues(nextProps.formData);
    }
  }

  onCancle = () => {
    this.emit('collect:edit', null);
  };

  onOk = () => {
    this.field.validate((errors, values) => {
      if (errors) {
        return;
      }

      // 请求接口并刷新
      axios
        .post(apiList.updateProject, values)
        .then((response) => {
          if (response.data.status !== 'success') {
            throw new Error('response error');
          }

          Feedback.toast.success('更新成功');
          this.emit('collect:refreshList');
        })
        .catch((err) => {
          Feedback.toast.error(err.message);
        });
    });
  };

  render() {
    const { formData } = this.props;
    const init = this.field.init;

    return (
      <Dialog
        style={{ width: '400px' }}
        title="项目信息修改"
        visible={!!formData}
        onCancel={this.onCancle}
        onClose={this.onCancle}
        onOk={this.onOk}
      >
        <Form field={this.field}>
          <Input {...init('id')} htmlType="hidden" />
          <Form.Item label="项目描述">
            <Input
              {...init('description')}
              multiple
              placeholder="请输入项目描述"
            />
          </Form.Item>
          <Form.Item label="项目主页">
            <Input {...init('projectUrl')} placeholder="请输入项目主页" />
          </Form.Item>
          <Form.Item label="项目状态">
            <Select
              {...init('status', {
                initValue: 'all',
              })}
            >
              <Option value="test">测试项目</Option>
              <Option value="notConfirmed">待确认项目</Option>
              <Option value="confirmed">已确认项目</Option>
            </Select>
          </Form.Item>
        </Form>
      </Dialog>
    );
  }
}
