/* eslint-disable react-hooks/exhaustive-deps */
import { Button, Checkbox, DatePicker, message, Popconfirm, Space, Spin } from 'antd';
import moment from 'moment';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useIntl, useModel, useRequest } from 'umi';
import AutoEmpty from '../Empty';
import RenewalModel from '../RenewalModel';
import UserSuperior from '../UserSuperior';
import { formatUserRender } from '../utils';
import publicConst from '../utils/const';
import useAppDetail, { AppDetailContext } from '../utils/hooks';
import { detailList, requestBatchUnbind } from './api';
import CityListTable from './components/city';
import FeatureTable from './components/feature';
import OptionListTable from './components/option';
import PolicyListTable from './components/policy';
import RoleListTable from './components/role';
import {
  emptyMarginTop,
  emptyRowSelected,
  filterCity,
  filterFeature,
  filterOption,
  filterPolicy,
  filterRole,
} from './util';

export interface AppDetailViewProps {
  /**
   * @description appId
   */
  appId: number;
  /**
   * @description 是否显示操作功能
   */
  isOptShow?: boolean;
  /**
   * @description 离职用户id
   */
  userId?: number;
}

const AppDetailView = (props: AppDetailViewProps) => {
  const { appId, isOptShow = false, userId } = props;
  const { formatMessage } = useIntl();
  const [expandedAll, setExpandedAll] = useState<API.ApplyMap>({
    optionListKey: true,
    featureTreeKey: true,
  });
  const { DataSensitiveMap, DataSensitiveLevelMap } = publicConst(formatMessage);
  // 存储批量参数
  const [batchParams, setBatchParams] = useState<API.ApplyMap>();
  const [openObj, setOpenObj] = useState<any>();
  const [renewalParams, setRenewalParams] = useState<API.ApplyMap>();
  const [params, setParams] = useState<API.ApplyMap>({});
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const expandedData = useRef<API.ApplyMap>({});
  const [permission, setPermission] = useState({});
  const appDetail = useAppDetail(appId);

  const { loading, data, run } = useRequest(
    () => {
      const param = userId ? { userId, appId } : { appId };
      return detailList(param);
    },
    {
      ready: !!appId,
      refreshDeps: [appId, userId],
    },
  );

  useEffect(() => {
    expandedData.current = { featureTree: data?.featureIds, optionList: data?.optionIds };
    setExpandedAll({
      featureTree: data?.featureTree,
      optionList: data?.optionList,
      featureTreeKey: true,
      optionListKey: true,
    });
    setBatchParams(() => {
      return {};
    });
  }, [loading]);

  const renderExtraFooter = useCallback(() => {
    const timestamp = moment().startOf('day').valueOf();
    return (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <a
          onClick={() => {
            setParams({ ...params, expired: (timestamp + 86400000 * 7) / 1000 });
          }}
        >
          {formatMessage({ id: 'base.date.week' })}
        </a>
        <a
          onClick={() => {
            setParams({ ...params, expired: (timestamp + 86400000 * 30) / 1000 });
          }}
        >
          {formatMessage({ id: 'base.date.month' })}
        </a>
        <a
          onClick={() => {
            setParams({ ...params, expired: (timestamp + 86400000 * 90) / 1000 });
          }}
        >
          {formatMessage({ id: 'base.date.three.month' })}
        </a>
      </div>
    );
  }, []);

  useEffect(() => {
    if (expandedAll?.featureTreeKey) {
      setExpandedAll({ ...expandedAll, featureTree: expandedData?.current?.featureTree });
    } else {
      setExpandedAll({ ...expandedAll, featureTree: [] });
    }
  }, [expandedAll?.featureTreeKey]);
  useEffect(() => {
    if (expandedAll?.optionListKey) {
      setExpandedAll({ ...expandedAll, optionList: expandedData?.current?.optionList });
    } else {
      setExpandedAll({ ...expandedAll, optionList: [] });
    }
  }, [expandedAll?.optionListKey]);

  useEffect(() => {
    setExpandedAll({
      optionList: expandedData?.current?.optionList,
      optionListKey: true,
      featureTree: expandedData?.current?.featureTree,
      featureTreeKey: true,
    });
  }, [loading]);

  useEffect(() => {
    if (openObj?.reload) setBatchParams({});
  }, [openObj?.reload]);

  useEffect(() => {
    setPermission((value) => {
      return { ...value, featureTree: filterFeature(data, params) };
    });
  }, [params?.featureTree, params?.expired]);
  useEffect(() => {
    setPermission((value) => {
      return { ...value, optionList: filterOption(data, params) };
    });
  }, [params?.optionList, params?.expired]);
  useEffect(() => {
    setPermission((value) => {
      return { ...value, policyList: filterPolicy(data, params) };
    });
  }, [params?.policyList, params?.expired]);
  useEffect(() => {
    setPermission((value) => {
      return { ...value, roleList: filterRole(data, params) };
    });
  }, [params?.roleList, params?.expired]);
  useEffect(() => {
    setPermission((value) => {
      return { ...value, userCityList: filterCity(data, params) };
    });
  }, [params?.userCityList, params?.expired]);

  const buttonDisabled = emptyRowSelected(batchParams);

  const [checked, setChecked] = useState(true);

  return (
    <AppDetailContext.Provider value={appDetail}>
      <Spin spinning={loading}>
        {Boolean(isOptShow) && (
          <div>
            {!userId && (
              <div style={{ padding: '0 24px' }}>
                <Space>
                  <h3>{formatMessage({ id: 'component.ApplyDetail.nav.title.current.user' })}</h3>
                  <h3>
                    {formatUserRender({
                      nameZh: currentUser?.nameZh,
                      account: currentUser?.account,
                      state: currentUser?.state,
                    })}
                  </h3>
                  <h3>{formatMessage({ id: 'component.ApplyDetail.nav.title.other.user' })}</h3>
                  <h3>
                    <UserSuperior />
                  </h3>
                </Space>
              </div>
            )}

            <div
              style={{ padding: '10px 24px 0', display: 'flex', justifyContent: 'space-between' }}
            >
              <Space>
                <h3>{formatMessage({ id: 'component.user.add.user.expires' })}</h3>
                <DatePicker
                  showNow={false}
                  value={params?.expired ? moment(params.expired * 1000) : null}
                  renderExtraFooter={renderExtraFooter}
                  onChange={(date: any, dateString: string) => {
                    setParams({ ...params, expired: moment(dateString).valueOf() / 1000 });
                  }}
                />
                <Button
                  onClick={() => {
                    setParams({
                      featureTree: '',
                      optionList: '',
                      policyList: '',
                      roleList: '',
                      userCityList: '',
                      expired: null,
                    });
                    setBatchParams(() => {
                      return {};
                    });
                  }}
                >
                  {formatMessage({ id: 'base.common.reset' })}
                </Button>
                <Button type={'primary'}>{formatMessage({ id: 'base.common.query' })}</Button>
              </Space>

              <Space>
                <Popconfirm
                  disabled={buttonDisabled}
                  key={`del`}
                  title={formatMessage({ id: 'pages.unbind.confirm' })}
                  onConfirm={() => {
                    const allSettledPromise = requestBatchUnbind(
                      batchParams,
                      currentUser,
                      appId,
                      formatMessage,
                    );
                    if (allSettledPromise) {
                      allSettledPromise.then(() => {
                        run();
                      });
                    }
                  }}
                >
                  <Button disabled={buttonDisabled}>
                    {formatMessage({ id: 'public.user.batchDel' })}
                  </Button>
                </Popconfirm>
                <Button
                  disabled={buttonDisabled}
                  onClick={() => {
                    const { userCityList, ...rest } = batchParams || {};
                    const restSize = Object.values(rest).flat(Infinity).length;
                    if (restSize) {
                      setRenewalParams(rest);
                      setOpenObj({ open: true, reload: false });
                    } else if (userCityList?.length) {
                      message.warn(
                        formatMessage({ id: 'component.AppDetail.city.permissions.renewal.tips' }),
                      );
                    }
                  }}
                  type={'primary'}
                >
                  {formatMessage({ id: 'public.user.renewal' })}
                </Button>
              </Space>
            </div>
          </div>
        )}

        <AutoEmpty
          description={formatMessage({ id: 'component.AppDetail.permissions.empty.tips' })}
          style={{ marginTop: emptyMarginTop(isOptShow) }}
          noEmptyRender={
            Boolean(isOptShow)
              ? undefined
              : () => {
                  return (
                    <Checkbox
                      checked={checked}
                      onChange={(e) => setChecked(e.target.checked)}
                      style={{ marginBottom: 20 }}
                    >
                      {formatMessage({ id: 'component.AppDetail.permissions.showSelected' })}
                    </Checkbox>
                  );
                }
          }
        >
          <FeatureTable
            isOptShow={isOptShow}
            DataSensitiveMap={DataSensitiveMap}
            DataSensitiveLevelMap={DataSensitiveLevelMap}
            setOpenObj={setOpenObj}
            params={params}
            setParams={setParams}
            setExpandedAll={setExpandedAll}
            expandedAll={expandedAll}
            formatMessage={formatMessage}
            moment={moment}
            appId={appId}
            setRenewalParams={setRenewalParams}
            currentUser={currentUser}
            batchParams={batchParams}
            setBatchParams={setBatchParams}
            data={data}
            permission={permission}
            run={run}
            showSelected={checked}
          />

          <OptionListTable
            isOptShow={isOptShow}
            DataSensitiveMap={DataSensitiveMap}
            DataSensitiveLevelMap={DataSensitiveLevelMap}
            setOpenObj={setOpenObj}
            params={params}
            setParams={setParams}
            setExpandedAll={setExpandedAll}
            expandedAll={expandedAll}
            formatMessage={formatMessage}
            moment={moment}
            appId={appId}
            setRenewalParams={setRenewalParams}
            currentUser={currentUser}
            batchParams={batchParams}
            setBatchParams={setBatchParams}
            data={data}
            permission={permission}
            run={run}
            showSelected={checked}
          />

          <PolicyListTable
            isOptShow={isOptShow}
            DataSensitiveMap={DataSensitiveMap}
            DataSensitiveLevelMap={DataSensitiveLevelMap}
            setOpenObj={setOpenObj}
            params={params}
            setParams={setParams}
            formatMessage={formatMessage}
            moment={moment}
            appId={appId}
            setRenewalParams={setRenewalParams}
            currentUser={currentUser}
            batchParams={batchParams}
            setBatchParams={setBatchParams}
            data={data}
            permission={permission}
            run={run}
            showSelected={checked}
          />

          <RoleListTable
            isOptShow={isOptShow}
            DataSensitiveMap={DataSensitiveMap}
            DataSensitiveLevelMap={DataSensitiveLevelMap}
            setOpenObj={setOpenObj}
            params={params}
            setParams={setParams}
            formatMessage={formatMessage}
            moment={moment}
            appId={appId}
            setRenewalParams={setRenewalParams}
            currentUser={currentUser}
            batchParams={batchParams}
            setBatchParams={setBatchParams}
            data={data}
            permission={permission}
            run={run}
            showSelected={checked}
          />

          <CityListTable
            isOptShow={isOptShow}
            DataSensitiveMap={DataSensitiveMap}
            DataSensitiveLevelMap={DataSensitiveLevelMap}
            setOpenObj={setOpenObj}
            params={params}
            setParams={setParams}
            formatMessage={formatMessage}
            moment={moment}
            appId={appId}
            setRenewalParams={setRenewalParams}
            currentUser={currentUser}
            batchParams={batchParams}
            setBatchParams={setBatchParams}
            data={data}
            permission={permission}
            run={run}
            showSelected={checked}
          />
        </AutoEmpty>

        <RenewalModel
          params={renewalParams}
          appId={appId}
          openObj={openObj}
          setOpenObj={setOpenObj}
        />
      </Spin>
    </AppDetailContext.Provider>
  );
};

export default AppDetailView;
