/* 组织管理
 * @Author: Li Hanlin
 * @Date: 2022-11-24 11:16:02
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2022-12-05 16:20:22
 */
import * as React from 'react';
import { useState, useMemo, useRef } from 'react';
import DrawerPro from '@/components/DrawerPro';
import AutoTable from '@/components/AutoTable';
import PremButton from '@/components/PremButton';
import getcolumns from './columns';
import { doFetch } from '@/utils/doFetch';
import { message } from 'antd';

function Type(props) {
  const actionRef = useRef(),
    formRef = useRef();
  const [drawer, setDrawer] = useState({
    visible: false,
  });

  const urlParams = {
    save: '/auth/sysDepartment/save',
    remove: '/auth/sysDepartment/deleteById',
    list: '/auth/sysDepartment/query/tree',
    detail: '/asset/equipmentType/queryById',
  };

  const detail = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          type: 'link',
          onClick: () => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              item: row,
              title: '详情',
              val: 'detail',
              title: row.userName + '的详细信息',
            }));
          },
        }}
      >
        详情
      </PremButton>
    );
  };

  const edit = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              // detailpath: urlParams.detail,
              // params: { id: row.key },
              item: {
                ...row,
                departmentName: row.title,
              },
              title: '编辑',
              val: 'edit',
              onFinish: async (vals) => {
                //console.log(vals);
                let params = {
                  ...vals,
                  id: row.key,
                  parentId: row.parentKey,
                  departmentType: row.departmentType,
                };
                //console.log(params);
                delete params.title;
                let res = await doFetch({
                  url: urlParams.save,
                  params,
                });
                if (res.code === '0000') {
                  message.success('编辑成功！');
                  setDrawer((s) => ({
                    ...s,
                    visible: false,
                  }));
                  actionRef.current.reload();
                }
              },
            }));
          },
        }}
      >
        编辑
      </PremButton>
    );
  };

  const addChild = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              detailpath: null,

              item: {
                parentKey: row.title,
                departmentTypeName: '部门类型',
              },
              title: '新增组织',
              val: 'addChild',
              onFinish: async (vals) => {
                let params = {
                  ...vals,
                  parentId: row.key,
                  equipmentTypeName: vals.title,
                  departmentType: '1',
                };
                delete params.title;
                delete params.parentKey;
                let res = await doFetch({
                  url: urlParams.save,
                  params,
                });
                if (res.code === '0000') {
                  message.success('新增组织成功！');
                  setDrawer((s) => ({
                    ...s,
                    visible: false,
                  }));
                  actionRef.current.reload();
                }
              },
            }));
          },
        }}
      >
        新增组织
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否删除该设备类型?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: async () => {
            let res = await doFetch({ url: urlParams.remove, params: { id: row.key } });
            if (res.code === '0000') {
              message.success('删除成功！');
              setDrawer((s) => ({
                ...s,
                visible: false,
              }));
              actionRef.current.reload();
            }
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        删除
      </PremButton>
    );
  };

  const columns = useMemo(() => {
    let defcolumn = getcolumns(setDrawer);
    if (drawer?.val == 'add' || drawer?.val == 'edit') {
      defcolumn[3].hideInForm = true;
    } else {
      defcolumn[3].hideInForm = false;
    }
    return defcolumn.concat({
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (text, row, _, action) => [
        addChild(text, row, _, action),
        edit(text, row, _, action),
        remove(text, row, _, action),
      ],
    });
  }, [drawer.val]);

  return (
    <div style={{ position: 'relative' }}>
      <AutoTable
        pagetitle={<h3 className="page-title">组织管理</h3>}
        columns={columns}
        path={urlParams.list}
        actionRef={actionRef}
        rowKey={'key'}
        pageextra={'add'}
        resizeable={false}
        addconfig={{
          // access: 'sysDepartment_save',
          btn: {
            disabled: false,
            type: 'primary',
            onClick: () => {
              setDrawer((s) => ({
                ...s,
                visible: true,
                item: {
                  departmentTypeName: '公司类型',
                },
                title: '新增',
                detailpath: null,
                val: 'add',
                onFinish: async (vals) => {
                  let params = {
                    ...vals,
                    departmentType: 0,
                  };
                  let res = await doFetch({
                    url: urlParams.save,
                    params,
                  });
                  if (res.code === '0000') {
                    message.success('新增成功！');
                    setDrawer((s) => ({
                      ...s,
                      visible: false,
                    }));
                    actionRef.current.reload();
                  }
                },
              }));
            },
          },
        }}
        pagination={false}
      />

      <DrawerPro
        fields={columns}
        defaultFormValue={drawer?.item ?? {}}
        formRef={formRef}
        placement="right"
        onClose={() => {
          setDrawer((s) => ({
            ...s,
            visible: false,
          }));
        }}
        {...drawer}
      />
    </div>
  );
}

export default Type;
