/* 角色管理
 * @Author: Li Hanlin
 * @Date: 2022-11-09 14:44:44
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2022-12-15 13:52:19
 */

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';
import { Drawer } from 'antd';
import PermissionTree from '@/components/PermissionTree/Permissiontree';

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

  const urlParams = {
    save: '/auth/sysRole/save',
    remove: '/auth/sysRole/deleteById',
    list: '/auth/sysRole/queryList',
    detail: '/auth/sysFactory/getById',
    person: '/auth/sysUser/queryPageByRoleId',
  };

  const detailPerson = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          // type: 'link',
          onClick: () => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              item: row,
              title: '详情',
              val: 'only',
              type: 'person',
              title: row.roleName + ' - 人员列表',
            }));
          },
        }}
      >
        查看人员
      </PremButton>
    );
  };

  const edit = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              item: row,
              title: '编辑',
              val: 'edit',
              onFinish: async (vals) => {
                let params = {
                  ...vals,
                  id: row.id,
                };
                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.id } });
            if (res.code === '0000') {
              message.success('删除成功！');
              setDrawer((s) => ({
                ...s,
                visible: false,
              }));
              actionRef.current.reload();
            }
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        删除
      </PremButton>
    );
  };

  // 权限配置
  const authority = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            // const { data } =  doFetch({
            //   url: '/sysRolePermission/queryAll',
            //   params: { roleId: row.id },
            // });
            // //console.log(data);
            //console.log(row);
            setDrawer((s) => ({
              ...s,
              authorityOpen: true,
              item: row,
              onFinish: async (vals) => {
                //console.log(vals);
                let res = await doFetch({
                  url: '/auth/sysRolePermission/queryAll',
                  params: { ...vals },
                });
                //console.log(res);
                if (res.code === '0000') {
                  message.success('修改成功！');
                  setDrawer((s) => ({
                    ...s,
                    visible: false,
                  }));
                  actionRef.current.reload();
                }
              },
            }));
          },
        }}
      >
        权限配置
      </PremButton>
    );
  };

  const PersonTable = () => {
    return (
      <>
        <AutoTable
          pagetitle={false}
          columns={[
            {
              title: '用户名',
              dataIndex: 'username',
              key: 'username',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
            },
            {
              title: '姓名',
              dataIndex: 'fullName',
              key: 'fullName',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
            },
            {
              title: '公司名称',
              dataIndex: 'organizationName',
              key: 'organizationId',
              valueType: 'select',
              options: { path: '/auth/sysDepartment/query/organization/selectbox', params: {} },
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
            },
            {
              title: '部门名称',
              dataIndex: 'departmentName',
              valueType: 'treeSelect',
              key: 'departmentId',
              options: {
                path: '/auth/sysDepartment/query/children/tree',
                linkParams: {
                  organizationId: 'parentId',
                },
              },
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
            },
            {
              title: '工厂名称',
              dataIndex: 'factoryNames',
              key: 'factoryNames',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
            },
            {
              title: '负责车间',
              dataIndex: 'shopNames',
              key: 'shopNames',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
            },
          ]}
          path={urlParams.person}
          params={{ roleId: drawer?.item?.id }}
          actionRef={actionRef}
          resizeable={false}
        />
      </>
    );
  };
  // 数据分权
  const distribution = (text, row, _, action) => {};

  const columns = useMemo(() => {
    let defcolumn = getcolumns(setDrawer);
    return defcolumn.concat({
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (text, row, _, action) => [
        authority(text, row, _, action),
        edit(text, row, _, action),
        remove(text, row, _, action),
        detailPerson(text, row, _, action),
      ],
    });
  }, []);

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

      <DrawerPro
        fields={columns}
        // detailpath={urlParams.detail}
        // params={{ id: drawer?.item?.id }}
        defaultFormValue={drawer?.item ?? {}}
        formRef={formRef}
        placement="right"
        onClose={() => {
          setDrawer((s) => ({
            ...s,
            visible: false,
          }));
        }}
        {...drawer}
      >
        {drawer.type == 'person' ? <PersonTable /> : null}
      </DrawerPro>

      <Drawer
        title="角色权限"
        onClose={() => {
          setDrawer((s) => ({
            ...s,
            authorityOpen: false,
          }));
        }}
        open={drawer.authorityOpen}
      >
        <PermissionTree
          id={drawer?.item?.id}
          close={() => {
            setDrawer((s) => ({
              ...s,
              authorityOpen: false,
              item: null,
            }));
            actionRef.current.reload();
          }}
          treeType="auth"
        />
      </Drawer>
    </div>
  );
}

export default Role;
