import React from 'react';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import { Field, Cell, CellGroup } from '@antmjs/vantui';
import LocType from '@/components/LocType';
import IssueType from '@/components/IssueType';
import OrgPicker from '@/components/OrgPicker';
import DatePicker from '@/components/DatePicker';
import Map from '@/components/map';
import Uploader from '@/components/Uploader/index';
import { getDateStr } from '@/utils/date';
import mapIcon from '@/assets/icons/marker.png';
import { getTaOrgIssueByIssueId } from '@/services/taorgissue';
import { PROCESS_END } from '@/utils/biz';
import { geocoder } from '@/utils/map';

import IssueStatus from './IssueStatus';

const today = new Date();

export default (props) => {
  const {
    issueId,
    issue,
    readOnly,
    showOrg,
    showExpireDate,
    renderFields,
    renderAction
  } = props;

  const fmRef = React.useRef({
    typeId: undefined,
    typeName: undefined,
    locId: undefined,
    locName: undefined,
    location: undefined,
    addr: undefined,
    content: undefined,
    attachList: [],
  });
  const [formData, setFormData] = React.useState(fmRef.current);
  const [showLocType, setShowLocType] = React.useState(false);
  const [showIssueType, setShowIssueType] = React.useState(false);
  const [showOrgPicker, setShowOrgPicker] = React.useState(false);
  const [showDatePicker, setShowDatePicker] = React.useState(false);
  const [orgIssue, setOrgIssue] = React.useState();

  // 办结时间
  const endDate = React.useMemo(() => {
    if (!formData) return null;

    // 如果单子办结了就是实际办结时间
    // 否则就是预计办结时间
    return formData.processNode == PROCESS_END ? formData.endDate : formData.expireDate;
  }, [formData]);

  const onLocTypeChange = (_, it) => {
    const data = {
      ...fmRef.current,
      locId: it.typeId,
      locName: it.name,
    }
    fmRef.current = data;
    setFormData(data);
    setShowLocType(false);
  }

  const onIssueTypeChange = (_, it) => {
    const data = {
      ...fmRef.current,
      typeId: it.typeId,
      typeName: it.name,
    }
    fmRef.current = data;
    setFormData(data);
    setShowIssueType(false);
  }

  const onOrgChange = (_, it) => {
    const data = {
      ...fmRef.current,
      orgId: it.orgId,
      orgName: it.name,
    }
    fmRef.current = data;
    setFormData(data);
    setShowOrgPicker(false);
  }

  const onDateChange = (dt) => {
    const date = getDateStr(dt);
    const data = {
      ...fmRef.current,
      expireDate: date,
    }
    fmRef.current = data;
    setFormData(data);
    setShowDatePicker(false);
  }

  const setFieldChange = (field, value) => {
    const data = {
      ...fmRef.current,
      [field]: value,
    }
    fmRef.current = data;
    setFormData(data);
  }

  
  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 (issue) {
      fmRef.current = issue;
      setFormData(issue);
      // console.log('---------issue-------->', issue)
      getTaOrgIssueByIssueId(issue.issueId, issue.orgId).then(r => {
        setOrgIssue(r);
      });

    }
  }, [issue]);

  // console.log('showIssueType', showIssueType)
  // console.log('readOnly', readOnly)
  return (
    <View>
      <LocType
        show={showLocType}
        value={formData.locId}
        onCancel={() => setShowLocType(false)}
        onChange={onLocTypeChange}
      />

      <IssueType
        show={showIssueType}
        value={formData.typeName}
        onCancel={() => setShowIssueType(false)}
        onChange={onIssueTypeChange}
      />

      <OrgPicker
        show={showOrgPicker}
        value={formData.orgName}
        onCancel={() => setShowOrgPicker(false)}
        onChange={onOrgChange}
      />

      <DatePicker
        type="date"
        minDate={today}
        show={showDatePicker}
        value={formData.expireDate}
        onCancel={() => setShowDatePicker(false)}
        onChange={onDateChange}
      />

      {/* 地图只在新增的时候允许修改 */}
      <Map
        readOnly={!!issueId}
        location={formData.location}
        onChange={onLocationChange}
      />

      <CellGroup>
        {
          issue?.issueId && (
            <Cell
              title="ID"
              value={issue.issueId}
            />
          )
        }
        <Cell
          title="点位"
          isLink={!readOnly}
          value={formData.locName}
          onClick={() => !readOnly && setShowLocType(true)}
        />
        <Field
          placeholder="请输入地址"
          value={formData.addr}
          leftIcon={mapIcon}
          readonly={readOnly}
          onChange={e => setFieldChange('addr', e.detail)}
        />
      </CellGroup>

      {
        readOnly && (
          <CellGroup style={{ marginTop: '20px' }}>
            <IssueStatus issue={issue} />
          </CellGroup>
        )
      }


      <CellGroup style={{ marginTop: '20px' }}>
        <Cell
          title="问题分类"
          isLink={!readOnly}
          style={{ marginTop: '20px' }}
          value={formData.typeName}
          onClick={() => !readOnly && setShowIssueType(true)}
        />
        <Cell title="问题描述" border={false} />

        <Field
          type="textarea"
          placeholder="请输入问题描述"
          readonly={readOnly}
          autosize={{ minHeight: '120px' }}
          value={formData.content}
          onChange={e => setFieldChange('content', e.detail)}
        />
      </CellGroup>

      <CellGroup style={{ marginTop: '20px' }}>
        <Cell title="拍照或视频" border={false} />

        <Cell
          renderTitle={
            <Uploader
              value={formData.attachList}
              disabled={readOnly}
              onChange={e => setFieldChange('attachList', e)}
            />
          }
        />
      </CellGroup>

      {
        (showOrg || showExpireDate) && (
          <CellGroup style={{ marginTop: '20px' }}>
            {
              showOrg && (
                <Cell
                  title="交办单位"
                  isLink={!readOnly}
                  value={formData.orgName}
                  onClick={() => !readOnly && setShowOrgPicker(true)}
                />
              )
            }
            {
              showExpireDate && (
                <Cell
                  title="办结时间"
                  isLink={!readOnly}
                  value={endDate}
                  onClick={() => !readOnly && setShowDatePicker(true)}
                />
              )
            }
          </CellGroup>
        )
      }

      {
        orgIssue && issue?.processNode == PROCESS_END && (
          <CellGroup style={{ marginTop: '20px' }}>
            <Cell title="整改结果" />
            <Field
              readonly
              type="textarea"
              autosize={{ minHeight: '120px' }}
              value={orgIssue?.result}
            />

            <Cell title="整改照片" border={false} />
            <Cell
              renderTitle={
                <Uploader
                  disabled
                  value={orgIssue?.attachList}
                />
              }
            />
          </CellGroup>
        )
      }

      {
        renderFields ?
          renderFields(
            formData,
            {
              setFieldChange,
              setFormData,
              showOrgPicker,
              setShowOrgPicker,
            }
          ) : null
      }

      {
        renderAction ? (
          <View style={{ margin: '20px auto' }}>
            {renderAction(formData)}
          </View>
        ) : null
      }
    </View>
  )
}
