import React from 'react';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import { CellGroup, Cell, Field } from '@antmjs/vantui';
import Map from '@/components/map';
import { getTaCheckItemAnswer } from '@/services/tacheckitem';
import mapIcon from '@/assets/icons/marker.png';
import { geocoder } from '@/utils/map';

export default (props) => {
  const { checkItemInfo, answer, readonly, onChange, onLoadingChange } = props;

  const setLoading = (v) => {
    if (onLoadingChange) {
      onLoadingChange(v)
    }
  }
  
  const setFieldChange = (key, val) => {
    onChange({
      ...answer || {},
      [key]: val,
    })
  }
  
  const onLocationChange = (loc) => {
    setFieldChange('location', loc);

    if (loc) {
      // 交换经纬度位置
      const [x, y] = loc.split(',');
      const location = [y, x].join(',');
      geocoder(location).then(e => setFieldChange('addr', e?.address_component?.street_number || e?.address)).catch(console.error)
    }
  }

  // 获取答题主记录信息
  React.useEffect(() => {
    if (checkItemInfo?.itemId) {
      setLoading(true);
      getTaCheckItemAnswer(checkItemInfo?.itemId).then((res) => {
        if (res) {
          onChange(res);
        }
        setLoading(false);
      }).catch(() => {
        setLoading(false);
      });
    }
  }, [checkItemInfo?.itemId])
  
  return (
    <View>
      <Map
        readOnly={readonly}
        location={answer?.location}
        onChange={onLocationChange}
      />
      <CellGroup>
        <Cell
          title="点位"
          value={checkItemInfo?.name}
        />
        <Field
          readonly={readonly}
          placeholder="请输入地址"
          value={answer?.addr}
          leftIcon={mapIcon}
          onChange={e => setFieldChange('addr', e.detail)}
        />
      </CellGroup>
    </View>
  )
}
