/**
 * Datart
 *
 * Copyright 2021
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { LoadingOutlined } from '@ant-design/icons';
import { Button, Card, Form, Input, message, Popconfirm, Select } from 'antd';
import { Authorized, EmptyFiller } from 'app/components';
import { DetailPageHeader } from 'app/components/DetailPageHeader';
import useI18NPrefix from 'app/hooks/useI18NPrefix';
import { useAccess, useCascadeAccess } from 'app/pages/MainPage/Access';
import {
  PermissionLevels,
  ResourceTypes,
} from 'app/pages/MainPage/pages/PermissionPage/constants';
import { fetchCheckName } from 'app/utils/fetch';
import debounce from 'debounce-promise';
import {
  CommonFormTypes,
  DEFAULT_DEBOUNCE_WAIT,
  TIME_FORMATTER,
} from 'globalConstants';
import moment from 'moment';
import React, {
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory, useRouteMatch } from 'react-router-dom';
import styled from 'styled-components/macro';
import {
  BORDER_RADIUS,
  SPACE_LG,
  SPACE_MD,
  SPACE_TIMES,
} from 'styles/StyleConstants';
import { request2 } from 'utils/request';
import {
  errorHandle,
  getInsertedNodeIndex,
  uuidv4,
} from 'utils/utils';
import {
  selectOrgId,
} from '../../../slice/selectors';
import { useDepartmentSlice } from '../slice';
import {
  selectDepartments,
  selectEditingDepartment
} from '../slice/selectors';
import {
  getDepartment
} from '../slice/thunks';

import { DepartmentFormModel,DepartmentSimple } from '../slice/types';

export function DepartmentDetailPage() {
  const [formType, setFormType] = useState(CommonFormTypes.Add);
  const [lastUpdateTime, setLastUpdateTime] = useState<string | undefined>();
  const { actions } = useDepartmentSlice();
  const dispatch = useDispatch();
  const orgId = useSelector(selectOrgId);
  const { params } = useRouteMatch<{ departmentId: string }>();
  const { departmentId } = params;
  const editingDepartment = useSelector(selectEditingDepartment);
  const [form] = Form.useForm<DepartmentFormModel>();
  const t = useI18NPrefix('department');
  const tg = useI18NPrefix('global');
  const allowManage = true;


  const resetForm = useCallback(() => {
    form.resetFields();
  }, [dispatch, form, actions]);


  useEffect(() => {
    resetForm();
      dispatch(getDepartment(departmentId));
  }, [dispatch, resetForm, departmentId]);

  useEffect(() => {
    if (editingDepartment) {
      const { code, name, level, isFolder } = editingDepartment;
      try {
        form.setFieldsValue({ name, code });
      } catch (error) {
        message.error(tg('operation.parseError'));
        throw error;
      }
    }
  }, [form, editingDepartment, tg]);

  return (
    <Authorized
      authority={allowManage}
      denied={<EmptyFiller title={t('noPermission')} />}
    >
      <Wrapper>
        <DetailPageHeader
          title={`${t('department')}`}
          actions={
              <></>
          }
        />
        <Content>
          <Card
            bordered={false}
            extra={
              <div>
                {lastUpdateTime && `${t('lastUpdateTime')}: ${lastUpdateTime}`}
              </div>
            }
          >
            <Form
              name="department_form_"
              className="detailForm"
              form={form}
              labelAlign="left"
              labelCol={{ offset: 1, span: 5 }}
              wrapperCol={{ span: 8 }}
            >
              <Form.Item
                name="code"
                label={t('form.code')}
              >
                 <Input  />
              </Form.Item>

              <Form.Item
                name="name"
                label={t('form.name')}
                rules={[
                  {
                    required: true,
                    message: `${t('form.name')}${tg('validation.required')}`,
                  },
                ]}
              >
                 <Input  />
              </Form.Item>
            </Form>
          </Card>
        </Content>
      </Wrapper>
    </Authorized>
  );
}

const Wrapper = styled.div`
  display: flex;
  flex: 1;
  flex-direction: column;
`;

const Content = styled.div`
  flex: 1;
  padding: ${SPACE_LG};
  overflow-y: auto;

  .ant-card {
    margin-top: ${SPACE_LG};
    background-color: ${p => p.theme.componentBackground};
    border-radius: ${BORDER_RADIUS};
    box-shadow: ${p => p.theme.shadowBlock};

    &:first-of-type {
      margin-top: 0;
    }
  }

  .detailForm {
    max-width: ${SPACE_TIMES(400)};
    padding-top: ${SPACE_MD};
  }
`;
