Agricultural water optimization at the basin scale is critical for sustainable irrigated agriculture and water resources management. Crop Water Production Function (CWPF) and surface water are key components of agricultural water optimization. CWPF relates closely to crop yield/growth-related parameters, and surface water of sub-basins is often different and impacted by water withdrawals. However, CWPF accounting for the crop yield-related parameter and natural runoff of sub-basins were scarcely involved in agricultural water optimization at the basin scale. To fill this gap, CWPFs of different water units are estimated using a distributed ecohydrological model involving the spatial heterogeneity of crop photosynthetic capacity parameter, and the natural runoff of sub-basins is reproduced by this model. Integrating these functions and variables, and taking the agricultural benefit of the whole basin as the main objective, an agricultural water optimization model at the basin scale (AWOMB) is developed and applied to a mountain-plain basin in North China. The results showed that agricultural water optimization in a representative year would lead to 0.4% increase of crop production for the whole basin at the expense of certain urban ecological water and equity of agricultural water. In this scenario, the river ecological water requirements in all sub-basins would be satisfied. Assuming the domestic, industrial and river ecological water demand being fully satisfied in 2020s, water deficits will be 8% and 26% for the whole basin under the normal and dry year scenarios, respectively. Correspondingly, increments of 2% and 7% crop production are predicted in these two scenarios by agricultural water optimization. It is demonstrated that water resources utilization and agricultural production are effectively improved by coupling a distributed ecohydrological model with water resources optimization in the study basin. This research provides a methodology for integrative catchment water resources management.