import { FC, useEffect, useState, useRef } from 'react';
import { Button, Table, Form, message, Tooltip, Checkbox, Card, Modal } from 'antd';
import { CardTabListType } from 'antd/lib/card/Card';
import { useNavigate, useLocation } from 'react-router-dom';
import FileSaver from 'file-saver';
import qs from 'query-string';
import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  AppstoreAddOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  RightOutlined,
  DownOutlined,
  ProfileOutlined,
} from '@ant-design/icons';
import AddCgyDailog from './components/addCgyDailog';
import EditableCell from './components/EditableCell';
import { CategoryManageAPI } from '~/api';
import { categoryEntity, categoryDec } from '~/api/interface/categoryManage';
import Viewer from '~/components/viewer';
import './index.scss';
import events from '~/events';

const Category: FC = () => {
  const location = useLocation();
  console.log('location', location);
  const navigate = useNavigate();
  const baseRef: any = useRef();
  // 分类目录
  const [tabList, setTabList] = useState<CardTabListType[]>([]);
  // 分类列表
  const [categoryList, setCategoryList] = useState<categoryEntity[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  // 子分类表单
  const [form] = Form.useForm();
  //  展开的行
  const [expandedRowKeys, setExpandedRowKeys] = useState<(number | string)[]>([]);
  // 编辑的行
  const [editingKey, setEditingKey]: any = useState([]);
  const isEditing = (record: categoryEntity) => {
    const index: number = editingKey.findIndex((item: any) => item == record.id);
    if (index != -1) {
      return true;
    }
    return false;
  };
  const pathArr = window.location.pathname.split('/');
  const type = pathArr.pop(); //分类所属模块id(0：通用分类 1：作业服务分类 2：设备租赁分类 3：飞手培训分类 4：产品商城分类)
  const columns = [
    {
      title: '分类名称',
      dataIndex: 'classifyName',
      key: 'classifyName',
      align: 'center',
      width: '12%',
      editable: true,
      ellipsis: true,
      render: (_text: string, record: categoryEntity) => {
        return (
          <Tooltip placement='top' title={<span>{record.classifyName}</span>}>
            <span
              style={{
                marginLeft: record.children && record.children.length != 0 ? '10px' : '24px',
              }}
            >
              {record.classifyName}
            </span>
          </Tooltip>
        );
      },
      onHeaderCell: () => {
        return {
          style: {
            textAlign: 'center',
          },
        };
      },
    },
    {
      title: '图片',
      // dataIndex: "icon",
      key: 'icon',
      width: '12%',
      align: 'center',
      render: (_text: string, record: categoryEntity) => {
        return record.icon ? (
          <img
            src={record.icon}
            style={{ width: '25px', height: '25px' }}
            onClick={() => imgClick(record.icon)}
            alt='图片'
          />
        ) : (
          ''
        );
      },
    },
    {
      title: '描述',
      key: 'description',
      dataIndex: 'description',
      width: '20%',
      align: 'center',
      editable: true,
      ellipsis: true,
      render: (_text: string, record: categoryEntity) => {
        return (
          <Tooltip placement='right' title={<span>{record.description}</span>}>
            <span>{record.description}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: '15%',
      key: 'createTime',
      align: 'center',
    },
    {
      title: '操作',
      width: '55%',
      key: 'option',
      align: 'center',
      render: (_text: string, record: categoryEntity) => {
        return (
          <div className='table-option-wrap'>
            {record.level == 1 ? (
              <>
                {btnAddChildCgy ? (
                  <Button
                    type='link'
                    onClick={() => {
                      addChildrenCgy(record);
                    }}
                    className='add-children-cgy'
                    icon={<AppstoreAddOutlined />}
                  >
                    新增子分类
                  </Button>
                ) : (
                  ''
                )}

                {/* {activeTabKey === 2 && btnShareCode ? (
                  <Button
                    type='link'
                    icon={<ShareAltOutlined />}
                    onClick={() => showShareCode(record)}
                  >
                    分享码
                  </Button>
                ) : (
                  ''
                )} */}
              </>
            ) : (
              ''
            )}
            {record.isADD ? (
              <>
                <Button type='link' onClick={() => sureAddChildrenCgy(record)}>
                  确定
                </Button>

                <Button type='link' onClick={() => cancelAddCldCgy(record)}>
                  取消
                </Button>
              </>
            ) : (
              <>
                {btnEdit ? (
                  <Button type='link' onClick={() => editCgy(record)} icon={<EditOutlined />}>
                    编辑
                  </Button>
                ) : (
                  ''
                )}
                {btnDetail ? (
                  <Button
                    type='link'
                    icon={<ProfileOutlined />}
                    onClick={() => toCategoryDetail(record)}
                  >
                    详情
                  </Button>
                ) : (
                  ''
                )}
                {btnDelete ? (
                  <Button
                    type='link'
                    onClick={() => deleteCgy(record)}
                    danger
                    icon={<DeleteOutlined />}
                  >
                    删除
                  </Button>
                ) : (
                  ''
                )}
              </>
            )}
          </div>
        );
      },
    },
  ];
  const mergedColumns = columns.map((col: any) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: categoryEntity, index: number) => ({
        record,
        index,
        inputType: 'textarea',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  // 图片放大
  const [visible, setvisible] = useState<boolean>(false);
  // 当前放大图片
  const [currentImgList, setcurrentImgList] = useState<{ src: string }[]>([]);
  // 当前图片下标
  const [activeViewerIndex] = useState<number>(0);
  // 新增弹窗
  const [isVisible, setIsVisible] = useState<boolean>(false);
  // 弹窗title
  const [title, setTitle] = useState<string>('');
  // 当前修改的行
  const [currentRecord, setCurrentRecord]: any = useState({});
  // 是否编辑
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any>([]);
  const [activeTabKey, setActiveTabKey] = useState<number>(-1);

  // 分享码弹窗显示/隐藏
  const [isShareCodeVble, setShareCodeVble] = useState<boolean>(false);
  const [shareCodeUrl] = useState<string>('');
  // 按钮权限
  const btnAdd = true; //useOption(22101);
  const btnUpperDown = true; //useOption(22102);
  // const btnDir = true; //useOption(22103);
  const btnAddChildCgy = true; //useOption(22104);
  // const btnShareCode = true; //useOption(22105);
  const btnEdit = true; //useOption(22106);
  const btnDelete = true; //useOption(22107);
  const btnDetail = true; //useOption(22108);
  const searchParams: any = new URLSearchParams(location.search);

  // 获取请求数据
  useEffect(() => {
    setTabList([]);
    setCategoryList([]);
    getDirectoryList();
    setActiveTabKey(-1);
  }, [location.pathname]); //url改变时,重新获取数据

  //目录列表取到后设置第一个目录为激活状态
  useEffect(() => {
    if (activeTabKey == -1 && tabList.length > 0) {
      const key = Number(searchParams.get('activeTabKey') || tabList[0]?.key || -1);
      setActiveTabKey(key);
      handleTabChange(String(key));
    }
  }, [tabList, searchParams, activeTabKey]);

  // tab变更后触发更新列表
  /* useEffect(() => {
    if (activeTabKey !== -1) {
      getCategoryList(activeTabKey);
    } else {
      setCategoryList([]);
    }
  }, [activeTabKey]); */

  // 获取分类目录
  const getDirectoryList = async () => {
    const res: any = await CategoryManageAPI.directoryList({
      pageNo: 1,
      pageSize: 999,
      type,
    });
    const tabList: CardTabListType[] = res.result?.list?.map((item: categoryDec) => {
      return {
        key: item.id.toString(),
        tab: item.directoryName,
      };
    });
    setTabList([...tabList]);
  };
  // 分类列表
  const getCategoryList = async (directoryId: number) => {
    setIsLoading(true);
    const res = await CategoryManageAPI.getClassificationList({
      type,
      pageSize: 999,
      pageNo: 1,
      directoryId: directoryId,
    });
    setIsLoading(false);
    setCategoryList(
      res.result.list?.map((item: categoryEntity) => {
        item.level = 1;
        return item;
      }) || [],
    );
    const arr: number[] =
      res.result.list?.map((item: any) => {
        return item.id;
      }) || [];
    setExpandedRowKeys([...arr]);
  };
  // 新增分类弹窗
  const addCayDailogShow = () => {
    setTitle('新增分类');
    setIsVisible(true);
  };
  const handleOk = () => {
    const addForm = baseRef.current.getForm();
    if (title === '新增分类') {
      addForm.validateFields().then(async (values: any) => {
        const res = await CategoryManageAPI.addClassification({
          ...values,
          pid: 0,
          directoryId: activeTabKey,
          type,
        });
        if (res.code == 200) {
          events.emit('removeFileList');
          message.success('新增成功');
          setIsVisible(false);
          getCategoryList(Number(activeTabKey));
          addForm.resetFields();
        }
      });
    } else {
      addForm.validateFields().then(async (values: any) => {
        const res = await CategoryManageAPI.updateClassification({
          ...values,
          id: currentRecord.id,
          pid: currentRecord.pid,
          directoryId: activeTabKey,
          type,
        });
        if (res.code === '200') {
          message.success('修改成功');
          getCategoryList(Number(activeTabKey));
          setIsVisible(false);
          events.emit('removeFileList');
          addForm.resetFields();
        }
      });
    }
  };
  const handleCancel = () => {
    const addForm = baseRef.current.getForm();
    addForm.resetFields();
    events.emit('setImgFile', '');
    events.emit('removeFileList');
    setIsVisible(false);
  };
  //   新增子分类
  const addChildrenCgy = (record: categoryEntity) => {
    if (editingKey.length === 0) {
      const item: categoryEntity | undefined = categoryList.find(
        (item: categoryEntity) => item.id === record.id,
      );
      item?.children.push({
        id: `${record.id}self`,
        classifyName: '',
        description: '',
        isADD: true,
        pid: record.id,
      });
      setCategoryList([...categoryList]);
      form.setFieldsValue({ classifyName: '', description: '' });
      editingKey.push(`${record.id}self`);
      setEditingKey(editingKey);
      setIsEdit(false);
    }
    const bol = expandedRowKeys.some((item: any) => item == record.id);
    if (!bol) {
      const arr: any = [];
      expandedRowKeys.push(record.id);
      arr.push(...expandedRowKeys);
      setExpandedRowKeys(arr);
    }
  };
  //   展开监听
  const onExpand = (_expanded: boolean, record: categoryEntity) => {
    const index = expandedRowKeys.findIndex((item: any) => item === record.id);
    if (index != -1) {
      expandedRowKeys.splice(index, 1);
      setExpandedRowKeys(expandedRowKeys);
    } else {
      expandedRowKeys.push(record.id);
      setExpandedRowKeys(expandedRowKeys);
    }
  };
  // 新增子分类
  const sureAddChildrenCgy = (record: categoryEntity) => {
    let pid: string | number;
    categoryList.map((item: categoryEntity) => {
      if (item.children && item.children.length != 0) {
        const bol: boolean = item.children.some(
          (item1: Partial<categoryEntity>) => item1.id === record.id,
        );
        if (bol) {
          pid = item.id;
        }
      }
    });
    form.validateFields().then(async (val: any) => {
      const obj: any = {
        pid,
        classifyName: val.classifyName,
        description: val.description,
        directoryId: activeTabKey,
        type,
      };
      if (isEdit) {
        const res = await CategoryManageAPI.updateClassification({
          ...obj,
          id: record.id,
        });
        if (res.code === '200') {
          message.success('修改成功');
          setEditingKey([]);
          getCategoryList(Number(activeTabKey));
          form.resetFields();
        } else {
          message.warning(res.message);
        }
      } else {
        const res = await CategoryManageAPI.addClassification(obj);
        if (res.code == 200) {
          message.success('新增成功');
          setEditingKey([]);
          getCategoryList(Number(activeTabKey));
          form.resetFields();
        } else {
          message.warning(res.message);
        }
      }
    });
  };
  // 取消新增子分类
  const cancelAddCldCgy = (record: categoryEntity) => {
    categoryList.map((item: categoryEntity) => {
      if (item.children && item.children.length != 0) {
        const index: number = item.children.findIndex(
          (item1: Partial<categoryEntity>) => item1.id === record.id,
        );
        if (index != -1) {
          if (isEdit) {
            item.children[index].isADD = false;
            setIsEdit(false);
          } else {
            item.children.splice(index, 1);
          }
        }
      }
    });
    setEditingKey([]);
    setCategoryList([...categoryList]);
  };
  // 删除分类
  const deleteCgy = (record: categoryEntity) => {
    Modal.confirm({
      title: '分类删除',
      content: '确认删除该分类?',
      async onOk() {
        const res = await CategoryManageAPI.deleteRelevantBusiness({
          id: record.id,
        });
        if (res.code === '200') {
          message.success('删除成功');
          getCategoryList(Number(activeTabKey));
        } else {
          message.error(res.message);
        }
      },
    });
  };
  // 编辑分类
  const editCgy = (record: categoryEntity) => {
    setCurrentRecord(record);
    const bol = categoryList.some((item: categoryEntity) => item.id === record.id);
    if (bol) {
      setTitle('修改分类');
      const addForm = baseRef.current.getForm();
      addForm.setFieldsValue({
        classifyName: record.classifyName,
        description: record.description,
        remark: record.remark,
      });
      events.emit('setImgFile', record.icon);
      setIsVisible(true);
    } else {
      // 编辑状态
      setIsEdit(true);
      categoryList.map((item: categoryEntity) => {
        if (item.children && item.children.length != 0) {
          const index: number = item.children.findIndex(
            (item1: Partial<categoryEntity>) => item1.id === record.id,
          );
          if (index != -1) {
            item.children[index].isADD = true;
          }
        }
      });
      setCategoryList([...categoryList]);
      setEditingKey([record.id]);
      form.setFieldsValue(record);
    }
  };
  const setVisibleEvent = () => {
    setvisible(false);
  };
  const imgClick = (str: string) => {
    setcurrentImgList([{ src: str }]);
    setvisible(true);
  };
  // 排序选择
  const onSelectChange = (record: categoryEntity) => {
    const index: number = selectedRowKeys.findIndex((item: any) => item === record.id);
    if (index != -1) {
      selectedRowKeys.splice(index, 1);
      setSelectedRowKeys([...selectedRowKeys]);
    } else {
      setSelectedRowKeys([...selectedRowKeys, record.id]);
    }
  };
  // 上移
  const upperEvent = async () => {
    if (selectedRowKeys.length === 0) {
      message.error('请选择分类');
    } else if (selectedRowKeys.length === 2) {
      message.error('分类只能选择一个');
    } else {
      const index: number = categoryList.findIndex(
        (item: categoryEntity) => item.id === selectedRowKeys[0],
      );
      if (index === 0) {
        message.error('已经是最上面了');
      } else {
        const res = await CategoryManageAPI.exchangeSortType({
          firstId: selectedRowKeys[0],
          secondId: categoryList[index - 1].id,
        });
        if (res.code === '200') {
          getCategoryList(Number(activeTabKey));
          message.success('上移成功');
        }
      }
    }
  };
  // 下移
  const shiftEvent = async () => {
    if (selectedRowKeys.length === 0) {
      message.error('请选择分类');
    } else if (selectedRowKeys.length === 2) {
      message.error('分类只能选择一个');
    } else {
      const index = categoryList.findIndex(
        (item: categoryEntity) => item.id === selectedRowKeys[0],
      );
      if (index === categoryList.length - 1) {
        message.error('已经是最下面了');
      } else {
        const res = await CategoryManageAPI.exchangeSortType({
          firstId: selectedRowKeys[0],
          secondId: categoryList[index + 1].id,
        });
        if (res.code === '200') {
          getCategoryList(Number(activeTabKey));
          message.success('下移成功');
        }
      }
    }
  };
  const rowSelection: any = {
    selectedRowKeys,
    onChange: onSelectChange,
    hideSelectAll: true,
    renderCell: (_checked: boolean, record: categoryEntity) => {
      return <>{record.level === 1 ? <Checkbox onChange={() => onSelectChange(record)} /> : ''}</>;
    },
  };
  // 页签改变监听
  const handleTabChange = (key: string) => {
    navigate({
      pathname: '',
      search: qs.stringify({ activeTabKey: key }),
    });
    setSelectedRowKeys([]);
    setActiveTabKey(Number(key));
    getCategoryList(Number(key));
  };
  // 分类详情
  const toCategoryDetail = (record: categoryEntity) => {
    navigate({
      pathname: `/categoryManage/detail/${record.id}`,
      search: qs.stringify({ directoryId: activeTabKey, pid: record.pid }),
    });
  };
  // 分享码弹窗显示
  // const showShareCode = async (record: any) => {
  //   const res: any = await CategoryManageAPI.getAppletQRCode({
  //     page: 'page-sort/sortDetail/index',
  //     scene: `?id=${record.id}&backTip=1`,
  //   });
  //   setShareCodeUrl(`data:image/png;base64,${res.result}`);
  //   setShareCodeVble(true);
  // };
  const shareCodeHandleCancel = () => {
    setShareCodeVble(false);
  };
  // 行业分享码下载
  const downLoadCode = () => {
    FileSaver.saveAs(shareCodeUrl, '无人机城行业分享码');
  };

  return (
    <div className='category-wrap'>
      <div className='option-wrap'>
        {btnAdd ? (
          <Button
            type='primary'
            style={{ marginRight: '10px' }}
            onClick={() => addCayDailogShow()}
            icon={<PlusOutlined />}
            disabled={tabList.length == 0}
          >
            新增分类
          </Button>
        ) : (
          ''
        )}
        {btnUpperDown ? (
          <>
            {' '}
            {/* 上移 */}
            <Button
              icon={<ArrowUpOutlined />}
              type='primary'
              style={{ marginRight: '10px' }}
              onClick={upperEvent}
            />
            {/* 下移 */}
            <Button
              icon={<ArrowDownOutlined />}
              type='primary'
              style={{ marginRight: '10px' }}
              onClick={shiftEvent}
            />
          </>
        ) : (
          ''
        )}
      </div>
      <Card
        style={{ width: '100%' }}
        tabList={tabList}
        activeTabKey={String(activeTabKey)}
        onTabChange={(key) => handleTabChange(key)}
      >
        <Form form={form} component={false}>
          <Table
            size='large'
            columns={mergedColumns}
            dataSource={categoryList}
            rowSelection={rowSelection}
            rowKey='id'
            bordered
            loading={isLoading}
            rowClassName={(record: any) => {
              if (record.children) {
                return '';
              }
              return 'row-bg';
            }}
            expandedRowKeys={expandedRowKeys}
            onExpand={(expanded: boolean, record: any) => onExpand(expanded, record)}
            components={{
              body: {
                cell: EditableCell,
              },
            }}
            childrenColumnName='children'
            expandable={{
              rowExpandable: (record) => {
                if (record.children && record.children.length != 0) {
                  return true;
                }
                return false;
              },
              expandIcon: ({ expanded, onExpand, record }) => {
                if (expanded && record.children && record.children.length != 0) {
                  return (
                    <DownOutlined
                      onClick={(e) => onExpand(record, e)}
                      // style={{marginRight:"10px"}}
                    />
                  );
                }
                if (record.children && record.children.length != 0) {
                  return (
                    <RightOutlined
                      onClick={(e) => onExpand(record, e)}
                      // style={{marginRight:"10px"}}
                    />
                  );
                }
                return <></>;
              },
            }}
            pagination={false}
          />
        </Form>
      </Card>
      <AddCgyDailog
        title={title}
        isVisable={isVisible}
        handleOk={handleOk}
        handleCancel={handleCancel}
        baseRef={baseRef}
        imgClick={imgClick}
      />
      {/* 图片放大 */}
      <Viewer
        visible={visible}
        currentImgList={currentImgList}
        activeViewerIndex={activeViewerIndex}
        setVisible={setVisibleEvent}
      />

      {/* 分享码弹窗 */}
      <Modal open={isShareCodeVble} title='分享码' footer={null} onCancel={shareCodeHandleCancel}>
        <div className='share-code'>
          <img src={shareCodeUrl} alt='' onClick={() => imgClick(shareCodeUrl)} />
          <div>
            <Button type='link' onClick={downLoadCode}>
              下载
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default Category;
