import React, { useEffect, useState } from 'react';
import { Button, Descriptions, Image, message, Table } from 'antd';
import { useNavigate } from 'react-router-dom';
import { ColumnsType } from 'antd/es/table';
import { IndustryManageAPI } from '~/api';
import { useSearchParams } from 'react-router-dom';
// import { inventoryType } from '../industryList/propsType';
import { InterDataType, PaginationProps } from '~/api/interface';
import {
  industryDetailType,
  industrySpecDetailType,
  industrySpecList,
} from '~/api/interface/industryManageType';
import AddOrEditSpecModal from './components/addOrEditSpecModal';
import ConnectProduceModal from './components/connectProduceModal';
import DesignateSpecModal from './components/designateSpecModal';
import ProductListModal from './components/productListModal';
import { productListType, ProductSpecListType } from '~/api/interface/produceManageType';
import { filterObjAttr } from '~/utils';

//行业详情返回类型
type detailType = InterDataType<industryDetailType>;
//方案规格返回类型
type industrySpecType = InterDataType<industrySpecList>['list'];
//产品sku返回类型
type produceSpecType = InterDataType<ProductSpecListType>['list'];
//自定义产品返回类型
type selfProduceItemType = InterDataType<productListType>['list'][0] & {
  radio?: number;
};
//方案规格详情返回类型
type specDetailType = InterDataType<industrySpecDetailType>;

function IndustryDetail() {
  const [searchParams] = useSearchParams();

  const navigate = useNavigate();
  //行业ID
  const [industryId, setIndustryId] = useState<number>(0);
  // 基本信息
  const [detailData, setDetailData] = useState<detailType>({
    id: 0,
    description: '',
    categoryId: 0,
    solutionName: '',
    categoryName: '',
  });
  // 方案规格
  const [industrySpecData, setIndustrySpecData] = useState<industrySpecType>([]);
  // 产品清单弹窗显示
  // const [visibleList, setVisibleList] = useState<boolean>(false);
  // 产品规格清单
  // const [listData, setListData] = useState<inventoryType[]>([]);
  // 配置价格弹窗显示
  // const [visiblePrice, setVisiblePrice] = useState<boolean>(false);
  // 当前配置价格数据
  // const [priceData, setPriceData] = useState([]);
  // 新增编辑规格弹窗是否显示
  const [addOrEditSpecModalShow, setAddOrEditSpecModalShow] = useState<boolean>(false);
  //关联产品弹窗
  const [connectProduceModalShow, setConnectProduceModalShow] = useState<boolean>(false);
  const [connectProduceList, setConnectProduceList] = useState<selfProduceItemType[]>([]);
  const [designateProduceId, setDesignateProduceId] = useState<number>(0);
  //指定sku弹窗
  const [designateSpecModalShow, setDesignateSpecModalShow] = useState<boolean>(false);
  const [selectProduceSpecList, setSelectProduceSpecList] = useState<produceSpecType>([]);
  //产品清单弹窗
  const [productListModalShow, setProductListModalShow] = useState<boolean>(false);
  //方案规格详情
  const [specDetails, setSpecDetails] = useState<specDetailType>({
    productInventoryList: [],
    id: 0,
    industrySkuId: 0,
    specImage: '',
    specName: '',
  });
  // 表格结构
  const columns: ColumnsType<industrySpecType[0]> = [
    { title: '规格名称', dataIndex: 'specName', align: 'center' },
    {
      title: '规格图片',
      dataIndex: 'specImage',
      align: 'center',
      render: (text) => {
        return <Image width={50} height={50} src={text} alt='图片' />;
      },
    },
    {
      title: '产品清单',
      dataIndex: 'id',
      align: 'center',
      render: (id: number) => {
        return (
          <Button type='link' onClick={() => lookProductList(id)}>
            查看产品清单
          </Button>
        );
      },
    },
    {
      title: '操作',
      align: 'center',
      width: '250px',
      render: (_text, record) => {
        return (
          <div>
            <Button
              type='link'
              onClick={() => {
                // handlePrice(record);
              }}
            >
              配置价格
            </Button>
            <Button
              type='link'
              onClick={() => {
                editIndustrySpec(record.id);
              }}
            >
              编辑
            </Button>
            <Button type='link' onClick={deleteIndustrySpec}>
              删除
            </Button>
          </div>
        );
      },
    },
  ];
  // 表格分页配置
  const [pagination, setPagination] = useState<
    PaginationProps & { totalCount: number; totalPage: number }
  >({
    totalCount: 0,
    pageSize: 10,
    pageNo: 1,
    totalPage: 0,
  });

  // 关闭产品清单
  // const handleListClosed = () => {
  //   setListData([]);
  //   setVisibleList(false);
  // };
  // 打开配置价格弹窗
  // const handlePrice = (arr: any) => {
  //   setPriceData(arr);
  //   setVisiblePrice(true);
  // };
  // 关闭配置价格弹窗
  // const handlePriceClosed = () => {
  //   setPriceData([]);
  //   setVisiblePrice(false);
  // };
  // 打开新增弹窗
  const handleAdd = () => {
    setAddOrEditSpecModalShow(true);
  };
  // 编辑方案规格
  const editIndustrySpec = (industrySpecId: number) => {
    IndustryManageAPI.getIndustrySpecDetail({
      industrySpecId,
    }).then(({ result }) => {
      setSpecDetails(result);
      const connectProduct: selfProduceItemType[] = result.productInventoryList.map((v) => ({
        categoriesId: v.productSku.goodsTypeId,
        ...filterObjAttr(v.productSku, ['goodsTypeId']),
        categoryName: v.productSku.categoryName,
        productSpecList: v.productSpecList,
        radio: v.select,
        id: v.productSkuId,
      }));
      const designateList = result.productInventoryList.reduce((pre: any, cur) => {
        if (cur.productSpecList) {
          pre.push(...cur.productSpecList);
        }
        return pre;
      }, []);
      setSelectProduceSpecList(designateList);
      setConnectProduceList(connectProduct);
    });
    setAddOrEditSpecModalShow(true);
  };

  // 删除方案规格
  const deleteIndustrySpec = () => {
    IndustryManageAPI.removeIndustrySpec({ id: industryId }).then(({ code, result }) => {
      if (code === '200') {
        if (result) {
          message.info({
            content: (
              <div style={{ textAlign: 'left' }}>
                {result.goodsName && (
                  <div>
                    <div style={{ color: 'red' }}>删除失败，已被商品关联</div>
                    <div style={{ display: 'flex' }}>
                      <div>关联的商品为：</div>
                      <div>{result.goodsName.join('、')}</div>
                    </div>
                  </div>
                )}
              </div>
            ),
            duration: 3,
          });
        } else {
          message.success('操作成功');
        }
      }
    });
  };

  // 获取方案规格详情
  const getIndustrySpecDetail = (industrySpecId: number) => {
    IndustryManageAPI.getIndustrySpecDetail({
      industrySpecId,
    }).then(({ result }) => {
      setSpecDetails(result);
    });
  };
  // 返回上一页
  const handleBack = () => {
    navigate(-1);
  };
  // 获取方案规格数据
  const getIndustrySpecList = (productSkuId: number) => {
    IndustryManageAPI.getIndustrySpecList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      productSkuId,
    }).then(({ result }) => {
      setIndustrySpecData(result.list || []);
      pagination.totalCount = result.totalCount;
      pagination.totalPage = result.totalPage;
      setPagination(pagination);
    });
  };
  // 获取行业信息
  const getIndustryDetail = (id: number) => {
    IndustryManageAPI.getIndustryDetail({ id }).then(({ result }) => {
      setDetailData(result);
    });
  };
  //新增、编辑规格弹窗
  const addOrEditSpecModalClose = () => {
    setAddOrEditSpecModalShow(false);
    setConnectProduceList([]);
  };
  const addOrEditSpecSuccess = () => {
    getIndustrySpecList(industryId);
    addOrEditSpecModalClose();
  };
  //关联指定产品弹窗
  const connectSpecModalShow = () => {
    setConnectProduceModalShow(true);
  };
  const connectProduceModalClose = () => {
    setConnectProduceModalShow(false);
  };
  const connectProduceSubmit = (data: selfProduceItemType[]) => {
    const cloneSelectProduce: selfProduceItemType[] = JSON.parse(JSON.stringify(data));
    //判断是否存在未指定规格
    const produceObj = cloneSelectProduce.find(
      (v) =>
        v.radio &&
        !selectProduceSpecList.some((item) => v.productSpecList.some((j) => item.id === j.id)),
    );
    if (produceObj) {
      return message.warning(`请选择 ${produceObj.productName} 指定的规格`);
    }
    //产品，规格组合好
    const filterConnectProduceList = cloneSelectProduce.reduce((pre: any, cur) => {
      const specList = selectProduceSpecList.filter((v) =>
        cur.productSpecList.some((i) => i.id === v.id && cur.radio == 1),
      );
      cur.productSpecList = specList;
      return [...pre, cur];
    }, []);
    setConnectProduceList(filterConnectProduceList);
    setConnectProduceModalShow(false);
  };
  //指定sku弹窗
  const toDesignateSpec = (id: number) => {
    setDesignateProduceId(id);
    setDesignateSpecModalShow(true);
  };
  const produceSpecSelectEvent = (data: produceSpecType) => {
    setSelectProduceSpecList([...selectProduceSpecList, ...data]);
    setDesignateSpecModalShow(false);
  };
  const designateSpecModalCancel = () => {
    setDesignateProduceId(0);
    setDesignateSpecModalShow(false);
  };
  //产品清单弹窗
  const lookProductList = (id: number) => {
    getIndustrySpecDetail(id);
    setProductListModalShow(true);
  };
  const productListModalCancel = () => {
    setSpecDetails({
      productInventoryList: [],
      id: 0,
      industrySkuId: 0,
      specImage: '',
      specName: '',
    });
    setProductListModalShow(false);
  };

  useEffect(() => {
    setIndustryId(Number(searchParams.get('id')));
    getIndustryDetail(Number(searchParams.get('id')));
    getIndustrySpecList(Number(searchParams.get('id')));
  }, []);

  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='所属行业'>{detailData.categoryName}</Descriptions.Item>
        <Descriptions.Item label='描述'>{detailData.description}</Descriptions.Item>
      </Descriptions>
      <Descriptions
        title='二、方案规格'
        column={1}
        size='middle'
        labelStyle={{ width: '200px' }}
        style={{ marginTop: '20px' }}
      >
        <Descriptions.Item>
          <Button type='primary' onClick={handleAdd}>
            新增规格
          </Button>
        </Descriptions.Item>
        <Descriptions.Item>
          <Table
            size='small'
            dataSource={industrySpecData}
            columns={columns}
            rowKey='id'
            style={{ width: '100%' }}
            bordered
            pagination={{
              total: pagination.totalCount,
              pageSize: pagination.pageSize,
              current: pagination.pageNo,
              showSizeChanger: true,
              showQuickJumper: true,
              // onChange: (page: number, pageSize: number) =>
              //   paginationChange(page, pageSize),
              showTotal: (total, range) =>
                `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
            }}
          />
        </Descriptions.Item>
      </Descriptions>
      {/*新增、编辑方案规格*/}
      <AddOrEditSpecModal
        open={addOrEditSpecModalShow}
        connectSpecModalShow={connectSpecModalShow}
        close={addOrEditSpecModalClose}
        produceSpecList={connectProduceList}
        industrySkuId={industryId}
        handleSuccess={addOrEditSpecSuccess}
        specDetail={specDetails}
      />
      {/*指定产品*/}
      <ConnectProduceModal
        open={connectProduceModalShow}
        close={connectProduceModalClose}
        data={connectProduceList}
        toDesignateSpec={toDesignateSpec}
        connectProduceSubmit={connectProduceSubmit}
      />
      {/*指定sku*/}
      <DesignateSpecModal
        open={designateSpecModalShow}
        productId={designateProduceId}
        onCancel={designateSpecModalCancel}
        produceSpecSelectEvent={produceSpecSelectEvent}
        data={selectProduceSpecList}
      />
      {/*产品清单*/}
      <ProductListModal
        open={productListModalShow}
        onCancel={productListModalCancel}
        data={specDetails.productInventoryList}
      />
    </div>
  );
}
export default IndustryDetail;
