{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['CH1灌水分布0419.shp', 'IL1水稻分布0419.shp', 'KH1水稻分布0419.shp', 'ML1水稻分布0419.shp', 'NT1水稻分布0419.shp', 'PT1水稻分布0419.shp', 'TC1水稻分布0419.shp', 'TN1水稻分布0419.shp', 'TP1水稻分布0419.shp']\n"
     ]
    }
   ],
   "source": [
    "import arcpy\n",
    "import os\n",
    "\n",
    "source_workspace  = r\"C:\\Users\\johnnychan\\Desktop\\115年一期作水稻灌水分布0506\"   # 原始檔案所在目錄\n",
    "merge_gdb = r\"C:\\Users\\johnnychan\\Desktop\\gis2\\output_20261_0506.gdb\"         # new geodatabase所建立，用來儲存結果\n",
    "output_name = r\"output\"\n",
    "\n",
    "arcpy.env.overwriteOutput = True\n",
    "\n",
    "# 設定來源工作目錄\n",
    "arcpy.env.workspace = source_workspace\n",
    "\n",
    "shpList = arcpy.ListFeatureClasses(\"*.shp\")\n",
    "print(shpList)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 合併所有shp檔"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "已將 9 個圖資 merge 並匯出至 C:\\Users\\johnnychan\\Desktop\\gis2\\output_20261_0506.gdb\\output\n"
     ]
    }
   ],
   "source": [
    "# 若 merge_gdb 尚未存在，則自動建立 geodatabase\n",
    "if not arcpy.Exists(merge_gdb):\n",
    "    parent_folder = os.path.dirname(merge_gdb)\n",
    "    gdb_name = os.path.basename(merge_gdb)\n",
    "    arcpy.CreateFileGDB_management(parent_folder, gdb_name)\n",
    "    print(f\"已建立 geodatabase：{merge_gdb}\")\n",
    "\n",
    "# 定義 merge 後輸出圖資的完整路徑\n",
    "merge_fc = os.path.join(merge_gdb, output_name)\n",
    "\n",
    "# 執行 merge\n",
    "arcpy.Merge_management(shpList, merge_fc)\n",
    "print(f\"已將 {len(shpList)} 個圖資 merge 並匯出至 {merge_fc}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 設定來源工作目錄\n",
    "arcpy.env.workspace = merge_gdb"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 判斷受益地(坵塊中心點位於受益地範圍內)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class='gpresult'><h2>Messages</h2><div id='messages' data-messages='[\"Start Time: 2026年5月12日 上午 10:48:45\",\"Succeeded at 2026年5月12日 上午 10:49:07 (Elapsed Time: 21.81 seconds)\"]' data-show='true'><div id = 'default' /></div></div>"
      ],
      "text/plain": [
       "<Result 'C:\\\\Users\\\\johnnychan\\\\Desktop\\\\gis2\\\\output_20261_0506.gdb\\\\parcel_sj'>"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 受益地shp檔案\n",
    "benefit_fc = r\"Z:\\91_數位發展處\\01_資料專區\\80_GIS圖資\\灌排受益地圖資\\農水署灌排受益地_113年11月版\\農水署灌排受益地_113年11月版.gdb\\彙整資料\\農水署灌排受益地_113年11月版\"\n",
    "sj_fc = \"parcel_sj\"\n",
    "\n",
    "# 執行 Spatial Join (中心點在多邊形內)\n",
    "arcpy.analysis.SpatialJoin(\n",
    "    target_features=merge_fc,\n",
    "    join_features=benefit_fc,\n",
    "    out_feature_class=sj_fc,\n",
    "    join_operation=\"JOIN_ONE_TO_ONE\",\n",
    "    join_type=\"KEEP_ALL\",\n",
    "    match_option=\"HAVE_THEIR_CENTER_IN\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class='gpresult'><h2>Messages</h2><div id='messages' data-messages='[\"Start Time: 2026年5月12日 上午 10:49:41\",\"Succeeded at 2026年5月12日 上午 10:49:41 (Elapsed Time: 0.06 seconds)\"]' data-show='true'><div id = 'default' /></div></div>"
      ],
      "text/plain": [
       "<Result 'true'>"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 建新欄位：\"受益地\"\n",
    "arcpy.management.AddField(\n",
    "    sj_fc,\n",
    "    \"受益地\",\n",
    "    \"TEXT\",\n",
    "    field_length=2\n",
    ")\n",
    "\n",
    "# 函數判斷 \"有坵塊段號\" 為是\n",
    "code_block = \"\"\"\n",
    "def f(a):\n",
    "    if a:\n",
    "        return '是'\n",
    "    else:\n",
    "        return '否'\n",
    "\"\"\"\n",
    "expression = 'f(!段號!)'\n",
    "\n",
    "arcpy.management.CalculateField(\n",
    "    in_table=sj_fc,\n",
    "    field=\"受益地\",\n",
    "    expression=expression,\n",
    "    expression_type=\"PYTHON3\",\n",
    "    code_block=code_block\n",
    ")\n",
    "\n",
    "# 將受益地加入原始圖資\n",
    "arcpy.management.JoinField(\n",
    "    in_data=merge_fc,\n",
    "    in_field=\"OBJECTID\",\n",
    "    join_table=sj_fc,\n",
    "    join_field=\"TARGET_FID\",\n",
    "    fields=[\"受益地\"]\n",
    ")\n",
    "\n",
    "# 刪除中繼圖層\n",
    "arcpy.management.Delete(sj_fc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Spatial Join對水利小組"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class='gpresult'><h2>Messages</h2><div id='messages' data-messages='[\"Start Time: 2026年5月12日 上午 10:50:15\",\"Succeeded at 2026年5月12日 上午 10:50:15 (Elapsed Time: 0.03 seconds)\"]' data-show='true'><div id = 'default' /></div></div>"
      ],
      "text/plain": [
       "<Result 'true'>"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# ==================執行Spatial Join對照水利小組編號====================\n",
    "# 讀取水利小組範圍圖層\n",
    "water_group_fc = r\"Z:\\91_數位發展處\\01_資料專區\\80_GIS圖資\\一所\\農水署灌區、圳路圖_112年版.gdb\\_4水利小組範圍\"\n",
    "sj_fc = \"parcel_sj\"\n",
    "\n",
    "# 執行 Spatial Join (中心點在多邊形內)\n",
    "arcpy.analysis.SpatialJoin(\n",
    "    target_features=merge_fc,\n",
    "    join_features=water_group_fc,\n",
    "    out_feature_class=sj_fc,\n",
    "    join_operation=\"JOIN_ONE_TO_ONE\",\n",
    "    join_type=\"KEEP_ALL\",\n",
    "    match_option=\"HAVE_THEIR_CENTER_IN\"\n",
    ")\n",
    "\n",
    "# 將水利小組編號加入原始圖資\n",
    "arcpy.management.JoinField(\n",
    "    in_data=merge_fc,\n",
    "    in_field=\"OBJECTID\",\n",
    "    join_table=sj_fc,\n",
    "    join_field=\"TARGET_FID\",\n",
    "    fields=[\"水利小組編號\"]\n",
    ")\n",
    "\n",
    "# 刪除中繼圖層\n",
    "arcpy.management.Delete(sj_fc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 輸出table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class='gpresult'><h2>Messages</h2><div id='messages' data-messages='[\"Start Time: 2026年5月12日 上午 10:50:28\",\"Succeeded at 2026年5月12日 上午 10:50:33 (Elapsed Time: 5.76 seconds)\"]' data-show='true'><div id = 'default' /></div></div>"
      ],
      "text/plain": [
       "<Result 'C:\\\\Users\\\\johnnychan\\\\Desktop\\\\gis2\\\\merge_fc_final_.csv'>"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "out_folder = r\"C:\\Users\\johnnychan\\Desktop\\gis2\"\n",
    "out_csv = \"merge_fc_final_.csv\"\n",
    "\n",
    "arcpy.conversion.TableToTable(\n",
    "    in_rows=merge_fc,\n",
    "    out_path=out_folder,\n",
    "    out_name=out_csv,\n",
    "    where_clause=\"水利小組編號 IS NOT NULL AND 受益地 = '是'\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ArcGISPro",
   "language": "Python",
   "name": "python3"
  },
  "language_info": {
   "file_extension": ".py",
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
