import React, {useRef, useState} from 'react';
import {PageContainer} from "@ant-design/pro-layout";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {Button, Card, message, Modal} from "antd";
import styles from './index.less';

import {
  EditableProTable,
  ModalForm,
  ProForm,
  ProFormDependency,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormTreeSelect
} from '@ant-design/pro-components';
import {addQuestion, deleteQuestion, questionList, updateQuestion} from "@/services/paperManager";
import {getPageQuery} from "@/utils/utils";
import {
  ACCESS_TYPE_INNER, ACCESS_TYPE_TAG,
  QUESTION_TYPE_JUDGE,
  QUESTION_TYPE_MULTIPLE_CHOICE,
  QUESTION_TYPE_RATE,
  QUESTION_TYPE_SINGER_CHOICE,
  QUESTION_TYPE_TEXT
} from "@/services/constants";

const QuestionList: React.FC = (props) => {
    const ref = useRef<ActionType>();
    const [currentQuestion, setCurrentQuestion] = useState<API.Question>();
    const [showDeleteConfirmDialog, setShowDeleteConfirmDialog] = useState(false);
    const [showAddQuestionDialog, setShowAddQuestionDialog] = useState(false);
    const [isEdit, setIsEdit] = useState(false);
    const addQuestionFormRef = useRef<ProFormInstance>();
    const paperId = parseInt(getPageQuery().id + '');
    const paperType = parseInt(getPageQuery().type + '');

    if (!paperId || !paperType) {
      return <>访问异常</>
    }

    const clickEditQuestion = (question: API.Question) => {
      setIsEdit(true)
      setCurrentQuestion(question)
      setShowAddQuestionDialog(true)
    }

    const clickDeleteQuestion = (paper: API.Question) => {
      setCurrentQuestion(paper)
      setShowDeleteConfirmDialog(true)
    }


    const handleDeletePaper = () => {
      deleteQuestion(paperId, currentQuestion!.id!).then(data => {
        setShowDeleteConfirmDialog(false)
        ref.current?.reload();
      })
    }

    const dimension = [
      {
        title: '无',
        value: '',
        children: []
      },
      {
        title: '战略可靠度(R)',
        value: 'R',
        selectable: false,
        children: [
          {
            title: '发展方向和未来环境契合度(R1)',
            value: 'R1',
          },
          {
            title: '目标与现实契合度(R2)',
            value: 'R2',
          },
        ],
      },
      {
        title: '战略认同度(A)',
        value: 'A',
        selectable: false,
        children: [
          {
            title: '参与度(A1)',
            value: 'A1',
          },
          {
            title: '共识度(A2)',
            value: 'A2',
          },
          {
            title: '承诺度(A3)',
            value: 'A3',
          },
          {
            title: '协同度(A4)',
            value: 'A4',
          },
        ],
      },
      {
        title: '策略清晰度(C)',
        value: 'C',
        selectable: false,
        children: [
          {
            title: '目标清晰度(C1)',
            value: 'C1',
          },
          {
            title: '策略清晰度(C2)',
            value: 'C2',
          },
          {
            title: '权责清晰度(C3)',
            value: 'C3',
          },
          {
            title: '奖惩清晰度(C4)',
            value: 'C4',
          },
        ],
      },
      {
        title: '组织支持度(E)',
        value: 'E',
        selectable: false,
        children: [
          {
            title: '组织支持(E1)',
            value: 'E1',
          },
          {
            title: '人才支持(E2)',
            value: 'E2',
          },
          {
            title: '文化支持(E3)',
            value: 'E3',
          },
          {
            title: '系统支持(E4)',
            value: 'E4',
          },
        ],
      },
    ]

    function getPath(value: string) {
      for (let i = 0; i < dimension.length; i++) {
        for (let j = 0; j < dimension[i].children.length; j++) {
          if (dimension[i].children[j].value == value) {
            return dimension[i].value;
          }
        }
      }
      return null;
    }

    const columns: ProColumns<API.Question>[] = [
      {
        title: '',
        dataIndex: 'subDimension',
        hideInSearch: true,
        width: 40,
        render: (text, record, _, action) => {
          if (record.subDimension) {
            return <div className={styles.dimension}>{record.subDimension}</div>
          } else {
            return <></>
          }
        }
      },
      {
        title: '标题',
        dataIndex: 'title',
        hideInSearch: true,
      },
      {
        title: '类型',
        dataIndex: 'type',
        hideInSearch: true,
        valueEnum: {
          0: {
            text: '评分',
          },
          1: {
            text: '单选',
          },
          2: {
            text: '多选',
          },
          3: {
            text: '判断',
          },
          4: {
            text: '文本',
          },
        }
      },
      {
        title: '操作',
        valueType: 'option',
        render: (text, record, _, action) => {
          return (
            [
              <a onClick={() => {
                clickEditQuestion(record)
                setTimeout(() => {
                  addQuestionFormRef?.current?.setFieldsValue({
                    questionId: record.id,
                    title: record.title,
                    type: record.type,
                    score: record.score,
                    optionList: record.optionList,
                    subDimension: record.subDimension,
                  })
                })
              }}>编辑</a>,
              (<a onClick={() => clickDeleteQuestion(record)}>删除</a>),
            ]
          );
        }
      },
    ]

    return (
      <div>
        <PageContainer>
          <Modal title="" visible={showDeleteConfirmDialog} onOk={handleDeletePaper}
                 onCancel={() => setShowDeleteConfirmDialog(false)}>
            <p>删除该问题</p>
          </Modal>

          <ModalForm<any>
            formRef={addQuestionFormRef}
            title={isEdit ? "编辑问题" : "添加问题"}
            visible={showAddQuestionDialog}
            modalProps={{
              onCancel: () => setShowAddQuestionDialog(false),
            }}

            onValuesChange={(changeValues) => {
              console.log(changeValues)
            }}

            onFinish={async (values) => {
              if (values.questionId) {
                let dimension = getPath(values['subDimension']);
                updateQuestion({
                  ...values, paperId, dimension
                }).then(data => {
                  if (data.code == 200) {
                    message.success("设置成功");
                    ref.current?.reload();
                    setShowAddQuestionDialog(false)
                  } else {
                    message.error(data.message)
                  }
                }).catch(data => {
                })
              } else {
                let dimension = getPath(values['subDimension']);
                addQuestion({...values, paperId, dimension}).then(data => {
                  if (data.code == 200) {
                    message.success("添加成功");
                    ref.current?.reload();
                    setShowAddQuestionDialog(false)
                  } else {
                    message.error(data.message)
                  }
                  addQuestionFormRef?.current?.resetFields()
                })
              }
            }}
          >
            <ProFormText name="questionId" hidden={true}/>
            {paperType == 1 && <ProFormTreeSelect
              name="subDimension"
              label="维度"
              allowClear
              request={() => dimension}
              placeholder="请选择问题维度"
              // rules={[{required: true}]}
              secondary
              fieldProps={{
                showArrow: false,
                filterTreeNode: true,
                dropdownMatchSelectWidth: false,
                treeDefaultExpandAll: true,
              }}
            />}
            <ProFormText name="title" label="标题" rules={[{required: true}, {max: 100}]}/>

            <ProFormSelect
              options={[
                {
                  value: QUESTION_TYPE_RATE,
                  label: '评分',
                },
                {
                  value: QUESTION_TYPE_SINGER_CHOICE,
                  label: '单选',
                },
                {
                  value: QUESTION_TYPE_MULTIPLE_CHOICE,
                  label: '多选',
                },
                {
                  value: QUESTION_TYPE_JUDGE,
                  label: '判断',
                },
                {
                  value: QUESTION_TYPE_TEXT,
                  label: '文本',
                },
              ]}
              name="type"
              label={"类型"}
              rules={[{required: true}]}
            />
            <ProFormDependency name={['type']}>
              {({type}) => {
                if (type == QUESTION_TYPE_RATE) {
                  return <ProFormSelect
                    name="score"
                    label="最高分值"
                    options={[
                      {
                        "value": 10,
                        "label": "10分"
                      },
                      {
                        "value": 5,
                        "label": "5分"
                      },
                    ]}
                    rules={[{required: true}]}/>
                } else if (type == QUESTION_TYPE_SINGER_CHOICE || type == QUESTION_TYPE_MULTIPLE_CHOICE) {
                  return <ProForm.Item
                    label="选项"
                    name="optionList"
                    rules={[{required: true}]}
                  >
                    <EditableProTable<API.QuestionOption>
                      rowKey="id"
                      size={"small"}
                      toolBarRender={false}
                      maxLength={5}
                      bordered
                      columns={[{
                        title: '标题',
                        dataIndex: 'title',
                        width: '60%',
                        formItemProps: {
                          rules: [
                            {
                              required: true,
                            },
                          ],
                        },
                      }, {
                        title: '分值',
                        dataIndex: 'score',
                        width: '20%',
                        valueType: 'digit',
                        formItemProps: {
                          label: '分值',
                          rules: [
                            {
                              required: true,
                            },
                            {
                              pattern: /^([0-9]|10)$/,
                              message: '分值只能0-10'
                            }
                          ],
                        },
                      }, {
                        title: '操作',
                        valueType: 'option',
                        width: 200,
                        render: (text, record, _, action) => [
                          <a
                            key="editable"
                            onClick={() => {
                              action?.startEditable?.(record!.id!);
                            }}
                          >
                            编辑
                          </a>,
                          <a
                            key="delete"
                            onClick={() => {
                              const tableDataSource = addQuestionFormRef.current?.getFieldValue('optionList') as API.QuestionOption[];
                              addQuestionFormRef.current?.setFieldsValue({
                                optionList: tableDataSource.filter((item) => item.id !== record.id),
                              });
                            }}
                          >
                            删除
                          </a>,
                        ],
                      },]}
                      recordCreatorProps={{
                        newRecordType: 'dataSource',
                        position: 'bottom',
                        creatorButtonText: '新增选项',
                        record: () => ({
                          id: Date.now(),
                        }),
                      }}
                    />
                  </ProForm.Item>
                } else {
                  return <></>
                }
              }}
            </ProFormDependency>


          </ModalForm>

          <Card>
            <ProTable<API.Question>
              actionRef={ref}
              columns={columns}
              search={false}
              request={async (params = {}, sort, filter) => {
                const response = await questionList(paperId);
                if (response.code === 200) {
                  return {
                    data: response.data!,
                    success: true,
                  };
                } else {
                  message.error(response.message)
                  return {}
                }
              }}
              editable={{
                type: 'multiple',
              }}
              rowKey={record => record.id!}
              pagination={false}
              dateFormatter="string"
              headerTitle="问题列表"
              toolBarRender={() => [
                <Button type="primary" key="primary" onClick={() => {
                  addQuestionFormRef?.current?.resetFields()
                  setShowAddQuestionDialog(true)
                  setIsEdit(false)
                }}>
                  添加问题
                </Button>,]}

            />
          </Card>
        </PageContainer>
      </div>
    );
  }
;

export default QuestionList
