import { useSearchParams, useNavigate } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { OrderManageAPI, RentManageAPI, SystemManageAPI } from '~/api';
import { InterDataType } from '~/api/interface';
import { leaseGoodsDetailsType } from '~/api/interface/rentManageType';
import { Badge, Button, Col, Descriptions, Image, Row, Switch, Table } from 'antd';
import { qualityList } from '~/utils/dictionary';
import './index.scss';

//租赁商品详情返回类型
type rentGoodsDetailType = InterDataType<leaseGoodsDetailsType>;
//规格表单数据类型
type specificationFormListType = {
  optionList: { label: string; value: string }[];
  id: number;
  name: string;
  addSpecificationValueShow: boolean;
  specificationValueList: { name: string; id: number; specificationName: string }[];
};

const RentDetail = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();

  //租赁-编辑-商品详情
  const [rentGoodsDetails, setRentGoodsDetails] = useState<rentGoodsDetailType>();
  const [skuColumns, setSkuColumns] = useState<any>([
    {
      title: '商品规格',
      align: 'center',
      children: [],
    },
    {
      title: '是否缺货',
      align: 'center',
      dataIndex: 'stockOut',
      render: (text: number) => <Switch checked={!!text} />,
    },
    {
      title: '押金',
      align: 'center',
      dataIndex: 'cashPledge',
      render: (text: number) => text.toLocaleString() + '元',
    },
    {
      title: '库存',
      align: 'center',
      dataIndex: 'stock',
    },
  ]);
  const [skuTableData, setSkuTableData] = useState<
    (rentGoodsDetailType['priceStock'][0] & { [x: string]: string })[]
  >([]);
  //全部租期
  const [allLeaseTermInfoList, setAllLeaseTermInfoList] = useState<
    {
      label: string;
      value: number;
      key: string;
    }[]
  >([]);
  const [addressOptionList, setAddressOptionList] = useState<
    { label: string; value: number; districtCode: string }[]
  >([]);
  const [expressOptionList, setExpressOptionList] = useState<{ label: string; value: string }[]>(
    [],
  );

  //获取租赁商品详情
  const getRentGoodsDetail = (id: number) => {
    RentManageAPI.getLeaseGoodsDetails({ id }).then(({ result }) => {
      if (result) {
        setRentGoodsDetails({ ...result });
        //转化数据
        const covertSpecAttrList = result.specAttrList.map((v, index) => ({
          id: v.id,
          name: 'specName' + index,
          optionList: [{ label: v.specName, value: v.specName }],
          specificationValueList: v.specValuesList.map((i) => ({
            id: i.id,
            name: i.specName,
            specificationName: v.specName,
          })),
          addSpecificationValueShow: false,
        }));
        const upLeaseTermInfoIndex = allLeaseTermInfoList.findIndex(
          (v) => v.value === result.maxLeaseTerm,
        );
        const lowLeaseTermInfoIndex = allLeaseTermInfoList.findIndex(
          (v) => v.value === result.minLeaseTerm,
        );
        const filterLeaseTermInfo = allLeaseTermInfoList.slice(
          lowLeaseTermInfoIndex,
          upLeaseTermInfoIndex + 1,
        );
        const addColumnsList: any = filterLeaseTermInfo.map((v) => ({
          title: v.label,
          align: 'center',
          dataIndex: v.key,
          width: '15%',
          render: (text: number) => text.toLocaleString() + '元',
        }));
        skuColumns.push(...addColumnsList);
        mergeTableRow(covertSpecAttrList);

        const tableDataList: (rentGoodsDetailType['priceStock'][0] & { [x: string]: string })[] =
          result.priceStock.map((v) => ({
            id: v.id,
            stockOut: !!v.stockOut,
            stock: v.stock || undefined,
            threeDaysRental: v.threeDaysRental || undefined,
            sevenDaysRental: v.sevenDaysRental || undefined,
            thirtyDaysRental: v.thirtyDaysRental || undefined,
            ninetyDaysRental: v.ninetyDaysRental || undefined,
            maxDaysRental: v.maxDaysRental || undefined,
            cashPledge: v.cashPledge,
            ...Object.getOwnPropertyNames(JSON.parse(v.productSpec)).reduce(
              (pre: any, cur, currentIndex) => {
                pre['name' + (currentIndex + 1)] = JSON.parse(v.productSpec)[cur];
                pre['specificationName' + (currentIndex + 1)] = cur;
                return pre;
              },
              {},
            ),
          }));
        setSkuTableData(tableDataList);
      }
    });
  };
  //表头拆分及合并列
  const mergeTableRow = (filterSpecificationFormList: specificationFormListType[]) => {
    const columns = filterSpecificationFormList.map((v, index) => ({
      title: v.optionList[0].value,
      dataIndex: 'name' + (index + 1),
      align: 'center',
      onCell: (_: any, i: number) => {
        //合并列
        if (index < filterSpecificationFormList.length - 1) {
          const count: number = filterSpecificationFormList
            .slice(index + 1, filterSpecificationFormList.length)
            .reduce((pre: number, cur) => {
              return pre * cur.specificationValueList.length;
            }, 1);
          return {
            rowSpan: count !== 1 ? ((i + 1) % count === 1 ? count : 0) : 1,
          };
        } else {
          return {
            rowSpan: 1,
          };
        }
      },
    }));
    skuColumns[0].children = columns;
    setSkuColumns([...skuColumns]);
  };

  //租赁-商品-租期信息
  const getLeaseTermInfo = () => {
    RentManageAPI.getLeaseTermInfo().then(({ result }) => {
      if (result) {
        const optionList = result.map((v, index) => ({
          label: v.leaseDate,
          value: v.id,
          key: [
            'threeDaysRental',
            'sevenDaysRental',
            'thirtyDaysRental',
            'ninetyDaysRental',
            'maxDaysRental',
          ][index],
        }));
        setAllLeaseTermInfoList(optionList);
      }
    });
  };
  //地址列表
  const getAddressList = () => {
    SystemManageAPI.getAddressList({}).then(({ result }) => {
      if (result) {
        const optionList = result.map((v) => ({
          label: v.takeName + v.takePhone + `(${v.takeRegion.split('/').join('') + v.takeAddress})`,
          value: v.id,
          districtCode: v.districtCode,
        }));
        setAddressOptionList(optionList);
      }
    });
  };
  //物流公司列表
  const getListExpressInfo = () => {
    OrderManageAPI.listExpressInfo().then(({ result }) => {
      if (result) {
        const optionList = result.map((v) => ({
          label: v.exName,
          value: v.exCode,
        }));
        setExpressOptionList(optionList);
      }
    });
  };

  //返回
  const backRoute = () => {
    navigate(-1);
  };

  useEffect(() => {
    getLeaseTermInfo();
    getAddressList();
    getListExpressInfo();
  }, []);

  useEffect(() => {
    if (allLeaseTermInfoList.length) {
      getRentGoodsDetail(Number(searchParams.get('id')));
    }
  }, [allLeaseTermInfoList]);

  return (
    <div className='rent-detail'>
      <Descriptions
        title='商品信息'
        bordered
        column={4}
        extra={
          <Button type='primary' onClick={backRoute}>
            返回
          </Button>
        }
      >
        <Descriptions.Item label='商品标题'>{rentGoodsDetails?.tradeName}</Descriptions.Item>
        <Descriptions.Item label='商品卖点'>{rentGoodsDetails?.sellingPoint}</Descriptions.Item>
        <Descriptions.Item label='商品成新'>
          {qualityList.find((v) => v.value === rentGoodsDetails?.level)?.label}
        </Descriptions.Item>
        <Descriptions.Item label='商品状态'>
          <Badge
            status={rentGoodsDetails?.shelfStatus ? 'processing' : 'default'}
            text={rentGoodsDetails?.shelfStatus ? '上架中' : '仓库中'}
          />
        </Descriptions.Item>
      </Descriptions>
      <Descriptions title='商品属性' bordered column={3} style={{ marginTop: '10px' }}>
        <Descriptions.Item label='商品类型'>{rentGoodsDetails?.productTypeName}</Descriptions.Item>
        <Descriptions.Item label='商品品牌'>{rentGoodsDetails?.brandName}</Descriptions.Item>
        <Descriptions.Item label='商品型号'>{rentGoodsDetails?.deviceModeName}</Descriptions.Item>
        <Descriptions.Item label='商品主图'>
          <Image src={rentGoodsDetails?.resourcesList.find((v) => v.type === 0)?.url} width={50} />
        </Descriptions.Item>
        <Descriptions.Item label='商品副图' span={2}>
          {rentGoodsDetails?.resourcesList.filter((v) => v.type === 1).length ? (
            <Row>
              {rentGoodsDetails?.resourcesList
                .filter((v) => v.type === 1)
                .map((v) => (
                  <Col key={v.id} offset={1}>
                    <Image src={v.url} width={50} height={50} />
                  </Col>
                ))}
            </Row>
          ) : (
            '暂无'
          )}
        </Descriptions.Item>
        <Descriptions.Item label='商品视频'>
          {rentGoodsDetails?.resourcesList.find((v) => v.type === 2)?.url ? (
            <video
              src={rentGoodsDetails?.resourcesList.find((v) => v.type === 2)?.url}
              controls
              style={{ width: '200px', height: '200px' }}
            />
          ) : (
            '暂无'
          )}
        </Descriptions.Item>
        <Descriptions.Item label='商品参数'>
          {rentGoodsDetails?.productParam
            ? JSON.parse(rentGoodsDetails?.productParam).map(
                (v: { [x: string]: string }, index: number) => (
                  <Row key={index} style={{ lineHeight: '40px' }}>
                    <Col>{Object.getOwnPropertyNames(v)[0]}：</Col>
                    <Col>{v[Object.getOwnPropertyNames(v)[0]]}</Col>
                  </Row>
                ),
              )
            : '暂无'}
        </Descriptions.Item>
      </Descriptions>
      <Descriptions title='价格库存信息' column={1} style={{ marginTop: '10px' }}>
        <Descriptions.Item>
          <Table
            style={{ width: '100%' }}
            bordered
            columns={skuColumns}
            dataSource={skuTableData}
            pagination={false}
          />
        </Descriptions.Item>
      </Descriptions>
      <Descriptions title='配件清单' column={1} style={{ marginTop: '10px' }}>
        <Descriptions.Item>
          <Table
            style={{ width: '100%' }}
            bordered
            columns={[
              {
                title: '名称',
                dataIndex: 'name',
                align: 'center',
              },
              {
                title: '数量',
                dataIndex: 'number',
                align: 'center',
              },
              {
                title: '价格',
                dataIndex: 'price',
                align: 'center',
                render: (text: number) => text.toLocaleString() + '元',
              },
            ]}
            dataSource={rentGoodsDetails?.leasePartsList}
            pagination={false}
          />
        </Descriptions.Item>
      </Descriptions>
      <Descriptions title='物流信息' bordered column={2} style={{ marginTop: '10px' }}>
        <Descriptions.Item label='发货地址'>
          {addressOptionList.find((v) => v.value === rentGoodsDetails?.shipAddress)?.label}
        </Descriptions.Item>
        <Descriptions.Item label='归还地址'>
          {addressOptionList.find((v) => v.value === rentGoodsDetails?.returnAddress)?.label}
        </Descriptions.Item>
        <Descriptions.Item label='寄出物流'>
          {expressOptionList.find((v) => v.value === rentGoodsDetails?.logisticsCompany)?.label}
        </Descriptions.Item>
        <Descriptions.Item label='配送方式'>
          {rentGoodsDetails?.modeOfDeliveryInfo}
        </Descriptions.Item>
      </Descriptions>
      <Descriptions title='商品详情页' column={1} style={{ marginTop: '10px' }}>
        <Descriptions.Item>
          <div
            dangerouslySetInnerHTML={{ __html: rentGoodsDetails?.productDetails || '' }}
            style={{ width: '100%' }}
            className='rent-detail-introduce'
          ></div>
        </Descriptions.Item>
      </Descriptions>
    </div>
  );
};
export default RentDetail;
