import {useEffect, useState} from "react";
import Taro from '@tarojs/taro'
import {Button} from '@nutui/nutui-react-taro'
import {Target, Scan, Truck} from '@nutui/icons-react-taro'
import {getUserInfo} from "@/api/layout";
import navTo from "@/utils/common";
import {pageHjmCar} from "@/api/hjm/hjmCar";
import { ScanType } from '@/hooks/useUnifiedQRScan';
import { isValidJSON } from '@/utils/jsonUtils';
import { parseQRContent, confirmWechatQRLogin } from '@/api/passport/qr-login';
import { getShopGiftByCode, updateShopGift, decryptQrData } from "@/api/shop/shopGift";
import { useUser } from '@/hooks/useUser';
import dayjs from 'dayjs';

const ExpirationTime = () => {
  const [isAdmin, setIsAdmin] = useState<boolean>(false)
  const [roleName, setRoleName] = useState<string>()
  const { isAdmin: isUserAdmin } = useUser();

  // 检测二维码类型
  const detectScanType = (scanResult: string): ScanType => {
    try {
      // 1. 检查是否为JSON格式（核销二维码）
      if (isValidJSON(scanResult)) {
        const json = JSON.parse(scanResult);
        if (json.businessType === 'gift' && json.token && json.data) {
          return ScanType.VERIFICATION;
        }
      }

      // 2. 检查是否为登录二维码
      const loginToken = parseQRContent(scanResult);
      if (loginToken) {
        return ScanType.LOGIN;
      }

      // 3. 检查是否为纯文本核销码（6位数字）
      if (/^\d{6}$/.test(scanResult.trim())) {
        return ScanType.VERIFICATION;
      }

      return ScanType.UNKNOWN;
    } catch (error) {
      console.error('检测二维码类型失败:', error);
      return ScanType.UNKNOWN;
    }
  };

  // 处理登录二维码
  const handleLoginQR = async (scanResult: string) => {
    const userId = Taro.getStorageSync('UserId');
    if (!userId) {
      throw new Error('请先登录小程序');
    }

    const token = parseQRContent(scanResult);
    if (!token) {
      throw new Error('无效的登录二维码');
    }

    const confirmResult = await confirmWechatQRLogin(token, parseInt(userId));
    if (confirmResult.success || confirmResult.status === 'confirmed') {
      Taro.showToast({
        title: '登录确认成功',
        icon: 'success',
        duration: 2000
      });
      return true;
    } else {
      throw new Error(confirmResult.message || '登录确认失败');
    }
  };

  // 处理核销二维码
  const handleVerificationQR = async (scanResult: string) => {
    if (!isUserAdmin()) {
      throw new Error('您没有核销权限');
    }

    let code = '';

    // 判断是否为加密的JSON格式
    if (isValidJSON(scanResult)) {
      const json = JSON.parse(scanResult);
      if (json.businessType === 'gift' && json.token && json.data) {
        // 解密获取核销码
        const decryptedData = await decryptQrData({
          token: json.token,
          encryptedData: json.data
        });

        if (decryptedData) {
          code = decryptedData.toString();
        } else {
          throw new Error('解密失败');
        }
      }
    } else {
      // 直接使用扫码结果作为核销码
      code = scanResult.trim();
    }

    if (!code) {
      throw new Error('无法获取有效的核销码');
    }

    // 验证核销码
    const gift = await getShopGiftByCode(code);

    if (!gift) {
      throw new Error('核销码无效');
    }

    if (gift.status === 1) {
      throw new Error('此礼品码已使用');
    }

    if (gift.status === 2) {
      throw new Error('此礼品码已失效');
    }

    if (gift.userId === 0) {
      throw new Error('此礼品码未认领');
    }

    // 执行核销
    await updateShopGift({
      ...gift,
      status: 1,
      operatorUserId: Number(Taro.getStorageSync('UserId')) || 0,
      takeTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      verificationTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
    });

    Taro.showToast({
      title: '核销成功',
      icon: 'success',
      duration: 2000
    });
    return true;
  };

  const onScanCode = () => {
    Taro.scanCode({
      onlyFromCamera: true,
      scanType: ['qrCode'],
      success: async (res) => {
        console.log(res, 'qrcode...')
        const scanContent = res.result;
        
        // 检测二维码类型
        const scanType = detectScanType(scanContent);
        
        try {
          if (scanType === ScanType.LOGIN) {
            // 处理登录二维码
            await handleLoginQR(scanContent);
            console.log('登录二维码处理成功');
            return;
          } else if (scanType === ScanType.VERIFICATION) {
            // 处理核销二维码
            await handleVerificationQR(scanContent);
            console.log('核销二维码处理成功');
            return;
          }
        } catch (error: any) {
          console.log('特殊二维码处理失败:', error.message);
          Taro.showToast({
            title: error.message,
            icon: 'error',
            duration: 2000
          });
          return;
        }
        
        // 如果不是特殊二维码，作为车辆查询处理
        console.log('作为车辆查询二维码处理:', scanContent);
        Taro.navigateTo({url: '/hjm/query?id=' + scanContent});
      },
      fail: (res) => {
        console.log(res, '扫码失败')
        Taro.showToast({
          title: '扫码失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  }

  const navToCarList = () => {
    if (isAdmin) {
      navTo('/hjm/list', true)
    }
  }

  useEffect(() => {
    getUserInfo().then((data) => {
      if (data) {
        if(data.certification){
          setIsAdmin( true)
        }
        if(Taro.getStorageSync('Certification') == 'jj'){
          setIsAdmin(true)
        }
        if(Taro.getStorageSync('Certification') == 'yz'){
          setIsAdmin(true)
        }
        if(Taro.getStorageSync('RoleCode') == 'Installer'){
          setIsAdmin(true)
        }
        data.roles?.map((item, index) => {
          if (index == 0) {
            setRoleName(item.roleCode)
          }
        })
      }
    })

    pageHjmCar({driverId: Taro.getStorageSync('UserId')}).then(res => {
      if(res?.list && res.list.length > 0){
        setIsAdmin(true)
      }
    })

  }, [])

  return (
    <div className={'mb-3 fixed top-36 z-20'} style={{width: '96%', marginLeft: '3%'}}>
      <div className={'w-full flex justify-around items-center py-3 rounded-lg'}>
        <>
          <Button size={'large'}
                  style={{background: 'linear-gradient(to right, #f3f2f7, #805de1)', borderColor: '#f3f2f7'}}
                  icon={<Truck/>} onClick={navToCarList}>车辆列表</Button>
          <Button size={'large'}
                  style={{background: 'linear-gradient(to right, #fffbe6, #ffc53d)', borderColor: '#f3f2f7'}}
                  icon={<Scan/>}
                  onClick={onScanCode}>扫一扫
          </Button>
        </>

        {
          roleName == 'youzheng' && <Button size={'large'} style={{
            background: 'linear-gradient(to right, #eaff8f, #7cb305)',
            borderColor: '#f3f2f7'
          }} icon={<Target/>} onClick={() => Taro.navigateTo({url: '/hjm/fence'})}>电子围栏</Button>
        }

        {
          roleName == 'kuaidiyuan' && <Button size={'large'} style={{
            background: 'linear-gradient(to right, #ffa39e, #ff4d4f)',
            borderColor: '#f3f2f7'
          }} icon={<Target/>} onClick={() => Taro.navigateTo({url: '/hjm/bx/bx-add'})}>一键报险</Button>
        }
      </div>
    </div>
  )
}
export default ExpirationTime
