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 {ModalForm, ProFormInstance, ProFormSelect, ProFormText, ProFormTextArea} from '@ant-design/pro-components';
import {USER_TYPE_ADMIN, USER_TYPE_INSTITUTION, USER_TYPE_OTHER, USER_TYPE_PLATFORM} from "@/services/constants";
import {addTag, deleteTag, tagCategoryList, tagList, updateTag} from "@/services/tag";
import UserTagTransfer from "@/components/TagUser";

const TagList: React.FC = (props) => {
    const ref = useRef<ActionType>();
    const [currentTag, setCurrentTag] = useState<API.Tag>();
    const [showDeleteConfirmDialog, setShowDeleteConfirmDialog] = useState(false);
    const {initialState} = useModel('@@initialState');
    const {currentUser} = initialState;
    const [showAddTagDialog, setShowAddTagDialog] = useState(false);
    const [showUserDialog, setShowUserTagDialog] = useState(false);
    const [isEdit, setIsEdit] = useState(false);
    const addTagFormRef = useRef<ProFormInstance>();
    const transferRef = useRef();

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

    const {data: tagCategories} = useRequest(() => {
      return tagCategoryList();
    });

    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 handleCategories = (tagCategoryList?: API.TagCategory[]) => {
    if (tagCategoryList) {
      const newList: {} = {};
      tagCategoryList.forEach(item => {
        if (item.name) {
          newList[item.id!] = {"text": item.name}
        }
      })
      return newList
    } else {
      return []
    }
  }


    const clickEditTag = (tag: API.Tag) => {
      setIsEdit(true)
      setCurrentTag(tag)
      setShowAddTagDialog(true)
    }

    const clickDeleteTag = (tag: API.Tag) => {
      setCurrentTag(tag)
      setShowDeleteConfirmDialog(true)
    }

    const clickUserTag = (tag: API.Tag) => {
      setCurrentTag(tag)
      setShowUserTagDialog(true)
      transferRef?.current?.reload();
    }

    const handleDeleteTag = () => {
      deleteTag(currentTag!.id!).then(data => {
        setShowDeleteConfirmDialog(false)
        ref.current?.reload();
      })
    }

    const columns: ProColumns<API.Tag>[] = [
      {
        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: 'name',
      },
      {
        title: '备注',
        dataIndex: 'remark',
        hideInSearch: true,
      },
      {
        title: '分类',
        dataIndex: 'categoryName',
        hideInSearch: true,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        hideInSearch: true,
      },
      {
        title: '操作',
        valueType: 'option',
        render: (text, record, _, action) => {
          return (
            [(
              <a onClick={() => {
                clickEditTag(record)
                setTimeout(() => {
                  addTagFormRef?.current?.setFieldsValue({
                    tagId: record.id,
                    categoryId: record.categoryId,
                    name: record.name,
                    remark: record.remark,
                  })
                })
              }}>编辑</a>
            ),
              (<a onClick={() => clickUserTag(record)}>标签用户</a>),
              (<a onClick={() => clickDeleteTag(record)}>删除</a>),
            ]
          );
        }
      },
    ]

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

          <Modal title="" visible={showUserDialog} footer={false} width={1200}
                 onCancel={() => setShowUserTagDialog(false)}>
            <p>标签用户</p>
            <UserTagTransfer tag={currentTag} ref={transferRef}/>
          </Modal>

          <ModalForm<{
            tagId: number;
            institutionId: number;
            name: string;
            remark: string;
          }>
            formRef={addTagFormRef}
            title={isEdit ? "编辑标签" : "添加标签"}
            visible={showAddTagDialog}
            modalProps={{
              onCancel: () => setShowAddTagDialog(false),
            }}
            onFinish={async (values) => {
              if (values.tagId) {
                updateTag({
                  ...values
                }).then(data => {
                  if (data.code == 200) {
                    message.success("设置成功");
                    ref.current?.reload();
                    setShowAddTagDialog(false)
                  } else {
                    message.error(data.message)
                  }
                }).catch(data => {
                  console.log(data)
                })
              } else {
                let institutionId = values.institutionId;
                if (currentUser?.type == USER_TYPE_INSTITUTION) {
                  institutionId = currentUser?.institutionId;
                }

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

            <ProFormSelect name="categoryId" label="标签分类" valueEnum={handleCategories(tagCategories)}
                           rules={[{required: true,}]}/>

            <ProFormText name="name" label="名称" rules={[{required: true}, {max: 16}]}/>
            <ProFormTextArea name="remark" label="备注" rules={[{max: 200},]}/>
          </ModalForm>

          <Card>
            <ProTable<API.Tag>
              actionRef={ref}
              columns={columns}
              request={async (params = {}, sort, filter) => {
                let institutionId = currentUser?.institutionId;
                if (institutionId <= 0) {
                  institutionId = params.institutionName
                }
                const response = await tagList({
                  institutionId: institutionId,
                  name: params.name,
                  page: params.current,
                  size: params.pageSize,
                });
                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={() => {
                  addTagFormRef?.current?.resetFields()
                  setShowAddTagDialog(true)
                  setIsEdit(false)
                }}>
                  添加标签
                </Button>,]}

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

export default TagList
