import AnimateContent from '@/components/AnimateContent'
import consts from '@/utils/consts'
import { PageContainer } from '@ant-design/pro-layout'
import ProTable from '@ant-design/pro-table'
import { Button, message, Popconfirm } from 'antd'
import { useRef, useState } from 'react'
import { useRequest } from 'umi'
import { addApproval, delApproval, getApprovalList, saveApproval } from '@/services/api/project'
import type { ActionType, ProColumnType } from '@ant-design/pro-table'

import ApprovalDetail from './Detail'
import { ModalForm, ProFormText } from '@ant-design/pro-form'
import type { ProFormInstance } from '@ant-design/pro-form'
import classNames from 'classnames'

// export enum PublishType {
//   FAIL = '0',
//   SUCCESS = '1'
// }
export enum ApprovalModalType {
  ADD,
  UPDATE
}

const FlowList = () => {
  const tRef = useRef<ActionType>(null)
  const formRef = useRef<ProFormInstance>(null)
  const [state, setState] = useState({
    params: {},
    visible: false,
    modalType: 'add',
    modalVisible: false,
    current: {
      dataID: null,
      name: null,
      readPretty: false
    }
  })

  const { run: tryDel } = useRequest(delApproval, {
    manual: true,
    onSuccess: () => {
      tRef.current?.reload()
    }
  })
  const { run: tryAdd } = useRequest(addApproval, {
    manual: true,
    onSuccess: () => {
      tRef.current?.reload()
    }
  })

  // const { run: tryPublish } = useRequest(publishApproval, {
  //   manual: true,
  //   onSuccess() {
  //     message.success('')
  //     tRef.current?.reload()
  //   }
  // })
  const { run: tryUpdate } = useRequest(saveApproval, {
    manual: true,
    onSuccess: () => {
      tRef.current?.reload()
    }
  })
  const columns: ProColumnType = [
    {
      dataIndex: 'name',
      title: '模板名称',
      onHeaderCell: () => ({ style: { textAlign: 'center' } }),
      render: (_, record) => (
        <span className="text-primary ">
          {record.stickyTop ? (
            <span className="w-30px text-center rounded-lg border border-hex-0089ff bg-hex-e9f5ff px-1">
              默
            </span>
          ) : null}
          <span
            className="ml-2 hover:cursor-pointer hover:text-blue-600"
            onClick={() => {
              setState({
                ...state,
                visible: true,
                current: { dataID: record.ID, name: record.name, readPretty: true }
              })
            }}>
            {record.name}
          </span>
        </span>
      )
    },
    // {
    //   dataIndex: 'publish',
    //   title: '流程状态',
    //   onHeaderCell: () => ({ style: { textAlign: 'center' } }),
    //   valueEnum: {
    //     [PublishType.SUCCESS]: {
    //       text: '已发布',
    //       status: 'Success'
    //     },
    //     [PublishType.FAIL]: {
    //       text: '未发布',
    //       statis: 'Default'
    //     }
    //   }
    // },
    {
      dataIndex: 'opreate',
      title: '操作',
      onHeaderCell: () => ({ style: { textAlign: 'center' } }),
      align: 'center',
      render: (_, record) => (
        <div className="divide-x divide-bg-gray-400">
          <span
            className="pr-2 text-primary cursor-pointer hover:text-hex-967bbd"
            onClick={() => {
              setState({
                ...state,
                modalType: ApprovalModalType.UPDATE,
                modalVisible: true,
                current: { dataID: record.ID, name: record.name }
              })
            }}>
            编辑名称
          </span>
          <span
            className="px-2 text-primary cursor-pointer hover:text-hex-967bbd"
            onClick={() => {
              setState({
                ...state,
                visible: true,
                current: { dataID: record.ID, name: record.name }
              })
            }}>
            配置流程
          </span>
          <Popconfirm
            title="是否删除此流程模板？"
            okText="确定"
            cancelText="取消"
            onConfirm={() => tryDel({ ID: record.ID })}>
            <span className={classNames('text-red-500 pl-2 cursor-pointer hover:text-red-600', {})}>
              删除
            </span>
          </Popconfirm>
        </div>
      )
    }
  ]
  return (
    <PageContainer title={false}>
      <ProTable
        columns={columns}
        rowKey="ID"
        actionRef={tRef}
        params={state.params}
        scroll={{ y: document.body.clientHeight - 313 }}
        request={async (params, filters, sorter) => {
          const {
            code = -1,
            data: { items, total }
          } = await getApprovalList({ ...params, ...filters, ...sorter })
          return {
            success: code === consts.RET_CODE.SUCCESS,
            data: items,
            total
          }
        }}
        search={false}
        toolbar={{
          search: {
            onSearch: value => setState({ ...state, params: { ...state.params, search: value } })
          },
          actions: [
            <Button
              type="primary"
              onClick={() =>
                setState({ ...state, modalType: ApprovalModalType.ADD, modalVisible: true })
              }
              key="add_flow_btn">
              新建流程
            </Button>
          ]
        }}
      />
      <AnimateContent
        title={state.current.name}
        visible={state.visible}
        onVisibleChange={visible => setState({ ...state, visible })}>
        <ApprovalDetail
          {...state.current}
          onVisibleChange={visible => setState({ ...state, visible })}
        />
      </AnimateContent>
      <ModalForm
        visible={state.modalVisible}
        isKeyPressSubmit
        layout="horizontal"
        modalProps={{
          width: '30%'
        }}
        onVisibleChange={visible => setState({ ...state, modalVisible: visible })}
        title={`${state.modalType === ApprovalModalType.ADD ? '新建' : '编辑'}审批流程`}
        formRef={formRef}
        onFinish={async values => {
          try {
            if (state.modalType === ApprovalModalType.ADD) {
              await tryAdd(values)
            } else {
              await tryUpdate({ ...values, ID: state.current.dataID })
            }
            message.success(`${state.modalType === ApprovalModalType.ADD ? '新增' : '编辑'}成功`)
            tRef.current?.reload()
            return true
          } catch (error) {
            message.error(error)
            return false
          }
        }}>
        <ProFormText name="name" label="名称" rules={[{ required: true }]} />
      </ModalForm>
    </PageContainer>
  )
}

export default FlowList
