import Taro from "@tarojs/taro";
import { Button, View } from "@tarojs/components";
import { useState, useEffect } from "react";
import withLayout from "@/layouts";
import CustomNav from "@/components/CustomNav";
import { getShopDetail } from '@/services/home';
import { getVerifyTargetList, putVerifyTarget } from "@/services/payOrder";
import Popup from "@/components/Popup";
import SpinBox from "@/components/Spin/SpinBox";

import LocationBig from "@/assets/icons/UserCenter/LocationBig.png";
import Perfection from "@/assets/icons/UserCenter/Perfection.png";
import BlackSpot from "@/assets/icons/GuideCheck/BlackSpot.png";
import TBCard from './Card'

import "./style.less";

export default withLayout((props) => {
  const { router, person, location } = props;
  const { id, subOrderId } = props.router.params;
  const [submiting, setSubmiting] = useState(false)
  const [showDialog, setShowDialog] = useState(false);
  //核销
  const [Consumption, setConsumption] = useState(false);

  const [checked, setChecked] = useState([]);
  const [shopContent, setShopContent] = useState([])

  const [loading, setLoading] = useState(false)
  const [list, setList] = useState([]);


  const getShop = () => {
    getShopDetail(id, { location: location }).then(e => {
      setShopContent(e)

    })
  }

  const getList = (params) => {
    setLoading(true)
    getVerifyTargetList({
      shopId: id,
      isMine: true,
      isVerified: 0,
      pageNum: 1,
      pageSize: 50,
    }).then((res) => {
      if (res) {
        setList(res.records)

        if (res.records && res.records.length > 0) {
          if (res.records.length === 1) {
            setChecked([res.records[0].verifyNo])
          } else {
            setChecked([res?.records.filter(x => x.subOrderId == subOrderId)[0]?.verifyNo].filter(Boolean))
          }
        } else {
          Taro.navigateBack({ delta: 1 })
        }
      }

      setLoading(false)
    }).catch(() => setLoading(false));
  };

  useEffect(() => {
    if (id) {
      getList();
      getShop();
    }
  }, [id]);

  const handleCheck = (verifyNo) => {
    const inx = checked.indexOf(verifyNo)
    if (inx === -1) {
      setChecked([...checked, verifyNo])
    } else {
      const p1 = checked.slice(0, inx)
      const p2 = checked.slice(inx + 1)
      setChecked(p1.concat(p2))
    }
  }

  const handleVerifyClick = () => {
    if (!checked || !checked.length) {
      Taro.showToast({
        title: '请选择待核销套餐',
        icon: 'none',
      })

      return;
    }

    setShowDialog(true);
  };
  const ButtonCancel = () => {
    setShowDialog(false);
  };
  const ButtonOK = (e) => {
    if (!submiting) {

      setSubmiting(true);
      Promise.all(checked.map(verifyNo => putVerifyTarget(verifyNo)))
        .then(res => {

          setSubmiting(false);
          setShowDialog(false);
          setConsumption(true);
        })
        .catch(e => {

          setShowDialog(false);
          setSubmiting(false);
          getList();  // 刷新数据
          Taro.showToast({
            title: '核销失败',
            icon: 'none',
            duration: 2000
          })
        })
    }
  };

  const PerfectionOK = () => {
    setConsumption(false);
    if (list?.length > 1) {
      getList()
    } else {
      Taro.redirectTo({
        url: '/pages/MineUserAll/AllOrder/index?tabJump=3',
      });
      // Taro.navigateBack({ delta: 1 })
    }
  };

  const btnText = ['确认核销', checked && checked.length > 0 ? `(${checked.length})` : undefined].filter(Boolean).join(' ')
  return (
    <view className='page-index shop-Eat'>
      <view className='index-navbar'>
        <CustomNav title='到店核销' />
      </view>
      <Popup show={showDialog} maskClosable={false}>
        <View className='Consumption-Now'>真的要翻我的牌子吗？</View>
        <View className='Consumption-text'>核销后套餐券不退不换,</View>
        <View className='Consumption-text'>请核对无误后再点击确认。</View>
        <view className='buy-button-box'>
          <button className='button-Cancel' onClick={ButtonCancel}>
            取消
          </button>
          <button className='button-OK' onClick={ButtonOK} loading={submiting}>
            确定
          </button>
        </view>
      </Popup>
      <Popup show={Consumption} maskClosable={false}>
        <view className='Perfection-image-view'>
          <image src={Perfection} className='Perfection-image' />
          <View>
            <text className='tleft'>请和店员说一下：</text><text className='tright'>“我核销好了”</text>
          </View>
        </view>
        <view className='buy-button-box'>
          <button className='button-OK' onClick={PerfectionOK}>
            说过了
          </button>
        </view>
      </Popup>
      <view>
        <view className='position-header'>
          <image className='position-LocationBig' src={LocationBig} />
          <text cla='position-LocationBig-text'>
            当前所在店铺：{shopContent?.shopName || []}
          </text>
        </view>
        <view className='shop-image'>
          <image
            mode='scaleToFill'
            className='shop-title-image-cup'
            src={BlackSpot}
          />
          <text className='shop-title-title'>请选择你要核销的套餐</text>
        </view>
        <SpinBox loading={loading}>
          {(list || []).map((item) => {
            return (
              <TBCard item={item} key={item.verifyNo} checked={checked} handleCheck={handleCheck} />
            )
          })}
        </SpinBox>
        <view className='button-info'>
          <Button className='button-box' onClick={handleVerifyClick}>
            {btnText}
          </Button>
        </view>
      </view>
    </view>
  );
});
