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.Default title={`编辑`} size="small" type="link" />}
      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);
        // values?.grid_ranges?.map((res: { asset_projects_id: string }) => {
        //   res.asset_projects_id = props?.item?.id;
        // });
        return Apis.Grid.Grids.Update({
          ...values,
          asset_projects_id: props?.item?.id || values?.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,
              }}
            />
          ),
        },
      ]}
    />
  );
}
