import React, { useState, useEffect } from 'react';
import {
  Input,
  Tree,
  Table,
  Button,
  Form,
  DatePicker,
  Divider,
  Modal,
  Checkbox,
  TreeSelect,
  Upload,
  Space,
  message,
  Spin,
} from 'antd';
import dayjs from 'dayjs';
import { useRequest, useModel } from '@umijs/max';
import {
  queryDirCreate,
  queryDirList,
  queryFileDelete,
  queryFileList,
  queryFileUpload,
  queryOAFile,
  queryPermitList,
  querySetPermit,
} from '../../services/file';
import { queryGetContractList } from '../../services/contract';
import { downloadFile, getToken } from '@/utils/utils';
import {
  ExclamationCircleOutlined,
  PlusCircleOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import AddFileModal from './components/model';
import PerModal from './components/PreModal';
import { queryAuditList, createAduit } from '@/services/boom';
import { stringify } from 'qs';
import FileViewerModal from '@/components/FileViewerNew';
import AddModal from './components/AddModal';
import { useMemo } from 'react';
import PageContent from '@/components/PageContent';

const tempData = [
  { name: '文件1', upload_user: '管理员', upload_time: '2023-04-08 11:00:00' },
  { name: '文件2', upload_user: '管理员', upload_time: '2023-04-10 11:00:00' },
];

const tempPer = [
  { name: '管理员', list: 1, read: 1, download: 1, delete: 1, permission: 1 },
  { name: '徐俊杰', list: 1, read: 1, download: 0, delete: 0, permission: 0 },
];

const { DirectoryTree } = Tree;
const { Search } = Input;
const { RangePicker } = DatePicker;

function FileManagement(props) {
  const [form] = Form.useForm();
  const [modal, contextHolder] = Modal.useModal();
  const { user } = useModel('userInfo');
  const { userList, run: userListRun } = useModel('userList');
  const [tableData, setTableData] = useState([]);
  const [visible, setVisible] = useState(false);
  const [node, setNode] = useState();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [fileViewerVisible, setFileViewerVisible] = useState(false);
  const [fileViewerData, setFileViewerData] = useState();
  const [editPer, setEditPer] = useState(false);
  const [preUserListData, setPreUserListData] = useState([]);

  const isSuper = useMemo(() => {
    if (user?.Permission['menu-001-audit']) return true;
    return false;
  }, [user]);

  const {
    data: treeData,
    loading: treeLoading,
    run: runFileDir,
  } = useRequest((data) => queryDirList(data), {
    formatResult: (res) => {
      const result = [];
      result[0] = res?.data.limit_list[0];
      result[1] = res?.data.list[0];
      return result;
    },
  });

  const { loading, run } = useRequest((data) => queryFileList(data), {
    manual: true,
    onSuccess: (data) => {
      let result =
        data?.list?.map((item, idx) => {
          return {
            ...item,
            dir_name: item.file_name,
            create_time: item.create_time,
            key: item.id,
          };
        }) || [];
      setTableData(result);
      setSelectedRowKeys([]);
    },
  });

  const { loading: OAloading, run: runOA } = useRequest(
    (data) => queryOAFile(data),
    {
      manual: true,
      onSuccess: (data) => {
        let result =
          data?.list.map((item, idx) => {
            let name;
            if (item?.name) {
              name = item.name;
            } else if (item?.path) {
              const list = item.path.split('/');
              name = list?.length > 0 ? list[list.length - 1] : '-';
            } else if (item?.url) {
              const list = item?.url?.split('/');
              name = list?.length > 0 ? list[list.length - 1] : '-';
            }
            return {
              ...item,
              dir_name: name,
              user_name: item.CreatorUser.CName,
              create_time: dayjs(item.c_time).format('YYYY-MM-DD'),
              key: item.id,
            };
          }) || [];
        setTableData(result);
        setSelectedRowKeys([]);
      },
    },
  );

  const { loading: contractLoading, run: runContract } = useRequest(
    (data) =>
      queryGetContractList({
        status: 3,
        name: data.file_name,
        check_start: data.start_time,
        check_end: data.end_time,
      }),
    {
      manual: true,
      onSuccess: (data) => {
        let result =
          data?.list.map((item, idx) => {
            return {
              ...item,
              dir_name: item.name,
              user_name: item.created_name,
              create_time: item.check_on,
              key: item.id,
            };
          }) || [];
        setTableData(result);
        setSelectedRowKeys([]);
      },
    },
  );

  const { loading: createLoading, run: RunCreate } = useRequest(
    (data) => queryDirCreate(data),
    {
      manual: true,
      onSuccess: () => {
        setVisible(false);
        runFileDir();
        message.success('创建成功');
      },
      onError: () => {
        message.success('创建失败');
      },
    },
  );
  //文件授权
  const { loading: perLoading, run: runPer } = useRequest(
    (data) => querySetPermit(data),
    {
      manual: true,
      onSuccess: (data) => {
        setAddOpen(false);
        const params = {
          file_type: node.dir_type,
          file_ids: selectedRowKeys[0].toString(),
          permit_type: 1,
        };
        runPreUserList(params);
        message.success('授权成功');
      },
      onError: () => {
        message.error('授权失败');
      },
    },
  );

  //上传文件
  const { run: runUploadFiles } = useRequest((data) => queryFileUpload(data), {
    manual: true,
    onSuccess: (data) => {
      updateTableFile(node);
      message.success('文件上传成功');
    },
    onError: () => {
      message.error('文件上传失败');
    },
  });

  //文件审批列表
  const { data: auditList } = useRequest(() =>
    queryAuditList({ flow_type: 1 }),
  );
  //发起申请权限的文件审批
  const { loading: createLoadin, run: runAuditCreate } = useRequest(
    createAduit,
    {
      manual: true,
      onSuccess() {
        message.success('申请审批成功');
        setPerOpen(false);
      },
    },
  );

  //当前用户文档权限列表
  const {
    data: preListData,
    loading: preListLoading,
    run: runPreList,
  } = useRequest((data) => queryPermitList(data), {
    manual: true,
  });

  //当前文件的所有用户的权限列表
  const {
    // data: preUserListData,
    loading: preUserListLoading,
    run: runPreUserList,
  } = useRequest((data) => queryPermitList(data), {
    manual: true,
    onSuccess: (data) => {
      if (!data.list) return [];
      const Ids = data.list?.map((item) => item.user_id);
      const result = [...new Set(Ids)].map((id) => {
        const userPres = data.list
          .filter((item) => item.user_id == id)
          .map((item) => item.permit);
        const user_name = userList?.find((item) => item.ID == id)?.CName;
        const downPermit =
          userPres.findIndex((pre) => pre == 1) > -1 ? true : false;
        const delPermit =
          userPres.findIndex((pre) => pre == 2) > -1 ? true : false;
        return {
          user_id: id,
          user_name,
          delPermit,
          downPermit,
          disabled: id == 7 ? true : false,
        };
      });
      setPreUserListData(result?.sort((a, b) => a.user_id - b.user_id));
    },
  });

  //删除文件
  const { loading: delFileLoading, run: runDelFile } = useRequest(
    (data) => queryFileDelete(data),
    {
      manual: true,
      onSuccess: () => {
        updateTableFile(node);
        message.success('删除成功');
      },
      onError: () => {
        message.success('删除失败');
      },
    },
  );

  const [expandedKeys, setExpandedKeys] = useState([]);
  const [searchValue, setSearchValue] = useState('');
  const [permissionOpen, setPerOpen] = useState(false);
  const [addOpen, setAddOpen] = useState(false);

  const delConfirm = (record) => {
    modal.confirm({
      title: '删除',
      icon: <ExclamationCircleOutlined />,
      content: `确定删除文件${record.dir_name}， 删除后不能恢复`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => runDelFile({ file_id: record.id }),
    });
  };

  const delPreConfirm = (record) => {
    const data = {
      user_id: record.user_id,
      file_type: node?.dir_type,
      permit: '1,2',
      file_id: selectedRowKeys[0],
      action_type: 1, // 1 删除权限
    };
    // runPer(data);
    modal.confirm({
      title: '删除',
      icon: <ExclamationCircleOutlined />,
      content: `是否取消对${record.user_name}的授权？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => runPer(data),
    });
  };

  const isShow = (id, num) => {
    //num  下载 1   删除 2
    let bool = false;
    const idx = preListData?.list?.findIndex(
      (item) => item.file_id == id && item.permit == num,
    );
    if (idx > -1) bool = true;
    return bool;
  };

  const columns = [
    { title: '文档名称', dataIndex: 'dir_name' },
    { title: '上传人员', align: 'center', dataIndex: 'user_name' },
    {
      title: '上传时间',
      align: 'center',
      dataIndex: 'create_time',
      render: (text) => dayjs(text).format('YYYY-MM-DD'),
    },
    {
      title: '操作',
      render: (record) => (
        <Space>
          {!(!record.classify_id && record.file_type == 1) && (
            <a onClick={() => handleSeeClick(record)}>查看</a> //部门文件中的文件夹不展示查看
          )}
          {isShow(record.id, 1) && (
            <a onClick={() => onDownload(record)}>下载</a>
          )}
          {isShow(record.id, 2) && node?.dir_type == 0 && (
            <a onClick={() => delConfirm(record)}>删除</a>
          )}
        </Space>
      ),
    },
  ];

  const columnsPer = [
    { title: '用户', dataIndex: 'user_name' },
    {
      title: '查看列表',
      render: () => <Checkbox checked={true} disabled />,
    },
    {
      title: '只读',
      render: () => <Checkbox checked={true} disabled />,
    },
    {
      title: '下载',
      // dataIndex: 'downPermit',
      render: (record) => (
        <Checkbox
          checked={record.downPermit}
          onChange={(e) => handlePreChange(record, e.target.checked, '1')}
          disabled={record.disabled}
        />
      ),
    },
    {
      title: '删除',
      // dataIndex: 'delPermit',
      render: (record) => (
        <Checkbox
          checked={record.delPermit}
          onChange={(e) => handlePreChange(record, e.target.checked, '2')}
          disabled={record.disabled}
        />
      ),
    },
    {
      title: '授权',
      dataIndex: 'permission',
      render: (value, _) => <Checkbox checked={value} disabled={!editPer} />,
    },
    {
      title: '操作',
      render: (record) => <a onClick={() => delPreConfirm(record)}>删除</a>,
    },
  ];
  const handlePreChange = (record, checked, permit) => {
    //checked 为true false->true 设置权限   反之删除权限
    const data = {
      user_id: record.user_id,
      file_type: node?.dir_type,
      permit,
      file_id: selectedRowKeys[0],
      action_type: checked ? 0 : 1, // 0 设置权限 1 删除权限
    };
    runPer(data);
  };

  const handlerEditClick = (record) => {
    const newData = [...preUserListData];
    const curIdx = preUserListData.findIndex(
      (item) => item.user_id == record.user_id,
    );
    newData[curIdx] = { ...newData[curIdx], disabled: false };
    setPreUserListData(newData);
  };

  useEffect(() => {
    userListRun();
  }, []);

  useEffect(() => {
    //获取列表的权限
    if (!tableData || tableData.length <= 0) return;
    const ids = tableData.map((item) => item.id);
    const data = {
      file_type: node.dir_type,
      file_ids: ids?.join(','),
      permit_type: 0,
    };
    runPreList(data);
  }, [tableData]);

  useEffect(() => {
    if (selectedRowKeys.length > 0) {
      const data = {
        file_type: node.dir_type,
        file_ids: selectedRowKeys[0].toString(),
        permit_type: 1,
      };
      runPreUserList(data);
    }
  }, [selectedRowKeys]);

  const showPerBtn = useMemo(() => {
    //申请权限按钮默认不可点击
    let bool = true;
    if (selectedRowKeys.length > 0) {
      const selectfile = tableData?.find(
        (item) => item.key == selectedRowKeys[0],
      );
      //不是文件夹并且 有还没有的权限时可店家申请权限按钮
      if (
        !(!selectfile.classify_id && selectfile.file_type == 1) &&
        !(isShow(selectedRowKeys[0], 1) && isShow(selectedRowKeys[0], 2))
      ) {
        bool = false;
      }
    }
    return bool;
  }, [selectedRowKeys]);

  // 搜索文件夹树
  const onSearchDirectory = (value, nodes = treeData) => {
    const expandedKeys = getExpandedKeys(nodes, value);
    setExpandedKeys(expandedKeys);
    setSearchValue(value);
  };

  // 根据搜索值(value)获取key列表
  const getExpandedKeys = (nodes, value) => {
    if (!value) return [];
    let result = [];
    nodes.forEach((node) => {
      // 若该节点名称包含搜索值,将key加入result
      if (node.dir_name.includes(value)) {
        result.push(node.id);
      }
      // 若该节点的子节点包含搜索值,将子节点key和该节点key加入result
      if (node.children) {
        let getChildren = getExpandedKeys(node.children, value);
        if (getChildren.length != 0)
          result = [...result, node.id, ...getChildren];
      }
    });
    return result;
  };

  const onExpand = (expandedKeys) => {
    setExpandedKeys(expandedKeys);
  };

  const filterTreeNode = (node) =>
    searchValue.length > 0 ? node.dir_name.includes(searchValue) : false;

  // 搜索文件
  const onSearch = () => {
    form
      .validateFields()
      .then((values) => {
        const start_time = values?.date
          ? dayjs(values?.date[0]).format('YYYY-MM-DD 00:00:00')
          : null;
        const end_time = values?.date
          ? dayjs(values?.date[1]).format('YYYY-MM-DD 23:59:59')
          : null;
        const req = { start_time, end_time, file_name: values.file_name };
        updateTableFile(node, req);
      })
      .catch((err) => {
        console.log(err);
        return;
      });
  };

  const findListById = (id) => {
    if (!id) return;
    const fun = (data) => {
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        if (item.id == id) {
          return item.children;
        } else if (item.children) {
          let res = fun(item.children);
          if (res) return res;
        }
      }
    };
    const list = fun(treeData);

    return list?.map((item, idx) => {
      return { ...item, key: idx };
    });
  };

  const updateTableFile = (node, req = {}) => {
    if (node.id == 1) {
      //点击受控文件直接把文件夹下的文件夹列表显示出来 或者直接展示空表格因为一些选中授权操作不能做
      // setTableData(findListById(1));
      setTableData([]);
      setSelectedRowKeys([]);
    } else if (node.id == 3) {
      //点击合同文件直接把文件夹下的文件夹列表显示出来 或者直接展示空表格因为一些选中授权操作不能做
      // setTableData(findListById(3));
      setTableData([]);
      setSelectedRowKeys([]);
    } else if (node.id == 7) {
      //合同归档走合同接口
      runContract(req);
    } else if (node.is_limit) {
      //其他受控文件走classify_id
      runOA({ ...req, classify_id: node.classify_id });
    } else {
      //部门文件
      run({ ...req, dir_id: node.id });
    }
  };

  const handleSelect = (SelectKeys, e) => {
    // console.log(e, SelectKeys);
    const node = e.node;
    setNode(node);
    updateTableFile(e.node);
  };

  const onDownload = (record) => {
    const data = {
      file_id: record.id,
      path: record.path,
      file_type: node.dir_type,
    };
    window.downloadFile(
      `/api/archive/v1/file/download?${stringify(data)}`,
      record.dir_name,
      false,
    );
  };

  const handleSeeClick = (record) => {
    if (node?.dir_type == 2) {
      // 合同归档
      if (!record.attach) return;
      const attach = JSON.parse(record.attach);
      setFileViewerData(attach);
      setFileViewerVisible(true);
    } else {
      const token = getToken();
      const params = {
        file_id: record.id,
        path: record.path,
        file_type: node.dir_type,
        'JWT-TOKEN': token,
      };
      const url = `${location.origin}/api/archive/v1/file/download?${stringify(
        params,
      )}`;
      const arr = record.dir_name.split('.');
      const type = arr[arr.length - 1];
      const data = { url, name: record.dir_name, type };
      setFileViewerData(data);
      setFileViewerVisible(true);
    }
  };

  const handleFilesChange = () => {
    const inputDom = document.getElementById('files');
    let formData = new FormData();
    formData.append('dir_id', node.id);
    formData.append('user_name', user.CName);
    if (inputDom.files?.length > 0) {
      for (let i = 0; i < inputDom.files.length; i++) {
        formData.append('files', inputDom.files[i]);
      }
      runUploadFiles(formData);
    }
  };

  return (
    <PageContent>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <div style={{ height: '100%', width: '30%' }}>
          <Search
            style={{ marginBottom: 20 }}
            onChange={(e) => onSearchDirectory(e.target.value)}
          />
          <Spin spinning={treeLoading}>
            <DirectoryTree
              expandedKeys={expandedKeys}
              onExpand={onExpand}
              treeData={treeData}
              onSelect={handleSelect}
              fieldNames={{
                key: 'id',
                title: 'dir_name',
                children: 'children',
              }}
              filterTreeNode={filterTreeNode}
              titleRender={(item) => {
                return item.dir_name == '部门文件' ? (
                  <Space>
                    <span>{item.dir_name}</span>
                    <PlusCircleOutlined
                      style={{ fontSize: '16px' }}
                      onClick={() => {
                        setNode(item);
                        setVisible(true);
                      }}
                    />
                  </Space>
                ) : (
                  <span>{item.dir_name}</span>
                );
              }}
              style={{ maxHeight: '78vh', overflowY: 'auto' }}
            />
          </Spin>
        </div>
        <div style={{ height: '100%', width: 'calc(70% - 20px)' }}>
          <Form layout="inline" form={form}>
            <Form.Item name="date">
              <RangePicker />
            </Form.Item>
            <Form.Item name="file_name">
              <Input />
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={onSearch}>
                查询
              </Button>
            </Form.Item>
            {node?.dir_type == 0 && (
              <Form.Item>
                <Button
                  type="primary"
                  onClick={() => document.getElementById('files')?.click()}
                  disabled={node ? false : true}
                >
                  上传
                </Button>
              </Form.Item>
            )}
            <Form.Item>
              <Button
                type="primary"
                onClick={() => setPerOpen(true)}
                disabled={
                  showPerBtn
                  // selectedRowKeys?.length > 0 &&
                  // // !(!record.classify_id && record.file_type == 1) &&
                  // !(
                  //   isShow(selectedRowKeys[0], 1) &&
                  //   isShow(selectedRowKeys[0], 2)
                  // )
                  //   ? false
                  //   : true
                }
              >
                申请权限
              </Button>
            </Form.Item>
            {isSuper && (
              <Form.Item>
                <Button
                  type="primary"
                  onClick={() => setAddOpen(true)}
                  disabled={selectedRowKeys?.length > 0 ? false : true}
                >
                  <PlusOutlined />
                  新增权限
                </Button>
              </Form.Item>
            )}
          </Form>
          <div style={{ marginTop: 20 }}>
            <Table
              columns={columns}
              dataSource={tableData}
              rowSelection={{
                selectedRowKeys,
                type: 'radio',
                onChange: (e, fileNode) => {
                  console.log(e);
                  setSelectedRowKeys(e);
                  // (fileNode[0])
                },
              }}
              loading={OAloading || contractLoading || loading}
              style={{ overflowY: 'auto' }}
              childrenColumnName="none"
              pagination={false}
            />
            {isSuper && selectedRowKeys?.length > 0 && (
              <>
                <div
                  style={{
                    marginTop: '30px',
                    fontWeight: 'bold',
                    fontSize: '20px',
                  }}
                >
                  《
                  {
                    tableData?.find((item) => item.key == selectedRowKeys[0])
                      ?.dir_name
                  }
                  》权限列表
                </div>
                <Table
                  loading={preUserListLoading}
                  columns={columnsPer}
                  dataSource={preUserListData}
                  style={{ overflowY: 'auto' }}
                />
              </>
            )}
          </div>
        </div>
        <Input
          id="files"
          type="file"
          style={{ display: 'none' }}
          onChange={handleFilesChange}
          multiple
        />
        {contextHolder}
      </div>
      <AddModal
        node={node}
        userList={userList}
        havePreList={[]}
        fileNode={tableData?.find((item) => item.key == selectedRowKeys[0])}
        addOpen={addOpen}
        onCancel={() => setAddOpen(false)}
        onOk={(data) => runPer(data)}
      />
      <AddFileModal
        id={node?.id}
        visible={visible}
        handleOk={(value) => {
          RunCreate({ ...value, user_name: user?.CName });
        }}
        handleCancel={() => setVisible(false)}
      />
      <PerModal
        node={node}
        fileNode={tableData?.find((item) => item.key == selectedRowKeys[0])}
        auditList={auditList}
        visible={permissionOpen}
        handleCancel={() => setPerOpen(false)}
        handleOk={(data) => {
          runAuditCreate(data);
        }}
      />
      <FileViewerModal
        data={fileViewerData}
        visible={fileViewerVisible}
        downloadFile={() => {}}
        onCancel={() => {
          setFileViewerVisible(false);
        }}
      />
    </PageContent>
  );
}

export default FileManagement;
