import { useState, useEffect } from 'react';
import { Form, Upload, Button, Table, Input, message } from 'antd';
import type { UploadFile } from 'antd/es/upload/interface';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import { ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons';
import { PaginationEntity } from '~/common/interface/PaginationEntity';
import { CategoryManageAPI } from '~/api';
import './index.scss';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { InterDataType } from '~/api/interface';
import { categoryDetailsType } from '~/api/interface/categoryManage';

//分类详情返回类型
type detailType = InterDataType<categoryDetailsType>;

const CategoryDetail = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  // 分页数据
  const [detailData, setDetailData] = useState<detailType>(null!);
  // 全部商品数据
  const [allGoodsInfo, setAllGoodsInfo] = useState<any>([]);
  const [categoryId, setCategoryId] = useState<number>(0);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [detailForm] = Form.useForm<any>();
  const [fileList, setFileList] = useState<any>([]);
  const [goodsInfo, setGoodsInfo] = useState<any>([]);
  const [pagination, setPagination] = useState<Pick<PaginationEntity, 'pageNo' | 'pageSize'>>({
    pageNo: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState<number>(0);
  const [sortTypeId, setSortTypeId] = useState<number>(-1);
  const [pid, setPid] = useState<number>(-1);
  const params = useParams();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();

  const columns: ColumnsType<any> = [
    {
      title: '序号',
      align: 'center',
      render: (_text: string, _record, index: number) => {
        return (pagination.pageNo - 1) * pagination.pageSize + index + 1;
      },
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      align: 'center',
    },
    {
      title: '商品图片',
      align: 'center',
      render: (text: string, record, index: number) => {
        return <img className='goods-img' src={record.goodsImg} />;
      },
    },
    {
      title: '状态',
      align: 'center',
      render: (text: string, record, index: number) => {
        return <div>{record.shelfStatus ? '上架' : '下架'}</div>;
      },
    },
  ];

  useEffect(() => {
    // 全部数据
    // getAllGoodsTypeDetail(_id);
    getGoodsTypeDetail(Number(params.id));
    setSortTypeId(Number(searchParams.get('directoryId')));
    setPid(Number(searchParams.get('pid')));
    setCategoryId(Number(params.id));
  }, []);

  const backRoute = () => {
    navigate(-1);
  };
  // 分类详情数据
  const getGoodsTypeDetail = (id: number) => {
    CategoryManageAPI.getGoodsTypeDetail({ id, ...pagination }).then(({ result }) => {
      detailForm.setFieldsValue({
        classifyName: result.classifyName || undefined,
        description: result.description || undefined,
        icon: result.icon || '',
      });
      if (result.icon) {
        setFileList([
          {
            id: new Date().getTime(),
            status: 'done',
            url: result.icon,
          },
        ]);
      }
      setDetailData(result);
    });
  };
  //分类关联-数据
  const getRelevantBusiness = (id: number, type: number) => {
    CategoryManageAPI.getRelevantBusiness({ id, type });
  };
  // 全部数据
  const getAllGoodsTypeDetail = async (id: number) => {
    const res: any = await CategoryManageAPI.getGoodsTypeDetail({
      id,
    });
    setAllGoodsInfo(res.result || []);
  };
  // 自定义上传
  const selfUploadRequest = async (val: any) => {
    const formData: FormData = new FormData();
    formData.append('uploadFile', val.file);
    const res: any = await CategoryManageAPI.cateGoryDetailUpload(formData);
    if (res.code === '200') {
      setFileList([
        {
          id: new Date().getTime(),
          status: 'done',
          url: res.result[0],
        },
      ]);
      detailForm.setFieldsValue({ icon: res.result[0] });
    } else {
      message.error(res.message);
    }
  };
  const onRemove = (file: UploadFile) => {
    if (!isEdit) {
      return Promise.resolve(false);
    }
    setFileList([]);
    detailForm.setFieldsValue({
      icon: '',
    });
  };

  const beforeUpload = (val: any) => {
    if (!['image/jpg', 'image/jpeg', 'image/png'].includes(val.type)) {
      message.error('请上传图片格式为jpg，jpeg，png的图片');
      return false;
    }
    const limitM = 2;
    const isLimit: boolean = val.size / 1024 / 1024 <= limitM;
    if (!isLimit) {
      message.error('图片最大上传2M');
      return false;
    }
    return true;
  };

  // 修改详情
  const changeDetailInfo = () => {
    setIsEdit(true);
  };
  const sureChangeDetailInfo = () => {
    detailForm.validateFields().then(async (value: any) => {
      const res = await CategoryManageAPI.updateClassification({
        ...value,
        sortTypeId,
        pid,
        id: categoryId,
      });
      if (res.code === '200') {
        message.success('修改成功');
        getGoodsTypeDetail(categoryId);
        setIsEdit(false);
      } else {
        message.error(res.message);
      }
    });
  };
  // 上移
  const shiftGoods = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择商品');
    } else {
      const allIndex: number = allGoodsInfo.findIndex(
        (item: any) => item.goodsId === selectedRowKeys[0],
      );
      const index: number = goodsInfo.findIndex((item: any) => item.goodsId === selectedRowKeys[0]);
      if (index === 0 && pagination.pageNo === 1) {
        message.warning('已经到最上面了!');
      } else {
        const res: any = await CategoryManageAPI.exchangeGoodsInfo(
          allGoodsInfo[allIndex].goodsId,
          allGoodsInfo[allIndex - 1].goodsId,
        );
        if (res.code === '200') {
          message.success('上移成功');
          if (index === 0) {
            pagination.pageNo--;
          }
          setPagination({ ...pagination });
          getAllGoodsTypeDetail(categoryId);
        }
      }
    }
  };
  // 下移
  const downGoods = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择商品');
    } else {
      const allIndex: number = allGoodsInfo.findIndex(
        (item: any) => item.goodsId === selectedRowKeys[0],
      );
      const index: number = goodsInfo.findIndex((item: any) => item.goodsId === selectedRowKeys[0]);
      if (allIndex === allGoodsInfo.length - 1) {
        message.warning('已经到最下面了!');
      } else {
        const res: any = await CategoryManageAPI.exchangeGoodsInfo(
          allGoodsInfo[index].goodsId,
          allGoodsInfo[index + 1].goodsId,
        );
        if (res.code === '200') {
          message.success('下移成功');
          if (index === goodsInfo.length - 1) {
            pagination.pageNo++;
          }
          setPagination({ ...pagination });
          getAllGoodsTypeDetail(categoryId);
        }
      }
    }
  };
  // 分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    setPagination({ pageNo, pageSize });
  };
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<any> = {
    selectedRowKeys,
    onChange: onSelectChange,
    type: 'radio',
  };

  return (
    <div className='category-detail'>
      <div className='category-detail-head'>
        <div className='category-detail-title'>一、基本信息</div>
        <div className='category-detail-head-option'>
          <Button type='primary' style={{ marginRight: '10px' }} onClick={sureChangeDetailInfo}>
            保存
          </Button>
          <Button type='primary' style={{ marginRight: '10px' }} onClick={changeDetailInfo}>
            修改
          </Button>
          <Button type='primary' onClick={backRoute}>
            返回
          </Button>
        </div>
      </div>
      <div className='category-detail-form'>
        <Form form={detailForm} labelCol={{ span: 2 }} wrapperCol={{ span: 5 }}>
          <Form.Item
            label='行业名称'
            name='classifyName'
            rules={[{ required: true, message: '请输入行业名称' }]}
          >
            {isEdit ? (
              <Input placeholder='请输入行业名称' disabled={!isEdit} maxLength={15} />
            ) : (
              <span>{detailData?.classifyName}</span>
            )}
          </Form.Item>
          <Form.Item label='分类描述' name='description'>
            {isEdit ? (
              <Input placeholder='请输入分类描述' disabled={!isEdit} maxLength={70} />
            ) : (
              <span>{detailData?.description || '暂无'}</span>
            )}
          </Form.Item>
          {detailData?.icon ? (
            <Form.Item
              label='分类图标'
              name='icon'
              rules={[{ required: true, message: '请上传分类图标' }]}
            >
              {/* 外层嵌套解决错乱问题和影响form数据问题 */}
              <div key={Math.random()}>
                <Upload
                  listType='picture-card'
                  fileList={fileList}
                  customRequest={selfUploadRequest}
                  onRemove={onRemove}
                  maxCount={1}
                  accept='image/*'
                  beforeUpload={beforeUpload}
                >
                  {fileList.length < 1 ? <div>上传</div> : ''}
                </Upload>
              </div>
            </Form.Item>
          ) : (
            ''
          )}
        </Form>
      </div>
      <div className='category-detail-title' style={{ marginTop: '20px' }}>
        二、关联商品
      </div>
      <div className='category-detail-option'>
        <Button
          icon={<ArrowUpOutlined />}
          type='primary'
          style={{ marginRight: '10px' }}
          onClick={shiftGoods}
        />
        <Button
          icon={<ArrowDownOutlined />}
          type='primary'
          style={{ marginRight: '10px' }}
          onClick={downGoods}
        />
      </div>
      <div className='category-detail-table'>
        <Table
          size='small'
          columns={columns}
          dataSource={goodsInfo}
          pagination={{
            total,
            pageSize: pagination.pageSize,
            current: pagination.pageNo,
            showSizeChanger: true,
            onChange: (page, pageSize) => paginationChange(page, pageSize),
            showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
          }}
          bordered
          rowKey='goodsId'
          rowSelection={rowSelection}
        />
      </div>
    </div>
  );
};

export default CategoryDetail;
