import withLayout from '@/layouts'
import Taro, { useDidShow } from '@tarojs/taro'
import CustomNav from '@/components/CustomNav'
import { View, Input, Button, Label, Textarea, Text, Image } from '@tarojs/components';
import { useEffect, useState } from "react"
import { saveRoom, getRoomDetail, updateRoom } from '@/services/landlord'
import GPS from '@/assets/icons/GuideCheck/GPS.png'
import { getExtendContent } from "@/services/home";
import { saveExtend } from '@/services/landlord'
//export default是导出模块的   export也是导出模块的    如果引用时不加{}就是引用默认模块加了就是引用相应的模块
import { uploadFile } from '@/utils/request'
import Popup from '@/components/Popup'
import Extend from "../../components/Extend";
import './addRoom.less'


export default withLayout((props) => {
  const { hotelId, hotelName, roomId } = props.router.params
  const [roomModel, setRoomModel] = useState({
    hotelId,
    roomName: '',
    address: '',
    location: '',
    parkingAddress: '',
    parkingLocation: '',
    wifiName: '',
    wifiPassword: '',
    weight: '',
    locName: '',
    pkLocName: ''
  })
  const [paddress, setpAddress] = useState()
  const [wifiName, setwifiName] = useState()

  const onRoomMap = () => {
    Taro.chooseLocation().then((res) => {
      setRoomModel({ ...roomModel, location: res.longitude + ',' + res.latitude, locName: res.name, address: res.address })
    })
  }

  const onParkMap = () => {
    Taro.chooseLocation().then((res) => {
      setRoomModel({ ...roomModel, parkingLocation: res.longitude + ',' + res.latitude, pkLocName: res.name, parkingAddress: res.address })
    })
  }
  const sumbit = () => {
    if (
      roomModel.roomName != null &&
      roomModel.roomName != '' &&

      roomModel.address != null &&
      roomModel.address != '' &&

      roomModel.location != null &&
      roomModel.location != '' &&

      roomModel.weight != null &&
      roomModel.weight != ''

    ) {
      const seveices = roomId ? updateRoom : saveRoom
      seveices(roomModel, roomId).then(() => {
        Taro.showModal({
          title: roomId ? '修改成功' : '保存成功',
          showCancel: false
        }).then(() => {
          Taro.navigateBack()
        })
      })
    } else {
      Taro.showToast({
        title: '有必填项未填哦',
        icon: 'none',
      })
    }
  }
  const [extend, setExtend] = useState([]);
  useEffect(() => {
    if (roomId) {
      getRoomDetail(roomId).then((res) => {
        setRoomModel(res)
        setpAddress(res.parkingAddress)
        setwifiName(res.wifiName)
      })
    }
  }, [roomId])//这个地方写这个单词的目的是   因为编辑时roomId有可能还没加载成功
  const [reset, setReset] = useState(false)
  useEffect(() => {
    if (roomId) {
      getExtendContent('room', roomId, { pageSize: 999 }).then((res) => {
        setExtend(res.records || []);
      })
      setReset(false)
    }
  }, [reset])

  //新增文字
  const [showCutover, setShowCutover] = useState(false)
  const [cont, setcont] = useState('')
  const onClose = () => {
    setShowCutover(false)
  }
  //判断是否只有空 空格 回车
  const javaTrim = (str) => {
    for (var i = 0; (str.charAt(i) == ' ') && i < str.length; i++);
    if (i == str.length) return ''; //whole string is space
    var newstr = str.substr(i);
    for (var i = newstr.length - 1; newstr.charAt(i) == ' ' && i >= 0; i--);
    newstr = newstr.substr(0, i + 1);
    return newstr;
  }
  const handelAdd = () => {
    var content = document.getElementById('cont').value

    content = content.replace(/\n/g, '');
    if (javaTrim(content) == '') {
      Taro.showToast({
        title: '您还没有添加文字哦',
        icon: 'none'
      })
      return;
    }
    const date = {
      targetId: roomId,
      targetType: 'room',
      content,
      contentType: 'text'
    }

    saveExtend(date)
    setcont('')
    onClose()
    setReset(!reset)
  }
  const showText = () => {
    setShowCutover(true)
    setcont('')
  }
  const addImage = () => {
    Taro.chooseImage({
      count: 1,
      success: function (res) {
        uploadFile(res.tempFilePaths[0]).then((res2) => {
          const date = {
            targetId: roomId,
            targetType: 'room',
            content: res2,
            contentType: 'image'
          }
          saveExtend(date)
          setReset(!reset)
        })
      }
    })
  }
  const isError = (s) => {
    if (!s) { return true }
    else {
      // 根据,(逗号)进行分割
      let split = s.split(",");
      if (split.length != 2) {
        return true
      } else {
        if (!split[0] || !split[1]) {
          return true
        }
      }
    }
    return false
  }
  return (
    <view className='page-index'>
      <view className='index-navbar'>
        <CustomNav title={hotelName} />
      </view>
      <view className='roomDetail' style={{ height: '100%', overflow: "hidden", }} >
        <scroll-view scrollY style={{ height: '100%' }}>
          <View id='det'>
            <Popup show={showCutover} onClose={onClose}>
              <View className='editword'>
                <View style={{ marginBottom: '25px' }}>
                  <View className='rzline' /><Label className='srl mg'>新增文字</Label><View className='rzline' />
                </View>
                <View>
                  <Textarea className='storezn' id='cont' value={cont} placeholder='请输入准备新增的文字' />
                </View>
                <View>
                  <Button className='cancel' onClick={onClose}>取消</Button>
                  <Button className='btn' onClick={handelAdd}>确认增加</Button>
                </View>
              </View>
            </Popup>
          </View>
          <mp-form models={roomModel} >
            <mp-cells title='房屋名称' footer='' ext-class='cells' >
              <mp-cell>
                <Input style={{ fontWeight: 'bold' }} onInput={(e) => setRoomModel({ ...roomModel, roomName: e.detail.value })} value={roomModel.roomName} placeholder='请输入房屋名称（必填）' />
              </mp-cell>
            </mp-cells>
            <mp-cells title='房屋位置'>
              <mp-cell>
                <View className='roomloc'>
                  <Label style={{ color: '#666', lineHeight: '30px' }} onClick={onRoomMap} >{roomModel.locName || '请选择定位'}</Label>
                  <Textarea style={{ height: '60px', width: '100%' }} onInput={(e) => setRoomModel({ ...roomModel, address: e.detail.value })} value={roomModel.address} placeholder='请输入房屋位置（必填）' />
                  <Label style={{ display: 'none' }} >{isError(roomModel.location) ? '房间定位（必填）' : roomModel.location}</Label>
                  <Image className='location' src={GPS} onClick={onRoomMap} />
                </View>
              </mp-cell>
            </mp-cells>
            {
              paddress != '' ?
                <mp-cells title='停车场位置'>
                  <mp-cell>
                    <View className='roomloc'>
                      <Label style={{ color: '#666', lineHeight: '30px' }} onClick={onParkMap}>{roomModel.pkLocName || '请选择定位'}</Label>
                      <Textarea style={{ height: '60px', width: '100%' }} onInput={(e) => setRoomModel({ ...roomModel, parkingAddress: e.detail.value })} value={roomModel.parkingAddress} placeholder='请输入停车场位置' />
                      <Label style={{ display: 'none' }}>{isError(roomModel.parkingLocation) ? '停车场定位' : roomModel.parkingLocation}</Label>
                      <Image className='location' src={GPS} onClick={onParkMap} />
                    </View>
                  </mp-cell>
                </mp-cells> : null
            }
            {
              wifiName != '' ?
                <mp-cells title='WiFi信息'>
                  <mp-cell>
                    <View style={{ color: '#666' }}>
                      <Input style={{ display: 'inline-block', background: '#fff', width: '20%' }} value='名称：' disabled /><Input style={{ display: 'inline-block', width: '80%' }} onInput={(e) => setRoomModel({ ...roomModel, wifiName: e.detail.value })} value={roomModel.wifiName} placeholder='请输入wifi名称' />
                      <Input style={{ display: 'inline-block', background: '#fff', width: '20%' }} value='密码：' disabled /><Input style={{ display: 'inline-block', width: '80%' }} onInput={(e) => setRoomModel({ ...roomModel, wifiPassword: e.detail.value })} value={roomModel.wifiPassword} placeholder='请输入wifi密码' />
                    </View>
                  </mp-cell>
                </mp-cells> : null
            }
            <mp-cells title='权重'>
              <mp-cell>
                <input type='number' value={roomModel.weight} onInput={(e) => setRoomModel({ ...roomModel, weight: e.detail.value })} placeholder='请输入权重（必填）' />
              </mp-cell>
            </mp-cells>
            {roomId ? <>
                <view className='weui-cells__title'>其他指引</view>
                {
                  extend == '' ? null :
                    <>
                      {extend.map((item) => (
                        <Extend key={item.extId} item={item} setReset={setReset} />
                      ))}
                    </>
                }
            </> : null
            }
          </mp-form>
          {roomId ? <>
            <View className='adds' >
              <Text className='zuobian'>增加文字</Text>
              <View className='add' onClick={showText}><Text className='jiahao'>+</Text><Text className='zengjia'>添加</Text></View>
            </View>
            <View className='adds' >
              <Text className='zuobian'>增加图片</Text>
              <View className='add' onClick={addImage}><Text className='jiahao'>+</Text><Text className='zengjia'>添加</Text></View>
            </View>
          </> : null
          }
          <Button className='button-OK' onClick={sumbit}>确定</Button>
        </scroll-view>
      </view>
    </view>
  )
})