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 { message } from 'antd'
import { useRef, useState } from 'react'
import { useRequest } from 'umi'
import { getApprovalList, publishApproval, saveApproval } from '@/services/api/project'
import type { ActionType } 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'

export enum PublishType {
  FAIL = '0',
  SUCCESS = '1'
}

const FlowList = () => {
  const tRef = useRef<ActionType>(null)
  const formRef = useRef<ProFormInstance>(null)
  const [state, setState] = useState({
    params: {},
    visible: false,
    modalType: 'add',
    modalVisible: false,
    current: {
      ID: 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 = [
    {
      dataIndex: 'name',
      title: '项目名称',
      onHeaderCell: () => ({ style: { textAlign: 'center' } })
    },
    {
      dataIndex: 'approval',
      title: '流程名称',
      onHeaderCell: () => ({ style: { textAlign: 'center' } }),
      renderText: (_, record) => (
        <span
          className="text-primary hover:cursor-pointer hover:text-blue-600"
          onClick={() => {
            setState({
              ...state,
              visible: true,
              current: record.approval
            })
          }}>
          {record.approval?.name}
        </span>
      )
    },
    {
      dataIndex: 'publish',
      title: '流程状态',
      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: 'update', modalVisible: true })

              setTimeout(() => {
                formRef.current?.setFieldsValue({ ID: record.ID, name: record.approval?.name })
              }, 80)
            }}>
            编辑流程名称
          </span>
          <span
            className="px-2 text-primary hover:cursor-pointer hover:text-blue-600"
            onClick={() =>
              setState({
                ...state,
                visible: true,
                current: { ...record.approval, readPretty: true }
              })
            }>
            查看流程图
          </span>
          <span
            className={[
              'pl-2',
              record.publish ? 'text-gray-500' : 'text-primary cursor-pointer'
            ].join(' ')}
            onClick={() => !record.publish && tryPublish({ ID: record.approval.ID })}>
            发布
          </span>
          {/* <Popconfirm
            title={`确认删除${record.name}吗？`}
            okText="确认"
            cancelText="取消"
            onConfirm={() => tryDel({ ID: record.ID })}>
            <span className="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: '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
        modalProps={{
          width: '30%'
        }}
        onVisibleChange={visible => setState({ ...state, modalVisible: visible })}
        title={`${state.modalType === 'add' ? '新建' : '编辑'}审批流程`}
        formRef={formRef}
        onFinish={async values => {
          try {
            if (state.modalType === 'add') {
              await tryAdd(values)
            } else {
              await tryUpdate(values)
            }
            message.success(`${state.modalType === 'add' ? '新增' : '编辑'}成功`)
            tRef.current?.reload()
            return true
          } catch (error) {
            message.error(error)
            return false
          }
        }}>
        <ProFormText name="ID" label="名称" hidden />
        <ProFormText name="name" label="名称" rules={[{ required: true }]} />
      </ModalForm>
    </PageContainer>
  )
}

export default FlowList
