import ProForm, { ProFormSelect, ProFormText } from '@ant-design/pro-form'
import type { ModalAction } from '@/components/Modal'
import { message, Modal } from 'antd'
import { addMatter, delMatter, queryMatterTree, updateMatter } from '@/services/api/business'
import { useState } from 'react'
import { useRequest } from '@umijs/max'
import consts from '@/utils/consts'

export enum MatterType {
  CATEGORY = 'category', // 分类
  MATTER = 'matter' // 事项
}

const MatterTitleEnum = {
  [MatterType.CATEGORY]: '分类名称',
  [MatterType.MATTER]: '事项名称'
}

interface IState {
  treeList?: API.MatterParams[]
  expandTreeIds: []
}

export function useRowScript(modal: ModalAction) {
  const [state, setState] = useState<IState>({})
  const {
    run: query,
    refresh,
    loading
  } = useRequest(queryMatterTree, {
    manual: true,
    onSuccess: (result?: API.MatterParams[]) => {
      function expandTreeList(data: API.MatterParams[]): string[] {
        let idArr: string[] = []
        data.forEach((item: API.MatterParams) => {
          if (item.children?.length) {
            idArr.push(item.ID)
            const childIDs = expandTreeList(item.children)
            idArr = [...idArr, ...childIDs]
          }
        })
        return idArr
      }
      setState({
        ...state,
        treeList: result,
        expandTreeIds: expandTreeList(result)
      })
      // setState({ ...state, treeList: result || [] })
    }
  })

  /** 新建 */
  const add = (mode: MatterType.CATEGORY | MatterType.MATTER, subjectParams) => {
    const text = mode === MatterType.CATEGORY ? '新建分类' : '新建事项'
    modal.open({
      title: text,
      okText: '确定',
      cancelText: '取消',
      type: 'form',
      children: (
        <ProForm submitter={false} layout="horizontal" labelCol={{ span: 5 }} isKeyPressSubmit>
          <ProFormText hidden name="ID" />
          {mode === MatterType.MATTER ? (
            <ProFormSelect
              name="parentID"
              label="分类名称"
              options={state.treeList
                ?.filter(item => MatterType.CATEGORY.includes(item.matterType))
                .map(data => ({ label: data.name, value: data.ID }))}
              rules={[{ required: true, message: '请选择' }]}
            />
          ) : null}
          <ProFormText
            name="name"
            label={MatterTitleEnum[mode]}
            rules={[{ required: true, message: '请输入' }]}
          />
        </ProForm>
      ),
      onOk: async (values: API.MatterItem) => {
        let requestFn: Nullable<() => Promise<viod>> = null
        requestFn = addMatter
        try {
          if (mode === MatterType.CATEGORY) {
            await requestFn?.({ ...values, ...subjectParams, matterType: MatterType.CATEGORY })
          } else {
            await requestFn?.({ ...values, ...subjectParams, matterType: MatterType.MATTER })
          }
          refresh()
          modal.close()
          message.success('新建成功')
        } catch (error) {}
      }
    })
  }

  /** 编辑 */
  const edit = (record, subjectParams) => {
    const text = record.matterType === MatterType.CATEGORY ? '编辑分类' : '编辑事项'
    modal.open({
      title: text,
      okText: '确定',
      cancelText: '取消',
      initialValues: { ...record },
      type: 'form',
      children: (
        <ProForm submitter={false} layout="horizontal" labelCol={{ span: 5 }} isKeyPressSubmit>
          <ProFormText hidden name="ID" />
          {record.matterType === MatterType.MATTER ? (
            <ProFormSelect
              name="parentID"
              label="分类名称"
              options={state.list?.map(item => ({ label: item.name, value: item.ID }))}
              rules={[{ required: true, message: '请选择' }]}
            />
          ) : null}
          <ProFormText
            name="name"
            label={MatterTitleEnum[record.matterType]}
            rules={[{ required: true, message: '请输入' }]}
          />
        </ProForm>
      ),
      onOk: async (values: API.MatterItem) => {
        let requestFn: Nullable<() => Promise<viod>> = null
        requestFn = updateMatter
        try {
          if (record.matterType === MatterType.CATEGORY) {
            await requestFn?.({ ...values, ...subjectParams, matterType: MatterType.CATEGORY })
          } else {
            await requestFn?.({ ...values, ...subjectParams, matterType: MatterType.MATTER })
          }
          refresh()
          modal.close()
          message.success('编辑成功')
        } catch (error) {}
      }
    })
  }

  /** 删除 */
  const deleteMatter = (ID: string, children: any[]) => {
    if (!children.length) {
      Modal.confirm({
        title: '删除',
        content: '确认删除该行数据？',
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          // 进行删除的接口请求
          const { code = -1 } = await delMatter({ ID })
          if (code === consts.RET_CODE.SUCCESS) {
            message.success('删除成功')
            refresh()
          }
        }
      })
    } else {
      message.warning('请先移除该分类下的所有事项')
    }
  }

  return {
    query,
    loading,
    treeList: state.treeList,
    expandTreeIds: state.expandTreeIds,
    add,
    edit,
    deleteMatter
  }
}
