import React from 'react';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import { Button, Dialog } from '@antmjs/vantui';
import { postIssueAssigned, putTaIssue, copyTaIssue } from '@/services/taissue';
import { warn } from '@/utils/message';

export default (props) => {

  const { issue, formData } = props;

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

  // 交办
  const onAssigned = () => {
    try {
      warn(!formData.addr, '请填写地址')
      warn(!formData.locId, '请选择点位')
      warn(!formData.content, '请填写问题描述')
      warn(!formData.typeId, '请选择问题分类')
      warn(!formData.attachList || formData.attachList.length < 1, '请上传照片')
      warn(!formData.orgId, '请选择交办单位')
      warn(!formData.expireDate, '请选择办结时间')
    } catch (e) {
      return;
    }

    setLoading1(true)

    const data = { ...issue, ...formData };

    // 先提交修改
    putTaIssue(issue.issueId, data).then(() => {
      // 再提交交办
      postIssueAssigned({ ...data, nextOrg: data.orgId }).then(() => {
        setLoading1(false);
        Taro.navigateBack({ delta: 1 });
      }).catch(() => {
        setLoading1(false);
      })
    }).catch(() => {
      setLoading1(false);
    })
  }

  // 复制
  const onCopy = () => {
    Dialog.confirm({
      title: '复制问题单',
      message: '确认复制当前问题单?',
      selector: dialogId,
    }).then((value) => {
      console.log('1value', 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)
        })
      }
    })
  }

  return (
    <View style={{ marginTop: '20px', display: 'flex' }}>
      <Dialog id={dialogId} />
      <Button
        block
        type="primary"
        loading={loading1}
        onClick={onAssigned}
        style={{ flex: 5 }}
      >交办</Button>
      <Button
        block
        type="info"
        loading={loading2}
        onClick={onCopy}
        style={{ flex: 1, marginLeft: 'var(--main-space)' }}
      >复制</Button>
    </View>
  )
}
