import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Form, Space, Input, Select, Button, Spin, Row, Col, Checkbox, Radio } from 'antd';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';

import { useSelector } from 'react-redux';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { DomEditor } from '@wangeditor/editor';

import { questionAdd, typeAllList, questionAddType, bookNameList } from '../request';
import AliOSS from 'ali-oss';
import dayjs from 'dayjs';
import { getAliOSSSTSToken } from '@/pages/setting/help/addedit/requet';
import { uploadFiles } from '@/utils/upload';
import QuestionEditr from '@/pages/books/question-bank/questionEditr';
import { values } from 'lodash-es';

const CustomerTopic = forwardRef((props, ref) => {
  const { getTopList, bookNameIdData, setPracticeStatus, bookId, setCustomerType } = props;
  // 获取操作权限
  const { operationPermissionsList } = useSelector((state) => state.user);

  useImperativeHandle(ref, () => {
    return {};
  });

  // oss
  const [ossClient, setOssClient] = useState(null); // oss 操作
  const [STSToken, setSTSToken] = useState(null); // oss 过期设置
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const questionType = Form.useWatch('question_style', form);
  // 题干名称的编辑器实例
  const [titlesEditor, setTitlesEditor] = useState(null);
  const [quesList, setQuesList] = useState([]);
  const [initialValues, setinitialValues] = useState({
    titles: '',
    type_id: '',
    question_style: '',
    analysis: '',
    answers: '',
    question_list: [],
    book_id: bookId,
  });
  // 书籍名称的参数和获取
  const [selectedBookId, setSelectedBookId] = useState(bookId);

  useEffect(() => {
    setSelectedBookId(bookId);
  }, [bookId]);

  const getStsAuthToken = async () => {
    const data = await getAliOSSSTSToken();
    if (data) {
      window.sessionStorage.setItem('sts', JSON.stringify(data));
      setSTSToken(data);
      const ossClientTemp = await new AliOSS({
        accessKeyId: data.AccessKeyId,
        accessKeySecret: data.AccessKeySecret,
        stsToken: data.SecurityToken,
        endpoint: data.endpoint,
        bucket: 'zxts-book-file',

        timeout: 180000,
        refreshSTSToken: async () => {
          const info = await getAliOSSSTSToken();
          return {
            AccessKeyId: info.AccessKeyId,
            AccessKeySecret: info.AccessKeySecret,
            SecurityToken: info.SecurityToken,
          };
        },
        refreshSTSTokenInterval: 14 * 60 * 1000,
      });
      setOssClient(ossClientTemp);
    }
  };

  // 显示不同类型的选项函数
  const [edierVal, setedierVal] = useState('');
  // 是否显示选项
  const [showList, setShowList] = useState(false);
  const [formLoading, setFormLoading] = useState(false);
  const [typeDate, setTypeDate] = useState([]);
  const [showAddClass, setShowAddClass] = useState(false);
  const [addClassVal, setaddClassVal] = useState(''); // 添加分类
  const [questionStyle, setQuestionStyle] = useState('');

  // 题目分类
  const getTypeList = async () => {
    const { list } = await typeAllList({ page: 1, page_size: 999 });
    setTypeDate(list);
  };

  // 获取数据
  useEffect(() => {
    (async () => {
      await getTypeList();
      await getStsAuthToken();
    })();
  }, []);

  // 分类
  const sureFn = async () => {
    const bool = await questionAddType({ typename: addClassVal });
    if (bool) {
      await getTypeList();
      form.setFieldsValue({ type_id: bool.type_id });
      setinitialValues({ ...initialValues, type_id: bool.type_id });
      setaddClassVal('');
      setShowAddClass(false);
    }
  };

  // 工具栏配置
  const toolbarConfig = {};
  toolbarConfig.toolbarKeys = ['uploadImage'];
  // 编辑器配置
  const editorConfig = {
    // JS 语法
    placeholder: '请输入内容...',
    hoverbarKeys: {
      text: {
        menuKeys: [],
      },
    },
    MENU_CONF: {
      // 配置默认字号
      // 配置上传图片
      uploadImage: {
        timeout: 5 * 1000, // 5s

        fieldName: 'image',
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: 'Bearer ' + localStorage.getItem('token'),
        },
        maxFileSize: 10 * 1024 * 1024, // 10M

        base64LimitSize: 5 * 1024, // 5kb 以下插入 base64
        customUpload: async (file, insertFn) => {
          if (!ossClient) {
            console.error('ossClient还未初始化', ossClient);
            return false;
          }

          const fileExt = file.name.substring(file.name.lastIndexOf('.'));
          const fileName = `practice-${dayjs().valueOf()}-${Math.random()
            .toString(36)
            .substring(2)}${fileExt}`;
          const filePath = `${dayjs().format('YYYY/MM/DD')}/${fileName}`;

          const result = await ossClient.put(filePath, file);

          console.log('result', result);
          insertFn(result.url, '题库图片');

          // const { url } = await uploadFiles({ file, file_type: 'question' });
          // insertFn(url, '题库图片');
        },
      },
    },
    customPaste: (editor, event) => {
      // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
      const text = event.clipboardData.getData('text/plain'); // 获取粘贴的纯文本
      // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）

      // 异步
      setTimeout(() => {
        editor.insertText(text);
      }, 500);

      // 阻止默认的粘贴行为
      event.preventDefault();
      return false;
    },
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    if (titlesEditor !== null) {
      const toolbar = DomEditor.getToolbar(titlesEditor);
    }

    return () => {
      if (titlesEditor === null) return;
      titlesEditor.destroy();
      setTitlesEditor(null);
    };
  }, [titlesEditor]);

  const submitForm = async (obj) => {
    let ilen = 0;
    let obj2 = { ...obj };
    if ([1, 2, 3].includes(parseInt(obj.question_style))) {
      obj.question_list.forEach((item, index) => {
        if (item.correct && item.correct === true) {
          ilen++;
        }
      });

      if ([1, 3].includes(parseInt(obj.question_style))) {
        if (ilen > 1 || ilen === 0) {
          form.setFields([
            {
              name: ['question_list', obj.question_list.length - 1, 'correct'],
              errors: [
                `${parseInt(obj.question_style) === 3 ? '判断题' : '单选题'}有且仅有一个正确答案！`,
              ],
            },
          ]);
          return false;
        } else {
          form.setFields([
            { name: ['question_list', obj.question_list.length - 1, 'correct'], errors: [''] },
          ]);
        }
      } else {
        if (ilen <= 1) {
          form.setFields([
            {
              name: ['question_list', obj.question_list.length - 1, 'correct'],
              errors: ['多选题需要2个及以上正确答案！'],
            },
          ]);
          return false;
        } else {
          form.setFields([
            { name: ['question_list', obj.question_list.length - 1, 'correct'], errors: [''] },
          ]);
        }
      }

      obj2['question_list'] = JSON.stringify(quesList);
    } else {
      obj2['answers'] = edierVal;
    }

    setLoading(true);
    const data = await questionAdd({
      ...obj,
      ...obj2,
    });

    if (data) {
      setCustomerType(obj.type_id);
      setPracticeStatus(false);
    }
    setLoading(false);
  };
  // 校验
  const vaildaterHtml = (_, value) => {
    if (value === '<p><br></p>') {
      return Promise.reject('问题内容不能为空');
    } else {
      return Promise.resolve();
    }
  };

  useEffect(() => {
    console.log(quesList);
  }, [quesList]);

  return (
    <div style={{ paddingTop: 20 }} className='practice_customer'>
      <Form
        form={form}
        initialValues={initialValues}
        onFinish={submitForm}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 19 }}
      >
        <Form.Item
          name='book_id'
          label='书籍名称'
          rules={[{ required: true, message: '请选择书籍' }]}
        >
          <Select
            placeholder='请选择书籍名称'
            allowClear
            id='classify'
            style={{ width: '200px' }}
            showSearch //下拉框出现搜素,并可以输入
            optionFilterProp='children' // 使搜索匹配子节点的文本内容
            defaultValue={selectedBookId}
            onChange={(value) => setSelectedBookId(value)}
          >
            {bookNameIdData &&
              bookNameIdData.length &&
              bookNameIdData.map((item, index) => (
                <Select.Option key={item.book_id} value={item.book_id}>
                  {item.name}
                </Select.Option>
              ))}
          </Select>
        </Form.Item>

        <Form.Item
          name='question_style'
          label='题目类型'
          rules={[{ required: true, message: '请选择题目类型' }]}
        >
          <Select
            onChange={(ev) => {
              setShowList(true);
              setQuestionStyle(ev);
            }}
            style={{ width: 260 }}
            placeholder='请请选择题目类型'
          >
            <Select.Option value={1}>单选题</Select.Option>
            <Select.Option value={2}>多选题</Select.Option>
            <Select.Option value={3}>判断题</Select.Option>
            <Select.Option value={4}>填空题</Select.Option>
            <Select.Option value={5}>简答题</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item
          label='题目分类'
          name='type_id'
          rules={[{ required: true, message: '请选择题目分类' }]}
        >
          {!showAddClass ? (
            <>
              <Select
                onChange={(value) => {
                  form.setFieldValue('type_id', value);
                }}
                style={{ width: 260 }}
                placeholder='请选择题目分类'
              >
                {typeDate &&
                  typeDate.length &&
                  typeDate.map((item) => (
                    <Select.Option key={item.id} value={item.id}>
                      {item.typename}
                    </Select.Option>
                  ))}
              </Select>
              <Button
                onClick={() => {
                  setShowAddClass(true);
                  form.setFieldsValue({ type_id: '' });
                }}
                type='link'
                style={{ textDecoration: 'underline', color: '#1672EC' }}
              >
                添加分类
              </Button>
            </>
          ) : (
            <>
              <Input
                style={{ width: 260 }}
                value={addClassVal}
                onChange={(e) => setaddClassVal(e.target.value)}
                autoComplete='off'
                placeholder='请输入题目分类'
              ></Input>
              <Space>
                <Button
                  onClick={sureFn}
                  type='link'
                  style={{ textDecoration: 'underline', color: '#1672EC' }}
                >
                  添加
                </Button>
                <Button
                  type='link'
                  onClick={() => setShowAddClass(false)}
                  style={{ textDecoration: 'underline', color: '#AA1941', marginLeft: -30 }}
                >
                  取消
                </Button>
              </Space>
            </>
          )}
        </Form.Item>
        <Form.Item
          name='titles'
          label='题干名称'
          rules={[
            { required: true, message: '请输入题干名称' },
            { validator: vaildaterHtml, validateTrigger: 'onChange' },
          ]}
          extra={questionType === 4 ? '请在需要填空的位置使用2个或以上的下划线进行区分！' : ''}
        >
          <Spin spinning={formLoading}>
            <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
              <Toolbar
                editor={titlesEditor}
                defaultConfig={toolbarConfig}
                mode='default'
                style={{ borderBottom: '1px solid #ccc' }}
              />
              {ossClient && (
                <Editor
                  defaultConfig={editorConfig}
                  value={initialValues.titles}
                  onCreated={setTitlesEditor}
                  onChange={(editor) => {
                    form.setFieldValue('titles', editor.getHtml());
                    // setHtml(editor.getHtml())
                  }}
                  config={{
                    uploadImgServer: 'your_upload_server_address',
                    // other config options
                  }}
                  mode='default'
                  style={{ height: '200px', overflowY: 'hidden' }}
                />
              )}
            </div>
          </Spin>
        </Form.Item>
        <Form.Item name='analysis' label='题目解析'>
          <Input.TextArea
            placeholder='请输入题目解析'
            autoSize={{
              minRows: 5,
              maxRows: 8,
            }}
          />
        </Form.Item>
        {(questionStyle === 1 || questionStyle === 2 || questionStyle === 3) && (
          <Form.List name='question_list'>
            {(fields, { add, remove }) => (
              <Form.Item label='题目选项'>
                {fields.map(({ key, name, ...restField }, index) => (
                  <Row gutter={4} key={key}>
                    <Col span={14} className='form_inside-out'>
                      <Form.Item className='inside-it'>
                        <QuestionEditr
                          editorValue={quesList && quesList[index] && quesList[index].option}
                          quesList={quesList}
                          setQuesList={setQuesList}
                          index={index}
                          form={form}
                        />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'option']}
                        rules={[
                          { required: true, message: '请输入内容' },
                          {
                            validator: (_, value) => {
                              if (value !== '') {
                                if (value === '<p><br></p>') {
                                  return Promise.reject(new Error('请输入正确的内容'));
                                } else {
                                  return Promise.resolve();
                                }
                              } else {
                                return Promise.reject(new Error(''));
                              }
                            },
                          },
                        ]}
                        className='form_inside-out-none'
                      >
                        <Input.TextArea />
                      </Form.Item>
                    </Col>
                    <Col span={7}>
                      <Form.Item
                        {...restField}
                        name={[name, 'correct']}
                        valuePropName='checked'
                        initialValue={restField.correct || false}
                      >
                        <Checkbox
                          onChange={(e) => {
                            if (quesList.length) {
                              let temp = JSON.parse(JSON.stringify(quesList));
                              if (questionStyle === 1 || questionStyle === 3) {
                                if (e.target.checked) {
                                  temp.forEach((item) => {
                                    item.correct = false;
                                  });
                                }
                              }
                              temp[index].correct = e.target.checked;
                              setQuesList(temp);
                              form.setFieldValue('question_list', temp);
                            }
                          }}
                        >
                          正确答案
                        </Checkbox>
                      </Form.Item>
                    </Col>
                    <Col span={3}>
                      <Button
                        onClick={async () => {
                          let temp = JSON.parse(JSON.stringify(quesList));
                          temp.splice(index, 1);
                          setQuesList(temp);

                          await remove(name);
                        }}
                        icon={<MinusOutlined />}
                      ></Button>
                    </Col>
                  </Row>
                ))}
                {quesList.length < 2 && questionStyle === 3 && (
                  <Form.Item>
                    <Button
                      type='dashed'
                      onClick={async () => {
                        await add();
                      }}
                      icon={<PlusOutlined />}
                    ></Button>
                  </Form.Item>
                )}
                {[1, 2].includes(questionStyle) && (
                  <Form.Item>
                    <Button
                      type='dashed'
                      onClick={async () => {
                        await add();
                      }}
                      icon={<PlusOutlined />}
                    ></Button>
                  </Form.Item>
                )}
              </Form.Item>
            )}
          </Form.List>
        )}
        {(questionStyle === 5 || questionStyle === 4) && (
          <Form.Item name='answers' label='正确答案'>
            <QuestionEditr
              editorValue={edierVal}
              setedierVal={setedierVal}
              form={form}
              name='answers'
            />
          </Form.Item>
        )}
        <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
          <Space size={20}>
            <Button className='submit' disabled={showAddClass} loading={loading} htmlType='submit'>
              提交
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  );
});

export default CustomerTopic;
