import React, {Fragment, useRef, useState, useEffect} from "react";
import { useIntl, FormattedMessage, useAccess, history } from '@umijs/max';
import {delCmsJobIds, getCmsJobList} from "@/services/Management/list";
import { Dropdown, FormInstance, Space, Button, message, Modal } from 'antd';
import { ActionType, FooterToolbar, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { PlusOutlined, DeleteOutlined, FormOutlined, DownOutlined, EditOutlined } from '@ant-design/icons';
import EditManageRow from './edit'
import {getDictValueEnum} from "@/services/system/dict";
import DictTag from "@/components/DictTag";

const handleRemoveOne = async (jobId: string) => {
  const hide = message.loading('正在删除');
  if (!jobId) return true;
  try {
    const resp = await delCmsJobIds(jobId);
    hide();
    if (resp.code === 200) {
      message.success('删除成功，即将刷新');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

function ManagementList() {
  const access = useAccess();

  const formTableRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();

  const [educationEnum, setEducationEnum] = useState<any>([])
  const [experienceEnum, setExperienceEnum] = useState<any>([])
  const [hotEnum, setHotEnum] = useState<any>([])
  const [currentRow, setCurrentRow] = useState<API.ManagementList.Manage>()
  const [modalVisible, setModalVisible] = useState<boolean>(false)

  useEffect(() => {
    getDictValueEnum('education',true).then((data) => {
      setEducationEnum(data)
    })
    getDictValueEnum('experience',true).then((data) => {
      setExperienceEnum(data)
    })
    // getDictValueEnum('job_hot',true).then((data) => {
    //   setHotEnum(data)
    // })
  }, [])

  const columns: ProColumns<API.ManagementList.Manage>[] = [
    {
      title: '岗位名称',
      dataIndex: 'jobTitle',
      valueType: 'text',
      align: 'center',
    },{
      title: '最大最小薪资',
      dataIndex: 'maxSalary',
      valueType: 'text',
      hideInSearch: true,
      align: 'center',
      render: (_, record) => <>{record.minSalary}-{record.maxSalary}</>
    },
    {
      title: '单位名称',
      dataIndex: 'companyName',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '学历要求',
      dataIndex: 'education',
      valueType: 'select',
      align: 'center',
      valueEnum: educationEnum,
      render: (_, record) => {
        return (<DictTag enums={educationEnum} value={record.education} />);
      },
    },
    {
      title: '经验要求',
      dataIndex: 'experience',
      hideInSearch: true,
      valueType: 'select',
      align: 'center',
      valueEnum: experienceEnum,
      render: (_, record) => {
        return (<DictTag enums={experienceEnum} value={record.experience} />);
      },
    },
    // {
    //   title: '是否热门',
    //   dataIndex: 'isHot',
    //   valueType: 'select',
    //   align: 'center',
    //   valueEnum: hotEnum,
    //   render: (_, record) => {
    //     return (<DictTag enums={hotEnum} value={record.isHot} />);
    //   },
    // },
    {
      title: '发布时间',
      dataIndex: 'postingDate',
      valueType: 'text',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '招聘人数',
      dataIndex: 'vacancies',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '浏览量',
      dataIndex: 'view',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '操作',
      hideInSearch: true,
      align: 'center',
      dataIndex: 'jobId',
      width: 300,
      render: (jobId, record) => [
        <Button
          type="link"
          size="small"
          key="edit"
          icon={<FormOutlined/>}
          hidden={!access.hasPerms('area:business:List.update')}
          onClick={() => {
            setModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </Button>,
        <Button
          type="link"
          size="small"
          danger
          key="batchRemove"
          icon ={<DeleteOutlined/>}
          hidden={!access.hasPerms('area:subway:List')}
          onClick={async () => {
            Modal.confirm({
              title: '删除',
              content: '确定删除该项吗？',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                const success = await handleRemoveOne(jobId as string);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              },
            });
          }}
        >
          删除
        </Button>
      ]
    }
  ]
  return (
    <Fragment>
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.ManagementList.Manage>
          // params 是需要自带的参数
          // 这个参数优先级更高，会覆盖查询表单的参数
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="jobId"
          key="index"
          columns={columns}
          request={(params) =>
            getCmsJobList({ ...params } as API.ManagementList.ListParams).then((res) => {
              console.log(params)
              const result = {
                data: res.rows,
                total: res.total,
                success: true,
              };
              return result;
            })
          }
          toolBarRender={() => [
            <Button
              type="primary"
              key="add"
              hidden={!access.hasPerms('manage:List:add')}
              onClick={async () => {
                setCurrentRow(undefined);
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
          ]}
        />
      </div>
      <EditManageRow
        open={modalVisible}
        onSubmit={(values) => {
          console.log(values)
          return Promise.resolve()
        }}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
      ></EditManageRow>
    </Fragment>
  )
}
export default ManagementList
