import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { FinFixedAssetApi } from '#/api/erp/finance/fixed-asset';

import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { handleTree } from '@vben/utils';

import { z } from '#/adapter/form';
import { getSimpleDeptList } from '#/api/system/dept';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';

import dayjs from 'dayjs';

/**
 * 使用部门下拉：系统部门树（value = 部门编号）
 * 与 CRM 统计页的「归属部门」写法保持一致
 */
function departmentSelectProps() {
  return {
    allowClear: true,
    class: 'w-full',
    api: async () => handleTree(await getSimpleDeptList()),
    labelField: 'name',
    valueField: 'id',
    childrenField: 'children',
    placeholder: '请选择使用部门',
    treeDefaultExpandAll: true,
  };
}

/**
 * 保管人下拉：系统用户列表（value = 用户编号，label = 昵称）
 * 与 WMS 单据里选用户的写法保持一致
 */
function keeperSelectProps() {
  return {
    allowClear: true,
    class: 'w-full',
    api: getSimpleUserList,
    labelField: 'nickname',
    valueField: 'id',
    placeholder: '请选择保管人',
    showSearch: true,
  };
}

/** 资产状态：1在用 2闲置 3维修中 4已报废 */
export const FIXED_ASSET_STATUS_IN_USE = 1;
export const FIXED_ASSET_STATUS_IDLE = 2;
export const FIXED_ASSET_STATUS_REPAIRING = 3;
export const FIXED_ASSET_STATUS_SCRAPPED = 4;

/** 可计提折旧的状态（已报废的资产不再计提） */
export const DEPRECIABLE_FIXED_ASSET_STATUS = [
  FIXED_ASSET_STATUS_IN_USE,
  FIXED_ASSET_STATUS_IDLE,
  FIXED_ASSET_STATUS_REPAIRING,
];

/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'id',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'assetCode',
      label: '资产编码',
      component: 'Input',
      componentProps: {
        placeholder: '请输入资产编码，如 GD2026100001',
        allowClear: true,
      },
      rules: 'required',
    },
    {
      fieldName: 'assetName',
      label: '资产名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入资产名称',
        allowClear: true,
      },
      rules: 'required',
    },
    {
      fieldName: 'category',
      label: '资产类别',
      component: 'Input',
      componentProps: {
        placeholder: '请输入资产类别，如 生产设备',
        allowClear: true,
      },
    },
    {
      fieldName: 'specification',
      label: '规格型号',
      component: 'Input',
      componentProps: {
        placeholder: '请输入规格型号',
        allowClear: true,
      },
    },
    {
      fieldName: 'purchaseDate',
      label: '购置日期',
      component: 'DatePicker',
      componentProps: {
        placeholder: '请选择购置日期',
        showTime: false,
        valueFormat: 'YYYY-MM-DD',
        format: 'YYYY-MM-DD',
        class: 'w-full',
      },
      rules: 'required',
      defaultValue: dayjs().format('YYYY-MM-DD'),
    },
    {
      fieldName: 'originalValue',
      label: '资产原值',
      component: 'InputNumber',
      componentProps: {
        class: 'w-full',
        placeholder: '请输入资产原值',
        min: 0,
        precision: 2,
      },
      rules: z.number().min(0).default(0),
    },
    {
      fieldName: 'usefulLife',
      label: '使用年限（年）',
      component: 'InputNumber',
      componentProps: {
        class: 'w-full',
        placeholder: '请输入使用年限',
        min: 1,
        precision: 0,
      },
      defaultValue: 10,
      rules: z.number().min(1).default(10),
    },
    {
      fieldName: 'residualRate',
      label: '残值率（%）',
      component: 'InputNumber',
      componentProps: {
        class: 'w-full',
        placeholder: '请输入残值率',
        min: 0,
        max: 100,
        precision: 2,
      },
      defaultValue: 5,
      rules: z.number().min(0).max(100).default(5),
      help: '月折旧额 =（原值 ×（1 - 残值率））÷（使用年限 × 12）',
    },
    {
      fieldName: 'location',
      label: '存放地点',
      component: 'Input',
      componentProps: {
        placeholder: '请输入存放地点',
        allowClear: true,
      },
    },
    {
      fieldName: 'departmentId',
      label: '使用部门',
      component: 'ApiTreeSelect',
      componentProps: departmentSelectProps(),
    },
    {
      fieldName: 'keeperId',
      label: '保管人',
      component: 'ApiSelect',
      componentProps: keeperSelectProps(),
    },
    {
      fieldName: 'status',
      label: '资产状态',
      component: 'RadioGroup',
      componentProps: {
        options: getDictOptions(
          DICT_TYPE.FINANCE_FIXED_ASSET_STATUS,
          'number',
        ),
        buttonStyle: 'solid',
        optionType: 'button',
      },
      defaultValue: FIXED_ASSET_STATUS_IN_USE,
      rules: 'selectRequired',
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入备注',
        rows: 3,
      },
      formItemClass: 'md:col-span-2',
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'assetCode',
      label: '资产编码',
      component: 'Input',
      componentProps: {
        placeholder: '请输入资产编码',
        allowClear: true,
      },
    },
    {
      fieldName: 'assetName',
      label: '资产名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入资产名称',
        allowClear: true,
      },
    },
    {
      fieldName: 'category',
      label: '资产类别',
      component: 'Input',
      componentProps: {
        placeholder: '请输入资产类别',
        allowClear: true,
      },
    },
    {
      fieldName: 'purchaseDate',
      label: '购置日期',
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        showTime: false,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        allowClear: true,
      },
    },
    {
      fieldName: 'departmentId',
      label: '使用部门',
      component: 'ApiTreeSelect',
      componentProps: departmentSelectProps(),
    },
    {
      fieldName: 'keeperId',
      label: '保管人',
      component: 'ApiSelect',
      componentProps: keeperSelectProps(),
    },
    {
      fieldName: 'status',
      label: '资产状态',
      component: 'Select',
      componentProps: {
        options: getDictOptions(
          DICT_TYPE.FINANCE_FIXED_ASSET_STATUS,
          'number',
        ),
        placeholder: '请选择资产状态',
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<FinFixedAssetApi.FixedAsset>['columns'] {
  return [
    { type: 'checkbox', width: 40 },
    {
      field: 'assetCode',
      title: '资产编码',
      minWidth: 150,
      fixed: 'left',
    },
    {
      field: 'assetName',
      title: '资产名称',
      minWidth: 160,
    },
    {
      field: 'category',
      title: '资产类别',
      minWidth: 120,
    },
    {
      field: 'specification',
      title: '规格型号',
      minWidth: 140,
      showOverflow: 'tooltip',
    },
    {
      field: 'purchaseDate',
      title: '购置日期',
      minWidth: 120,
      formatter: 'formatDate',
    },
    {
      field: 'originalValue',
      title: '资产原值',
      minWidth: 130,
      align: 'right',
      formatter: 'formatAmount2',
    },
    {
      field: 'usefulLife',
      title: '使用年限',
      minWidth: 100,
      align: 'right',
    },
    {
      field: 'residualRate',
      title: '残值率(%)',
      minWidth: 110,
      align: 'right',
    },
    {
      field: 'monthlyDepreciation',
      title: '月折旧额',
      minWidth: 130,
      align: 'right',
      formatter: 'formatAmount2',
    },
    {
      field: 'accumulatedDepreciation',
      title: '累计折旧',
      minWidth: 130,
      align: 'right',
      formatter: 'formatAmount2',
    },
    {
      field: 'netValue',
      title: '净值',
      minWidth: 130,
      align: 'right',
      formatter: 'formatAmount2',
    },
    {
      // 后端 departmentId 存的是部门编号，列表展示用后端解析好的 departmentName
      field: 'departmentName',
      title: '使用部门',
      minWidth: 120,
    },
    {
      field: 'keeperName',
      title: '保管人',
      minWidth: 100,
    },
    {
      field: 'status',
      title: '资产状态',
      minWidth: 110,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.FINANCE_FIXED_ASSET_STATUS },
      },
    },
    {
      field: 'createTime',
      title: '创建时间',
      minWidth: 180,
      formatter: 'formatDateTime',
    },
    {
      title: '操作',
      width: 200,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
