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 {
  addInstitution,
  deleteInstitution,
  institutionList,
  restartInstitution,
  stopInstitution,
  updateInstitution
} from "@/services/institution";
import {ModalForm, ProForm, ProFormInstance, ProFormText, ProFormTextArea} from '@ant-design/pro-components';
import AliyunOSSUpload from "@/components/Oss/AliyunOSSUpload";

const InstitutionList: React.FC = (props) => {
  const ref = useRef<ActionType>();
  const [currentId, setCurrentId] = useState(-1);
  const [showDeleteConfirmDialog, setShowDeleteConfirmDialog] = useState(false);
  const [showAddInstitutionDialog, setShowAddInstitutionDialog] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const addInstitutionFormRef = useRef<ProFormInstance>();
  const imgUploadRef = useRef<AliyunOSSUpload>();

  const clickStopInstitution = (id: number) => {
    stopInstitution(id).then(data => {
      ref.current?.reload();
    })
  }

  const clickEditInstitution = (id: number) => {
    setIsEdit(true)
    setCurrentId(id)
    setShowAddInstitutionDialog(true)
  }

  const clickDeleteInstitution = (id: number) => {
    setCurrentId(id)
    setShowDeleteConfirmDialog(true)
  }

  const handleDeleteInstitution = () => {
    deleteInstitution(currentId).then(data => {
      setShowDeleteConfirmDialog(false)
      ref.current?.reload();
    })
  }

  const clickRestartUser = (id: number) => {
    restartInstitution(id).then(data => {
      ref.current?.reload();
    })
  }

  const columns: ProColumns<API.Institution>[] = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '邀请码',
      dataIndex: 'inviteCode',
    },
    {
      title: '描述',
      dataIndex: 'desc',
      hideInSearch: true,
      width: 200,
      ellipsis: true,
    },
    {
      title: '注册情况',
      dataIndex: 'register',
      valueEnum: {
        0: {
          text: '未注册',
          status: 'Default'
        },
        1: {
          text: '已注册',
          status: 'Success'
        }
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        0: {
          text: '停用',
          status: 'Default'
        },
        1: {
          text: '正常',
          status: 'Success'
        }
      }
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => {
        return (
          [(
            <a onClick={() => {
              clickEditInstitution(record.id!)
              setTimeout(() => {
                addInstitutionFormRef?.current?.setFieldsValue({
                  institutionId: record.id,
                  name: record.name,
                  logo: record.logo,
                  desc: record.desc,
                })
                imgUploadRef.current?.setState({"url": record.logo})
              })
            }}>编辑</a>
          ),
            record.status === 1 ? (<a onClick={() => clickStopInstitution(record.id!)}>停用</a>) : null,
            record.status === 0 ? (<a onClick={() => clickRestartUser(record.id!)}>启用</a>) : null,
            (<a onClick={() => clickDeleteInstitution(record.id!)}>删除</a>),

          ]
        );
      }
    },
  ]
  // @ts-ignore
  // @ts-ignore
  // @ts-ignore
  return (
    <div>
      <PageContainer>
        <Modal title="" visible={showDeleteConfirmDialog} onOk={handleDeleteInstitution}
               onCancel={() => setShowDeleteConfirmDialog(false)}>
          <p>删除该企业</p>
        </Modal>


        <ModalForm<{
          institutionId: number;
          name: string;
          logo: string;
          desc: string;
        }>
          formRef={addInstitutionFormRef}
          title={isEdit ? "编辑企业" : "添加企业"}
          visible={showAddInstitutionDialog}
          modalProps={{
            onCancel: () => setShowAddInstitutionDialog(false),
          }}
          onFinish={async (values) => {
            if (values.institutionId) {
              updateInstitution({
                ...values
              }).then(data => {
                if (data.code == 200) {
                  message.success("设置成功");
                  ref.current?.reload();
                  setShowAddInstitutionDialog(false)
                } else {
                  message.error(data.message)
                }
              }).catch(data => {
                console.log(data)
              })
            } else {
              addInstitution({...values}).then(data => {
                if (data.code == 200) {
                  message.success("添加成功");
                  ref.current?.reload();
                  setShowAddInstitutionDialog(false)
                } else {
                  message.error(data.message)
                }
                addInstitutionFormRef?.current?.resetFields()
              })
            }
          }}
        >
          <ProFormText name="institutionId" hidden={true}/>
          <ProFormText name="name" label="名字" rules={[{required: true},]}/>
          <ProForm.Item
            label="Logo"
            name="logo"
          >
            <AliyunOSSUpload uploaded={(url: string) => {
              addInstitutionFormRef.current?.setFieldsValue({
                logo: url
              });
            }} isImg={true} ref={imgUploadRef}/>
          </ProForm.Item>
          <ProFormTextArea name="desc" label="描述" rules={[{max: 200},]}/>

        </ModalForm>

        <Card>
          <ProTable<API.UserList>
            actionRef={ref}
            columns={columns}
            request={async (params = {}, sort, filter) => {
              const response = await institutionList({
                name: params.name,
                page: params.current,
                size: params.pageSize,
                register: params.register,
              });
              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="id"
            search={{
              labelWidth: 'auto',
            }}
            pagination={{
              pageSize: 5,
            }}
            dateFormatter="string"
            headerTitle="企业列表"
            toolBarRender={() => [
              <Button type="primary" key="primary" onClick={() => {
                addInstitutionFormRef?.current?.resetFields()
                setShowAddInstitutionDialog(true)
                setIsEdit(false)
              }}>
                添加企业
              </Button>,]}
          />
        </Card>
      </PageContainer>
    </div>
  );
}

export default InstitutionList
