import {
  MyButtons,
  MyColumns,
  MyPageContainer,
  MyProTableProps,
  MyTableActions,
  MyToolBarActions,
} from '@/common';
import { Selects } from '@/components/Select';
import { Apis } from '@/gen/Apis';
import {
  ContractsContractNatureEnum,
  ContractsStatusEnum,
  ContractTemplatesIncomeExpenseTypeEnum,
} from '@/gen/Enums';
import { ProTable } from '@ant-design/pro-components';
import { useNavigate, useSearchParams } from '@umijs/max';
import dayjs from 'dayjs';

import Archives from '../contract_archives/modals/Archive';
import UseSeal from '../contract_seal_logs/modals/UseSeal';
import Change from './modals/Change';
import Terminated from './modals/Terminated';
import Voided from './modals/Voided';

export default function Index({ title = '合同拟制' }) {
  const navigate = useNavigate();
  const [searchParams, setSearchParams]: any = useSearchParams();

  return (
    <MyPageContainer
      title={title}
      enableTabs={true}
      tabKey="contracts_list"
      tabLabel={title}
    >
      <ProTable
        {...MyProTableProps.props}
        request={async (params, sort) => {
          setSearchParams(params);
          return MyProTableProps.request(
            !searchParams?.get('page')
              ? {
                  status: searchParams?.get('status') || null,
                  ...params,
                  is_agreement: false,
                }
              : { ...params, is_agreement: false },
            sort,
            Apis.Contract.Contracts.List,
          );
        }}
        headerTitle="合同列表"
        toolBarRender={() => [
          <MyToolBarActions
            key="toolbar"
            actions={{
              add: (
                <MyButtons.Create
                  key="add"
                  size="middle"
                  onClick={() => {
                    navigate('/contract/contracts/pages/contract_create');
                  }}
                  title="新增合同"
                />
              ),
            }}
          />,
        ]}
        columns={[
          MyColumns.ID({ search: false }),
          Selects?.AssetProjects({
            title: '关联项目',
            key: 'asset_projects_id',
            hidden: true,
          }),
          MyColumns.EnumTag({
            title: '合同状态',
            dataIndex: 'status',
            valueEnum: ContractsStatusEnum,
            fieldProps: {
              defaultValue: searchParams?.get('status') || undefined,
            },
          }),
          {
            title: '合同编号',
            dataIndex: 'code',
          },
          {
            title: '合同名称',
            dataIndex: 'name',
          },
          {
            title: '合同类型',
            dataIndex: 'contract_type_name',
            search: false,
          },

          MyColumns.EnumTag({
            title: '收支类型',
            dataIndex: 'income_expense_type',
            valueEnum: ContractTemplatesIncomeExpenseTypeEnum,
          }),
          MyColumns.EnumTag({
            title: '合同性质',
            dataIndex: 'contract_nature',
            valueEnum: ContractsContractNatureEnum,
            search: false,
          }),
          {
            title: '合同总价',
            search: false,
            render: (_, item: any) => {
              return `¥${item.total_amount}`;
            },
          },
          {
            title: '账单金额',
            render: (_, item: any) => {
              return `¥${item.total_bill_amount}`;
            },
            search: false,
          },
          {
            title: '履约金额',
            render: (_, item: any) => {
              return item.income_expense_type === 'Income'
                ? `¥${item.total_income_amount}`
                : item.income_expense_type === 'Expense'
                ? `¥${item.total_expense_amount}`
                : '-';
            },
            search: false,
          },
          {
            title: '履约率',
            search: false,
            render: (_, item: any) => {
              const numerator = parseFloat(
                item.income_expense_type === 'Income'
                  ? item?.total_income_amount || 0
                  : item.income_expense_type === 'Expense'
                  ? item?.total_expense_amount || 0
                  : 0,
              );
              const denominator = parseFloat(item.total_bill_amount || 0);
              const rate =
                denominator > 0 ? (numerator / denominator) * 100 : 0;
              return `${rate.toFixed(1)}%`;
            },
          },
          {
            title: '有效期',
            search: false,
            render: (_, item: any) => {
              return item.start_time
                ? `${dayjs(item.start_time).format('YYYY-MM-DD')}至${dayjs(
                    item.end_time,
                  ).format('YYYY-MM-DD')}`
                : '-';
            },
          },
          {
            title: '关联项目',
            dataIndex: ['asset_project', 'name'],
            // search: {
            //   transform: (value) => {
            //     return { full_name: value };
            //   },
            // },
            search: false,
          },

          {
            title: '合同对接人',
            dataIndex: 'contract_liaison',
            search: false,
            // render: (_, item: any) => (
            //   <Space>
            //     <span>{item?.contract_liaison?.name || ''}</span>
            //     {item?.contract_liaison?.id && (
            //       <EmployeeShow
            //         item={{ id: item?.contract_liaison?.id, type: 'link' }}
            //       />
            //     )}
            //   </Space>
            // ),
          },
          {
            title: '用印日期',
            dataIndex: 'sign_time',
            valueType: 'date',
            render: (_, item: any) => {
              return item.sign_time
                ? dayjs(item.sign_time).format('YYYY-MM-DD')
                : '-';
            },
          },
          MyColumns.CreatedAt(),
          MyColumns.Option({
            render: (_, item: any, __, action) => (
              <MyTableActions
                actions={{
                  View: (
                    <MyButtons.View
                      key="configInfo"
                      title="查看"
                      disabled={item.status === 'Cancelled'}
                      onClick={() => {
                        navigate(`/contract/contracts/show/${item.id}`);
                      }}
                    />
                  ),
                  Update: (
                    <MyButtons.Default
                      key="Update"
                      size="small"
                      type="primary"
                      disabled={
                        item.status !== 'TemporaryStorage' &&
                        item.status !== 'Rejected'
                      }
                      onClick={() => {
                        if (item.parent_id) {
                          navigate(
                            `/contract/contracts/pages/contract_add_update?id=${item.id}`,
                          );
                        } else {
                          navigate(
                            `/contract/contracts/pages/contract_update?id=${item.id}`,
                          );
                        }
                      }}
                      title="编辑"
                    />
                  ),
                  UseSeal: (
                    <UseSeal
                      key="UseSeal"
                      item={{ ...item, disabled: true }}
                      reload={action?.reload}
                      title="申请用印"
                    />
                  ),
                  Bill: (
                    <MyButtons.View
                      key="configInfoBill"
                      title="账单"
                      disabled={item.status === 'Cancelled'}
                      onClick={() => {
                        navigate(`/contract/contracts/show/${item.id}?key=4`);
                      }}
                    />
                  ),
                  Archives: (
                    <Archives
                      key="Archives"
                      item={{ ...item, disabled: true }}
                      reload={action?.reload}
                      title="归档"
                    />
                  ),
                  Change: (
                    <Change
                      key="Change"
                      item={{ ...item, disabled: true }}
                      reload={action?.reload}
                      title="变更"
                    />
                  ),
                  Supplement: (
                    <MyButtons.Default
                      key="Supplement"
                      size="small"
                      type="primary"
                      disabled={
                        item.status !== 'Signed' && item.status !== 'Archived'
                      }
                      onClick={() => {
                        navigate(
                          `/contract/contracts/pages/contract_add?id=${item.id}`,
                        );
                      }}
                      title="补充"
                    />
                  ),
                  Terminated: (
                    <Terminated
                      key="Terminated"
                      item={item}
                      reload={action?.reload}
                      title="解除"
                    />
                  ),
                  Voided: (
                    <Voided
                      key="Voided"
                      item={item}
                      reload={action?.reload}
                      title="撤销"
                    />
                  ),
                  Copy: (
                    <MyButtons.Default
                      key="Copy"
                      title="复制"
                      type="primary"
                      disabled={
                        item.status === 'TemporaryStorage' ||
                        item.status === 'UnderApproval' ||
                        item.status === 'Rejected'
                      }
                      onClick={() => {
                        Apis.Contract.Contracts.ContractCopy({
                          id: item?.id ?? 0,
                        }).then((res) => {
                          navigate(
                            `/contract/contracts/pages/contract_update?id=${res?.data?.id}`,
                          );
                        });
                      }}
                    />
                  ),
                  Delete: (
                    <MyButtons.Default
                      key="Delete"
                      title="取消"
                      disabled={
                        item?.status !== 'TemporaryStorage' &&
                        item?.status !== 'Voided'
                      }
                      isConfirm={true}
                      description={`您正在操作取消「${item.name}」，取消后，合同不能做任何操作，是否继续？`}
                      onConfirm={() =>
                        Apis.Contract.Contracts.SoftDelete({
                          id: item.id,
                        }).then(() => action?.reload())
                      }
                    />
                  ),
                }}
              />
            ),
          }),
        ]}
      />
    </MyPageContainer>
  );
}
