import {useState, forwardRef, useImperativeHandle} from 'react';
import {Input, Button, Modal, message} from 'antd';
import {ImportOutlined, ExclamationCircleFilled} from "@ant-design/icons";
import { tauriPost } from "../../utils/http.ts";

interface PublishToCongShangProps {
  reportContent?: string;
}

interface PublishToCongShangRef {
  handleInitThisWorkVal: (key: string) => void;
}

const {TextArea} = Input;
const { confirm } = Modal;

const PublishToCongShang = forwardRef<PublishToCongShangRef, PublishToCongShangProps>(
  ({reportContent = ''}, ref) => {

    const [thisWorkVal, setThisWorkVal] = useState(reportContent || '');
    const [nextPlanVal, setNextPlanVal] = useState('');

    const handleImport = () => {
      if (!reportContent){
        message.warning("无内容可导入");
        return;
      }
      if (thisWorkVal){
        confirm({
          title: '提醒',
          icon: <ExclamationCircleFilled />,
          content: '内容已存在，确定覆盖吗',
          onOk() {
            setThisWorkVal(reportContent)
          },
          onCancel() {
            console.log('取消覆盖');
          },
        });
        return;
      }
      setThisWorkVal(reportContent)
    };

    useImperativeHandle(ref, () => ({
      handleInitThisWorkVal: (newVal) => {
        if (thisWorkVal) return;
        setThisWorkVal(newVal)
      },
    }));

    const handleSubmit = async () => {
      console.log(thisWorkVal, nextPlanVal);
      const congShangId = localStorage.getItem('congShangId');
      try {
        const response :any = await tauriPost('/apiWebServer', {
          realAction: 'report.SPReport/apiInsert',
          content: thisWorkVal,
          plantowork: nextPlanVal,
          stat: 1,
          reporttype: '2',
          teamid: 26,
          sysuserid: congShangId,
          spapi_rows: [
            {
              spapi_rows: [
                {
                  "id": 1035046,
                  "type": 1,
                  "name": "田颖",
                  "num": 1,
                  "teamid": 26,
                }
              ]
            },
            {
              spapi_rows: []
            }
          ],
        })
        console.log('Response:', response);
        if (response.errcode !== 0) {
          message.error(response.message || response.errmsg || '系统错误');
          return;
        }
        message.success("提交成功");

      } catch (error) {
        console.error('Error submitting data:', error);
      }
    };

    return (
      <div className="flex flex-col gap-y-4">
        <div>
          <div className="flex items-center justify-between">
            <div>本周工作</div>
            <ImportOutlined className="cursor-pointer" onClick={handleImport}/>
          </div>
          <TextArea autoSize={{minRows: 4, maxRows: 20}} value={thisWorkVal}
                    onChange={(e) => setThisWorkVal(e.target.value)}/>
        </div>
        <div>
          <p>下周计划</p>
          <TextArea autoSize={{minRows: 4, maxRows: 8}} value={nextPlanVal}
                    onChange={(e) => setNextPlanVal(e.target.value)}/>
        </div>


        <Button type="primary" onClick={handleSubmit}>发布</Button>
      </div>

    );
  });

export default PublishToCongShang;