import PageHeader from '@/components/PageHeader';
import CueBubble from '@/components/Popconfirm';
import CompanyTable from '@/components/CompanyTable';
import MenuStatus from '@/components/StatusCollection';
import {
  USER_CENTER_COMPANY_MANAGE_LIST,
  COMPANY_DEL,
} from '@/services/Urls';
import {
  addCompany,
  findCompany,
  editCompany,
  sortsCompany,
  companyStatus
} from '@/services/common/userCenter';
import PremissBtn from '@/utils/btnPermissions';
import { PlusOutlined, DownOutlined, } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Modal, Popconfirm, Space, MenuProps, Dropdown, Input } from 'antd';
import { useRef, useState, useEffect } from 'react';
import EditForm from './component/EditForm';
import './style.less';
import { smallPopup } from '@/utils/constant';
type TableListItem = {
  [key: string]: any;
};
const CompanyManage = () => {
  const t = useIntl();
  const companyMes: any = useRef();
  const [reloadNum, setReloadNum] = useState<number>(0);
  const [addOrEdit, setAddOrEdit] = useState<string>('add');
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [editDataInitValue, setEditDataInitValue] = useState<
    TableListItem | any
  >({});
  const [onFormSubmit, setOnFormSubmit] = useState<number>(0);
  const [listId, setListId] = useState<number | undefined>();
  const [sortType, setSortType] = useState<any>();
  const [disableEnable, setdisableEnable] = useState<any>();
  
  const [listItem, setListItem] = useState<TableListItem|any>();
  const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
  const [isDelClick, setIsDelClick] = useState<boolean>(false);
  const [reloadChildren, setReloadChildren] = useState<number>(1);
  const [searchParams, setSearchParams] = useState<any>({});
  // const [companyWorker, setCompanyWorker] = useState<any>([]);
  // const dictData = JSON.parse(
  //   localStorage.getItem('dictParentMessage') as string,
  // );
  // const companyId = JSON.parse(
  //   localStorage.getItem('currentUser') as string,
  // ).companyId;
  // const dictId = dictData?.filter(
  //   (item: any) => item.dictName === '组织类型',
  // )[0]?.id;
  // 查看詳情

  //部门详情信息获取
  const findCompanyFn = (deptId: string | number, str: string) => {
    findCompany({ deptId }).then((resp) => {
      if (resp.data){
        const data = resp.data;
        companyMes.current = { 
          version: data.version, 
          status: !data.status, 
          deptId: data.deptId,
          parentName: data.parentName
        };
        if (str === 'edit') setDrawerVisible(true);
      }
    });
  };

  // 添加组织
  const onFinish = (value: API.addCompany) => {
    // console.log(value, 'value');
    if (value.locationId) {
      const loaction = [...value.locationId];
      value.locationId = loaction[loaction.length - 1];
      value.deptLocation = value.deptLocation.join(',');
    }

    if (listId){
      value.parentId = listId;
    }

    if (
      value.parentId === '无' ||
      value.parentId === undefined ||
      value.parentId === 'None'
    ) {
      value.parentId = '0';
    }

    if (listItem){
      value.version = companyMes.current.version;
      value.deptId = companyMes.current.deptId;
    }
    if (addOrEdit !== 'edit') {
      addCompany(value).then(() => {
        setDrawerVisible(false);
        setEditDataInitValue({});
        setOnFormSubmit(0);
        if (listId) {
          setReloadChildren((reloadChildren)=>reloadChildren + 1);
        }else{
          setReloadNum(reloadNum + 1);
        }
      });
      
    } else {
      delete value.parentId;
      editCompany({...value}).then(() => {
          setDrawerVisible(false);
          setEditDataInitValue({});
          setOnFormSubmit(0);
          setReloadChildren((reloadChildren)=>reloadChildren + 1);
        },
      );
    }
  };
  //部门位置排序
  const sortMeuns = (data: any) => {
    sortsCompany(data).then(() => {
      const query = {
        id: data.deptId,
        type: data.type,
      };
      setSortType(query);
      // 回調触发更新列表
    });
  };

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

      {
        label: (
          <div
            onClick={() => {
              if (!record.finally) {
                sortMeuns({
                  deptId: record.deptId,
                  type: 'next',
                });
              }
            }}
          >
            {t.formatMessage({ id: 'columns.handel.next' })}
          </div>
        ),
        key: 'retreat',
        disabled: record.finally,
      },
    ];
    return items;
  };

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

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


  const columns: ProColumns<TableListItem>[] = [
    // {
    //   title: (
    //     <FormattedMessage
    //       id="companyMange.columns.CompanyID"
    //       defaultMessage="组织ID"
    //     />
    //   ),
    //   dataIndex: 'deptId',
    //   ellipsis: true,
    //   hideInSearch: true,
    //   width: 240
    // },
    {
      title: (
        <FormattedMessage
          id="companyMange.columns.CompanyName"
          defaultMessage="组织名称"
        />
      ),
      dataIndex: 'deptName',
      ellipsis: true,
      renderText: (_, { status, deptName}:any) => {
        return (
          <div className={!status ? '' : 'color-disable'}>
            {deptName}
          </div>
        );
      },
      renderFormItem: () => {
        return (
          <Input
            style={{ width: 350 }}
            allowClear
            onChange={onSearchKeyChange}
            placeholder={t.formatMessage({
              id: 'form.info.text.entrt',
              defaultMessage: '请输入',
            })}
          />
        );
      },
    },
    {
      title: (
        <FormattedMessage
          id="companyMange.columns.CompanyStatus"
          defaultMessage="组织状态"
        />
      ),
      dataIndex: 'status',
      hideInSearch: true,
      ellipsis: true,
      render: (_, { status }) => <MenuStatus code={status} />,
    },
    {
      title: (
        <FormattedMessage id="columns.title.option" defaultMessage="操作" />
      ),
      key: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, record, index) => [
        <div key="space" className="btn-action">
          {/* add */}
          <PremissBtn
            buttonKey={'companyAdd'}
            buttonRender={
              <Button
                key="companyAdd"
                disabled={record.status}
                type="link"
                style={{ padding: '0 7px' }}
                onClick={() => {
                  setAddOrEdit('add');
                  findCompanyFn(record.deptId, 'add');
                  setListId(record.deptId);
                  setListItem(record);
                  setDrawerVisible(true);
                }}
              >
                {t.formatMessage({
                  id: 'columns.handel.addChild',
                  defaultMessage: '新增子项',
                })}
              </Button>
            }
          />
          {/* Edit */}
          <PremissBtn
            buttonKey={'companyEdit'}
            buttonRender={
              <Button
                key="companyEdit"
                disabled={record.status}
                type="link"
                style={{ padding: '0 7px' }}
                onClick={() => {
                  setAddOrEdit('edit');
                  findCompanyFn(record.deptId, 'edit');
                  setListId(record.deptId);
                  setListItem(record);
                  // setEditDataInitValue({...record});
                }}
              >
                {t.formatMessage({
                  id: 'columns.handel.edit',
                  defaultMessage: '编辑',
                })}
              </Button>
            }
          />
          {/* view */}
          {/* <PremissBtn
            buttonKey={'companyView'}
            buttonRender={
              <Button
                // disabled={record.status === 1}
                onClick={() => {
                  viewDetails({
                    ...record,
                    area: record.deptLocation,
                    type: record.typeName,
                    status:
                      record.status === 1
                        ? t.locale === 'zh-CN'
                          ? '禁用'
                          : 'Disable'
                        : t.locale === 'zh-CN'
                        ? '启用'
                        : 'Enable',
                  });
                }}
                size="small"
                type="link"
                key="view"
              >
                {t.formatMessage({
                  id: 'columns.handel.view',
                  defaultMessage: '查看',
                })}
              </Button>
            }
          /> */}

          <PremissBtn
            buttonKey={'companyDisable'}
            buttonRender={
              <Popconfirm
                title={
                  !record.status
                    ? t.formatMessage({
                        id: 'columns.handel.disabled',
                        defaultMessage: '禁用',
                      })
                    : t.formatMessage({
                        id: 'columns.handel.enable',
                        defaultMessage: '启用',
                      })
                }
                description={
                  !record.status
                    ? t.formatMessage({
                        id: 'companyMange.columns.disableCompanyConfirm',
                        defaultMessage: '是否禁用组织',
                      }) + ` ${record.deptName}`
                    : t.formatMessage({
                        id: 'companyMange.columns.EnableCompanyConfirm',
                        defaultMessage: '是否启用组织',
                      }) + ` ${record.deptName}`
                }
                onConfirm={() => {
                  // disableCompanyFunc({
                  //   id: record.id,
                  //   status: record.status === 1 ? 1 : 0,
                  // });
                  setAddOrEdit('enable');
                  findCompanyFn(record.deptId, 'enable');
                  setTimeout(() => {
                    setListItem(record);
                  }, 750);
                }}
                onCancel={(e: any) => {
                  console.log(e);
                }}
                okText="确认"
                cancelText="取消"
                disabled={record.disableParent}
                
              >
                <Button key="disable" type="link" style={{ padding: '0 7px' }} disabled={record.disableParent}>
                  {!record.status
                    ? t.formatMessage({
                        id: 'columns.handel.disabled',
                        defaultMessage: '禁用',
                      })
                    : t.formatMessage({
                        id: 'columns.handel.enable',
                        defaultMessage: '启用',
                      })}
                </Button>
              </Popconfirm>
            }
          />

          <PremissBtn
            key="del"
            buttonKey={'companyDel'}
            buttonRender={
              <CueBubble
                disable={record.status}            
                url={COMPANY_DEL}
                idObj={{ deptId: record.deptId}}
                onSave={() => {
                  setAddOrEdit('del');
                  setIsDelClick(true);
                  setListItem(record);
                  setTimeout(() => {
                    setReloadChildren((reloadChildren)=>reloadChildren + 1);
                  }, 100);
                }}
                // delTypeTitle={'columns.title.company.del'}
                delTypeTitle={record.deptName}
              />
            }
          />

          <PremissBtn
            key="sort"
            buttonKey={'companySort'}
            buttonRender={
              <Dropdown
                disabled={record.status}
                menu={{
                  items: DropdownItems(record, index),
                }}
                key="other"
                placement="bottomRight"
                arrow
                trigger={['click']}
              >
                <Button
                  key="sort" 
                  type="link"
                  onClick={(e) => e.preventDefault()}
                  style={{ padding: '0 7px' }}
                >
                  {t.formatMessage({ id: 'columns.handel.sort' })}
                  <DownOutlined style={{ fontSize: 10, marginLeft: 4 }} />
                </Button>
              </Dropdown>
            }
          />
        </div>,
      ],
    },
  ];

  useEffect(()=>{
    if (addOrEdit === 'add' && listItem){
      setDrawerVisible(true);
    }else if (addOrEdit === 'edit' && listItem){
      setEditDataInitValue({...listItem});
    }else if (addOrEdit === 'enable' && listItem){
      const data = {
        deptId: parseInt(listItem.deptId),
        parentId: listItem.parentId,
        ...companyMes.current,
      };
      if (data.status !== undefined){
        companyStatus(data).then(() => {
          setdisableEnable({
            id: listItem.deptId,
            status: listItem.status,
          });
          setReloadChildren((reloadChildren)=>reloadChildren + 1);
        });
      }
    }
  },[listItem]);
  return (
    <>
      <PageHeader />
      <CompanyTable
        headerTitle={t.formatMessage({ id: 'columns.title.header' })}
        toolbar={{
          title: (
            <span>
              {t.formatMessage({
                id: 'columns.title.header'
              })}
            </span>
          ),
        }}
        // setReloadNum={setReloadNum}
        reload={reloadNum}
        reloadChildren={reloadChildren}
        expandChildrenColumnName={'routes'}
        isSerial={true}
        // serialWidth={170}
        columns={columns}
        isMass={false}
        // isChildExpand={true}
        rowKey={'deptId'}
        listItem={listItem}
        searchParams={searchParams}
        onResetSearch={onResetSearch}
        setListItem={setListItem}
        toolBarRender={() => [
          <div key="primary">
            <PremissBtn
              buttonKey={'companyAdd'}
              buttonRender={
                <Button
                  type="primary"
                  key="primary"
                  onClick={() => {
                    setAddOrEdit('add');
                    setDrawerVisible(true);
                    setEditDataInitValue({
                      parentId: t.locale === 'zh-CN' ? '无' : 'None',
                    });
                    setListId(undefined);
                    setListItem(undefined);
                    setListId(undefined);
                    companyMes.current = {};
                    setExpandedRowKeys([]);
                  }}
                >
                  <PlusOutlined className="margin-r-s" />
                  <FormattedMessage
                    id="columns.handel.add"
                    defaultMessage="添加"
                  />
                </Button>
              }
            />
          </div>,
        ]}
        initAPI={USER_CENTER_COMPANY_MANAGE_LIST}
        sortType={sortType}
        pageSize={999}
        disableEnable={disableEnable}
        onExpandType={'company'}
        lastTable={true}
        expandedRowKeys={expandedRowKeys}
        setExpandedRowKeys={setExpandedRowKeys}
        isDelClick={isDelClick}
        setIsDelClick={setIsDelClick}
      />
      <Modal
        title={
          addOrEdit === 'edit'
            ? t.formatMessage({
                id: 'columns.handel.edit',
                defaultMessage: '编辑',
              })
            : t.formatMessage({
                id: 'columns.handel.add',
                defaultMessage: '添加',
              })
        }
        onCancel={()=>{
          setListItem(undefined);
          setDrawerVisible(false);
          setEditDataInitValue({});
          setOnFormSubmit(0);
        }}
        width={smallPopup}
        open={drawerVisible}
        destroyOnClose={true}
        footer={
          <div className="text-right">
            <Space>
              <Button
                onClick={() => {
                  setListItem(undefined);
                  setDrawerVisible(false);
                  setEditDataInitValue({});
                  setOnFormSubmit(0);
                }}
              >
                <FormattedMessage
                  id="form.handel.cancel"
                  defaultMessage="取消"
                />
              </Button>
              <Button
                onClick={() => {
                  setOnFormSubmit(onFormSubmit + 1);
                }}
                type="primary"
                htmlType="submit"
              >
                <FormattedMessage id="form.handel.save" defaultMessage="保存" />
              </Button>
            </Space>
          </div>
        }
      >
        <EditForm
          editDataInitValue={editDataInitValue}
          onFinish={onFinish}
          onFormSubmit={onFormSubmit}
          addOrEdit={addOrEdit}
          listId={listId}
          listItem={listItem}
          parentName={companyMes?.current?.parentName || undefined}
        />
      </Modal>
    </>
  );
};

export default CompanyManage;
