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

export default (props) => {

  const { issue } = props;
  const formDataRef = React.useRef();

  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 [showOrgPicker, setShowOrgPicker] = 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(!formDataRef.current?.orgId, '请选择交办单位')
      // warn(!formData.expireDate, '请选择办结时间')
    } catch (e) {
      return;
    }

    setLoading1(true)

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

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

  return (
    <View style={{ marginTop: '20px', display: 'flex' }}>
      <Dialog id={dialogId} />
      <OrgPicker
        parentId={issue.orgId}
        show={showOrgPicker}
        value={formDataRef.current?.orgName}
        onCancel={() => setShowOrgPicker(false)}
        onChange={onOrgChange}
      />
      <Button
        block
        type="primary"
        loading={loading1}
        onClick={() => setShowOrgPicker(true)}
      >交办</Button>
    </View>
  )
}
