import BaseTable, { ActionType, ProColumns } from '../../components/BaseTable';
import { PlusOutlined, RollbackOutlined } from '@ant-design/icons';
import { ParamsType } from '@ant-design/pro-components';
import { useSize } from 'ahooks';
import { Button, Modal, Space, Tag, message } from 'antd';
import React, { useMemo, useRef, useState } from 'react';
import FooterDiv from '../../components/FooterDiv';
import Truly from '../../components/Truly';
import {
  OPTIONS_APPROVAL,
  OPTIONS_APPROVAL_SEARCH,
} from '../../constants/options';
import { RegionController } from '../../services';
import { isSomeTrue, isTrue } from '../../utils/auth';
import EditForm from './components/EditForm';

const User: React.FC<unknown> = () => {
  const [selectedRows, setSelectedRows] = useState<
    RegionController.RegionFields[]
  >([]);
  const actionRef = useRef<ActionType>();
  const widthRef = useRef(null);
  const size = useSize(widthRef);

  const [supRegion, setSupRegion] = useState<RegionController.RegionFields[]>(
    [],
  );
  const { onSubRegionForward, onSubRegionBack } = useMemo(() => {
    const onSubRegionForward = (record: RegionController.RegionFields) => {
      setSupRegion((pre) => {
        if (record.regionCode === pre[pre.length - 1]?.regionCode) return pre;
        return [...pre, { ...record }];
      });
      actionRef.current?.reset?.();
    };
    const onSubRegionBack = () => {
      setSupRegion((pre) => {
        return pre.slice(0, -1);
      });
      actionRef.current?.reset?.();
    };
    return {
      onSubRegionForward,
      onSubRegionBack,
    };
  }, []);

  /**
   * @name 批量启用/批量停用
   * @param selectedRows
   * @param regionStatus
   * @param optionName
   */
  const onBatch = (
    selectedRows: RegionController.RegionFields[],
    regionStatus: string,
    optionName: string,
  ) => {
    const { label } =
      OPTIONS_APPROVAL.find((item) => item.value !== regionStatus) || {};
    const flag = selectedRows.some(
      (item) => item.regionStatus === regionStatus,
    );
    if (flag) {
      return message.warning(`请勾选状态为${label}的数据`);
    }
    Modal.confirm({
      content: `是否确认执行批量${optionName}操作？`,
      maskClosable: true,
      onOk: async () => {
        const regionCodes = (selectedRows || []).map(({ regionCode }) => {
          return regionCode;
        });
        await RegionController.batchApi({ regionCodes, regionStatus });
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  const columns: ProColumns<RegionController.RegionFields>[] = [
    {
      title: '区划代码',
      dataIndex: 'regionCode',
    },
    {
      title: '区划简称',
      dataIndex: 'regionDesc',
      hideInSearch: true,
    },
    {
      title: '区划名称',
      dataIndex: 'regionName',
      // valueType: 'select',
      // fieldProps: {
      //   showSearch: true,
      //   options: orgList,
      // },
    },
    {
      title: '子地区数量',
      dataIndex: 'subcounts',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'regionStatus',
      valueType: 'select',
      hideInTable: true,
      request: async () => OPTIONS_APPROVAL_SEARCH,
    },
    {
      title: '状态',
      dataIndex: 'regionStatus',
      valueType: 'select',
      hideInSearch: true,
      render: (text, record) => {
        const { label, color } =
          OPTIONS_APPROVAL_SEARCH.find(
            (item) => record.regionStatus === item.value,
          ) || {};
        return <Tag color={color}>{label || '0'}</Tag>;
      },
    },
    {
      title: '版本',
      dataIndex: 'version',
    },
    // {
    //   title: '创建时间',
    //   dataIndex: 'createDate',
    //   align: 'center',
    //   hideInSearch: true,
    // },
    // {
    //   title: '更新时间',
    //   dataIndex: 'updateDate',
    //   align: 'center',
    //   hideInSearch: true,
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <a onClick={() => onSubRegionForward(record)}>查看子地区</a>
          <Truly truly={isTrue('masterdata:region:edit')}>
            <EditForm
              key="edit"
              type="update"
              title="编辑区划信息"
              value={record}
              supRegion={supRegion}
              trigger={
                <a type="link" style={{ padding: 4 }}>
                  编辑
                </a>
              }
              HandleonSubmit={() => {
                actionRef.current?.reload();
              }}
            />
          </Truly>
        </Space>
      ),
    },
  ];

  /**
   * @name 获取列表数据
   */
  async function getBaseData(params: ParamsType) {
    const supRegionCode = supRegion[supRegion.length - 1]?.regionCode;
    const { current: pageNum } = params;
    const PegParams = {
      ...params,
      pageNum,
      // regionCode: regionCode,
      supRegionCode: supRegionCode || '',
    };
    const res = await RegionController.getListApi(PegParams);
    const { total, data } = res || {};
    actionRef.current?.clearSelected?.();
    return {
      data,
      total,
    };
  }

  return (
    <div style={{ width: '100%' }} ref={widthRef}>
      <BaseTable<RegionController.RegionFields>
        rowKey={'regionCode'}
        actionRef={actionRef}
        search={{ span: 6 }}
        rowSelection={{
          onChange(keys, selectedRows) {
            setSelectedRows(selectedRows);
          },
        }}
        expandable={{
          onExpand: () => {},
        }}
        style={{ marginBottom: 50 }}
        tableAlertRender={false}
        toolBarRender={() => [
          <Truly truly={isTrue('masterdata:region:add')} key="add">
            <EditForm
              key="add"
              type="add"
              title="新增区划信息"
              supRegion={supRegion}
              trigger={
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  disabled={supRegion.length === 0}
                >
                  新增
                </Button>
              }
              HandleonSubmit={() => {
                actionRef.current?.reload();
              }}
            />
          </Truly>,
          <Button
            disabled={supRegion.length === 0}
            type="primary"
            key="back"
            icon={<RollbackOutlined />}
            onClick={onSubRegionBack}
          >
            返回上级地区
          </Button>,
        ]}
        columns={columns}
        pagination={{
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          hideOnSinglePage: true,
        }}
        childrenColumnName="children"
        expandRowByClick={true}
        request={(params) => getBaseData(params)}
      />
      <Truly
        truly={isSomeTrue(
          'masterdata:region:enable',
          'masterdata:region:deactivate',
        )}
      >
        <FooterDiv size={size?.width} selectedRowsNumber={selectedRows.length}>
          <Space>
            <Truly truly={isTrue('masterdata:region:enable')}>
              <Button
                type="primary"
                key="enable"
                disabled={selectedRows.length <= 0}
                onClick={() => onBatch(selectedRows, '1', '启用')}
              >
                批量启用
              </Button>
            </Truly>
            <Truly truly={isTrue('masterdata:region:deactivate')}>
              <Button
                key="deactivate"
                danger
                disabled={selectedRows.length <= 0}
                onClick={() => onBatch(selectedRows, '2', '停用')}
              >
                批量停用
              </Button>
            </Truly>
          </Space>
        </FooterDiv>
      </Truly>
    </div>
  );
};

export default User;
