import React, { useRef, useState } from 'react';
import { Button, Col, Empty, Row, message } from 'antd';
import ApprovalProcess from './components/ApprovalProcess';
import AuditDetailed from './components/AuditDetailed';
import PageContent from '@/components/PageContent';
// import AliyunOSSUpload from '@/components/OssUpload/AliyunOssUploader';
import {
  queryProcessFlows,
  createAduit,
  advanceSubmitNextNode,
  // queryOSSData,
} from '@/services/boom';
import { useParams, useRequest, useNavigate } from 'umi';

const OaDetail = () => {
  const [approvalProcess, setApprovalProcess] = useState([]);
  const { oaId } = useParams();
  const formValueRef = useRef({
    form: '',
  });
  const uploadList = useRef([]);
  const navigate = useNavigate();
  const { data, loading } = useRequest(queryProcessFlows, {
    defaultParams: [{ ids: oaId }],
    onSuccess() {
      advanceSubmit(null, {});
    },
  });
  // const { data: OSSData } = useRequest(queryOSSData, {
  //   defaultParams: [{ ids: oaId }],
  // });

  const { loading: createLoadin, run: createRun } = useRequest(createAduit, {
    manual: true,
    onSuccess() {
      message.success('申请审批成功');
      navigate(-1);
    },
  });

  const { run } = useRequest(advanceSubmitNextNode, {
    debounceInterval: 500,
    manual: true,
    formatResult(res) {
      setApprovalProcess(res.data[0]);
    },
  });

  //填写表单实时计算审批流程
  const advanceSubmit = async (changedFields, allValues) => {
    console.log(changedFields, allValues);
    let formValues = (data?.formData || [])
      .map((item) => {
        const itemProps = item.props;
        let val = allValues[itemProps.id];
        if (!itemProps.label) return;
        if (!val && val !== 0) return;
        if (val instanceof Object) {
          return {
            name: itemProps.label,
            id: itemProps.id,
            value: [...val],
          };
        } else if (allValues[itemProps.id]) {
          return {
            name: itemProps.label,
            id: itemProps.id,
            type: item.componentName,
            value: [allValues[itemProps.id]] || undefined,
          };
        }
      })
      .filter((item) => item);

    let params = {
      flow_id: Number(oaId),
      template_node_id: 0,
      formComponentValues: formValues,
      audit_list: [],
    };
    formValueRef.current.form = formValues;
    run(params);
  };

  const submit = () => {
    const { form } = formValueRef.current;
    const audit_list = approvalProcess?.map((item) => {
      if (item[0].type == 'role') return item[0].nowValue;
      return item[0].value;
    });
    let files = [],
      formData = [];
    form.forEach((item) => {
      if (item.type == 'DDAttachment') {
        files = files.concat(item.value);
      } else {
        formData.push(item);
      }
    });
    createRun({
      flow_id: Number(oaId),
      form: JSON.stringify(formData),
      audit_list,
      files: files.join(','),
    });
  };
  // const OnModelFileDone = (file) => {
  //   var path = OSSData.host + '/' + file.url;
  //   uploadList.current = [...uploadList.current, path];
  // };

  return (
    <PageContent
      loading={loading}
      footer={[
        <Button onClick={submit} type="primary" loading={createLoadin}>
          提交审批
        </Button>,
      ]}
    >
      <Row gutter={24}>
          <Col span={12}>
            {/* {OSSData && (
              <AliyunOSSUpload
                OSSData={OSSData}
                onDone={OnModelFileDone}
                directory={false}
                noStyle={false}
                label="上传文件"
              />
            )} */}
            <AuditDetailed
              items={data?.formData}
              onValuesChange={advanceSubmit}
            />
          </Col>
          <Col span={12}>
            {approvalProcess.length == 0 ? (
              <Empty description="请先填写表单" />
            ) : (
              <ApprovalProcess
                approvalProcess={approvalProcess}
                onChange={setApprovalProcess}
              />
            )}
          </Col>
        </Row>
    </PageContent>
  );
};

export default OaDetail;
