import React from 'react';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import Page from '@/layouts/index';
import { Cell, CellGroup, Field, Button, Radio, RadioGroup, Dialog } from '@antmjs/vantui';
import Uploader from '@/components/Uploader/index';
import { putTaIssueApply, getTaIssueApplyById } from '@/services/taissueapply';
import { warn } from '@/utils/message';
import { APPLY_PASS, APPLY_REJECT, PROCESS_APPLY_DELAY, PROCESS_APPLY_REJECT } from '@/utils/biz';
import { getTaOrgIssueByIssueId } from '@/services/taorgissue';
import { copyTaIssue, getTaIssueById } from '@/services/taissue';
import { getSysOrgById } from '@/services/sysorg';
import Issue from '../components/Issue';
import useTitle from '../useTitle';

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

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

  const [loading, setLoading] = React.useState(false);
  const [applyInfo, setApplyInfo] = React.useState({});
  const [orgIssue, setOrgIssue] = React.useState({});

  const [submitting, setSubmitting] = React.useState(false);
  const [formData, setFormData] = React.useState({});

  const dialogId = React.useMemo(() => `dialog-${Math.random().toString(36).substring(2, 7)}`, []);
  const [loading2, setLoading2] = React.useState(false);
  const [issue, setIssue] = React.useState();

  useTitle(applyType);

  const setFieldValue = (key, value) => {
    setFormData({
      ...formData,
      [key]: value,
    })
  }

  const onSubmit = () => {
    try {
      warn(!formData.verifyStatus, '请选择审批结果');
      warn(!formData.verifyDesc && formData.verifyStatus == 'reject', '请填写审批说明');
    } catch (e) {
      return;
    }

    const data = {
      ...applyInfo,
      ...formData
    }

    setSubmitting(true);
    putTaIssueApply(data.applyId, data).then((res) => {
      setSubmitting(false);
      if (formData.verifyStatus == APPLY_PASS) {
        if (applyInfo.applyType == PROCESS_APPLY_REJECT) {
          // Dialog 有 bug,
          // 使用 setTimeout 延迟一会规避一下
          const t = setTimeout(() => {
            clearTimeout(t);
            Dialog.confirm({
              title: '审批通过',
              message: `确定要跳转问题单详情页吗？`,
              selector: dialogId,
            }).then((value2) => {
              if ('confirm' === value2) {
                Taro.navigateTo({
                  url: `/pages/issue/edit/index?id=${res.issueId}`
                })
              }
            });
          }, 500);
        } else {
          Taro.navigateBack({ delta: 1 });
        }
      }
    }).catch(() => {
      setSubmitting(false);
    })
  }

  React.useEffect(() => {
    if (id) {
      setLoading(true);
      getTaIssueApplyById(id).then(res => {
        setApplyInfo(res);

        getTaOrgIssueByIssueId(res.issueId, res.orgId).then(r => {
          setOrgIssue(r);
        });

        setLoading(false);
      }).catch(() => {
        setLoading(false);
      });
    }

    if (id) {
      setLoading(true)
      getTaIssueById(id).then(res => {
        setLoading(false);
        if (res.orgId) {
          getSysOrgById(res.orgId).then(r => {
            setIssue({
              ...res,
              orgName: r?.name
            });
          }).catch(() => {
            setIssue(res);
          })
        } else {
          setIssue(res);
        }
      }).catch(() => {
        setLoading(false);
      });
    }
  }, [id]);

  // 复制
  const onCopy = () => {
    console.log('<------------------------------------>')
    Dialog.confirm({
      title: '复制问题单',
      message: '确认复制当前问题单?',
      selector: dialogId,
    }).then((value) => {
      // console.log('2value', value);
      if ('confirm' === value) {
        setLoading2(true)
        copyTaIssue(issue.issueId).then(res => {
          setLoading2(false)

          // Dialog 有 bug,
          // 使用 setTimeout 延迟一会规避一下
          const t = setTimeout(() => {
            clearTimeout(t);
            Dialog.confirm({
              title: '复制成功',
              message: `新问题单号: ${res.issueId}, 是否跳转`,
              selector: dialogId,
            }).then((value2) => {
              if ('confirm' === value2) {
                Taro.navigateTo({
                  url: `/pages/issue/edit/index?id=${res.issueId}`
                })
              }
            });
          }, 200);
        }).catch(() => {
          setLoading2(false)
        })
      }
    })
  }
  // console.log('applyInfo', applyInfo);

  return (
    <Page loading={loading}>
      <Dialog id={dialogId} />
      <Issue issueId={issueId} />

      {
        applyInfo.applyType == PROCESS_APPLY_DELAY && (
          <CellGroup style={{ marginTop: '20px' }}>
            <Cell
              title="延期日期"
              value={applyInfo.content}
            />
            <Cell title="申请说明" />
            <Field
              readonly
              type="textarea"
              autosize={{ minHeight: '120px' }}
              value={applyInfo.remark}
            />
          </CellGroup>
        )
      }

      {
        applyInfo.applyType == PROCESS_APPLY_REJECT && (
          <CellGroup style={{ marginTop: '20px' }}>
            <Cell title="申请说明" />
            <Field
              readonly
              type="textarea"
              autosize={{ minHeight: '120px' }}
              value={applyInfo.remark}
            />
          </CellGroup>
        )
      }

      {
        applyInfo.applyType != PROCESS_APPLY_DELAY && applyInfo.applyType != PROCESS_APPLY_REJECT && (
          <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>
        )
      }

      <CellGroup style={{ marginTop: '20px' }}>
        <Cell
          title="审批结果"
        >
          <RadioGroup
            direction="horizontal"
            value={formData.verifyStatus}
            onChange={(e) => setFieldValue('verifyStatus', e.detail)}
          >
            <Radio name={APPLY_PASS} checkedColor="var(--main-bg-color)">通过</Radio>
            <Radio name={APPLY_REJECT} checkedColor="red">驳回</Radio>
          </RadioGroup>
        </Cell>
        <Cell title="审批说明" />
        <Field
          type="textarea"
          autosize={{ minHeight: '120px' }}
          value={formData.verifyDesc}
          onChange={(e) => setFieldValue('verifyDesc', e.detail)}
        />
      </CellGroup>
      <CellGroup>
        <View style={{ marginTop: '20px', display: 'flex' }}>
          <Button block type="primary" loading={submitting} onClick={onSubmit} style={{ flex: 5, marginLeft: 'var(--main-space)' }}>审 批</Button>
          <Button block type="info" loading={loading2} onClick={onCopy} style={{ flex: 1, margin: '0 var(--main-space)' }}>复制</Button>
        </View>
      </CellGroup>
    </Page>
  )
}
