import { delProject, getProjectList } from '@/services/api/project'
import ProTable from '@ant-design/pro-table'
import type { ProColumnType, ActionType } from '@ant-design/pro-table'
import { Button, Popconfirm } from 'antd'
import consts from '@/utils/consts'
import { useRef, useState, useEffect } from 'react'
import { connect, useRequest } from 'umi'
import type { ConnectProps } from 'umi'
import type { ProjectModelState } from '../model'
import { DeleteOutlined } from '@ant-design/icons'
import ProjectModal, { ModalType } from './components/ProjectModal'
import dayjs from 'dayjs'
import { PageContainer } from '@ant-design/pro-layout'
import type { SchemaBaseModelState } from '@/pages/Schema/Base/model'
import { BaseMenuEnum } from '@/pages/Schema/Base'
import { generateColumns } from '@/utils/util'
import Detail from './components/Detail'
import AnimateContent from '@/components/AnimateContent'

type ListProps = ConnectProps & {
  pTypeList: { label: string; value: string }[]
  schema?: Record<string, any> | null
}

const List: React.FC<ListProps> = ({ schema, dispatch, pTypeList }) => {
  const tRef = useRef<ActionType>(null)
  useEffect(() => {
    if (!pTypeList.length) {
      dispatch({
        type: 'project/queryProjectTypeList'
      })
    }
    dispatch({
      type: 'schemaBase/querySchema',
      payload: {
        columnType: BaseMenuEnum.PROJECT
      }
    })
  }, [])

  const [state, setState] = useState({
    params: {
      search: null
    },
    visible: false,
    visibles: false,
    readOnly: true,
    currentModalType: ModalType.ADD,
    defaultFormData: null
  })
  const { run: tryDelProject } = useRequest(delProject, {
    manual: true,
    onSuccess: () => tRef.current?.reload()
  })
  const columns: ProColumnType<API.ProjectListItem>[] = [
    {
      dataIndex: 'ID',
      hideInTable: true
    },
    {
      dataIndex: 'name',
      title: '项目名称',
      render: (name, record) => (
        <div
          className="text-primary cursor-pointer hover:text-hex-967bbd"
          onClick={() => {
            setState({
              ...state,
              visible: true,
              readOnly: true,
              defaultFormData: {
                ID: record.ID,
                name: record.name,
                projectTypeID: record.projectType.ID
              }
            })
          }}>
          {name}
        </div>
      )
    },
    {
      dataIndex: 'createdTime',
      title: '创建时间',
      renderText: text => dayjs(text * 1000).format('YYYY-MM-DD')
    },
    {
      dataIndex: 'projectTypeID',
      title: '项目类型',
      filters: true,
      filterMultiple: false,
      render: (_, record) => <div>{record.projectType.name}</div>,
      valueEnum: pTypeList.reduce((prev, curr) => {
        const items = { ...prev }
        items[curr.value] = {
          text: curr.label
        }
        return items
      }, {})
    },
    {
      dataIndex: 'created',
      key: 'created',
      title: '创建人'
    },
    {
      dataIndex: 'reportAccount',
      key: 'reportAccount',
      title: '数据上报',
      renderText: (_, record) => record.reportAccount?.name
    },
    {
      dataIndex: 'approval',
      key: 'approval',
      title: '审批流程',
      renderText: (_, record) => record.approval?.name
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => (
        <div className="divide-x divide-bg-gray-400 flex flex-row">
          <div
            className="pr-2 text-primary cursor-pointer hover:text-hex-967bbd"
            onClick={() => {
              setState({
                ...state,
                visibles: true,
                currentModalType: ModalType.UPDATE,
                defaultFormData: {
                  ID: record.ID,
                  name: record.name,
                  projectTypeID: record.projectType.ID
                }
              })
            }}>
            编辑
          </div>
          <Popconfirm
            title="确认删除吗？"
            okText="确认"
            cancelText="取消"
            onConfirm={() => tryDelProject({ ID: record.ID })}>
            <div className="pl-2 text-hex-fd3995 cursor-pointer hover:text-hex-e7026e">
              <DeleteOutlined />
            </div>
          </Popconfirm>
        </div>
      )
    }
  ]
  return (
    <PageContainer title={false}>
      <ProTable<API.ProjectListItem>
        rowKey="ID"
        params={state.params}
        actionRef={tRef}
        columns={generateColumns(columns, schema)}
        request={async (params, filter, sorter) => {
          const { code = -1, data: { items = [], totle = 0 } = {} } = await getProjectList({
            ...params,
            ...filter,
            ...sorter
          })
          return {
            data: items,
            success: code === consts.RET_CODE.SUCCESS,
            totle
          }
        }}
        toolbar={{
          search: {
            onSearch: val => setState({ ...state, params: { ...state.params, search: val } })
          },
          actions: [
            // <Button onClick={() => history.push('/project/management/add')}>新建项目</Button>
            <Button
              type="primary"
              onClick={() =>
                setState({ ...state, visibles: true, currentModalType: ModalType.ADD })
              }>
              新建项目
            </Button>
          ]
        }}
        search={false}
      />

      <ProjectModal
        type={state.currentModalType}
        defaultFormData={state.defaultFormData}
        pTypeList={pTypeList}
        visibles={state.visibles}
        reloadTable={() => tRef.current?.reload()}
        setVisible={(visibles: boolean) => setState({ ...state, visibles })}
      />

      <AnimateContent
        visible={state.visible}
        onVisibleChange={visible => setState({ ...state, visible })}>
        <Detail
          visible={state.visible}
          onVisibleChange={visible => setState({ ...state, visible })}
          defaultFormData={state.defaultFormData}
          pTypeList={pTypeList}
          readOnly={state.readOnly}
          reloadTable={() => tRef.current?.reload()}
        />
      </AnimateContent>

      {/* <DetailModal
        defaultFormData={state.defaultFormData}
        pTypeList={pTypeList}
        visibles={state.visibles}
        readOnly={state.readOnly}
        reloadTable={() => tRef.current?.reload()}
        setVisible={(visibles: boolean) => setState({ ...state, visibles })}
      /> */}
    </PageContainer>
  )
}

export default connect(
  ({ project, schemaBase }: { project: ProjectModelState; schemaBase: SchemaBaseModelState }) => ({
    pTypeList: project.projectTypeList.map(item => ({ label: item.name, value: item.ID })),
    schema: schemaBase.base[BaseMenuEnum.PROJECT]?.schema
  })
)(List)
