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 {useRequest} from "@@/plugin-request/request";
import {useModel} from "@@/plugin-model/useModel";
import {institutionList} from "@/services/institution";
import copy from 'copy-to-clipboard';

import {
  ModalForm,
  ProForm,
  ProFormDatePicker,
  ProFormDependency,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormTextArea
} from '@ant-design/pro-components';
import {
  ACCESS_TYPE_ALL,
  ACCESS_TYPE_INNER,
  ACCESS_TYPE_TAG,
  USER_TYPE_ADMIN,
  USER_TYPE_INSTITUTION,
  USER_TYPE_OTHER,
  USER_TYPE_PLATFORM
} from "@/services/constants";
import {
  addPaper,
  deletePaper, exportPaper360,
  exportResult,
  paperList,
  restartPaper,
  stopPaper,
  updatePaper
} from "@/services/paperManager";
import {tagList} from "@/services/tag";
import {history} from "umi";
import {createReport} from "@/services/report";

const PaperList: React.FC = (props) => {
    const ref = useRef<ActionType>();
    const [currentPaper, setCurrentPaper] = useState<API.Tag>();
    const [showDeleteConfirmDialog, setShowDeleteConfirmDialog] = useState(false);
    const {initialState} = useModel('@@initialState');
    const {currentUser} = initialState;
    const [showAddPaperDialog, setShowAddPaperDialog] = useState(false);
    const [isEdit, setIsEdit] = useState(false);
    const addPaperFormRef = useRef<ProFormInstance>();

    const {data: institutions} = useRequest(() => {
      return institutionList({page: 1, size: 100}, true);
    });

    const handleInstitutions = (institutions?: API.Institution[]) => {
      if (institutions) {
        const newList: {} = {};
        institutions.forEach(item => {
          if (item.name) {
            newList[item.id!] = {"text": item.name}
          }
        })
        return newList
      } else {
        return {}
      }
    }

    const clickStopPaper = (paper: API.PaperList) => {
      stopPaper(paper!.id!).then(data => {
        ref.current?.reload();
      })
    }

    const clickRestartPaper = (paper: API.PaperList) => {
      restartPaper(paper!.id!).then(data => {
        ref.current?.reload();
      })
    }

    const clickEditPaper = (paper: API.PaperList) => {
      setIsEdit(true)
      setCurrentPaper(paper)
      setShowAddPaperDialog(true)
    }

    const clickDeletePaper = (paper: API.PaperList) => {
      setCurrentPaper(paper)
      setShowDeleteConfirmDialog(true)
    }


    const handleDeletePaper = () => {
      deletePaper(currentPaper!.id!).then(data => {
        setShowDeleteConfirmDialog(false)
        ref.current?.reload();
      })
    }

    const exportExcel = async (paperId: number, title: string) => {
      const res = await exportPaper360(paperId);
      if (res) {
        const url = window.URL.createObjectURL(new Blob([res]));
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.download = title + '-统计.xls';
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      }
    };

    const columns: ProColumns<API.PaperList>[] = [
      {
        dataIndex: 'index',
        valueType: 'indexBorder',
        width: 48,
      },
      {
        title: '企业',
        dataIndex: 'institutionName',
        valueType: 'select',
        hideInSearch: currentUser?.type == USER_TYPE_INSTITUTION || currentUser?.type == USER_TYPE_OTHER,
        hideInTable: currentUser?.type == USER_TYPE_INSTITUTION || currentUser?.type == USER_TYPE_OTHER,
        valueEnum: handleInstitutions(institutions?.records),
      },
      {
        title: '标题',
        dataIndex: 'title',
      },
      {
        title: '类型',
        dataIndex: 'type',
        valueEnum: {
          1: {
            text: 'RACE问卷',
          },
          2: {
            text: '360环评问卷',
          }
        }
      },
      {
        title: '开始时间',
        dataIndex: 'startTime',
        hideInSearch: true,
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
        hideInSearch: true,
      },
      {
        title: '权限',
        dataIndex: 'accessType',
        hideInSearch: true,
        render: (_, record) => {
          if (record.accessType == ACCESS_TYPE_ALL) {
            return <>所有用户</>
          } else if (record.accessType == ACCESS_TYPE_INNER) {
            return <>内部用户</>
          } else if (record.accessType == ACCESS_TYPE_TAG) {
            return <>{record.accessExtraInfo}</>
          } else {
            return <></>
          }
        },
      },
      {
        title: '状态',
        dataIndex: 'status',
        valueEnum: {
          0: {
            text: '草稿',
            status: 'Default'
          },
          1: {
            text: '发布',
            status: 'Success'
          }
        }
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        hideInSearch: true,
      },
      {
        title: '操作',
        valueType: 'option',
        render: (text, record, _, action) => {
          return (
            [(
              <a onClick={() => {
                clickEditPaper(record)
                setTimeout(() => {
                  addPaperFormRef?.current?.setFieldsValue({
                    paperId: record.id,
                    title: record.title,
                    desc: record.desc,
                    startTime: record.startTime,
                    endTime: record.endTime,
                    allowAutoRegister: record.allowAutoRegister,
                    accessType: record.accessType,
                    accessExtra: record.accessType == ACCESS_TYPE_TAG ? parseInt(record.accessExtra || '') : record.accessExtra
                  })
                })
              }}>编辑信息</a>
            ),
              <a onClick={() => {
                history.push(`/question?id=${record.id}&type=${record.type}`)
              }}>编辑问题</a>,
              record.status === 1 && (<a onClick={() => clickStopPaper(record)}>停用</a>),
              record.status === 0 && (<a onClick={() => clickRestartPaper(record)}>发布</a>),
              (<a onClick={() => clickDeletePaper(record)}>删除</a>),
              record.status === 1 && record.type === 1 && (<a onClick={() => {
                copy("http://" + window.location.host + "/paper/detail?id=" + record.id)
                message.success("复制成功")
              }}>复制链接</a>),
              record.status === 1 && record.type === 2 && (<a onClick={() => {
                history.push("/paper360?id=" + record.id)
              }}>环评管理</a>),
              record.status === 1 && record.type === 1 && (<a onClick={() => {
                history.push("/paperResult?id=" + record.id)
              }}>答题情况</a>),
              record.status === 1 && record.type === 2 && (<a onClick={() => {
                exportExcel(record!.id!, record!.title!)
              }}>导出统计</a>),
              record.status === 1 && record.type === 1 && (<a onClick={() => {
                createReport(record!.institutionId!, record!.id!).then(data => {
                  history.push("/report")
                })
              }}>生成报告</a>),
            ]
          );
        }
      },
    ]

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

          <ModalForm<any>
            formRef={addPaperFormRef}
            title={isEdit ? "编辑问卷" : "添加问卷"}
            visible={showAddPaperDialog}
            modalProps={{
              onCancel: () => setShowAddPaperDialog(false),
            }}

            onValuesChange={(changeValues) => {
              if (changeValues.institutionId) {
                addPaperFormRef?.current?.setFieldsValue(
                  {
                    accessType: ACCESS_TYPE_INNER,
                  }
                )
              }
            }}
            onFinish={async (values) => {
              if (values.paperId) {
                updatePaper({
                  ...values
                }).then(data => {
                  if (data.code == 200) {
                    message.success("设置成功");
                    ref.current?.reload();
                    setShowAddPaperDialog(false)
                  } else {
                    message.error(data.message)
                  }
                }).catch(data => {
                })
              } else {
                let institutionId = values.institutionId;
                if (currentUser?.type == USER_TYPE_INSTITUTION) {
                  institutionId = currentUser?.institutionId;
                }

                addPaper({...values, institutionId, status: 0}).then(data => {
                  if (data.code == 200) {
                    message.success("添加成功");
                    ref.current?.reload();
                    setShowAddPaperDialog(false)
                  } else {
                    message.error(data.message)
                  }
                  addPaperFormRef?.current?.resetFields()
                })
              }
            }}
          >
            <ProFormText name="paperId" hidden={true}/>
            {!isEdit && (currentUser?.type == USER_TYPE_PLATFORM || currentUser?.type == USER_TYPE_ADMIN) &&
            <ProFormSelect name="institutionId" label="企业名称" valueEnum={handleInstitutions(institutions?.records)}
                           rules={[{required: true,}]}/>}

            {!isEdit && <ProFormSelect
              name="type"
              label="问卷类型"
              options={[
                {
                  "value": 1,
                  "label": "RACE问卷"
                },
                {
                  "value": 2,
                  "label": "360环评问卷"
                }]}
              rules={[{required: true}]}/>}

            <ProFormText name="title" label="标题" rules={[{required: true}, {max: 50}]}/>
            <ProFormTextArea name="desc" label="描述" rules={[{required: true}, {max: 500},]}/>
            <ProForm.Group>
              <ProFormDatePicker
                name="startTime"
                label="开始日期"
                fieldProps={{
                  format: (value) => value.format('YYYY-MM-DD'),
                }}
                rules={[{required: true}]}
              />
              <ProFormDatePicker
                name="endTime"
                label="结束日期"
                fieldProps={{
                  format: (value) => value.format('YYYY-MM-DD'),
                }}
                rules={[{required: true}]}
              />
            </ProForm.Group>

            <ProFormDependency name={['type']}>
              {({type}) => {
                if (type === 1) {
                  return <ProFormSelect
                    name="accessType"
                    label="允许用户"
                    options={[
                      {
                        "value": ACCESS_TYPE_INNER,
                        "label": "内部用户"
                      },
                      {
                        "value": ACCESS_TYPE_TAG,
                        "label": "指定标签"
                      },
                    ]}
                    rules={[{required: true}]}/>
                } else if (type === 2) {
                  return <></>
                } else {
                  return <></>
                }
              }}

            </ProFormDependency>
            <ProFormSelect
              name="allowAutoRegister"
              label="是否匿名用户"
              options={[
                {
                  "value": 1,
                  "label": "是"
                },
                {
                  "value": 0,
                  "label": "否"
                },
              ]}
              rules={[{required: true}]}/>

            <ProFormDependency name={['institutionId', 'accessType']}>
              {({institutionId, accessType}) => {
                if (accessType == ACCESS_TYPE_TAG) {
                  return <ProFormSelect
                    name="accessExtra"
                    label="标签"
                    rules={[{required: true}]}
                    request={async (params) => {
                      if (!institutionId) {
                        institutionId = currentUser?.institutionId
                      }
                      const response = await tagList({institutionId: institutionId, page: 1, size: 100})
                      if (response.code === 200) {
                        const newList: { value?: number, label?: string }[] = [];
                        response?.data?.records?.forEach(item => {
                          if (item.name) {
                            newList.push({
                              value: item.id,
                              label: item.name,
                            })
                          }
                        })
                        return newList
                      } else {
                        return []
                      }
                    }}
                  />
                } else {
                  return <></>;
                }
              }}
            </ProFormDependency>

          </ModalForm>

          <Card>
            <ProTable<API.PaperList>
              actionRef={ref}
              columns={columns}
              request={async (params = {}, sort, filter) => {
                let institutionId = currentUser?.institutionId;
                if (institutionId <= 0) {
                  institutionId = params.institutionName
                }
                const response = await paperList({
                  institutionId: institutionId,
                  page: params.current,
                  size: params.pageSize,
                  title: params.title,
                  status: params.status,
                });
                if (response.code === 200) {
                  return {
                    data: response.data!.records,
                    success: true,
                    total: response.data!.total,
                  };
                } else {
                  message.error(response.message)
                  return {}
                }
              }}
              editable={{
                type: 'multiple',
              }}
              rowKey={record => record.id!}
              search={{
                labelWidth: 'auto',
              }}
              pagination={{
                pageSize: 5,
              }}
              dateFormatter="string"
              headerTitle="问卷列表"
              toolBarRender={() => [
                <Button type="primary" key="primary" onClick={() => {
                  addPaperFormRef?.current?.resetFields()
                  setShowAddPaperDialog(true)
                  setIsEdit(false)
                }}>
                  添加问卷
                </Button>,]}

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

export default PaperList
