import React, { useEffect, useState } from 'react';
import qs from 'query-string';
import { Button, Descriptions, message, Table } from 'antd';
import { useNavigate } from 'react-router-dom';
import { ColumnsType } from 'antd/es/table';
// import { ListModal } from '@/pages/goodsManage/industryManage/comp/listModal';
// import { PriceModal } from '@/pages/goodsManage/industryManage/comp/priceModal';
// import { AddEditDetailModal } from '@/pages/goodsManage/industryManage/comp/addEditDetailModal';
import useOption from '~/common/hook/optionHook';
import { IndustryManageAPI } from '~/api';
import { IndustrySkuType, IndustrySpecType, inventoryType } from '../industryList/propsType';
// import DeleteModal from '@/components/DeleteModal';

// eslint-disable-next-line react/no-unused-prop-types
function IndustryDetail(props: any) {
  // const productSkuId = Number(qs.parse(props.location.search).id);

  const navigate = useNavigate();
  // 行业列表对象
  const [industryTypeObj, setIndustryTypeObj] = useState<{}>({});
  // 产品类型对象
  const [productTypeObj, setProductTypeObj] = useState<{}>({});
  // 基本信息
  const [detailData, setDetailData] = useState<IndustrySkuType>();
  // 表格数据
  const [tableData, setTableData] = useState<IndustrySpecType[]>([]);
  // 图片是否放大
  const [visibleImg, setVisibleImg] = useState<boolean>(false);
  // 当前放大图片
  const [currentImgList, setCurrentImgList] = useState<{ src: string }[]>([]);
  // 产品清单弹窗显示
  const [visibleList, setVisibleList] = useState<boolean>(false);
  // 产品规格清单
  const [listData, setListData] = useState<inventoryType[]>([]);
  // 配置价格弹窗显示
  const [visiblePrice, setVisiblePrice] = useState<boolean>(false);
  // 当前配置价格数据
  const [priceData, setPriceData] = useState([]);
  // 新增编辑规格弹窗是否显示
  const [visibleAddEdit, setVisibleAddEdit] = useState<boolean>(false);
  // 删除行业规格弹窗是否显示
  const [visibleDeleteSpec, setVisibleDeleteSpec] = useState<boolean>(false);
  // 当前行业规格id
  const [industrySpecId, setIndustrySpecId] = useState<number>();

  // 新增编辑规格弹窗数据
  const [addEditData, setAddEditData] = useState<IndustrySpecType>({
    createTime: '',
    id: 0,
    industrySkuId: 0,
    list: [],
    specImage: '',
    specName: '',
    productSkuId: 0,
  });
  // 按钮权限
  const btnAdd = useOption(22205);
  const btnSetPrice = useOption(22206);
  const btnEdit = useOption(22207);
  const btnDelete = useOption(22208);
  // 预览图片
  const previewImage = (url: string) => {
    setVisibleImg(true);
    setCurrentImgList([{ src: url }]);
  };
  // 关闭图片放大
  const setVisibleEvent = () => {
    setVisibleImg(false);
  };
  // 查看产品清单
  const handleList = async (id: number) => {
    const obj = await getIndustrySpecDetail(id);
    setListData(obj?.list || []);
    setVisibleList(true);
  };
  // 关闭产品清单
  const handleListClosed = () => {
    setListData([]);
    setVisibleList(false);
  };
  // 打开配置价格弹窗
  const handlePrice = (arr: any) => {
    setPriceData(arr);
    setVisiblePrice(true);
  };
  // 关闭配置价格弹窗
  const handlePriceClosed = () => {
    setPriceData([]);
    setVisiblePrice(false);
  };
  // 打开新增弹窗
  const handleAdd = () => {
    setAddEditData({
      createTime: undefined,
      id: 0,
      productSkuId,
      industrySkuId: 0,
      list: [],
      specImage: '',
      specName: '',
    });
    setVisibleAddEdit(true);
  };
  // 打开编辑弹窗
  const handleEdit = async (id: number) => {
    const obj: any = await getIndustrySpecDetail(id);
    setAddEditData({ ...obj, productSkuId });
    setVisibleAddEdit(true);
  };
  // 关闭新增编辑弹窗
  const handleAddEditClosed = async (isRefresh: boolean) => {
    // setAddEditData({ id: 0, img: "", list: [], name: "" });
    setVisibleAddEdit(false);
    if (isRefresh) {
      await getDetailData();
      await getTableList();
    }
  };
  // 打开删除行业规格弹窗
  const openDeleteDialog = (id: number) => {
    setVisibleDeleteSpec(true);
    setIndustrySpecId(id);
  };

  // 关闭删除行业规格弹窗
  const handleDeleteSpecClosed = () => {
    setVisibleDeleteSpec(false);
  };

  // 删除行业规格
  const handleDeleteSpec = async () => {
    const res: any = await IndustryManageAPI.removeIndustrySpec({ id: industrySpecId });
    if (res.code === '200') {
      if (res.result) {
        message.info({
          content: (
            <div style={{ textAlign: 'left' }}>
              {res.result.goodsName && (
                <div>
                  <div style={{ color: 'red' }}>删除失败，已被商品关联</div>
                  <div style={{ display: 'flex' }}>
                    <div>关联的商品为：</div>
                    <div>{res.result.goodsName.join('、')}</div>
                  </div>
                </div>
              )}
            </div>
          ),
          // className: "custom-class",
          duration: 3,
        });
      } else {
        message.success('操作成功');
        getTableList().then();
      }

      handleDeleteSpecClosed();
    } else {
      message.error(res.message);
      handleDeleteSpecClosed();
    }
  };

  // 表格结构
  const columns: ColumnsType<IndustrySpecType> = [
    { title: '规格名称', dataIndex: 'specName', align: 'center' },
    {
      title: '规格图片',
      dataIndex: 'specImage',
      align: 'center',
      render: (text: string) => {
        return (
          <img
            style={{ width: '50px', height: '50px' }}
            src={text}
            alt='图片'
            onClick={() => {
              previewImage(text);
            }}
          />
        );
      },
    },
    {
      title: '产品清单',
      dataIndex: 'id',
      align: 'center',
      render: (id: number) => {
        return (
          <Button type='link' onClick={() => handleList(id)}>
            查看产品清单
          </Button>
        );
      },
    },
    {
      title: '操作',
      align: 'center',
      width: '250px',
      render: (text: string, record: IndustrySpecType) => {
        return (
          <div>
            {btnSetPrice ? (
              <Button
                type='link'
                onClick={() => {
                  handlePrice(record);
                }}
              >
                配置价格
              </Button>
            ) : (
              ''
            )}
            {btnEdit ? (
              <Button
                type='link'
                onClick={() => {
                  handleEdit(record.id);
                }}
              >
                编辑
              </Button>
            ) : (
              ''
            )}
            {btnDelete ? (
              <Button
                type='link'
                onClick={() => {
                  openDeleteDialog(record.id);
                }}
              >
                删除
              </Button>
            ) : (
              ''
            )}
          </div>
        );
      },
    },
  ];
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 获取所属行业下拉列表
  const getFirstIndustryTypeInfo = async () => {
    const res: any = await IndustryManageAPI.getFirstIndustryTypeInfo({});
    if (res && res.code === '200') {
      const obj = res.result.reduce((prev: any, curt: any) => {
        prev[curt.goodsMasterTypeId] = curt.goodsMasterType;
        return prev;
      }, {});
      setIndustryTypeObj(obj);
    }
  };

  // 获取产品类型
  const getFirstProductTypeInfo = async () => {
    const res: any = await IndustryManageAPI.getFirstProductTypeInfo({});
    if (res && res.code === '200') {
      const obj = res.result.reduce((prev: any, curt: any) => {
        prev[curt.goodsMasterTypeId] = curt.goodsMasterType;
        return prev;
      }, {});
      setProductTypeObj(obj);
    }
  };

  // 获取产品清单详情
  const getIndustrySpecDetail = async (id: number) => {
    const res: any = await IndustryManageAPI.getIndustrySpecDetail({
      industrySpecId: id,
    });
    if (res && res.code === '200') {
      const { specImage, specName, productInventoryList, createTime, id, industrySkuId } =
        res.result;
      const list =
        productInventoryList &&
        productInventoryList.map((item: inventoryType) => {
          return {
            ...item.productSku,
            sku: item.productSpecList,
            radio: item.select,
            typeName: productTypeObj[item.productSku.goodsTypeId as keyof typeof productTypeObj],
            id: item.productSkuId,
          };
        });
      // console.log("当前数据--->", list);
      const obj = { list, specImage, specName, createTime, id, industrySkuId };
      return obj;
    }
  };
  useEffect(() => {
    // const sku: SkuType[] = [1, 2, 3].map((i, j) => {
    //   return {
    //     id: [469, 466, 458][j],
    //     name: `入云龙【红黑】${i}`,
    //     img:
    //       i % 2 === 1
    //         ? "https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/file/test111.gif"
    //         : "https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/file/111.gif",
    //     desc: "上盖丝印",
    //     no: "3.1.29.0068-G",
    //   };
    // });
    // const list: ArrType[] = [1, 2, 3, 4].map((i, j) => {
    //   return {
    //     id: i,
    //     skuId: [
    //       "772189430646845440",
    //       "771012649717870592",
    //       "771037713385402368",
    //       "771016084857040896",
    //     ][j],
    //     name: `入云龙${i}`,
    //     type: "无人机",
    //     num: "SN_000001",
    //     brand: "科比特",
    //     radio: j % 2 === 1 ? 1 : 2,
    //     sku: j % 2 === 1 ? [] : sku,
    //   };
    // });
    // const arr: ListType[] = [1, 2, 3, 4, 5].map((i) => {
    //   return {
    //     id: i,
    //     name: `升级方案${i}`,
    //     img:
    //       i % 2 === 1
    //         ? "https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/file/test111.gif"
    //         : "https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/file/111.gif",
    //     list,
    //   };
    // });
    // console.log("数据源 --->", arr);
    // setTableData(arr);

    (async () => {
      // await getFirstIndustryTypeInfo();
      // await getFirstProductTypeInfo();
      // await getDetailData();
      // await getTableList();
    })();
  }, []);

  // 返回上一页
  const handleBack = () => {
    navigate(-1);
  };
  // 获取方案规格数据
  const getTableList = async (value = {}) => {
    const res: any = await IndustryManageAPI.listPageIndustrySpec({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      productSkuId,
    });

    if (res && res.code === '200') {
      setTableData(res.result.list || []);
    }
  };
  // 获取基本信息
  const getDetailData = async () => {
    const { id } = qs.parse(props.location.search);
    const res: any = await IndustryManageAPI.getIndustrySkuDetail({ id });
    if (res && res.code === '200') {
      setDetailData(res.result);
    }
  };
  return (
    <div className='detail-wrap'>
      <Descriptions
        title='一、基本信息'
        bordered
        column={1}
        size='middle'
        labelStyle={{ width: '200px' }}
        style={{ width: '100%' }}
        extra={
          <Button type='primary' onClick={handleBack}>
            返回
          </Button>
        }
      >
        <Descriptions.Item label='方案名称'>{detailData?.solutionName}</Descriptions.Item>
        <Descriptions.Item label='所属行业'>
          {' '}
          {industryTypeObj[detailData?.goodsTypeId as keyof typeof industryTypeObj] || ''}
        </Descriptions.Item>
        <Descriptions.Item label='描述'>{detailData?.description}</Descriptions.Item>
      </Descriptions>
      <Descriptions
        title='二、方案规格'
        column={1}
        size='middle'
        labelStyle={{ width: '200px' }}
        style={{ marginTop: '20px' }}
      >
        {btnAdd ? (
          <Descriptions.Item>
            <Button type='primary' onClick={handleAdd}>
              新增规格
            </Button>
          </Descriptions.Item>
        ) : (
          ''
        )}
        <Descriptions.Item>
          <Table
            size='small'
            dataSource={tableData}
            columns={columns}
            rowKey='id'
            style={{ width: '100%' }}
            bordered
            pagination={{
              total: pagination.total,
              pageSize: pagination.pageSize,
              current: pagination.current,
              showSizeChanger: true,
              showQuickJumper: true,
              // onChange: (page: number, pageSize: number) =>
              //   paginationChange(page, pageSize),
              showTotal: (total, range) =>
                `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
            }}
          />
        </Descriptions.Item>
      </Descriptions>
      {/*<ListModal visible={visibleList} closed={handleListClosed} data={listData} />*/}
      {/*<PriceModal visible={visiblePrice} closed={handlePriceClosed} data={priceData} />*/}
      {/*<AddEditDetailModal*/}
      {/*  visible={visibleAddEdit}*/}
      {/*  closed={handleAddEditClosed}*/}
      {/*  data={addEditData}*/}
      {/*/>*/}
      {/*<DeleteModal*/}
      {/*  visible={visibleDeleteSpec}*/}
      {/*  onCancel={handleDeleteSpecClosed}*/}
      {/*  onOK={handleDeleteSpec}*/}
      {/*/>*/}
    </div>
  );
}
export default IndustryDetail;
