/*
 * @Note:
 * @Author: 2058827620@qq.com
 * @Date: 2021-12-29 16:19:02
 */
import React, { useState, useEffect } from 'react';
import {
  Divider, Image, Modal, Badge, Button, Space, Upload,
  Pagination, Popconfirm, message, Select, Popover, Tooltip, Input
} from 'antd';
import { UploadOutlined, FileUnknownOutlined, CloseOutlined } from '@ant-design/icons';
import {
  ProForm,
  ProFormText,
} from '@ant-design/pro-components';
import Iconfont from '../IconSelect/iconfont';

import FilesCategory from './FilesCategory'
import { deepCopy, copy } from '@/utils/func';

import services from '@/services/admin';

const {
  filesItems, filesItem, filesCreate,
  filesDelete, filesUpdate
} = services.FilesController;
const {
  ossUptoken
} = services.ComController;

export const FilesManager = ({ fileType, count, defaultValue, mode, imagesShow = true, ...restProps }) => {
  const [filesItemsData, setFilesItemsData] = useState([]);
  const [checkedFilesItems, setCheckedFilesItems] = useState([]);
  const [checkedFilesIds, setCheckedFilesIds] = useState([]);
  const [checkedFilesKey, setCheckedFilesKey] = useState([]);

  const [filesCategoryItems, setFilesCategoryItems] = useState([]);
  const [OSSData, setOSSData] = useState();
  const [fileList, setFileList] = useState([]);

  const [modalOpenState, setModalOpenState] = useState(false);

  const [cid, setCid] = useState(null);
  const [page, setPage] = useState(1);

  const { onChange } = restProps;

  const inputChange = (e) => {
    onChange(e.target.value);
  };

  useEffect(() => {
    ossUptoken().then(({ data }) => {
      setOSSData(data);
    });
  }, []);
  useEffect(() => {
    getFilesItems();
  }, [cid, page]);

  const getFilesItems = () => {
    filesItems({
      cid: cid,
      page: page,
      type: fileType
    }).then(({ data }) => {
      setFilesItemsData(data);
    });
  };

  const onCheckedFile = (item) => {
    const current = checkedFilesIds.indexOf(item.id);
    //不存在添加
    if (current === -1) {
      setCheckedFilesIds((prev) => prev.concat(item.id));
      setCheckedFilesItems((prev) => prev.concat(item));
      //超出数量，删除第一个
      if (checkedFilesIds.length >= count) {
        setCheckedFilesIds((prev) => prev.filter((row, idx) => idx !== 0));
        setCheckedFilesItems((prev) => prev.filter((row, idx) => idx !== 0));
      }

    } else {
      //存在删除
      setCheckedFilesIds((prev) => prev.filter(row => row !== item.id));
      setCheckedFilesItems((prev) => prev.filter(row => row.id !== item.id));

    }
  }

  const handleDelete = async () => {
    const { success } = await filesDelete({ ids: checkedFilesIds });
    if (success) {
      setCheckedFilesIds([]);
      setCheckedFilesItems([]);
      getFilesItems();
    }
  };
  const handleUpdate = async (cid) => {
    const { success } = await filesUpdate({ ids: checkedFilesIds, cid: cid });
    if (success) {
      setCheckedFilesIds([]);
      setCheckedFilesItems([]);
      getFilesItems();
    }
  };

  const handleUse = () => {
    //key用于提交接口
    const key = checkedFilesKey;
    //ids用于删除、移动分类
    checkedFilesItems.map((item) => {
      key.push(item.key);
    });

    //form 表单值
    if (count <= 1) {
      onChange(key.slice(-1)[0]);
      setCheckedFilesKey([key.slice(-1)[0]]);
    } else {
      onChange(key);
      setCheckedFilesKey(key);
    }
    setCheckedFilesIds([]);
    setCheckedFilesItems([]);
    setModalOpenState(false);
  };
  const deleteCheckedFilesKey = (key) => {

    if (typeof checkedFilesKey === 'string') {
      setCheckedFilesKey('');
    } else {
      setCheckedFilesKey(checkedFilesKey.splice(key, 1));
    }
    setCheckedFilesKey(checkedFilesKey.splice(key, 1));

    //form 表单值
    if (checkedFilesKey.length >= 1) {
      onChange(checkedFilesKey);
    } else {
      onChange('');
    }

  };

  useEffect(() => {

    if (defaultValue && defaultValue.length) {
      if (typeof defaultValue === 'string') {
        setCheckedFilesKey([defaultValue]);
      } else {
        setCheckedFilesKey(defaultValue);
      }
    } else {
      setCheckedFilesKey([]);
    }
  }, [defaultValue]);

  const uploadProps = {
    name: 'file',
    action: OSSData?.host,
    //maxCount: 1,
    multiple: true,
    fileList: fileList,
    data: (file) => {
      const data = {
        key: OSSData?.dir + file.name,
        OSSAccessKeyId: OSSData?.accessid,
        policy: OSSData?.policy,
        'success_action_status': '200',
        Signature: OSSData?.signature,
      };
      return data;
    },

    progress: {
      strokeColor: {
        '0%': '#108ee9',
        '100%': '#87d068',
      },
      size: 3,
      format: (percent) => `${parseFloat(percent.toFixed(2))}%`,
    },
    beforeUpload: (file) => {

    }
  };
  const onChangeUpload = (info) => {
    console.log(info, '666')

    setFileList(info.fileList);
    if (info.file.status !== 'uploading') {
    }
    if (info.file.status === 'done') {
      console.log(info)
      filesCreate({
        key: OSSData?.dir + info.file.name,
        cid: cid,
      }).then(() => {
        setFileList(null);
        getFilesItems();
      });
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    }
  };



  return (
    <>
      <ProForm.Item {...restProps}>
        <ProFormText
          hidden={true}
          onChange={inputChange}
          placeholder={restProps.placeholder}
          {...restProps.fieldProps}
        />
        {
          mode === 'text' ? <Button size="small" type="link" onClick={() => {
            setModalOpenState(true);
          }}>文件管理</Button> :
            <Space>
              {checkedFilesKey.map((item) => {
                return (
                  imagesShow && <a key={item} className='w-20'>
                    {
                      fileType === 'image' ? <Image width="100px" height="100px" src={item} /> : ''
                    }
                    <Popover content={
                      <div style={{ width: 500 }}>
                        <video src={item} controls width={500} />
                        <Input defaultValue={item} />
                      </div>
                    }
                      title="">
                      {
                        fileType === 'video' ? <Iconfont type='icon-video' className='text-7xl' /> : ''
                      }
                    </Popover>


                    <Badge
                      offset={[-4, -60]}
                      onClick={() => {
                        deleteCheckedFilesKey(item);
                      }}
                      count={<CloseOutlined />}
                    >
                    </Badge>
                  </a>
                );
              })}

              <Button
                onClick={() => {
                  setModalOpenState(true);
                }}
                type="primary"
                icon={<UploadOutlined />}
              />

            </Space>
        }
      </ProForm.Item>
      <Modal
        title="文件管理"
        open={modalOpenState}
        onCancel={() => {
          setModalOpenState(false);
        }}
        onOk={() => {
          setModalOpenState(false);
        }}
        footer={null}
        width={'70%'}
        styles={{ body: { padding: 0 } }}
      >
        <div
          className={`flex`}
        >
          <FilesCategory cid={cid} setCid={setCid} setFilesCategoryItems={setFilesCategoryItems} />
          <div
            className={`w-2`}
          >
            <Divider></Divider>
          </div>
          <div>
            <div>
              <Space>
                <Button
                  type="primary"
                  disabled={!checkedFilesIds.length || mode === 'text'}
                  onClick={handleUse}
                >使用</Button>
                <Upload
                  onChange={onChangeUpload} {...uploadProps}
                >
                  <Button
                    type="primary"
                  >上传文件</Button>
                </Upload>

                <Popconfirm
                  title="确认删除？"
                  disabled={!checkedFilesIds.length}
                  onConfirm={() => { handleDelete() }}
                >
                  <Button
                    disabled={!checkedFilesIds.length}
                    danger
                  >删除</Button>
                </Popconfirm>

                <Select
                  className={`w-52`}
                  placeholder="移动"
                  disabled={!checkedFilesIds.length}
                  onChange={(e) => {
                    handleUpdate(e);
                  }}
                  fieldNames={{
                    label: "name",
                    value: "id",
                  }}
                  options={filesCategoryItems}
                />

              </Space>
            </div>
            <div className={`h-2`}></div>
            <div
              className={`max-w-[712px]`}
            >
              <Space wrap>

                {
                  filesItemsData?.data?.map(item =>

                    <Badge
                      key={item.id}
                      count={checkedFilesIds.indexOf(item.id) + 1}
                      offset={[-16, 16]}
                    >
                      <Image
                        width={112}
                        height={100}
                        preview={false}
                        src={item.key}
                        onClick={() => {
                          onCheckedFile(item)
                        }}
                      />
                      <div className={`flex justify-between	 h-6 leading-6`}>
                        <Tooltip title={item.name}>
                          <div className={`w-20 truncate`}>{item.name}</div>
                        </Tooltip>
                        <a
                          onClick={() => copy(item.key)}
                        >复制</a>
                      </div>
                    </Badge>
                  )
                }
              </Space>
            </div>
            <div className={`h-2`}></div>
            <div>
              <Pagination
                onChange={
                  (page, pageSize) => {
                    setPage(page);
                  }
                }
                showQuickJumper
                showTotal={total => `共 ${filesItemsData.total} 条`}
                defaultCurrent={1}
                defaultPageSize={18}
                total={filesItemsData.total}
              />
            </div>
          </div>
        </div>
      </Modal>
    </>
  );
};

export default FilesManager;
