import {
  Button,
  Col,
  Image,
  message,
  Modal,
  Row,
  Space,
  InputNumber,
} from 'antd'
import { Dispatch, SetStateAction, useEffect, useState } from 'react'
import errImg from '~/assets/errImg'
import { GetLeaseGoodsDetailResp, ProductSpecList } from '../../api'
import styles from './index.module.scss'
import api from './api'
import Item from 'antd/es/list/Item'

type Props = {
  open?: boolean
  onOk?: () => void
  onCancel: () => void
  detail: GetLeaseGoodsDetailResp | null
  setIsorderForGoods: Dispatch<SetStateAction<boolean>>
  setMallDetail: Dispatch<SetStateAction<any>>
}
export default function IntentionModal(props: Props) {
  const [checkedMap, setCheckedMap] = useState<{ string?: boolean }>({}) //通过索引记录选中的产品规格 例: {'1,1': true|false} props.detail?.goodsSpec[1].productSpecList[1]
  const [checkItems, setCheckItems] = useState<ProductSpecList[]>([]) //选中的规格
  const [loading, setLoading] = useState(false) //下单中
  const [numValue, setNumValue] = useState<number | null>(1) //数量

  useEffect(() => {
    let list: ProductSpecList[] = []
    Object.keys(checkedMap).forEach((key) => {
      if (checkedMap[key as keyof typeof checkedMap]) {
        let arr = key.split(',')
        let item =
          props.detail?.goodsSpec[Number(arr[0])].productSpecList[
            Number(arr[1])
          ]
        if (item) {
          list.push(item)
        }
      }
    })
    setCheckItems(list)
    setNumValue(1)
  }, [checkedMap])

  //添加规格到购物车
  function addProductSpec(goodsSpecIndex: number, productSpecIndex: number) {
    let temp = {}
    //@ts-ignore
    temp[`${goodsSpecIndex},${productSpecIndex}`] =
      //@ts-ignore
      !checkedMap[`${goodsSpecIndex},${productSpecIndex}`]

    setCheckedMap({
      ...checkedMap,
      ...temp,
    })
  }
  //数量
  const onChangeNum = (value: number | null) => {
    console.log('changed', value)
    setNumValue(value)
  }

  //提交
  function onSubmit() {
    let buyNum = 0
    let mallSpecIds: number[] = []
    Object.keys(checkedMap).forEach((key) => {
      if (checkedMap[key as keyof typeof checkedMap]) {
        buyNum++
        let arr = key.split(',')
        let specId =
          props.detail?.goodsSpec[Number(arr[0])].productSpecList[
            Number(arr[1])
          ].id
        if (specId) {
          mallSpecIds.push(specId)
        }
      }
    })
    if (buyNum > 0) {
      setLoading(true)
      api
        .commitMallOrder({
          buyNum: numValue || 1,
          directoryId: 1,
          goodsInfoId: props.detail!.id,
          mallSpecIds,
          userAddressId: 1,
        })
        .then((res) => {
          if (res.code == '200') {
            // message.success('提交意向成功')

            //重置为未选中
            let temp = {
              ...checkedMap,
            }
            Object.keys(temp).forEach((key) => {
              temp[key as keyof typeof temp] = false
            })
            setCheckedMap(temp)
            props.onCancel()
            props.setIsorderForGoods(true)
            props.setMallDetail({
              ...res.result,
              buyNum: numValue || 1,
              directoryId: 1,
              goodsInfoId: props.detail!.id,
              mallSpecIds,
              userAddressId: 1,
            })
          } else {
          }
          setLoading(false)
        })
        .catch((err) => {
          message.error('提交意向失败')
          console.log('err', err)
          setLoading(false)
        })
    }
  }

  return (
    <Modal
      open={props.open}
      onOk={props.onOk}
      onCancel={props.onCancel}
      width={420}
      style={{ padding: 0 }}
      className={styles.model}
      footer={
        <div style={{ padding: '13px 36px' }}>
          <Button
            type="primary"
            className={styles.font5}
            style={{ width: '100%', height: 44 }}
            onClick={onSubmit}
            loading={loading}
          >
            提交意向
          </Button>
        </div>
      }
    >
      <Row style={{ padding: '22px 39px 12px 39px' }} wrap={false}>
        <Col>
          <Image
            width={100}
            height={100}
            fallback={errImg}
            style={{ borderRadius: 8 }}
            src={props.detail?.images?.[0]?.imgUrl}
          ></Image>
        </Col>
        <Col flex="auto" style={{ marginLeft: 13, width: 230 }}>
          <div
            className={`${styles.font1} ${styles.ellipsis1}`}
            style={{ marginTop: 28 }}
          >
            {props.detail?.goodsName}
          </div>
          <div
            className={`${styles.font2} ${styles.ellipsis2}`}
            style={{ marginTop: 7 }}
          >
            已选:{' '}
            {checkItems
              .map((item) => {
                return item.specName
              })
              .join('+')}
          </div>
        </Col>
      </Row>
      <div style={{ paddingRight: 13 }}>
        <div className={styles.specsContent}>
          <div className={styles.font3} style={{}}>
            无人机
          </div>
          {props.detail?.goodsSpec?.map((item, goodsSpecIndex) => {
            return (
              <div key={item.id}>
                <div
                  className={styles.font2}
                  style={{ marginBottom: 5, marginTop: 11 }}
                >
                  {item.goodsSpecName}
                </div>
                <Space size={10} direction="vertical" style={{ width: '100%' }}>
                  {item.productSpecList?.map((product, productSpecIndex) => {
                    return (
                      <Row
                        key={product.id}
                        align="middle"
                        wrap={false}
                        style={{
                          borderRadius: 5,
                          //@ts-ignore
                          border: checkedMap[
                            `${goodsSpecIndex},${productSpecIndex}`
                          ]
                            ? '1px solid #FF552D'
                            : '1px solid #d6d6d6',
                          height: 50,
                          cursor: 'pointer',
                        }}
                        onClick={() =>
                          addProductSpec(goodsSpecIndex, productSpecIndex)
                        }
                      >
                        <Col style={{ marginLeft: 7 }}>
                          <Image
                            width={52}
                            height={36}
                            src={product.specImage}
                            fallback={errImg}
                            preview={false}
                          ></Image>
                        </Col>
                        <Col
                          className={`${styles.ellipsis1} ${styles.font4}`}
                          style={{ width: 238, marginLeft: 18 }}
                        >
                          {product.specName}
                        </Col>
                      </Row>
                    )
                  })}
                </Space>
              </div>
            )
          })}
          <div className={styles.numBox}>
            <div className={styles.numLeft}>
              <div className={styles.label}>数量</div>
            </div>
            <div className={styles.numRight}>
              <InputNumber
                min={1}
                max={100}
                value={numValue}
                onChange={onChangeNum}
              />
            </div>
          </div>
        </div>
      </div>
    </Modal>
  )
}
