import React, { useEffect, useRef, useState } from 'react';
import { Form, Row, Col, Card, Modal, Input, Select, Upload, Button, message } from 'antd';
import { connect } from 'umi';
import styles from './index.less';
import {
  ForkOutlined,
  PlusOutlined,
  ExclamationCircleFilled,
  UploadOutlined,
  EditOutlined,
  EyeOutlined,
} from '@ant-design/icons';

import { recurrent, severity, bug_categories } from './const';

const formItemLayout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 19,
  },
};

const Step2 = (props) => {
  const [form] = Form.useForm();
  const [addCaseForm] = Form.useForm();
  const [addBugForm] = Form.useForm();
  const { data, dispatch, reportCommonInfo, testCaseList, caseBugList,categories } = props;

  const [showTaskRecommendModal, setTaskRecommendModal] = useState(false);
  const [showAddTestCaseModal, setAddTestCaseModal] = useState(false);
  const [showAddBugModal, setAddTestBugModal] = useState(false);
  const currentTestCaseRef = useRef({});
  const [isAddCaseStatus, setIsAddCaseStatus] = useState(true);
  const [currActiveTestCase, setCurrActiveTestCase] = useState({});


  if (!data) {
    return null;
  }

  const handleAddOrEditTestCase = () => {
    addCaseForm.validateFields().then((res) => {
      let formData = new FormData();
      // formData.append("id", values.reportName);
      formData.append('report_id', reportCommonInfo.id);
      formData.append('name', res.name);
      formData.append('front', res.front);
      formData.append('behind', res.behind);
      formData.append('description', res.description);
      if (!isAddCaseStatus) {
        //处理编辑用例
        formData.append('id', currentTestCaseRef.current.id);
        dispatch({
          type: 'editReport/updateTestCase',
          payload: {
            formData,
            report_id: reportCommonInfo.id,
          },
        }).then((res) => {
          if (res && res.status === 200) {
            message.success('修改成功！');
          }
        });
      } else {
        //处理添加用例
        dispatch({
          type: 'editReport/createTestCase',
          payload: {
            formData,
            report_id: reportCommonInfo.id,
          },
        }).then((res) => {
          if (res && res.id) {
            message.success('添加成功！');
          }
        });
      }

      setAddTestCaseModal(false);
    });
  };

  const handleAddBug = () => {
    addBugForm.validateFields().then((res) => {
      console.log(res);
      let formData = new FormData();
      formData.append('report_id', reportCommonInfo.id);
      formData.append('name', res.name);
      formData.append('front', res.front);
      formData.append('behind', res.behind);
      formData.append('description', res.description);
    });
    // if (true) {
    //   //新建bug的逻辑
    //   setAddTestBugModal(true);
      // dispatch({
      //   type: 'editReport/createTestCase',
      //   payload: {
      //     report_id:reportCommonInfo.id
      //   },
      // }).then((res)=>{
      //   if(res&&res.id){
      //     message.success('添加成功！');
      //   }
      // });
    // } else {
    //   //编辑bug的逻辑
    // }
  };

  const handleClickTestCase = (caseItem) => {
    setCurrActiveTestCase(caseItem);
    dispatch({
      type: 'editReport/getCaseBugList',
      payload: caseItem.id,
    });
  };

  const handleEditTestCase = (item) => {
    setIsAddCaseStatus(false);
    currentTestCaseRef.current = item;
    addCaseForm.setFieldsValue(currentTestCaseRef.current);
    setAddTestCaseModal(true);
  };

  const handleClickAddCase = () => {
    currentTestCaseRef.current = {};
    addCaseForm.resetFields();
    setAddTestCaseModal(true);
  };

  // const handleEditBug = (item) => {
  //   setIsAddCaseStatus(false);
  //   currentTestCaseRef.current = item;
  //   addBugForm.setFieldsValue(currentTestCaseRef.current)
  //   setAddTestCaseModal(true);
  // };

  const handleClickAddBug = () => {
    addBugForm.resetFields();
    setAddTestBugModal(true);
  };

  useEffect(() => {
    //判断是否已经有报告
    dispatch({
      type: 'editReport/getReportInfo',
      payload: {
        case_take_id: '1718-1718',
        worker_id: 1,
      },
    }).then(() => {
      //有报告，获取对应信息。没有就直接转去了第一步
      dispatch({
        type: 'editReport/getTestCaseList',
        payload: { report_id: reportCommonInfo.id },
      });
      dispatch({
        type: 'editReport/getCategories',
        payload: { examId: 1945 },
      });
    });
  }, [dispatch]);

  return (
    <div>
      <Form
        {...formItemLayout}
        form={form}
        layout="horizontal"
        className={styles.stepForm}
        hideRequiredMark
        initialValues={data}
      >
        <Row gutter={10}>
          <Col span={5}>
            <Form.Item label="创建日期" rules={[{ required: true, message: '请输入报告名称' }]}>
              {'2021.4.12'}
            </Form.Item>
          </Col>
          <Col span={5}>
            <Form.Item label="报告名称" rules={[{ required: true, message: '请输入报告名称' }]}>
              {reportCommonInfo.name}
            </Form.Item>
          </Col>
          <Col span={5}>
            <Form.Item label="设备名称" required>
              {reportCommonInfo.device_brand}
            </Form.Item>
          </Col>
          <Col span={5}>
            <Form.Item label="设备品牌" required>
              {reportCommonInfo.device_model}
            </Form.Item>
          </Col>
          <Col span={4}>
            <Form.Item label="操作系统" required>
              {reportCommonInfo.device_os}
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <Card>
        <div className={styles.reportContainer}>
          <Row gutter={10}>
            <Col span={8}>
              <div>
                <Row gutter={10} style={{ marginBottom: 10 }}>
                  <Col span={20}><h3>测试用例列表</h3></Col>
                  <Col span={4}>
                    <Button size="small" onClick={() => {
                      handleClickAddCase();
                    }}>
                      <PlusOutlined className={styles.addIcon} />
                      用例
                    </Button>
                  </Col>
                </Row>
              </div>

              <div className={styles.testCaseList}>
                {testCaseList && testCaseList.map((item) => {
                  return (
                    <div
                      className={`${styles.testCaseItem} ${currActiveTestCase.id === item.id ? styles.activeCase : ''}`}
                      key={item.id}
                      onClick={() => {
                        handleClickTestCase(item);
                      }}>
                      <Row gutter={10}>
                        <Col span={21}><p>{item.name}</p></Col>
                        <Col span={3}>
                          <EditOutlined className={styles.editTestBug}
                                        onClick={() => handleEditTestCase(item)} />
                        </Col>
                      </Row>
                    </div>);
                })}
              </div>
            </Col>

            <Col span={16} style={{ paddingLeft: 20 }}>
              <Row gutter={10} style={{ marginBottom: 10 }}>
                <Col span={20}><h3>缺陷列表</h3></Col>
                <Col span={2}>
                  <Button size="small" onClick={() => handleClickAddBug()}>
                    <PlusOutlined className={styles.addIcon} />
                    缺陷
                  </Button>
                </Col>
                <Col span={2}>
                  <Button size="small" onClick={() => setTaskRecommendModal(true)}>
                    <ForkOutlined className={styles.addIcon} />
                    推荐
                  </Button>
                </Col>
              </Row>
              <div className={styles.testBugList}>
                {caseBugList.map((item) => {
                  return (
                    <div className={styles.testBugItem} key={item.detail.id}>
                      <Row gutter={10}>
                      <Col span={20}>
                        <div><span className={styles.bugItemTitle}>Bug标题:</span>{item.detail.title}</div>
                        <div><span className={styles.bugItemTitle}>复现程度:</span>{recurrent.get(item.detail.recurrent)}</div>
                        <div><span className={styles.bugItemTitle}>严重程度:</span>{item.detail.severity}</div>
                        <div><span className={styles.bugItemTitle}>缺陷分类:</span>{severity.get(item.detail.bug_category)}
                        </div>
                      </Col>
                      <Col span={4}>
                        <Button size='small' style={{ marginTop: 10 }}>
                          <EyeOutlined />详情</Button>
                      </Col>
                    </Row>
                    </div>
                  );
                })}
              </div>
            </Col>

          </Row>
        </div>
      </Card>
      <Modal title={isAddCaseStatus ? '添加测试用例' : '编辑测试用例'} width={720}
             visible={showAddTestCaseModal}
             forceRender={true}
             className="addModal"
             footer={[
               <Button key='submit' type="primary" htmlType="submit" onClick={handleAddOrEditTestCase}>确定</Button>,
               <Button key='cancel' htmlType="button" style={{ marginLeft: '10px' }}
                       onClick={() => {
                         setAddTestCaseModal(false);
                       }}>取消</Button>]}
             onCancel={() => {
               setAddTestCaseModal(false);
             }}
      >
        <ExclamationCircleFilled className={styles.addModalInfo} />为了评分准确,请勿提交重复测试用例
        <Form
          {...formItemLayout}
          form={addCaseForm}
          layout="horizontal"
          className={styles.stepForm}
        >
          <Form.Item
            label="用例名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入用例名称！',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="前置条件"
            name="front"
            rules={[
              {
                required: true,
                message: '请输入前置条件！',
              },
            ]}
          >
            <Input.TextArea autoSize={{ minRows: 3, maxRows: 999 }} />
          </Form.Item>
          <Form.Item
            label="测试步骤"
            name="behind"
            rules={[
              {
                required: true,
                message: '请输入测试步骤！',
              },
            ]}
          >
            <Input.TextArea autoSize={{ minRows: 3, maxRows: 999 }} />
          </Form.Item>
          <Form.Item
            label="预期结果"
            name="description"
            rules={[
              {
                required: true,
                message: '请输入预期结果！',
              },
            ]}
          >
            <Input.TextArea autoSize={{ minRows: 3, maxRows: 999 }} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal title="添加用例缺陷" visible={showAddBugModal} width={720}
             footer={[
               <Button key='submit' type="primary" htmlType="submit" onClick={handleClickAddBug}>确定</Button>,
               <Button key='cancel' htmlType="button" style={{ marginLeft: '10px' }}
                       onClick={() => { handleAddBug();}}>取消</Button>]}
               onCancel={() => {
                 setAddTestBugModal(false);
               }}
      >
        <ExclamationCircleFilled className={styles.addModalInfo} />为了评分准确,请勿提交重复Bug
        <Form
          labelCol={{ span: 4 }}
          form={addBugForm}
          {...formItemLayout}
          layout="horizontal"
          className={styles.stepForm}
        >
          <Form.Item
            label="测试题目"
            name="testName"
            rules={[
              {
                required: true,
                message: '请输入测试题目！',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="前置条件"
            name="precondition"
            rules={[
              {
                required: true,
                message: '请输入前置条件！',
              },
            ]}
          >
            <Input.TextArea autoSize />
          </Form.Item>
          <Form.Item
            label="三级页面"
            name="pages"
            rules={[
              {
                required: true,
                message: '请确保输入了三级页面',
              },
            ]}
          >
            <Row gutter={5}>
              <Col span={8}>
                <Select>
                  {categories.map((item)=>{
                    return <Select.Option value="demo" key={item.item}>{item.item}</Select.Option>
                  })}
                </Select>
              </Col>
              <Col span={8}>
                <Select>
                  <Select.Option value="demo">Demo2</Select.Option>
                </Select>
              </Col>
              <Col span={8}>
                <Select>
                  <Select.Option value="demo">Demo3</Select.Option>
                </Select>
              </Col>
            </Row>
          </Form.Item>
          <Form.Item
            label="漏洞分类"
            name="bugType"
            rules={[
              {
                required: true,
                message: '请输入漏洞分类！',
              },
            ]}
          >
            <Select>
              <Select.Option value="demo">Demo</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="严重等级"
            name="service"
            rules={[
              {
                required: true,
                message: '请输入严重等级！',
              },
            ]}
          >
            <Select>
              <Select.Option value="demo">Demo</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="复现程度"
            name="recurrent"
            rules={[
              {
                required: true,
                message: '请输入测试题目！',
              },
            ]}
          >
            <Select>
              <Select.Option value="demo">Demo</Select.Option>
            </Select>
          </Form.Item>
          {/*<Form.Item*/}
          {/*  label="上传截图"*/}
          {/*  name="testName"*/}
          {/*>*/}
          {/*  <Upload*/}
          {/*    action="https://www.mocky.io/v2/5cc8019d300000980a055e76"*/}
          {/*    listType="picture"*/}
          {/*  >*/}
          {/*    <Button icon={<UploadOutlined />}>Upload</Button>*/}
          {/*  </Upload>*/}
          {/*</Form.Item>*/}
        </Form>
      </Modal>
      <Modal title="任务推荐" visible={showTaskRecommendModal} onOk={() => setTaskRecommendModal(false)}
             onCancel={() => setTaskRecommendModal(false)} className="addModal">
        <div>
          <div id="forceChart"></div>
        </div>
      </Modal>
    </div>
  );
};

export default connect(({ editReport, loading }) => ({
  submitting: loading.effects['editReport/submitStepForm'],
  data: editReport.step,
  reportCommonInfo: editReport.reportCommonInfo,
  testCaseList: editReport.testCaseList,
  caseBugList: editReport.caseBugList,
  categories:editReport.categories
}))(Step2);
