import CompanyTable from '@/components/CompanyTable';
import PageHeader from '@/components/PageHeader';
import CueBubble from '@/components/Popconfirm';
import {
  ADD_DICTIONARY,
  DELETE_DICTIONARY,
  DICTIONARY_DETAIL,
  DICTIONARY_LIST,
  OPEN_DICTIONARY,
  SORT_DICTIONARY,
  UPDATE_DICTIONARY,
} from '@/services/Urls';
import { updateData } from '@/services/common/components';
import PremissBtn from '@/utils/btnPermissions';
import { objectToFormData } from '@/utils/formDataHandel';
import { deleteListData } from '@/utils/tableFC';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-components';
import { useIntl, useMutation } from '@umijs/max';
import type { MenuProps } from 'antd';
import { Button, Dropdown, Modal, Popconfirm,Input } from 'antd';
import { useState } from 'react';
// import DictionaryConfiguration from './components/DictionaryConfiguration';
import Descriptions from './components/Details';
import SettingForm from './components/Setting';
import { smallPopup } from '@/utils/constant';
import MenuStatus from '@/components/StatusCollection';
import { getRequest, postRequest } from '@/services/common/role';
import './index.less';
type TableListItem = {
  [key: string]: any;
};
const Dictionaries = () => {
  const intl = useIntl();
  const [reloadNum, setReloadNum] = useState<number>(0);
  const [massIds, setMassIds] = useState<(string | number)[]>([]);
  const [visible, setVisible] = useState<boolean>(false);
  const [visibleConfig, setVisibleConfig] = useState<boolean>(false);
  const [submitHandle, setSubmitHandle] = useState<number>(0);
  const [editData, setEditData] = useState<TableListItem>({});
  const [isEdit, setEdit] = useState<boolean>(false);
  const [dictId, setDictId] = useState<number | string>(0);
  const [parentId, setParentId] = useState<number | string>(0);
  const [disableEnable, setdisableEnable] = useState<any>();
  const [sortType, setSortType] = useState<any>();
  const [listItem, setListItem] = useState<TableListItem>();
  const [reloadChildren, setReloadChildren] = useState<number>(0);
  const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
  const [isDelClick, setIsDelClick] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState<any>({});

  //菜单位置排序
  const sortMeuns = (data: any) => {
    postRequest(SORT_DICTIONARY, data).then(() => {
      const query = {
        id: data.dictId,
        type: data.type,
      };
      setSortType(query);
    });
  };

     
  // 搜索框值改变
  const onSearchKeyChange = (e: any) => {
    const searchObj = e.target.value !== '' ? { queryParams: e.target.value } : {};
    setSearchParams(searchObj);
  };

   // 重置输入框
   const onResetSearch = () => {
    setSearchParams({});
  };

  //其他操作
  const DropdownItems = (record: any, index: any) => {
    const items: MenuProps['items'] = [
      {
        label: (
          <div
            onClick={() => {
              if (index !== 0) {
                sortMeuns({
                  dictId: record.dictId,
                  type: 'top',
                });
              }
            }}
          >
            {intl.formatMessage({ id: 'columns.handel.top' })}
          </div>
        ),
        key: 'top',
        disabled: index === 0,
      },
      {
        label: (
          <div
            onClick={() => {
              if (index !== 0) {
                sortMeuns({
                  dictId: record.dictId,
                  type: 'prev',
                });
              }
            }}
          >
            {intl.formatMessage({ id: 'columns.handel.pre' })}
          </div>
        ),
        key: 'advance',
        disabled: index === 0,
      },
      {
        label: (
          <div
            onClick={() => {
              if (!record.finally) {
                sortMeuns({
                  dictId: record.dictId,
                  type: 'bottom',
                });
              }
            }}
          >
            {intl.formatMessage({ id: 'columns.handel.bottom' })}
          </div>
        ),
        key: 'bottom',
        disabled: record.finally,
      },

      {
        label: (
          <div
            onClick={() => {
              if (!record.finally) {
                sortMeuns({
                  dictId: record.dictId,
                  type: 'next',
                });
              }
            }}
          >
            {intl.formatMessage({ id: 'columns.handel.next' })}
          </div>
        ),
        key: 'retreat',
        disabled: record.finally,
      },
    ];
    return items;
  };
  const columns: ProColumns<TableListItem>[] = [
    {
      title: intl.formatMessage({ id: 'dictionaries.select.label.dictName/dictNumber' }),
      dataIndex: 'queryParams',
      key: 'queryParams',
      valueType: 'text',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <Input
            style={{ width: 350 }}
            allowClear
            onChange={onSearchKeyChange}
            placeholder={intl.formatMessage({
              id: 'form.info.text.entrt',
              defaultMessage: '请输入',
            })}
          />
        );
      },
    },
    {
      title: intl.formatMessage({ id: 'dictionaries.columns.title.name' }),
      dataIndex: 'dictLabel',
      key: 'dictLabel',
      search: false,
      valueType: 'text',
      renderText: (_, { dictLabel, status }) => {
        return <div className={!status ? '' : 'color-disable'}>{dictLabel}</div>;
      },
    },
    {
      title: intl.formatMessage({ id: 'dictionaries.columns.title.number' }),
      dataIndex: 'dictValue',
      key: 'dictValue',
      search: false,
      valueType: 'text',
      renderText: (_, { dictValue, status }) => {
        return <div className={!status ? '' : 'color-disable'}>{dictValue}</div>;
      },
    },
    {
      title: intl.formatMessage({ id: 'dictionaries.columns.title.status' }),
      dataIndex: 'status',
      key: 'status',
      search: false,
      renderText: (item) => <MenuStatus code={item as boolean} />,
    },
    {
      title: intl.formatMessage({ id: 'columns.title.option' }),
      valueType: 'option',
      key: 'option',
      // width: 240,
      // ellipsis:true,
      fixed: 'right',
      render: (_, record, index) => [
        <PremissBtn
          key="editable"
          buttonKey={'dicEdit'}
          buttonRender={
            <Button
              type="link"
              disabled={record.status}
              onClick={async () => {
                const nowData = await getRequest(DICTIONARY_DETAIL, {
                  dictId: record.dictId,
                });
                setEditData({
                  ...nowData.data,
                  dictId: record.dictId,
                });
                setEdit(true);
                setVisible(true);
                setListItem({ ...nowData.data, dictId: record.dictId });
              }}
            >
              {intl.formatMessage({ id: 'columns.handel.edit' })}
            </Button>
          }
        />,
        <PremissBtn
          key={'view'}
          buttonKey={'dicView'}
          buttonRender={
            <Button
              size="small"
              type="link"
              disabled={record.status}
              onClick={() => {
                setParentId(record.parentId);
                setDictId(record.dictId);
                setVisibleConfig(true);
              }}
            >
              {intl.formatMessage({ id: 'columns.handel.view' })}
            </Button>
          }
        />,
        <PremissBtn
          key={'able'}
          buttonKey={'dicDisable/dicEnable'}
          buttonRender={
            <Popconfirm
              title={intl.formatMessage({
                id: !record.status ? 'columns.handel.disabled' : 'columns.handel.enable',
              })}
              description={`${intl.formatMessage({
                id: !record.status ? 'modal.text.disableMes' : 'modal.text.enableMes',
              })}${record.dictLabel}?`}
              onConfirm={() => {
                setTimeout(async () => {
                  const nowData = await getRequest(DICTIONARY_DETAIL, {
                    dictId: record.dictId,
                  });
                  const data = {
                    dictId: record.dictId,
                    version: nowData.data.version,
                    status: !nowData.data.status,
                  };
                  postRequest(OPEN_DICTIONARY, data).then(() => {
                    setdisableEnable({
                      id: record.dictId,
                      status: record.status,
                    });
                  });
                }, 500);
              }}
              okText={intl.formatMessage({ id: 'columns.handel.ok' })}
              cancelText={intl.formatMessage({ id: 'columns.handel.cancel' })}
              disabled={record.disableParent}
            >
              <Button size="small" type="link" disabled={record.disableParent}>
                {intl.formatMessage({
                  id: !record.status ? 'columns.handel.disabled' : 'columns.handel.enable',
                })}
              </Button>
            </Popconfirm>
          }
        />,

        <PremissBtn
          key={'add'}
          buttonKey={'dicAdd'}
          buttonRender={
            <Button
              type="link"
              disabled={record.status}
              onClick={() => {
                setListItem(record);
                setEditData({ dictId: record.dictId });
                setEdit(false);
                setVisible(true);
              }}
            >
              {intl.formatMessage({ id: 'dictionaries.handel.addChild' })}
            </Button>
          }
        />,
        <PremissBtn
          key="del"
          buttonKey={'dicDel'}
          buttonRender={
            <CueBubble
              disable={record.status}
              hidden={parseInt(record.parentId)===0}
              url={DELETE_DICTIONARY}
              idObj={{ dictId: record.dictId, version: record.version }}
              onSave={() => {
                setIsDelClick(true);
                setListItem(record);
                setReloadChildren((reloadChildren) => reloadChildren + 1);
              }}
              delTypeTitle={record.dictLabel}
            />
          }
        />,
        <PremissBtn
          key="sort"
          buttonKey={'dicSort'}
          buttonRender={
            parseInt(record.parentId)!==0 ? (
              <Dropdown
                disabled={record.status}
                menu={{
                  items: DropdownItems(record, index),
                }}
                placement="bottomRight"
                arrow
                trigger={['click']}
              >
                <a
                  onClick={(e) => e.preventDefault()}
                  style={{
                    padding: '0 7px',
                  }}
                >
                  {intl.formatMessage({ id: 'columns.handel.sort' })}
                  <DownOutlined
                    style={{
                      fontSize: 10,
                      marginLeft: 4,
                    }}
                  />
                </a>
              </Dropdown>
            ) : null
          }
        />,
        
      ],
    },
  ];

  const onClose = () => {
    setVisible(false);
    setSubmitHandle(0);
    setEditData({});
  };

  const { mutate } = useMutation(updateData, {
    onSuccess: async () => {
      onClose();
      // setReloadNum((reloadNum) => reloadNum + 1);
      setReloadChildren((reloadChildren) => reloadChildren + 1);
      // getAllParentDictMessage().then((res: any) => {
      //   localStorage.setItem(DICT_MSG, JSON.stringify(res.data));
      // });
    },
    onError: () => {},
  });
  // 添加或者编辑
  const onAddOREdit = (values: { [key: string]: any }) => {
    // 处理数据
    const formValue: TableListItem = objectToFormData(values);
    //连接后端接口，阻止重复提交，提交接口数据
    mutate({
      url: !isEdit ? ADD_DICTIONARY : UPDATE_DICTIONARY,
      values: formValue,
    });
  };

  return (
    <div>
      <PageHeader />
      {/* 字典配置 */}
      {/* <Modal
        title={intl.formatMessage({ id: 'dictionaries.title.dictionaryConfiguration' })}
        open={visibleConfig}
        width={960}
        onCancel={() => setVisibleConfig(false)}
        destroyOnClose={true}
        maskClosable={false}
        footer={null}
      >
        <DictionaryConfiguration initialValues={editData} />
      </Modal> */}
      <Modal
        title={intl.formatMessage({ id: 'dictionaries.title.dictionaryConfiguration' })}
        open={visibleConfig}
        width={smallPopup}
        onCancel={() => setVisibleConfig(false)}
        destroyOnClose={true}
        maskClosable={false}
        footer={null}
      >
        <Descriptions url={DICTIONARY_DETAIL} dictId={dictId} parentId={parentId} />
      </Modal>
      <Modal
        title={
          !isEdit
            ? intl.formatMessage({ id: 'dictionaries.columns.title.addDictionary' })
            : intl.formatMessage({ id: 'dictionaries.columns.title.editDictionary' })
        }
        open={visible}
        width={smallPopup}
        onCancel={() => {
          setListItem(undefined);
          onClose();
        }}
        onOk={() => setSubmitHandle(submitHandle + 1)}
        destroyOnClose={true}
        maskClosable={false}
      >
        <SettingForm
          onSave={onAddOREdit}
          initialValues={editData}
          handelSubmit={submitHandle}
          isEdit={isEdit}
        />
      </Modal>
      <CompanyTable
        columns={columns}
        headerTitle={intl.formatMessage({ id: 'columns.title.header' })}
        // isMass={true}
        rowKey={'dictId'}
        reload={reloadNum}
        expandedRowKeys={expandedRowKeys}
        setExpandedRowKeys={setExpandedRowKeys}
        isDelClick={isDelClick}
        setIsDelClick={setIsDelClick}
        setMassIds={setMassIds}
        disableEnable={disableEnable}
        // otherParams={{ parentId: 0 }}
        expandChildrenColumnName={'routes'}
        onExpandType={'dictionaries'}
        sortType={sortType}
        listItem={listItem}
        lastTable={true}
        setListItem={setListItem}
        searchParams={searchParams}
        onResetSearch={onResetSearch}
        toolBarRender={() => [
          <PremissBtn
            key="del"
            buttonKey={'Delete'}
            buttonRender={
              <Button
                onClick={() => {
                  deleteListData(DELETE_DICTIONARY, massIds, () =>
                    setReloadNum((reloadNum) => reloadNum + 1),
                  );
                }}
                disabled={massIds.length === 0}
              >
                {intl.formatMessage({ id: 'columns.handel.delete' })}
              </Button>
            }
          />,
          <PremissBtn
            key="add"
            buttonKey={''}
            buttonRender={
              <Button
                type="primary"
                onClick={() => {
                  setEdit(false);
                  setEditData({});
                  setVisible(true);
                }}
              >
                <PlusOutlined />
                {intl.formatMessage({ id: 'columns.handel.add' })}
              </Button>
            }
          />,
        ]}
        initAPI={DICTIONARY_LIST}
        reloadChildren={reloadChildren}
      />
    </div>
  );
};
export default Dictionaries;
