import consts from '@/utils/consts'
import { useState } from 'react'
import { useRequest } from 'ahooks'
import { Form, Input, message } from 'antd'
import ProForm, { ProFormRadio, ProFormSelect, ProFormText } from '@ant-design/pro-form'
import type { ModalAction } from '@/components/Modal'
import {
  addAccountBg,
  delAccountBg,
  fetchRoleBgList,
  fetchRoleBgStaffListByRoleId,
  updateAccountBg
} from '@/services/api/permission'
import { RoleType } from '@/pages/Permission/FrontRole/components/RoleLeftMenu'
import { omit } from 'lodash'

type iState = {
  items: API.AccountBgParams[]
  total: number
}

export default function useScripts(modal: ModalAction) {
  const [state, setState] = useState<iState>({
    items: [],
    total: 0
  })

  const { refresh, loading } = useRequest(() => fetchRoleBgStaffListByRoleId(), {
    onSuccess: result => {
      setState({
        ...state,
        items: result?.data.items
      })
    }
  })

  const addOrEdit = (mode: 'add' | 'edit', accountValues?: API.AccountBgParams) => {
    const text = mode === 'add' ? '添加人员' : '编辑人员'
    modal.open({
      title: text,
      okText: '确定',
      cancelText: '取消',
      type: 'form',
      initialValues: accountValues ?? { enable: true },
      children: (
        <ProForm submitter={false} layout="horizontal" labelCol={{ span: 5 }} isKeyPressSubmit>
          <ProFormText hidden name="ID" />
          <ProFormText
            name="account"
            disabled={mode === 'add' ? false : true}
            label="账号"
            rules={[{ required: true, message: '请输入' }]}
          />
          <ProFormText name="name" label="名称" rules={[{ required: true, message: '请输入' }]} />
          <Form.Item
            label="密码"
            hidden={mode === 'add' ? false : true}
            name="password"
            rules={[{ required: mode === 'add' ? true : false, message: '请输入' }]}>
            <Input.Password placeholder="请输入" />
          </Form.Item>
          <ProFormSelect
            label="角色"
            name="roleIDs"
            className="w-full"
            rules={[{ required: true, message: '请输入' }]}
            request={async () => {
              const params = await fetchRoleBgList()
              return params.data
                ?.filter(item => !RoleType.SYSTEM.includes(item.roleType))
                .map(item => ({ value: item.ID, label: item.name }))
            }}
          />
          <ProFormRadio.Group
            options={[
              { label: '启用', value: true },
              { label: '停用', value: false }
            ]}
            name="enable"
            label="状态"
            rules={[{ required: true, message: '请选择' }]}
          />
        </ProForm>
      ),
      onOk: async (values: API.AccountBgParams) => {
        let requestFn: Nullable<() => Promise<viod>> = null
        if (mode === 'add') {
          requestFn = addAccountBg
        } else {
          requestFn = updateAccountBg
        }
        try {
          if (mode === 'add') {
            await requestFn?.(values)
          } else {
            await requestFn?.(omit(values, ['account', 'password']))
          }
          refresh()
          modal.close()
          message.success(text + '成功')
        } catch (error) {}
      }
    })
  }

  const del = (ID: string) => {
    modal.open({
      title: '删除人员',
      okText: '确定',
      cancelText: '取消',
      children: <div>确认删除该行数据？</div>,
      onOk: async () => {
        try {
          const { code = -1 } = await delAccountBg({ ID })
          if (code === consts.RET_CODE.SUCCESS) {
            refresh()
            modal.close()
            message.success('删除成功')
          }
        } catch (error) {}
      }
    })
  }
  return { items: state.items, loading, addOrEdit, del }
}
