import {
  MyBetaModalFormProps,
  MyButtons,
  MyModalFormProps,
  rulesHelper,
} from '@/common';
import { Selects } from '@/components/Select';
import MyTransferUnits from '@/components/TransferUnits';
import { Apis } from '@/gen/Apis';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Form, message } from 'antd';

export default function Update(props: MyBetaModalFormProps) {
  const [form] = Form.useForm();
  return (
    <BetaSchemaForm<ApiTypes.Grid.Grids.Update>
      {...MyModalFormProps.props}
      title={`调整范围`}
      width="700px"
      layout="horizontal"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 24 }}
      labelAlign="right"
      trigger={<MyButtons.Edit title={'范围'} size="small" type="primary" />}
      form={form}
      key={new Date().getTime()}
      onOpenChange={(open: any) => {
        if (open) {
          let arr: any = [];
          Apis.Grid.Grids.Show({ id: props?.item?.id }).then((res) => {
            if (res?.data?.grid_ranges) {
              res?.data?.grid_ranges?.forEach((k: any) => {
                arr.push(k.asset_units_id);
              });
            }
            form.setFieldsValue({ ...res?.data, grid_ranges: arr });
          });
        }
      }}
      onFinish={async (values: any) => {
        console.log(values);
        // 确保grid_ranges是正确的对象数组格式
        if (
          values.grid_ranges &&
          Array.isArray(values.grid_ranges) &&
          typeof values.grid_ranges[0] === 'number'
        ) {
          // 如果是ID数组，需要转换为对象数组
          const dataSource = form.getFieldValue('_dataSource') || [];
          const grid_ranges = values.grid_ranges.map((id: any) => {
            const unit = dataSource.find(
              (item: any) => item.asset_units_id === id.toString(),
            );
            return {
              asset_projects_id: props?.item?.asset_projects_id,
              asset_buildings_id: unit?.asset_buildings_id,
              asset_units_id: id.toString(),
            };
          });
          values.grid_ranges = grid_ranges;
        }

        return Apis.Grid.Grids.Update({
          ...values,
          asset_projects_id: props?.item?.asset_projects_id,
          id: props?.item?.id,
        })
          .then(() => {
            props.reload?.();
            message.success('网格编辑成功');
            return true;
          })
          .catch(() => false);
      }}
      columns={[
        Selects?.GetGridMark({
          key: 'grid_mark',
          title: '范围标识',
          params: {
            asset_projects_id: props?.item?.id,
          },
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.text },
        }),
        {
          key: 'grid_ranges',
          title: '选择单元',
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.array },
          renderFormItem: () => (
            <MyTransferUnits
              item={{
                asset_projects_id: props?.item?.asset_projects_id,
              }}
            />
          ),
        },
      ]}
    />
  );
}
