import './WasherStart.scss';
import { View, Image } from '@tarojs/components';

import CheckIcon from '../../images/washingmachine/pc_nor_icon@2x.png';
import CheckedIcon from '../../images/washingmachine/pc_sel_icon@2x.png';
import AimiIcon from '../../images/order/pay_aimi_icon@2x.png';
import BeanIcon from '../../images/order/pay_chuifengdou_icon@2x.png';
import WxIcon from '../../images/washingmachine/pay_wechat_icon@2x.png';
import WasherDevice from './components/WasherDevice';
import Taro, { useState, useEffect } from '@tarojs/taro';
import useArrayValue from '@/hooks/useArrayValue';
import { useSelector, useDispatch } from '@tarojs/redux';
import { createWasherOrder } from '@/api/washingMachine';
import { Customer } from '@/types/Customer/Customer';
import {
  WasherStoreState,
  updateWasherOrderInfo,
} from '@/store/rootReducers/washer';
import { ITouchEvent } from '@tarojs/components/types/common';

const WasherStart = () => {
  const dispatch = useDispatch();
  const userInfo = useSelector(
    (state: { userinfo: Customer }) => state.userinfo,
  );
  const data = useSelector(
    (state: { washer: WasherStoreState }) => state.washer.deviceInfo,
  );
  console.log('WasherStart Props:', data);
  const [programId, setProgramId] = useState(0);
  const initOptionProgramIds: number[] = [];
  const [optionProgramIds, setOptionProgramId] = useArrayValue(
    initOptionProgramIds,
  );
  const [paywayId, setPaywayId] = useState(0);
  // const [orderType, setOrderType] = useState(0);

  const goAppointmentPayHandle = (orderType: number) => {
    if (!programId) {
      return Taro.showToast({
        title: '请选择洗衣功能',
        icon: 'none',
      });
    }
    if (!paywayId) {
      return Taro.showToast({
        title: '请选择支付方式',
        icon: 'none',
      });
    }
    // setOrderType(orderType);

    if (data.deviceCode && orderType) {
      Taro.showLoading();
      let modelServiceIds = programId.toString();
      if (optionProgramIds && optionProgramIds.length) {
        modelServiceIds += ',' + optionProgramIds.join(',');
      }
      let ids = modelServiceIds.split(',').map(id => Number(id));
      createWasherOrder({
        customerId: userInfo.customerId,
        customerName: userInfo.customerName,
        customerPhone: userInfo.customerPhone,
        deviceCode: data.deviceCode,
        modelServiceIds: ids,
        orderType: orderType,
        payType: paywayId,
      })
        .then(res => {
          Taro.hideLoading();
          console.log(res.data);
          // setOrderData(res.data);
          dispatch(updateWasherOrderInfo(res.data));
          Taro.navigateTo({
            url: '/pages/WashingMachine/AppointmentPay',
          });
        })
        .catch(err => {
          Taro.hideLoading();
          console.log(err);
          Taro.showToast({
            title: err.msg || '创建订单失败！',
            icon: 'none',
          });
        });
    }
  };
  const goAccountPage = (e: ITouchEvent) => {
    e.stopPropagation();
    Taro.navigateTo({
      url: '/pages/Account/Account',
    });
  };

  return (
    <View className='WasherStart'>
      <View className='WasherStart-content'>
        <WasherDevice
          data={{
            deviceCode: data.deviceCode,
            postion: data.position,
          }}
        />
        <View className='WasherStart-serviceList'>
          <View className='WasherStart-serviceTitle'>请选择洗衣功能</View>
          {data.requiredPrograms &&
            data.requiredPrograms.length &&
            data.requiredPrograms.map(program => (
              <View
                key={program.id}
                className={`WasherStart-serviceItem ${
                  programId === program.id ? 'checked' : ''
                }`}
                onClick={() => setProgramId(program.id)}>
                <View className='WasherStart-serviceName'>
                  {program.name} - {program.duration}分钟
                </View>
                <View className='WasherStart-servicePrice'>
                  {program.price.toFixed(2)}元
                </View>
                <View className='WasherStart-serviceIcon'>
                  {programId === program.id ? (
                    <Image src={CheckedIcon}></Image>
                  ) : (
                    <Image src={CheckIcon}></Image>
                  )}
                </View>
              </View>
            ))}
        </View>
        {data.optionalPrograms && data.optionalPrograms.length && (
          <View className='WasherStart-serviceList'>
            <View className='WasherStart-serviceTitle'>可选功能</View>
            {data.optionalPrograms.map(program => (
              <View
                key={program.id}
                className={`WasherStart-serviceItem ${
                  optionProgramIds.indexOf(program.id) > -1 ? 'checked' : ''
                }`}
                onClick={() => setOptionProgramId(program.id)}>
                <View className='WasherStart-serviceName'>
                  {program.name} - {program.duration}分钟
                </View>
                <View className='WasherStart-servicePrice'>
                  {program.price.toFixed(2)}元
                </View>
                <View className='WasherStart-serviceIcon'>
                  {optionProgramIds.indexOf(program.id) > -1 ? (
                    <Image src={CheckedIcon}></Image>
                  ) : (
                    <Image src={CheckIcon}></Image>
                  )}
                </View>
              </View>
            ))}
          </View>
        )}

        <View className='WasherStart-serviceList'>
          <View className='WasherStart-serviceTitle'>请选择支付方式</View>
          {data.paymentWaysInner &&
            data.paymentWaysInner.length &&
            data.paymentWaysInner.map(payway => (
              <View
                key={payway.paymentWayId}
                className='WasherStart-payItem'
                onClick={() => setPaywayId(payway.paymentWayId)}>
                <View className='WasherStart-payIcon'>
                  {payway.paymentWayId === 6 ? (
                    <Image src={AimiIcon}></Image>
                  ) : (
                    <Image src={BeanIcon}></Image>
                  )}
                </View>
                <View className='WasherStart-serviceName'>
                  {payway.paymentWayName}
                </View>
                {payway.paymentWayId === 6 && (
                  <View className='WasherStart-payBtn' onClick={goAccountPage}>
                    去购买
                  </View>
                )}
                <View className='WasherStart-serviceIcon'>
                  {paywayId === payway.paymentWayId ? (
                    <Image src={CheckedIcon}></Image>
                  ) : (
                    <Image src={CheckIcon}></Image>
                  )}
                </View>
              </View>
            ))}
          {data.paymentWaysOuter &&
            data.paymentWaysOuter.length &&
            data.paymentWaysOuter.map(payway => (
              <View
                key={payway.paymentWayId}
                className='WasherStart-payItem'
                onClick={() => setPaywayId(payway.paymentWayId)}>
                <View className='WasherStart-payIcon'>
                  <Image src={WxIcon}></Image>
                </View>
                <View className='WasherStart-serviceName'>
                  {payway.paymentWayName}
                </View>
                <View className='WasherStart-serviceIcon'>
                  {paywayId === payway.paymentWayId ? (
                    <Image src={CheckedIcon}></Image>
                  ) : (
                    <Image src={CheckIcon}></Image>
                  )}
                </View>
              </View>
            ))}
        </View>
      </View>
      <View className='WasherStart-footer'>
        {data.enabledAppoint && (
          <View
            className='WasherStart-footerItem'
            onClick={() => goAppointmentPayHandle(2)}>
            我要预约
          </View>
        )}
        {data.enabledAppoint && (
          <View className='WasherStart-footerLine'></View>
        )}
        <View
          className='WasherStart-footerItem'
          onClick={() => goAppointmentPayHandle(1)}>
          马上使用
        </View>
      </View>
    </View>
  );
};
WasherStart.config = {
  navigationBarBackgroundColor: '#f9faff',
  navigationBarTitleText: '洗衣',
};
export default WasherStart;
