import React, { useState, useMemo, useRef, useEffect } from 'react';
import DrawerPro from '@/components/DrawerPro';
import AutoTable from '@/components/AutoTable';
import PremButton from '@/components/PremButton';
import getcolumns from './columns';
import { doFetch, exportFetch } from '@/utils/doFetch';
import { useRequest } from 'ahooks';
import { Divider, Tabs, ProDescriptions, message } from 'antd';
import dayjs from 'dayjs';
import Leaseterminformation from './Leaseterminformation';
import { useLocation } from '@umijs/max';
const Costanalysis = () => {
  const { pathname, state } = useLocation();
  let actionRef = useRef(),
    formRef = useRef(),
    boxRef = useRef();
  const [drawer, setdrawer] = useState({
    open: false,
  }),
    [extraparams, setextraparams] = useState({}),
    [activeKey, catk] = useState(''),
    [searchParams, csearch] = useState({});
  const { run, loading, runAsync } = useRequest(doFetch, {
    manual: true,
    onSuccess: (res, params) => {
      if (res?.code == '0000') {
        actionRef?.current?.reload();
        setdrawer((s) => ({
          ...s,
          open: false,
        }));
      }
    },
  });
  const columns = useMemo(() => {
    csearch({});
    let defcolumn =
      getcolumns(setdrawer, activeKey)?.filter((it) => it.key == activeKey)?.[0]?.columns ?? [];
    return defcolumn.concat({
      title: '操作',
      valueType: 'option',
      width: activeKey == 'item-1' ? 260 : 100,
      render: (text, row, _, action) => rightExtra(text, row, _, action),
    });
  }, [activeKey]);
  const tabList = useMemo(() => {
    return getcolumns();
  }, [activeKey]);
  const rightExtra = (text, row, _, action) => {
    return [
      activeKey == 'item-1' && (
        <PremButton
          key="confirm"
          btn={{
            size: 'small',
            onClick: async () => {
              let res = await doFetch({
                url: '/lease/umContractEquipment/queryBeforeCollection',
                params: { id: row.id },
              });
              if (res?.data?.data?.waitNum == 0) {
                message.warning('该设备需回款的租期已全部回款，无需再次回款！');
              } else {
                setdrawer((s) => ({
                  ...s,
                  open: true,
                  item: {
                    ...row,
                    waitNum: res?.data?.data?.waitNum,
                    isColl: res?.data?.data?.isColl,
                  },
                  val: 'confirm',
                  title: '回款确认',
                  fields: [
                    {
                      title: '本期是否回款',
                      dataIndex: 'isColl',
                      key: 'isColl',
                      fieldProps: {
                        disabled: true,
                      },
                      colProps: { span: 8 },
                    },
                    {
                      title: '剩余回款期数',
                      dataIndex: 'waitNum',
                      key: 'waitNum',
                      fieldProps: {
                        disabled: true,
                      },
                      valueType: 'digit',
                      colProps: { span: 8 },
                    },
                    {
                      title: '本次回款期数',
                      dataIndex: 'collNum',
                      key: 'collNum',
                      valueType: 'digit',
                      colProps: { span: 8 },
                      precision: 0,
                      formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
                    },
                    {
                      title: '回款形式',
                      dataIndex: 'collType',
                      key: 'collType',
                      valueType: 'select',
                      options: [
                        { label: '现金', value: 1 },
                        { label: '银行承兑', value: 2 },
                      ],
                      colProps: { span: 8 },
                      formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
                    },
                  ],
                }));
              }
            },
          }}
        >
          回款确认
        </PremButton>
      ),
      activeKey == 'item-1' && (
        <PremButton
          key="reduction"
          btn={{
            size: 'small',
            onClick: () => {
              setdrawer((s) => ({
                ...s,
                open: true,
                item: { ...row, reducePrice: null },
                val: 'reduction',
                title: '租金减免',
                fields: [
                  {
                    title: '当前减免金额',
                    dataIndex: 'reducePrice',
                    key: 'reducePrice',
                    valueType: 'digit',
                    colProps: { span: 8 },
                    precision: 0,
                    formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
                  },
                  {
                    title: '减免情况说明',
                    dataIndex: 'reduceRemark',
                    key: 'reduceRemark',
                    valueType: 'textarea',
                    colProps: { span: 24 },
                  },
                  {
                    title: '附件上传',
                    dataIndex: 'reduceFileList',
                    key: 'reduceFileList',
                    valueType: 'uploadBtn',
                    fieldProps: {
                      limit: 1,
                    },
                    colProps: { span: 24 },
                  },
                ],
              }));
            },
          }}
        >
          租金减免
        </PremButton>
      ),
      <PremButton
        key="invoicing"
        btn={{
          size: 'small',
          onClick: async () => {
            let res = await doFetch({
              url: '/lease/umContractEquipment/queryBeforeInvoicing',
              params: { id: row.id },
            });
            if (res?.data?.data?.openNum == 0) {
              message.warning('该设备已无需要开票的租期，无需开票记录！');
            } else {
              setdrawer((s) => ({
                ...s,
                open: true,
                item: { ...row, openNum: null },
                val: 'invoicing',
                title: '开票记录',
                fields: [
                  {
                    title: '开票期数',
                    dataIndex: 'openNum',
                    key: 'openNum',
                    valueType: 'digit',
                    colProps: { span: 8 },
                    precision: 0,
                    formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
                  },
                ],
              }));
            }
          },
        }}
      >
        开票记录
      </PremButton>,
    ];
  };
  useEffect(() => {
    if (state) {
      setdrawer((s) => ({
        ...s,
        open: false,
      }));
      catk(state.pageStatus == 1 ? 'item-1' : 'item-2');
      setextraparams(state.extraparams);
    } else {
      catk('item-1');
      setextraparams({});
    }
  }, [state]);
  return (
    <div ref={boxRef}>
      <AutoTable
        pagetitle={<h3 className="page-title">租赁营收</h3>}
        columns={columns}
        extraparams={extraparams}
        path={
          activeKey == 'item-1'
            ? '/lease/umContractEquipment/queryNoAnalysis'
            : '/lease/umContractEquipment/queryYesAnalysis'
        }
        actionRef={actionRef}
        resizeable={false}
        bordered={false}
        x={3200}
        onTabChange={(key) => {
          catk(key);
          setextraparams({});
        }}
        activeTabKey={activeKey}
        tabList={tabList}
        pageextra={'export'}
        formRef={formRef}
        dataSourceFieldsChange={(vals) => {
          csearch(vals);
        }}
        exportconfig={{
          btn: {
            type: 'primary',
            onClick: async () => {
              message.warning('导出中，请稍后');
              await exportFetch({
                url:
                  activeKey == 'item-1'
                    ? '/lease/umContractEquipment/exportExcelNoAnalysis'
                    : '/lease/umContractEquipment/exportExcelYesAnalysis',
                params: { ...extraparams, ...searchParams },
              });
            },
          },
        }}
        options={{
          reload: () => {
            setextraparams({});
          }
        }}
      />

      <DrawerPro
        {...drawer}
        fields={drawer.fields}
        params={{ id: drawer?.item?.id }}
        defaultFormValue={drawer?.item ?? {}}
        placement="right"
        onClose={() => {
          setdrawer((s) => ({
            ...s,
            open: false,
          }));
        }}
        onValuesChange={(changedValues, allValues) => { }}
        onFinish={async (vals) => {
          let newVals = JSON.parse(JSON.stringify(vals));
          if (drawer?.val == 'confirm') {
            await runAsync({
              url: '/lease/umContractEquipment/collection',
              params: {
                collNum: newVals.collNum,
                collType: newVals.collType,
                id: drawer?.item?.id,
              },
            });
          } else if (drawer?.val == 'reduction') {
            await runAsync({
              url: '/lease/umContractEquipment/exemption',
              params: { ...newVals, id: drawer?.item?.id },
            });
          } else if (drawer?.val == 'invoicing') {
            await runAsync({
              url: '/lease/umContractEquipment/invoicing',
              params: { ...newVals, id: drawer?.item?.id },
            });
          }
        }}
      >
        <Leaseterminformation drawer={drawer} boxRef={boxRef} />
      </DrawerPro>
    </div>
  );
};
export default Costanalysis;
