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 * as echarts from 'echarts'
import { recurrent, severity, bug_categories } from './const';
import { timeToString } from '../../utils';

const formItemLayout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 19,
  },
};
const images = [
  '../../assents/noArrived.png',
  '../../assents/yellowFlag.png',
  '../../assents/redFlag.png',
  '../../assents/recPage.png',
];

const Step2 = (props) => {
  const [reportForm] = Form.useForm();
  const [addCaseForm] = Form.useForm();
  const [addBugForm] = Form.useForm();

  const { data, dispatch, reportCommonInfo,
    testCaseList, caseBugList, categories,pathInfo } = props;

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

  const chartRef = useRef();

  if (!data) {
    return null;
  }

  const handleEditReportInfo = ()=>{
    console.log('sss')

  }

  const initEcharts = () => {
    let item_color = 'rgba(226,245,240,1)';
    let border_color = 'rgba(0,0,0,0.9)';
    // let userPath = this.userPath;
    let categories = [
      {
        'name': '暂无Bug',
        'icon': images[0],
        'itemStyle': {'normal': {'color': item_color, 'borderColor': border_color}}
      },
      {
        'name': '已有Bug',
        'icon': images[1],
        'itemStyle': {'normal': {'color': item_color, 'borderColor': border_color}}
      },
      {
        'name': '我的Bug',
        'icon': images[2],
        'itemStyle': {'normal': {'color': item_color, 'borderColor': border_color}}
      },
      {
        'name': '推荐页面',
        'icon': images[3],
        'itemStyle': {'normal': {'color': item_color, 'borderColor': border_color}}
      }
    ];
    let option2 = {
      legend: {     //配置legend，这里的data，要对应type为‘bar’的series数据项的‘name’名称，作为图例的说明
        data: categories,
        selecedMode: false,  //图例禁止点击
        top: '5%',
        left: '3%',
        itemWidth: 10,
        itemHeight: 10,
        orient: 'vertical',
      },
      tooltip: {
        trigger: 'item',
        triggerOn: 'mousemove',
        formatter: function (params) {
          if (params.data.category == 1) {
            return params.name + '<br>' + '我发现/所有: 0/' + params.value;
          } else {
            return '还未有人在该页面发现Bug,努力寻找第一个Bug吧!';
          }
        }
      },
      grid: {
        z: 1,    //grid作为柱状图的坐标系，其层级要和仪表图层级不同，同时隐藏
        show: false,
        left: '-30%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
        splitLine: {
          show: false    //隐藏分割线
        },

      },

      xAxis: [   //这里有很多的show，必须都设置成不显示
        {
          type: 'category',
          data: [],
          axisLine: {
            show: false
          },
          splitLine: {
            show: false
          },
          splitArea: {
            interval: 'auto',
            show: false
          }
        }
      ],

      yAxis: [ //这里有很多的show，必须都设置成不显示
        {
          type: 'value',
          axisLine: {
            show: false
          },
          splitLine: {
            show: false
          },
        }
      ],
      series: [
        {
          type: 'tree',
          name: 'tree1',
          data: [pathInfo],
          //categories:categories,
          top: '5%',
          left: '9%',
          bottom: '1%',
          right: '15%',

          symbolSize: 12,

          label: {
            normal: {
              position: 'left',
              verticalAlign: 'middle',
              align: 'right',
              fontSize: 9
            }
          },

          leaves: {
            label: {
              normal: {
                position: 'right',
                verticalAlign: 'middle',
                align: 'left'
              }
            }
          },

          expandAndCollapse: true,
          initialTreeDepth: 4,
          animationDuration: 550,
          animationDurationUpdate: 750
        },
        {
          name: categories[0].name,
          type: 'bar',
          barWidth: '60%',  //不显示，可以随便设置
          data: [0],
          itemStyle: {
            normal: {
              color: '#41C468',  //这里的图例要注意，颜色设置和仪表盘的颜色对应起来
            }
          }
        },
        {
          name: categories[1].name,
          type: 'bar',
          barWidth: '60%',
          data: [0],
          itemStyle: {
            normal: {
              color: '#70C1B3',
            }
          }
        },
        {
          name: categories[2].name,
          type: 'bar',
          barWidth: '60%',
          data: [0],
          itemStyle: {
            normal: {
              color: '#00A1E9',
            }
          }
        },
        {
          name: categories[3].name,
          type: 'bar',
          barWidth: '60%',
          data: [0],
          itemStyle: {
            normal: {
              color: '#00A1E9',
            }
          }
        }
      ]
    }
    const chart = echarts.init(document.getElementById('myChart'));
    chart.setOption(option2);
  }

  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.result);
      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) => {
      let formData = new FormData();
      formData.append('report_id', reportCommonInfo.id);
      formData.append('title', res.title);
      formData.append('description', res.description);
      formData.append('bug_category', res.bug_category);
      formData.append('severity', res.severity);
      formData.append('recurrent', res.recurrent);
      formData.append('parent', null);
      formData.append('useCase', currentTestCaseRef.current.id);
      formData.append('case_id', '1718');
      formData.append('case_take_id', '1718-1718');
      formData.append('worker_id', '1');
      formData.append('page', `${res.page1}-${res.page2}-${res.page3}`);
      //新建bug
      dispatch({
        type:'editReport/createCaseBug',
        payload: {
          formData,
          useCase:currentTestCaseRef.current.id
        }
      }).then(res=>{
        console.log(res.status)
      })
    });
  };

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

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

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

  const handleClickAddBug = () => {
    //current目前只在点击edit cease的时候会有用
    addBugForm.resetFields();
    setAddTestBugModal(true);
  };

  const handleClickRecommendBtn = () => {
    dispatch({
      type: 'editReport/getPathInfo',
      payload: {
        case_take_id: '1718-1718',
        report_id: reportCommonInfo.id,
      },
    })
    dispatch({
      type: 'editReport/getBugRecommendPath',
      payload: {
        case_take_id: '1718-1718',
        report_id: reportCommonInfo.id,
      },
    })
    dispatch({
      type: 'editReport/getBugRecommendList',
      payload: {
        case_take_id: '1718-1718',
        report_id: reportCommonInfo.id,
      },
    })
    setTaskRecommendModal(true);
    initEcharts();
  }

  const handleSelectPage1 = (val) =>{
    let item = categories.find(x=>x.item === val);
    setPage2List(item.children)
  }

  const handleSelectPage2 = (val) =>{
    let item = page2List.find(x=>x.item === val);
    setPage3List(item.children)
  }

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

  return (
    <div>
      <Row gutter={10}>
        <Col span={23}>
          <Form
            {...formItemLayout}
            form={reportForm}
            className={styles.stepForm}
            hideRequiredMark
            initialValues={data}
          >
            <Row gutter={10}>
              <Col span={5}>
                <Form.Item label="创建日期" rules={[{ required: true, message: '请输入报告名称' }]}>
                  {timeToString(reportCommonInfo.create_time_millis)}
                </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>
        </Col>
        <Col span={1}>
          <EditOutlined className={styles.editReportInfoIcon}
                        onClick={() => handleEditReportInfo()}
          />
        </Col>
      </Row>

      <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} ${currentTestCaseRef.current.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={() => handleClickRecommendBtn()}>
                    <ForkOutlined className={styles.addIcon} />
                    推荐
                  </Button>
                </Col>
              </Row>
              <div className={styles.testBugList}>
                {caseBugList && 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[item.detail.recurrent]}
                          </div>
                          <div><span className={styles.bugItemTitle}>严重程度:</span>{severity[item.detail.severity]}</div>
                          <div><span
                            className={styles.bugItemTitle}>缺陷分类:</span>{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="result"
            rules={[
              {
                required: true,
                message: '请输入预期结果！',
              },
            ]}
          >
            <Input.TextArea autoSize={{ minRows: 3, maxRows: 999 }} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal title="添加用例缺陷" visible={showAddBugModal} width={720}
             forceRender={true}
             footer={[
               <Button key='submit' type="primary" htmlType="submit" onClick={handleAddBug}>确定</Button>,
               <Button key='cancel' htmlType="button" style={{ marginLeft: '10px' }}
                       onClick={() => {
                         setAddTestBugModal(false);
                       }}>取消</Button>]}
             onCancel={() => {
               setAddTestBugModal(false);
             }}
             className={styles.bugForm}
      >
        <ExclamationCircleFilled className={styles.addModalInfo} />为了评分准确,请勿提交重复Bug
        <Form
          form={addBugForm}
          {...formItemLayout}
          layout="horizontal"
          className={styles.stepForm}
        >
          <Form.Item
            label="测试标题"
            name="title"
            rules={[
              {
                required: true,
                message: '请输入测试标题！',
              },
            ]}
          >
            <Input.TextArea autoSize={{ minRows: 1, maxRows: 999 }} />
          </Form.Item>
          <Form.Item
            label="题目描述"
            name="description"
            rules={[
              {
                required: true,
                message: '请输入题目描述！',
              },
            ]}
          >
            <Input.TextArea autoSize={{ minRows: 2, maxRows: 999 }} />
          </Form.Item>
          <Form.Item
            label="三级页面"
            name="pages"
          >
            <Row gutter={5} className={styles.pageSelect}>
              <Col span={8}>
                <Form.Item
                  name="page1"
                  rules={[
                    {
                      required: true,
                      message: '请输入一级页面',
                    },
                  ]}
                >
                  <Select onSelect={(val)=>{handleSelectPage1(val)}}>
                    {categories.map((item) => {
                      return <Select.Option value={item.item} key={item.item}>{item.item}
                      </Select.Option>;
                    })}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="page2"
                  rules={[
                    {
                      required: true,
                      message: '请输入二级页面',
                    },
                  ]}
                >
                  <Select disabled={!page2List.length}
                    onSelect={(val)=>{handleSelectPage2(val)}}>
                    {page2List.map((item)=>{
                        return <Select.Option value={item.item} key={item.item}>{item.item}</Select.Option>
                    })}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="page3"
                  rules={[
                    {
                      required: true,
                      message: '请输入三级页面',
                    },
                  ]}
                >
                  <Select disabled={!page3List.length}>
                    {page3List.map((item)=>{
                      return <Select.Option value={item.item} key={item.item}>{item.item}</Select.Option>
                    })}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
          </Form.Item>
          <Form.Item
            label="漏洞分类"
            name="bug_category"
            rules={[
              {
                required: true,
                message: '请选择漏洞分类！',
              },
            ]}
          >
            <Select>
              {bug_categories.map((item) => {
                return <Select.Option value={item} key={item}>{item}</Select.Option>;
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label="严重等级"
            name="severity"
            rules={[
              {
                required: true,
                message: '请选择严重等级！',
              },
            ]}
          >
            <Select>
              {severity.map((item) => {
                return <Select.Option value={item} key={item}>{item}</Select.Option>;
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label="复现程度"
            name="recurrent"
            rules={[
              {
                required: true,
                message: '请选择复现程度！',
              },
            ]}
          >
            <Select>
              {recurrent.map((item) => {
                return <Select.Option value={item} key={item}>{item}</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>*/}
      <Modal title="任务推荐" visible={showTaskRecommendModal} onOk={() => setTaskRecommendModal(false)}
             onCancel={() => setTaskRecommendModal(false)} className="addModal">
        <div>
          <div id="myChart" ref={chartRef}></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,
  pathInfo:editReport.pathInfo
}))(Step2);
