import React, { useEffect, useState } from 'react';
import { Button, Descriptions, message, Table, Modal, Image } from 'antd';
import { ColumnsType } from 'antd/es/table';
import AddOrEditProduceSpecModal from './components/addOrEditProduceSpecModal';
import SetProduceSpecPriceModal from './components/setProduceSpecPriceModal';
import { ProduceManageAPI } from '~/api';
import { useSearchParams } from 'react-router-dom';
import { InterDataType, PaginationProps } from '~/api/interface';
import { productDetailType, ProductSpecListType } from '~/api/interface/produceManageType';

//产品详情返回类型
type detailType = InterDataType<productDetailType>;
//产品规格返回类型
type specType = InterDataType<ProductSpecListType>['list'];

const { confirm } = Modal;
function ProduceDetail() {
  const [searchParams] = useSearchParams();

  //产品id
  const [productId, setProductId] = useState<number>(0);
  // 基本信息
  const [detailData, setDetailData] = useState<detailType>();
  // 表格数据
  const [tableData, setTableData] = useState<specType>([]);
  //新增、编辑产品规格弹窗
  const [addOrEditProduceSpecModalShow, setAddOrEditProduceSpecModalShow] =
    useState<boolean>(false);
  // 当前数据
  const [addEditData, setAddEditData] = useState<specType[0]>();
  //配置价格弹窗
  const [produceSpecPriceModalShow, setProduceSpecPriceModalShow] = useState<boolean>(false);
  // 表格结构
  const columns: ColumnsType<specType[0]> = [
    { title: '规格名称', dataIndex: 'specName', align: 'center' },
    {
      title: '规格图片',
      dataIndex: 'specImage',
      align: 'center',
      render: (text: string) => {
        return <Image width={50} height={50} src={text} />;
      },
    },
    { title: '版本描述', dataIndex: 'versionDesc', align: 'center' },
    { title: '料号', dataIndex: 'partNo', align: 'center' },
    {
      title: '操作',
      align: 'center',
      width: '250px',
      render: (_text: string, record) => {
        return (
          <div>
            <Button
              type='link'
              onClick={() => {
                handlePrice(record);
              }}
            >
              配置价格
            </Button>
            <Button
              type='link'
              onClick={() => {
                handleEdit(record);
              }}
            >
              编辑
            </Button>
            <Button type='link' onClick={() => handleDelete(record)}>
              删除
            </Button>
          </div>
        );
      },
    },
  ];
  // 表格分页配置
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    totalCount: 0,
    pageSize: 10,
    pageNo: 1,
  });
  // 打开新增弹窗
  const handleAdd = () => {
    setAddEditData(undefined);
    setAddOrEditProduceSpecModalShow(true);
  };
  // 打开编辑弹窗
  const handleEdit = (record: specType[0]) => {
    setAddEditData({ ...record });
    setAddOrEditProduceSpecModalShow(true);
  };
  // 关闭新增编辑弹窗
  const addOrEditProduceSpecModalCancel = () => {
    setAddOrEditProduceSpecModalShow(false);
    setAddEditData(undefined);
  };
  const addOrEditProduceSpecModalOk = () => {
    setAddOrEditProduceSpecModalShow(false);
    getProductSpecList(productId);
  }; // 删除产品
  const handleDelete = (record: specType[0]) => {
    confirm({
      title: '提示',
      content: '删除后此数据将会丢失，确定删除吗？',
      async onOk() {
        const { code, result } = await ProduceManageAPI.removeProductSpec({ id: record.id });
        if (!result && code === '200') {
          message.success('操作成功');
          getProductSpecList(productId);
          return;
        }
        message.info({
          content: (
            <div style={{ textAlign: 'left' }}>
              {result.goodsName && (
                <div>
                  <div style={{ color: 'red' }}>删除失败，已被商品关联</div>
                  <div>关联商品为： {result.goodsName.join(',')}</div>
                </div>
              )}
              {result.industrySkuName && (
                <div>
                  <div style={{ color: 'red' }}>删除失败，已被方案关联</div>
                  <div>关联方案SKU为： {getTipInfo(result.industrySkuName)}</div>
                </div>
              )}
            </div>
          ),
          duration: 2,
        });
      },
    });
  };
  // 获取基本信息
  const getDetailData = (id: number) => {
    ProduceManageAPI.getProductSkuDetail({ id }).then(({ result }) => {
      setDetailData(result || {});
    });
  };
  //获取产品规格列表
  const getProductSpecList = (productSkuId: number) => {
    ProduceManageAPI.listPageProductSpec({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      productSkuId,
    }).then(({ result }) => {
      setTableData(result.list);
      pagination.totalCount = result.totalCount;
      setPagination(pagination);
    });
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getProductSpecList(productId);
  };
  //配置价格
  const handlePrice = (record: specType[0]) => {
    setAddEditData({ ...record });
    setProduceSpecPriceModalShow(true);
  };
  const produceSpecPriceModalCancel = () => {
    setProduceSpecPriceModalShow(false);
  };
  // 返回上一页
  const handleBack = () => {
    history.go(-1);
  };
  // 获取提示信息
  const getTipInfo = (data: any) => {
    return data.map((v: any) => `${v.industrySkuName}(${v.industrySpecNames})`).join('、');
  };
  useEffect(() => {
    setProductId(Number(searchParams.get('id')));
    getDetailData(Number(searchParams.get('id')));
    getProductSpecList(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?.productName}</Descriptions.Item>
        <Descriptions.Item label='归属商品'>
          {detailData?.type === 1 ? '租赁商品' : detailData?.type === 0 ? '商城商品' : ''}
        </Descriptions.Item>
        <Descriptions.Item label='型号'>{detailData?.model}</Descriptions.Item>
        <Descriptions.Item label='产品品牌'>{detailData?.productBrand}</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={tableData}
            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>
      {/*新增、编辑*/}
      <AddOrEditProduceSpecModal
        open={addOrEditProduceSpecModalShow}
        onCancel={addOrEditProduceSpecModalCancel}
        data={addEditData}
        onOk={addOrEditProduceSpecModalOk}
        productSkuId={productId}
      />
      {/*配置价格*/}
      <SetProduceSpecPriceModal
        open={produceSpecPriceModalShow}
        onCancel={produceSpecPriceModalCancel}
        data={addEditData}
        type={detailData?.type || 0}
      />
    </div>
  );
}
export default ProduceDetail;
