import MemberItem from '../components/MemberItem'
import consts from '@/utils/consts'
import { useState } from 'react'
import { useRequest } from 'ahooks'
import { addExecutor, delExecutor, queryExecutorList, updateExecutor } from '@/services/api/business'
import { ApprovalType, BusinessType, ExecutorSetType } from '@/enums/gc'
import { QuestionCircleFilled } from '@ant-design/icons'
import { Form, message, Tooltip } from 'antd'
import ProForm, { ProFormDependency, ProFormRadio, ProFormSelect, ProFormText } from '@ant-design/pro-form'

import type { ModalAction } from '@/components/Modal'

const setTypeOptions = [
  {
    label: (
      <div>
        <span className="mr-1">预置成员</span>
        <Tooltip title="审批用户为该角色绑定成员">
          <QuestionCircleFilled style={{ color: 'orange' }} />
        </Tooltip>
      </div>
    ),
    value: ExecutorSetType.PRESET_MEMBER
  },
  {
    label: (
      <div>
        <span className="mr-1">步骤设置</span>
        <Tooltip title="审批用户为该角色动态配置">
          <QuestionCircleFilled style={{ color: 'orange' }} />
        </Tooltip>
      </div>
    ),
    value: ExecutorSetType.STEP_SETTING
  }
]

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

export default function useScripts(modal: ModalAction, business: BusinessType) {
  const [state, seState] = useState<iState>({
    items: [],
    total: 0
  })
  const { refresh, loading } = useRequest(() => queryExecutorList({ businessType: BusinessType.BUDGET }), {
    onSuccess: result => {
      seState(result.data)
    }
  })

  const addOrEdit = (mode: 'add' | 'edit', initialValues?: API.ExecutorItem) => {
    const text = mode === 'add' ? '新增执行者' : '编辑执行者'
    modal.open({
      title: text,
      okText: '确定',
      cancelText: '取消',
      type: 'form',
      initialValues: initialValues ?? {
        setType: ExecutorSetType.PRESET_MEMBER,
        approvalType: ApprovalType.TARGET
      },
      children: (
        <ProForm submitter={false} layout="horizontal" labelCol={{ span: 5 }} isKeyPressSubmit>
          <ProFormText hidden name="ID" />
          <ProFormText
            label="执行者名称"
            name="name"
            rules={[{ required: true, message: '请输入' }]}
            placeholder="请输入"
          />
          <ProFormRadio.Group
            label="配置方式"
            name="setType"
            options={setTypeOptions}
            rules={[{ required: true, message: '请选择' }]}
          />
          <ProFormDependency name={['setType']}>
            {({ name }) => {
              if (name === ExecutorSetType.PRESET_MEMBER)
                return (
                  <Form.Item label="成员" name="members" rules={[{ required: true, message: '请选择' }]}>
                    <MemberItem />
                  </Form.Item>
                )
              return <ProFormSelect name="" label="范围选择" />
            }}
          </ProFormDependency>
        </ProForm>
      ),
      onOk: async (values: API.ExecutorItem) => {
        let requestFn: Nullable<() => Promise<viod>> = null
        if (mode === 'add') {
          requestFn = addExecutor
          values.businessType = business
        } else {
          requestFn = updateExecutor
        }
        try {
          await requestFn?.(values)
          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 delExecutor({ ID })
          if (code === consts.RET_CODE.SUCCESS) {
            refresh()
            modal.close()
            message.success('删除成功')
          }
        } catch (error) {}
      }
    })
  }
  return { data: state, loading, addOrEdit, del }
}
