import { PageContainer } from '@ant-design/pro-layout'
import { useState, useEffect, useRef } from 'react'
import ProTable from '@ant-design/pro-table'
import type { ActionType } from '@ant-design/pro-table'
import { ModalForm } from '@ant-design/pro-form'
import type { ProFormInstance } from '@ant-design/pro-form'
import type { ProFormColumnsType } from '@ant-design/pro-form'
import { DeleteOutlined } from '@ant-design/icons'
import { queryAcountList } from '@/services/api/institution'
import consts from '@/utils/consts'
import { Button, Form, message, Table } from 'antd'
import { saveCreator } from '@/services/api/user'
import { useRequest } from 'umi'
import { getProjectList } from '@/services/api/project'
import TreeNodeSelect from '../Management/List/components/TreeNodeSelect'

enum CreatedModalType {
  ADD = '1',
  DEL = '2'
}

const Created = () => {
  const tRef = useRef<ActionType>(null)
  const mRef = useRef<ProFormInstance>(null)
  const [state, setState] = useState({
    dataID: null,
    modalType: CreatedModalType.ADD,
    options: [],
    projectList: [],
    modalVisible: false
  })
  const { run: tryQueryProjectList } = useRequest(
    createdID => getProjectList({ current: 1, pageSize: 21300, createdID }),
    {
      manual: true,
      onSuccess: ({ items }) => {
        setState({ ...state, projectList: items })
      }
    }
  )

  useEffect(() => {
    if (state.dataID && state.modalType === CreatedModalType.DEL) {
      tryQueryProjectList(state.dataID)
    }
  }, [state.dataID, state.modalType])

  const columns: ProFormColumnsType<AccountListItem>[] = [
    {
      dataIndex: 'account',
      title: '账号',
      width: 116,
      align: 'center',
      onHeaderCell: () => ({ style: { textAlign: 'center' } })
    },
    {
      dataIndex: 'name',
      title: '名称',
      width: 86,
      align: 'center',
      onHeaderCell: () => ({ style: { textAlign: 'center' } })
    },
    {
      dataIndex: 'institutionID',
      title: '企事业单位',
      width: 286,
      onHeaderCell: () => ({ style: { textAlign: 'center' } }),
      renderText: (_, record) => record?.institution?.name
    },
    {
      dataIndex: 'organizationalStructureID',
      title: '组织架构',
      width: 146,
      align: 'center',
      onHeaderCell: () => ({ style: { textAlign: 'center' } }),
      renderText: (_, record) => record?.organizationalStructure?.name
    },
    {
      dataIndex: 'opreate',
      title: '操作',
      width: 61,
      align: 'center',
      onHeaderCell: () => ({ style: { textAlign: 'center' } }),
      render: (_, record) => (
        <div
          className="text-hex-fd3995 cursor-pointer hover:text-hex-e7026e"
          onClick={() =>
            setState({
              ...state,
              dataID: record.ID,
              modalType: CreatedModalType.DEL,
              modalVisible: true
            })
          }>
          <DeleteOutlined />
        </div>
      )
    }
  ]

  const { run: trySaveCreator } = useRequest(saveCreator, {
    manual: true,
    onSuccess: () => {
      tRef?.current?.reload()
      return message.success('操作成功')
    }
  })
  const onFinish = async formData => {
    try {
      if (state.modalType === CreatedModalType.ADD) {
        await trySaveCreator({ ...formData, isCreated: 1 })
      } else {
        await trySaveCreator({ ID: state.dataID, isCreated: 0 })
      }
      tRef?.current?.reload()
      mRef?.current?.resetFields()
      setState({ ...state, modalVisible: false })
      return true
    } catch (error) {
      return false
    }
  }
  return (
    <PageContainer title={false}>
      <ProTable
        rowKey="ID"
        actionRef={tRef}
        columns={columns}
        search={false}
        toolbar={{
          actions: [
            <Button
              type="primary"
              onClick={() =>
                setState({ ...state, modalVisible: true, modalType: CreatedModalType.ADD })
              }>
              添加创建人
            </Button>
          ]
        }}
        scroll={{ y: document.body.clientHeight - 313 }}
        request={async (params, filter, sort) => {
          const {
            code = -1,
            data: { items, total }
          } = await queryAcountList({ ...params, ...filter, ...sort, isCreated: 1 })
          return {
            success: code === consts.RET_CODE.SUCCESS,
            data: items,
            total
          }
        }}
      />
      <ModalForm
        title={state.modalType === CreatedModalType.ADD ? '添加创建人' : '移除创建人'}
        onFinish={onFinish}
        formRef={mRef}
        submitter={{
          submitButtonProps: {
            danger: state.modalType === CreatedModalType.ADD ? false : true
          }
        }}
        isKeyPressSubmit
        visible={state.modalVisible}
        onVisibleChange={visible => setState({ ...state, modalVisible: visible })}>
        {state.modalType === CreatedModalType.ADD ? (
          <>
            {/* <p className="mb-4">创建人可在前台创建项目、上传项目数据、编制项目等</p> */}
            <Form.Item
              name="ID"
              label="创建人可在前台创建项目、上传项目数据、编制项目等"
              rules={[{ required: true, message: '请选择创建人' }]}>
              <TreeNodeSelect params={{ isCreated: 0 }} />
            </Form.Item>
            {/* <ProFormSelect
              name="ID"
              request={async () => {
                const {
                  code = -1,
                  data: { items }
                } = await queryAcountInstitutionList({
                  current: 1,
                  pageSize: 21400,
                  isCreated: '0'
                })
                return code === consts.RET_CODE.SUCCESS
                  ? items.map(item => ({
                      label: `${item.name} - ${item?.institution?.name}`,
                      value: item.ID
                    }))
                  : []
              }}
            /> */}
          </>
        ) : (
          <>
            <p className="text-red-500">
              当前创建人已经管理以下项目，移除后，这些项目对应创建人也将被移除。
            </p>
            <div className="mt-7">
              <Table
                rowKey="ID"
                columns={[
                  // {
                  //   dataIndex: 'sort',
                  //   title: '序号',
                  //   render: (_, __, idx) => idx + 1,
                  //   width: '10%'
                  // },
                  { dataIndex: 'name', title: '项目名称' }
                ]}
                size="small"
                scroll={{ y: 250 }}
                dataSource={state.projectList}
                pagination={false}
              />
            </div>
          </>
        )}
      </ModalForm>
    </PageContainer>
  )
}

export default Created
