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 { Router } from 'react-router-dom';
import FileSaver from 'file-saver';
import qs from 'query-string';
import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  AppstoreAddOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  RightOutlined,
  DownOutlined,
  ShareAltOutlined,
  ProfileOutlined,
} from '@ant-design/icons';
import AddCgyDailog from './components/addCgyDailog';
import DeleteCgyDailog from './components/deleteCgyDailog';
import EditableCell from './components/EditableCell';
import AddOrEditDec from './components/addOrEditDec';
import { CategoryManageAPI } from '~/api';
import { categoryEntity, categoryDec } from '~/api/interface/categoryManage';
import Viewer from '~/components/viewer';
import useOption from '~/common/hook/optionHook';
import './index.scss';
import events from '~/events';

const Category: FC = (props: any) => {
  const baseRef: any = useRef();
  // 分类目录
  const [tabList, setTabList] = useState<CardTabListType[]>([]);
  const [directoryList, setDirectoryList] = useState<categoryDec[]>([]);
  const [isAddOrEditDecModal, setIsAddOrEditDecModal] = useState<boolean>(false);
  // 分类列表
  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.goodsMasterTypeId);
    if (index != -1) {
      return true;
    }
    return false;
  };
  const columns = [
    {
      title: '分类名称',
      dataIndex: 'goodsMasterType',
      key: 'goodsMasterType',
      // align: "center",
      width: '12%',
      editable: true,
      ellipsis: true,
      render: (text: string, record: categoryEntity, index: number) => {
        return (
          <Tooltip placement='top' title={<span>{record.goodsMasterType}</span>}>
            <span
              style={{
                marginLeft:
                  record.goodsSlaveTypeDTO && record.goodsSlaveTypeDTO.length != 0
                    ? '10px'
                    : '24px',
              }}
            >
              {record.goodsMasterType}
            </span>
          </Tooltip>
        );
      },
      onHeaderCell: () => {
        return {
          style: {
            textAlign: 'center',
          },
        };
      },
    },
    {
      title: '图片',
      // dataIndex: "icon",
      key: 'icon',
      width: '12%',
      align: 'center',
      render: (text: string, record: categoryEntity, index: number) => {
        return record.icon ? (
          <img
            src={record.icon}
            style={{ width: '50px', height: '50px' }}
            onClick={() => imgClick(record.icon)}
          />
        ) : (
          ''
        );
      },
    },
    {
      title: '描述',
      key: 'desc',
      dataIndex: 'desc',
      width: '20%',
      align: 'center',
      editable: true,
      ellipsis: true,
      render: (text: string, record: categoryEntity, index: number) => {
        return (
          <Tooltip placement='right' title={<span>{record.desc}</span>}>
            <span>{record.desc}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: '15%',
      key: 'createTime',
      align: 'center',
    },
    {
      title: '操作',
      width: '55%',
      key: 'option',
      align: 'center',
      render: (text: string, record: categoryEntity, index: number) => {
        return (
          <div className='table-option-wrap'>
            {record.goodsSlaveTypeDTO ? (
              <>
                {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, index)}>
                  取消
                </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);
  // 删除弹窗
  const [isDeleteVisible, setIsDeleteVisible] = useState<boolean>(false);
  // 删除分类id
  const [cgyId, setCgyId] = useState<number>(0);
  // 弹窗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>(2);

  // 分享码弹窗显示/隐藏
  const [isShareCodeVble, setShareCodeVble] = useState<boolean>(false);
  const [shareCodeUrl, setShareCodeUrl] = useState<string>('');
  // 按钮权限
  const btnAdd = useOption(22101);
  const btnUpperDown = useOption(22102);
  const btnDir = useOption(22103);
  const btnAddChildCgy = useOption(22104);
  const btnShareCode = useOption(22105);
  const btnEdit = useOption(22106);
  const btnDelete = useOption(22107);
  const btnDetail = useOption(22108);
  // 获取请求数据
  useEffect(() => {
    if (qs.parse(props.location?.search).activeTabKey) {
      // console.log("当前数据--->", qs.parse(props.location?.search).activeTabKey);
      setActiveTabKey(Number(qs.parse(props.location?.search).activeTabKey));
    }
    getCategoryList(Number(qs.parse(props.location?.search).activeTabKey) || Number(activeTabKey));
    getDirectoryList();
  }, []);
  // 获取分类目录
  const getDirectoryList = async () => {
    const res: any = await CategoryManageAPI.directoryList();
    const tabList: CardTabListType[] = res.result.map((item: categoryDec) => {
      return {
        key: item.id.toString(),
        tab: item.sortName,
      };
    });
    setTabList([...tabList]);
    setDirectoryList([...res.result]);
  };
  // 分类列表
  const getCategoryList = async (type: number) => {
    setIsLoading(true);
    const res = await CategoryManageAPI.getListGoodsTypeList(type);
    setIsLoading(false);
    setCategoryList(res.result || []);
    const arr: number[] = res.result.map((item: any) => {
      return item.goodsMasterTypeId;
    });
    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,
            sortTypeId: activeTabKey,
          });
          if (res.code == 200) {
            events.emit('removeFileList');
            message.success('新增成功');
            setIsVisible(false);
            getCategoryList(Number(activeTabKey));
            addForm.resetFields();
          }
        })
        .catch((err: any) => {});
    } else {
      addForm
        .validateFields()
        .then(async (values: any) => {
          const res = await CategoryManageAPI.updateClassification({
            ...values,
            id: currentRecord.goodsMasterTypeId,
            pid: currentRecord.pid,
            sortTypeId: activeTabKey,
          });
          if (res.code === '200') {
            message.success('修改成功');
            getCategoryList(Number(activeTabKey));
            setIsVisible(false);
            events.emit('removeFileList');
            addForm.resetFields();
          }
        })
        .catch((err: any) => {});
    }
  };
  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.goodsMasterTypeId === record.goodsMasterTypeId,
      );
      item?.goodsSlaveTypeDTO.push({
        goodsMasterTypeId: `${record.goodsMasterTypeId}self`,
        goodsMasterType: '',
        desc: '',
        isADD: true,
        pid: record.goodsMasterTypeId,
      });
      setCategoryList([...categoryList]);
      form.setFieldsValue({ goodsMasterType: '', desc: '' });
      editingKey.push(`${record.goodsMasterTypeId}self`);
      setEditingKey(editingKey);
      setIsEdit(false);
    }
    const bol = expandedRowKeys.some((item: any) => item == record.goodsMasterTypeId);
    if (!bol) {
      const arr: any = [];
      expandedRowKeys.push(record.goodsMasterTypeId);
      arr.push(...expandedRowKeys);
      setExpandedRowKeys(arr);
    }
  };
  //   展开监听
  const onExpand = (expanded: boolean, record: categoryEntity) => {
    const index = expandedRowKeys.findIndex((item: any) => item === record.goodsMasterTypeId);
    if (index != -1) {
      expandedRowKeys.splice(index, 1);
      setExpandedRowKeys(expandedRowKeys);
    } else {
      expandedRowKeys.push(record.goodsMasterTypeId);
      setExpandedRowKeys(expandedRowKeys);
    }
  };
  // 新增子分类
  const sureAddChildrenCgy = (record: categoryEntity) => {
    let pid: string | number = -1;
    categoryList.map((item: categoryEntity) => {
      if (item.goodsSlaveTypeDTO && item.goodsSlaveTypeDTO.length != 0) {
        const bol: boolean = item.goodsSlaveTypeDTO.some(
          (item1: Partial<categoryEntity>) => item1.goodsMasterTypeId === record.goodsMasterTypeId,
        );
        if (bol) {
          pid = item.goodsMasterTypeId;
        }
      }
    });
    form.validateFields().then(async (val: any) => {
      const obj: any = {
        pid,
        groupName: val.goodsMasterType,
        description: val.desc,
        sortTypeId: activeTabKey,
      };
      if (isEdit) {
        const res = await CategoryManageAPI.updateClassification({
          ...obj,
          id: record.goodsMasterTypeId,
        });
        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, index: number) => {
    categoryList.map((item: categoryEntity) => {
      if (item.goodsSlaveTypeDTO && item.goodsSlaveTypeDTO.length != 0) {
        const index: number = item.goodsSlaveTypeDTO.findIndex(
          (item1: Partial<categoryEntity>) => item1.goodsMasterTypeId === record.goodsMasterTypeId,
        );
        if (index != -1) {
          if (isEdit) {
            item.goodsSlaveTypeDTO[index].isADD = false;
            setIsEdit(false);
          } else {
            item.goodsSlaveTypeDTO.splice(index, 1);
          }
        }
      }
    });
    setEditingKey([]);
    setCategoryList([...categoryList]);
  };
  // 删除分类
  const deleteCgy = (record: categoryEntity) => {
    setCgyId(Number(record.goodsMasterTypeId));
    setIsDeleteVisible(true);
  };
  // 删除弹窗确认
  const deleteHandleOk = async () => {
    const bol = categoryList.some((item: categoryEntity) => item.goodsMasterTypeId === cgyId);
    if (bol) {
      const res = await CategoryManageAPI.deleteGoodsTypeByOneLevel({
        id: cgyId,
        sortTypeId: activeTabKey,
      });
      if (res.code === '200') {
        message.success('删除成功');
        getCategoryList(Number(activeTabKey));
      } else {
        message.warning(res.message);
      }
    } else {
      const res = await CategoryManageAPI.deleteGoodsTypeByChildren({
        id: cgyId,
        sortTypeId: activeTabKey,
      });
      if (res.code === '200') {
        message.success('删除成功');
        getCategoryList(Number(activeTabKey));
      } else {
        message.warning(res.message);
      }
    }
    setIsDeleteVisible(false);
  };
  // 删除弹框取消
  const deleteHandleCancel = () => {
    setIsDeleteVisible(false);
  };
  // 编辑分类
  const editCgy = (record: categoryEntity) => {
    setCurrentRecord(record);
    const bol = categoryList.some(
      (item: categoryEntity) => item.goodsMasterTypeId === record.goodsMasterTypeId,
    );
    if (bol) {
      setTitle('修改分类');
      const addForm = baseRef.current.getForm();
      addForm.setFieldsValue({
        groupName: record.goodsMasterType,
        description: record.desc,
        remark: record.remark,
      });
      events.emit('setImgFile', record.icon);
      setIsVisible(true);
    } else {
      // 编辑状态
      setIsEdit(true);
      categoryList.map((item: categoryEntity) => {
        if (item.goodsSlaveTypeDTO && item.goodsSlaveTypeDTO.length != 0) {
          const index: number = item.goodsSlaveTypeDTO.findIndex(
            (item1: Partial<categoryEntity>) =>
              item1.goodsMasterTypeId === record.goodsMasterTypeId,
          );
          if (index != -1) {
            item.goodsSlaveTypeDTO[index].isADD = true;
          }
        }
      });
      setCategoryList([...categoryList]);
      setEditingKey([record.goodsMasterTypeId]);
      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.goodsMasterTypeId,
    );
    if (index != -1) {
      selectedRowKeys.splice(index, 1);
      setSelectedRowKeys([...selectedRowKeys]);
    } else {
      setSelectedRowKeys([...selectedRowKeys, record.goodsMasterTypeId]);
    }
  };
  // 上移
  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.goodsMasterTypeId === selectedRowKeys[0],
      );
      if (index === 0) {
        message.error('已经是最上面了');
      } else {
        const res = await CategoryManageAPI.exchangeSortType({
          firstId: selectedRowKeys[0],
          secondId: categoryList[index - 1].goodsMasterTypeId,
          sortTypeId: activeTabKey,
        });
        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.goodsMasterTypeId === selectedRowKeys[0],
      );
      if (index === categoryList.length - 1) {
        message.error('已经是最下面了');
      } else {
        const res = await CategoryManageAPI.exchangeSortType({
          firstId: selectedRowKeys[0],
          secondId: categoryList[index + 1].goodsMasterTypeId,
          sortTypeId: activeTabKey,
        });
        if (res.code === '200') {
          getCategoryList(Number(activeTabKey));
          message.success('下移成功');
        }
      }
    }
  };
  const rowSelection: any = {
    selectedRowKeys,
    onChange: onSelectChange,
    hideSelectAll: true,
    renderCell: (checked: boolean, record: categoryEntity) => {
      return (
        <>
          {record.goodsSlaveTypeDTO != null ? (
            <Checkbox onChange={() => onSelectChange(record)} />
          ) : (
            ''
          )}
        </>
      );
    },
  };
  // 页签改变监听
  const handleTabChange = (key: string) => {
    Router.push({
      pathname: '/goodsManage/category',
      search: qs.stringify({ activeTabKey: key }),
    });
    setSelectedRowKeys([]);
    setActiveTabKey(Number(key));
    getCategoryList(Number(key));
  };
  // 分类详情
  const toCategoryDetail = (record: categoryEntity) => {
    Router.push({
      pathname: `/goodsManage/category/detail/${record.goodsMasterTypeId}`,
      search: qs.stringify({ sortTypeId: activeTabKey, pid: record.pid }),
    });
  };
  // 分享码弹窗显示
  const showShareCode = async (record: any) => {
    const res: any = await CategoryManageAPI.getAppletQRCode({
      page: 'page-sort/sortDetail/index',
      scene: `?id=${record.goodsMasterTypeId}&backTip=1`,
    });
    setShareCodeUrl(`data:image/png;base64,${res.result}`);
    setShareCodeVble(true);
  };
  const shareCodeHandleCancel = () => {
    setShareCodeVble(false);
  };
  // 行业分享码下载
  const downLoadCode = () => {
    FileSaver.saveAs(shareCodeUrl, '无人机城行业分享码');
  };
  // 目录弹窗
  const showDecModal = () => {
    setDirectoryList([...directoryList]);
    setIsAddOrEditDecModal(true);
  };
  const addOrEditDecHandleOk = () => {
    getDirectoryList();
    setIsAddOrEditDecModal(false);
  };
  const addOrEditDecHandleCancel = () => {
    setIsAddOrEditDecModal(false);
  };
  const refreshDec = (id: number) => {
    const index: number = directoryList.findIndex((item: categoryDec) => item.id === activeTabKey);
    if (id === directoryList[index].id) {
      setActiveTabKey(directoryList[index - 1].id);
      Router.push({
        pathname: '/goodsManage/category',
        search: qs.stringify({ activeTabKey: directoryList[index - 1].id }),
      });
      getCategoryList(directoryList[index - 1].id);
    }
    getDirectoryList();
    // if (qs.parse(props.location?.search).activeTabKey) {
    //   setActiveTabKey(Number(qs.parse(props.location?.search).activeTabKey));
    // }
  };
  return (
    <div className='category-wrap'>
      <div className='option-wrap'>
        {btnAdd ? (
          <Button
            type='primary'
            style={{ marginRight: '10px' }}
            onClick={() => addCayDailogShow()}
            icon={<PlusOutlined />}
          >
            新增分类
          </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)}
        tabBarExtraContent={
          btnDir ? (
            <Button type='link' onClick={showDecModal}>
              目录管理
            </Button>
          ) : (
            ''
          )
        }
      >
        <Form form={form} component={false}>
          <Table
            size='small'
            columns={mergedColumns}
            dataSource={categoryList}
            rowSelection={rowSelection}
            rowKey='goodsMasterTypeId'
            bordered
            loading={isLoading}
            rowClassName={(record: any, index: number) => {
              if (record.goodsSlaveTypeDTO) {
                return '';
              }
              return 'row-bg';
            }}
            expandedRowKeys={expandedRowKeys}
            onExpand={(expanded: boolean, record: any) => onExpand(expanded, record)}
            components={{
              body: {
                cell: EditableCell,
              },
            }}
            childrenColumnName='goodsSlaveTypeDTO'
            expandable={{
              rowExpandable: (record) => {
                if (record.goodsSlaveTypeDTO && record.goodsSlaveTypeDTO.length != 0) {
                  return true;
                }
                return false;
              },
              expandIcon: ({ expanded, onExpand, record }) => {
                if (expanded && record.goodsSlaveTypeDTO && record.goodsSlaveTypeDTO.length != 0) {
                  return (
                    <DownOutlined
                      onClick={(e) => onExpand(record, e)}
                      // style={{marginRight:"10px"}}
                    />
                  );
                }
                if (record.goodsSlaveTypeDTO && record.goodsSlaveTypeDTO.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}
      />
      <DeleteCgyDailog
        isDeleteVisable={isDeleteVisible}
        deleteHandleOk={deleteHandleOk}
        deleteHandleCancel={deleteHandleCancel}
      />
      {/* 图片放大 */}
      <Viewer
        visible={visible}
        currentImgList={currentImgList}
        activeViewerIndex={activeViewerIndex}
        setVisible={setVisibleEvent}
      />
      {/* 目录管理 */}
      <AddOrEditDec
        isModalVisible={isAddOrEditDecModal}
        handleOk={addOrEditDecHandleOk}
        handleCancel={addOrEditDecHandleCancel}
        directoryList={directoryList}
        refreshDec={refreshDec}
      />
      {/* 分享码弹窗 */}
      <Modal
        visible={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;
