import React from 'react';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import Page from '@/layouts/index';
import { Cell, CellGroup, Field, Button } from '@antmjs/vantui';
import DatePicker from '@/components/DatePicker';
import { getDateStr } from '@/utils/date';
import { postTaIssueApply } from '@/services/taissueapply';
import { warn } from '@/utils/message';
import { PROCESS_APPLY_DELAY } from '@/utils/biz';
import Issue from '../components/Issue';
import useTitle from '../useTitle';

const today = new Date();
export default (props) => {

  const router = Taro.useRouter();
  const { issueId, applyType } = router.params;

  const [loading, setLoading] = React.useState(false); 
  const [submitting, setSubmitting] = React.useState(false);
  const [formData, setFormData] = React.useState({});
  const [showDatePicker, setShowDatePicker] = React.useState(false);
  
  useTitle(applyType);

  const setFieldValue = (key, value) => {
    setFormData({
      ...formData,
      [key]: value,
    })
  }
  
  const onDateChange = (dt) => {
    const date = getDateStr(dt);
    setFieldValue('content', date);
    setShowDatePicker(false);
  }

  const onSubmit = () => {
    try {
      if (applyType == PROCESS_APPLY_DELAY) {
        warn(!formData.content, '请选择延期时间');
      }
      warn(!formData.remark, '请填写申请说明');
    } catch (e) {
      return ;
    }

    const data = {
      issueId,
      applyType,
      ...formData
    }

    setSubmitting(true);
    postTaIssueApply(data).then(() => {
      Taro.navigateBack({delta: 1});
      setSubmitting(false);
    }).catch(() => {
      setSubmitting(false);
    })
  }
  
  
  return (
    <Page loading={loading}>
      <Issue issueId={issueId} onLoading={setLoading} />
      
      <DatePicker
        type="date"
        minDate={today}
        show={showDatePicker}
        value={formData.content}
        onCancel={() => setShowDatePicker(false)}
        onChange={onDateChange}
      />

      <CellGroup style={{marginTop: '20px'}}>
        {
          applyType == PROCESS_APPLY_DELAY && (
            <Cell
              isLink
              title="延期时间"
              value={formData.content}
              onClick={() => setShowDatePicker(true)}
            />
          )
        }
        <Cell title="申请说明" />
        <Field
          type="textarea"
          autosize={{ minHeight: '120px' }}
          value={formData.remark}
          onChange={e => setFieldValue('remark', e.detail)}
        />
      </CellGroup>
      <View style={{marginTop: '20px', padding: 'var(--main-space)'}}>
        <Button block type="primary" loading={submitting} onClick={onSubmit}>提交申请</Button>
      </View>
    </Page>
  )
}
