import React, { Fragment, useEffect, useRef, useState } from 'react';
import { FormattedMessage, useAccess } from '@umijs/max';
import { Button, FormInstance, message } from 'antd';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { PlusOutlined } from '@ant-design/icons';
import EditCompanyListRow from './edit';
import { addCmsCompanyList, delCmsCompanyList, putCmsCompanyList } from '@/services/company/list';
import { exportCmsJobTitleList, getCmsJobTitleList } from '@/services/classify/jobs';
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 delCmsCompanyList(jobId);
    hide();
    if (resp.code === 200) {
      message.success('删除成功，即将刷新');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const handleExport = async (values: API.ClassifyJobs.Params) => {
  const hide = message.loading('正在导出');
  try {
    await exportCmsJobTitleList(values);
    hide();
    message.success('导出成功');
    return true;
  } catch (error) {
    hide();
    message.error('导出失败，请重试');
    return false;
  }
};
const buildTree = (
  data: API.ClassifyJobs.Jobs[],
  parentId: number = 0,
  depth = 0,
): API.ClassifyJobs.Jobs[] => {
  const children = data
    .filter((item) => item.parentId === parentId)
    .map((item) => {
      const child = buildTree(data, item.jobId, depth + 1);
      return {
        ...item,
        depth,
        children: child.length ? child : undefined,
      };
    });
  return children || [];
};

const ManagementList: React.FC = () => {
  const access = useAccess();

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

  const [currentRow, setCurrentRow] = useState<API.ClassifyJobs.Jobs>();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [jobsStatusEnum, setJobsStatusEnum] = useState<any>([]);

  useEffect(() => {
    getDictValueEnum('sys_jobs_status', true).then(setJobsStatusEnum);
  }, []);

  const editSubmit = () => {};

  const columns: ProColumns<API.ClassifyJobs.Jobs>[] = [
    {
      title: '岗位名称',
      dataIndex: 'jobName',

      align: 'left',
      render: (text, record) => (
        <span
          style={{
            display: 'flex',
            alignItems: 'center',
          }}
        >
          {text}
        </span>
      ),
    },
    {
      title: '父级岗位',
      dataIndex: 'parentName',
      valueType: 'text',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '显示顺序',
      dataIndex: 'orderNum',
      valueType: 'text',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      valueType: 'select',
      valueEnum: jobsStatusEnum,
      render: (_, record) => {
        return <DictTag enums={jobsStatusEnum} value={record.status} />;
      },
    },
  ];
  return (
    <Fragment>
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.ClassifyJobs.Jobs>
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="jobId"
          key="index"
          columns={columns}
          expandable={{
            childrenColumnName: 'children',
            defaultExpandAllRows: true,
            indentSize: 24,
            rowExpandable: (record) => Array.isArray(record.children) && record.children.length > 0,
          }}
          search={{
            labelWidth: 120,
          }}
          request={async (params) => {
            const res = await getCmsJobTitleList({
              ...params,
              tree: false,
              pageSize: 1000,
            });
            const treeData = buildTree(res.rows);
            return {
              data: treeData,
              total: res.total,
              success: true,
            };
          }}
          pagination={false}
          toolBarRender={() => [
            <Button
              type="primary"
              key="add"
              hidden={!access.hasPerms('manage:List:add')}
              onClick={async () => {
                setCurrentRow(undefined);
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
            <Button
              type="primary"
              key="export"
              hidden={!access.hasPerms('system:user:export')}
              onClick={async () => {
                const searchVal = formTableRef.current && formTableRef.current.getFieldsValue();
                handleExport(searchVal as API.ClassifyJobs.Params);
              }}
            >
              <PlusOutlined />
              <FormattedMessage id="pages.searchTable.export" defaultMessage="导出" />
            </Button>,
          ]}
        />
      </div>
      <EditCompanyListRow
        open={modalVisible}
        onSubmit={async (values) => {
          let resData;
          if (values.jobId) {
            resData = await putCmsCompanyList(values);
          } else {
            resData = await addCmsCompanyList(values);
          }
          if (resData.code === 200) {
            setModalVisible(false);
            setCurrentRow(undefined);
            if (values.jobId) {
              message.success('修改成功');
            } else {
              message.success('新增成功');
            }
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        values={currentRow}
      ></EditCompanyListRow>
    </Fragment>
  );
};

export default ManagementList;
