/*
 * ~Author: 龚洪江
 * ~Date: 2022-07-22 15:13:52
 * ~LastEditors: 龚洪江
 * ~LastEditTime: 2022-08-12 10:29:36
 * ~FilePath: \code\mmc-store\src\pages\goodsManage\children\category\detail\index.tsx
 * ~Description:
 *
 * Copyright (c) 2022 by 龚洪江 2238959530~qq.com, All Rights Reserved.
 */
import { FC, useState, useEffect } from 'react';
import { Form, Upload, Button, Table, Modal, Input, Switch, message } from 'antd';
import type { UploadFile } from 'antd/es/upload/interface';
import type { ColumnsType, ColumnType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import { ArrowUpOutlined, ArrowDownOutlined, SearchOutlined } from '@ant-design/icons';
import qs from 'query-string';
import Viewer from '~/components/viewer';
import { PaginationEntity } from '~/common/interface/PaginationEntity';
import { categoryDetailEntity, GoodsInfo } from '~/api/modules/goods';
import { CategoryManageAPI } from '~/api';
import useOption from '~/common/hook/optionHook';
import './index.scss';

const CategoryDetail: FC = (props: any) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [addModalVisible, setModalVisible] = useState<boolean>(false);
  // 分页数据
  const [detailData, setDetailData] = useState<categoryDetailEntity>(null!);
  // 全部商品数据
  const [allGoodsInfo, setAllGoodsInfo] = useState<GoodsInfo[]>([]);
  const [categoryId, setCategoryId] = useState<number>(0);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [detailForm] =
    Form.useForm<Pick<categoryDetailEntity, 'description' | 'groupName' | 'icon'>>();
  const [fileList, setFileList] = useState<any>([]);
  const [goodsInfo, setGoodsInfo] = useState<GoodsInfo[]>([]);
  const [viewerVisible, setViewerVisible] = useState<boolean>(false);
  const [pagination, setPagination] = useState<Pick<PaginationEntity, 'pageNo' | 'pageSize'>>({
    pageNo: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState<number>(0);
  // 当前放大图片
  const [currentImgList, setcurrentImgList]: any = useState([]);
  const [sortTypeId, setSortTypeId] = useState<number>(-1);
  const [pid, setPid] = useState<number>(-1);
  const columns: ColumnsType<GoodsInfo> = [
    {
      title: '序号',
      align: 'center',
      render: (text: string, record: GoodsInfo, index: number) => {
        return (pagination.pageNo - 1) * pagination.pageSize + index + 1;
      },
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      align: 'center',
    },
    {
      title: '商品图片',
      align: 'center',
      render: (text: string, record: GoodsInfo, index: number) => {
        return (
          <img
            className='goods-img'
            src={record.goodsImg}
            onClick={() => showViewerEvent(record.goodsImg)}
          />
        );
      },
    },
    {
      title: '状态',
      align: 'center',
      render: (text: string, record: GoodsInfo, index: number) => {
        return <div>{record.shelfStatus ? '上架' : '下架'}</div>;
      },
    },
    {
      title: '安全编码开关',
      align: 'center',
      render: (text: string, record: GoodsInfo, index: number) => {
        return (
          btnCode && (
            <Switch
              checked={!!record.showCode}
              onChange={(checked, e) => switchChangeEvent(checked, e, record, index)}
            />
          )
        );
      },
    },
    // {
    //   title: "操作",
    //   align: "center",
    //   filterDropdownVisible:false,
    //   render: (text: string, record: GoodsInfo, index: number) => {
    //     return (
    //       <Button type="link" danger onClick={() => deleteGoods(record)}>
    //         删除
    //       </Button>
    //     );
    //   },
    // },
  ];
  // 按钮权限
  const btnUpperDown = useOption(22109);
  const btnChange = useOption(22110);
  const btnCode = useOption(22111);
  useEffect(() => {
    // 分页数据
    getGoodsTypeDetail(props.match.params.id);
  }, [pagination]);

  useEffect(() => {
    // 全部数据
    getAllGoodsTypeDetail(props.match.params.id);
    setSortTypeId(Number(qs.parse(props.location.search).sortTypeId));
    setPid(Number(qs.parse(props.location.search).pid));
    setCategoryId(props.match.params.id);
  }, []);

  const backRoute = () => {
    props.history.go(-1);
  };
  //   关联商品新增
  const addModalShowEvent = () => {
    setModalVisible(true);
  };
  const addConnectGoods = () => {
    setModalVisible(false);
  };
  const cancelHandle = () => {
    setModalVisible(false);
  };
  // 分页数据
  const getGoodsTypeDetail = async (id: number) => {
    const res: any = await CategoryManageAPI.getGoodsTypeDetail({ id, ...pagination });
    detailForm.setFieldsValue({
      groupName: res.result.groupName ? res.result.groupName : undefined,
      description: res.result.description ? res.result.description : undefined,
      icon: res.result.icon ? res.result.icon : '',
    });
    if (res.result.icon) {
      setFileList([
        {
          id: new Date().getTime(),
          status: 'done',
          url: res.result.icon,
        },
      ]);
    }
    setDetailData(res.result);
    setGoodsInfo(res.result.goodsInfo || []);
    setTotal(res.result.totalCount);
  };
  // 全部数据
  const getAllGoodsTypeDetail = async (id: number) => {
    const res: any = await CategoryManageAPI.getGoodsTypeDetail({
      id,
      pageNo: 1,
      pageSize: 99999,
    });
    setAllGoodsInfo(res.result.goodsInfo || []);
  };
  // 自定义上传
  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 iconValidator=(rule:any,value:any)=>{
  //   console.log('数据--->',value)
  // }

  const onPreview = (file: UploadFile) => {
    showViewerEvent(file.url as string);
  };

  // 安全编码
  const switchChangeEvent = async (
    checked: boolean,
    e: React.MouseEvent<HTMLButtonElement>,
    record: GoodsInfo,
    index: number,
  ) => {
    record.showCode = checked ? 1 : 0;
    // goodsInfo.splice(index, 1, record);
    // setDetailData({ ...detailData });
    // setGoodsInfo([...goodsInfo]);
    const res: any = await CategoryManageAPI.updateIsShowCode({
      goodsId: record.goodsId,
      showCode: record.showCode,
    });
    if (res.code === '200') {
      message.success('修改成功');
      getGoodsTypeDetail(props.match.params.id);
    }
  };

  // 商品删除
  const deleteGoods = (record: GoodsInfo) => {};

  // 修改详情
  const changeDetailInfo = () => {
    setIsEdit(true);
  };
  const sureChangeDetailInfo = () => {
    detailForm
      .validateFields()
      .then(async (value: Pick<categoryDetailEntity, 'description' | 'groupName' | 'icon'>) => {
        // console.log("数据--->", value);
        const res = await CategoryManageAPI.updateClassification({
          // description:value.description,
          // groupName:value.groupName,
          // icon:fileList.length?fileList[0].url:'',
          ...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: GoodsInfo) => item.goodsId === selectedRowKeys[0],
      );
      const index: number = goodsInfo.findIndex(
        (item: GoodsInfo) => 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);
          // let obj: GoodsInfo = goodsInfo[index];
          // goodsInfo.splice(index, 1, goodsInfo[index - 1]);
          // goodsInfo.splice(index - 1, 1, obj);
          // setGoodsInfo([...goodsInfo]);
        }
      }
    }
  };
  // 下移
  const downGoods = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择商品');
    } else {
      const allIndex: number = allGoodsInfo.findIndex(
        (item: GoodsInfo) => item.goodsId === selectedRowKeys[0],
      );
      const index: number = goodsInfo.findIndex(
        (item: GoodsInfo) => 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);
          // let obj: GoodsInfo = goodsInfo[index];
          // goodsInfo.splice(index, 1, goodsInfo[index + 1]);
          // goodsInfo.splice(index + 1, 1, obj);
          // setGoodsInfo([...goodsInfo]);
        }
      }
    }
  };
  // 分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    setPagination({ pageNo, pageSize });
  };
  const showViewerEvent = (src: string) => {
    setcurrentImgList([{ src }]);
    setViewerVisible(true);
  };
  const setVisibleEvent = () => {
    setViewerVisible(false);
  };
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<GoodsInfo> = {
    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'>
          {isEdit ? (
            <Button type='primary' style={{ marginRight: '10px' }} onClick={sureChangeDetailInfo}>
              保存
            </Button>
          ) : btnChange ? (
            <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='groupName'
            rules={[{ required: true, message: '请输入行业名称' }]}
          >
            {isEdit ? (
              <Input placeholder='请输入行业名称' disabled={!isEdit} maxLength={15} />
            ) : (
              <span>{detailData?.groupName}</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}
                  onPreview={onPreview}
                  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'>
        {btnUpperDown ? (
          <>
            <Button
              icon={<ArrowUpOutlined />}
              type='primary'
              style={{ marginRight: '10px' }}
              onClick={shiftGoods}
            />
            <Button
              icon={<ArrowDownOutlined />}
              type='primary'
              style={{ marginRight: '10px' }}
              onClick={downGoods}
            />
          </>
        ) : (
          ''
        )}

        {/* <Button type="primary" onClick={addModalShowEvent}>
          添加
        </Button> */}
      </div>
      <div className='category-detail-table'>
        <Table
          size='small'
          columns={
            Number(qs.parse(props.location.search).sortTypeId) === 1
              ? columns.filter((item: ColumnType<GoodsInfo>) => item.title != '安全编码开关')
              : 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>
      <Modal
        visible={addModalVisible}
        title='关联商品新增'
        onOk={addConnectGoods}
        onCancel={cancelHandle}
      >
        {/* <Form form={connectForm}>
          <Form.Item label="商品">
            <Select placeholder="请选择商品" mode="multiple">
              <Select.Option value={1}>{1}</Select.Option>
              <Select.Option value={2}>{2}</Select.Option>
            </Select>
          </Form.Item>

        </Form> */}
        <div className='add-goods'>
          <div>
            <Input suffix={<SearchOutlined />} placeholder='请输入商品名称' />
          </div>
          <div className='add-goods-select'>
            <div className='add-goods-select-value'>
              <div className='label'>您选择的商品是：</div>
              <div className='select-value' />
            </div>
            <div className='add-goods-select-list' />
          </div>
        </div>
      </Modal>
      {/* 图片放大 */}
      <Viewer
        visible={viewerVisible}
        currentImgList={currentImgList}
        activeViewerIndex={0}
        setVisible={setVisibleEvent}
      />
    </div>
  );
};

export default CategoryDetail;
