<template>
    <div class="base-container">
        <common-box name="Location Information">
            <div class="base-list">
                <div
                    class="base-item common-item"
                    v-for="(item, index) in baseList"
                    :key="index"
                    :style="{ background: item.color }"
                >
                    <div class="value">{{ item.value }}{{ item.unit }}</div>
                    <div class="label">{{ item.name }}</div>
                </div>
            </div>
        </common-box>
        <div class="box-wrap">
            <common-box name="Maps" class="map-wrap">
                <map-item class="map" ref="detailMap" :locationId="route.query.id" :showOverview="false"></map-item>
                <div class="big-icon" @click="toggleMapPopup()">
                    <img src="@/assets/images/home/big-icon.png" alt="" />
                </div>
            </common-box>
            <common-box name="Plant Information" class="plant-wrap">
                <div class="plant-list">
                    <div
                        class="plant-item common-item"
                        v-for="(item, index) in plantList"
                        :key="index"
                        :style="{ background: item.color }"
                    >
                        <div class="value">{{ item.value }} {{ item.unit }}</div>
                        <div class="label">{{ item.name }}</div>
                    </div>
                </div>
            </common-box>
        </div>
        <div class="card-wrap">
            <common-box name="Detail Data Plot" class="table-wrap">
                <el-table class="table" :data="tableData" :summary-method="getSummary" show-summary >
                    <el-table-column prop="name" label="Plot"/>
                    <el-table-column prop="luas" label="Luas CE（ha）" sortable >
                        <template #default="scope">
                            <span>{{ scope.row.luas.toFixed(4) }}</span>
                          </template>
                    </el-table-column>
                    <el-table-column prop="standarPopulasi" label="Standar Populasi" sortable ></el-table-column>
                    <el-table-column prop="plantCount" label="Drone AI Counting" sortable />
                    <el-table-column prop="populasiPerHa" label="Populasi Per Ha" sortable />
                    <el-table-column prop="achivement" label="Achivement" sortable >
                      <template #default="scope">
                        <span>{{ scope.row.achivement}}%</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="gapPopulasi" label="Gap Populasi" sortable />
                    <el-table-column fixed="right" label="Operations" width="110px">
                        <template #default="scope">
                            <div class="edit" @click="handleEdit(scope.$index, scope.row)">
                                <img class="icon" src="@/assets/images/common/edit-icon.png" alt="" />
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </common-box>
            <common-box class="info-wrap" name="Recomendation Value" bgName="green">
                <el-tabs v-model="activeName" class="tabs-wrap" @tab-click="handleClick">
                    <el-tab-pane label="Trend" name="first">
                        <div class="info-list">
                            <template v-for="item in tableData" :key="item">
                            <div class="info-item" v-if="parseFloat(item.achivement) < 97">
                                <img class="icon" src="@/assets/images/home/arrow-icon.png" alt="" />
                                <span>Replanting {{ item.achivement }}% ({{ item.plantCount }}) in Plot {{item.name}}</span>
                            </div>
                            </template>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="Recomendation" name="second">
                        <line-chart class="line-chart" styleName="styleName1" :xData="xData" :yData="yData"></line-chart>
                    </el-tab-pane>
                </el-tabs>
            </common-box>
        </div>
    </div>
    <!-- 编辑地图弹窗 -->
    <popup class="edit-popup" v-model:show="showMapPopup" round closeable :close-on-click-overlay="false" @close="closePopup">
        <div class="title">
            <img src="@/assets/images/common/popup-title.png" alt="" />
            <span>Edit Lokasi</span>
        </div>
        <div class="content">
            <div class="map-wrap">
                <div class="map" ref="popupMap"></div>
                <div class="delete" @click="handleDelete">
                    <el-icon><Delete /></el-icon>
                </div>
                <div class="close" @click="handleClear" v-show="isHide">
                    <Icon name="revoke" />
                </div>
                <div class="polygon-info">
                    <span class="name">Informasi Polygon</span>
                    <div class="info">
                        <div class="text">
                            <span class="label">Lokasi Area</span>
                            <div class="value">{{rowData.area.toFixed(4)}} ha</div>
                        </div>
                        <div class="text">
                            <div class="label">Jumlah Titikc</div>
                            <div class="value">{{rowData.plantCount}}</div>
                        </div>
                    </div>
                </div>
                <div class="operations">
                    <img @click="handleZoom('add')" src="@/assets/images/common/plus.png" alt="" />
                    <img @click="handleZoom('minus')" src="@/assets/images/common/minus.png" alt="" />
                </div>
            </div>
            <div class="map-info">
                <el-form label-position="top" :model="ruleForm" :rules="rules">
                    <div class="info-title">
                        <img src="@/assets/images/common/info-icon.png" alt="" />
                        <span>Informasi Dasar</span>
                    </div>
                    <el-form-item label="ID Lokasi" size="large" prop="name">
                        <el-input v-model="rowData.id" disabled />
                    </el-form-item>
                    <el-form-item label="Name Lokasi" size="large" prop="name">
                        <el-input v-model="ruleForm.name" />
                    </el-form-item>
                    <div class="info-title">
                        <img src="@/assets/images/common/info-icon-2.png" alt="" />
                        <span>Informasi Wilayah</span>
                    </div>
                    <el-form-item label="Plantation Group" size="large" prop="group">
                        <el-input v-model="rowData.plantGroupName" disabled />
                        <!-- <el-select v-model="ruleForm.group">
                            <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select> -->
                    </el-form-item>
                    <div class="button" @click="handleSubmit">Simpan Perubahan</div>
                </el-form>
            </div>
        </div>
    </popup>
    <!-- 放大地图 -->
    <popup class="map-popup" v-model:show="showPopup" round closeable>
        <div class="map-name">{{ route.query.name }}</div>
        <map-item key="popup" ref="myMap" :locationId="route.query.id" :showOverview="false"></map-item>
        <!-- <map-item key="popup" ref="myMap" :isPopup="true" @toSmall="toSmall" :mapData="mapData[mapIndex].pointArr"></map-item> -->
    </popup>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { Icon } from 'vant';
import commonBox from "@/components/commonBox";
import mapItem from "./components/mapItem";
import IndexMap from "./map/index";
import eventBus from "@/api/eventBus";
import { Popup } from "vant";
import { onMounted, ref, reactive, nextTick } from "vue";
import { useRoute } from "vue-router";
import lineChart from "@/components/charts/lineChart";
const route = useRoute();

const activeName = ref('first')

const handleClick = (tab, event) => {
  console.log(tab, event)
}

const xData = ref([])
const yData = ref([])

const showPopup = ref(false)
const myMap = ref(null)
function toggleMapPopup() {
    showPopup.value = true
    nextTick(()=>{
        myMap.value.updateMapDate(curData.value.geom, curData.value?.locationCode);
    })
}

const baseList = ref([
    {
        name: "Location",
        value: "#01A",
        key: "locationCode",
        color: "#D2F3DE",
    },
    {
        name: "Fight Date",
        value: "9 JAN",
        key: "createDate",
        color: "#F5F5F5",
    },
    {
        name: "Plant Age",
        value: "F-11",
        key: "age",
        color: "#F5F5F5",
    },
    {
        name: "Achivement",
        value: "74",
        key: "achivement",
        unit: "%",
        color: "#FFE6E6",
    },
    {
        name: "Loss Population",
        value: "26",
        key: "lossPopulation",
        unit: "",
        color: "#FFE6E6",
    },
]);

const plantList = ref([
    {
        name: "Wilayah",
        value: "W01",
        key: "wilayahName",
    },
    {
        name: "Area Bruto",
        value: "10.21",
        key: "area",
        unit: "Ha",
    },
    {
        name: "Status",
        value: "NSFC",
        key: "status",
    },
    {
        name: "Area Netto",
        value: "9.33",
        key: "areaNetto",
        unit: "Ha",
    },
    {
        name: "Plant Age",
        value: "F-11",
        key: "age",
    },
    {
        name: "Seed",
        value: "Sucker/Kecil",
        key: "seed",
    },
    {
        name: "Plant Maintenance Date",
        value: "Januari 9,2025",
        key: "plantingDate",
    },
    {
        name: "Standar pop",
        value: "68.000",
        key: "standarPop",
    },
]);

//表格数据
const tableData = ref([]);
const getTableList = () => {
    VE_API.region.plotList({ locationId:plotId.value }).then((res) => {
        tableData.value = res.data || [];
    });
};

const showMapPopup = ref(false);
const ruleForm = reactive({
    name: "",
});
const options = [
    {
        value: "Plantation Group 1",
        label: "Plantation Group 1",
    },
    {
        value: "Option2",
        label: "Option2",
    },
    {
        value: "Option3",
        label: "Option3",
    },
    {
        value: "Option4",
        label: "Option4",
    },
    {
        value: "Option5",
        label: "Option5",
    },
];
const rules = reactive({
    id: [{ required: true, message: "Please input Activity name", trigger: ["change", "blur"] }],
    name: [
        {
            required: true,
            message: "Please input Activity name",
            trigger: ["change", "blur"],
        },
    ],
    group: [
        {
            required: true,
            message: "Please select Activity group",
            trigger: ["change", "blur"],
        },
    ],
});

const popupMap = ref(null);
const indexMap = new IndexMap();

const handleZoom = (type) =>{
    indexMap.zoomMap(type)
}

//删除点
const handleDelete = () =>{
    indexMap.removePoint();
}

//取消选中
const handleClear = () =>{
    indexMap.clearSelectPoint();
    isHide.value = false
}

//编辑
const rowData = ref({})
const handleEdit = (index, row) => {
    ruleForm.name = row.name
    rowData.value = row
    showMapPopup.value = true;
    nextTick(()=>{
        indexMap.initMap("POINT(105.3251497742969 -4.76353839996651)", popupMap.value);
        indexMap.setAreaGeometry([{ featureWkt: row.geom }])
    })
};

//保存
const handleSubmit = () =>{
    const { geometryArr } = indexMap.getAreaGeometry();
    const params = {
        ...rowData.value,
        name:ruleForm.name,
        geom:geometryArr[0].featureWkt
    }
    VE_API.home.plotSave(params).then(res =>{
        if(res.success){
            showMapPopup.value = false
            ElMessage.success('Saved Successfully')
            getTableList()
        }
    })
}

const closePopup = () =>{
    indexMap.clearLayer();
}

const detailMap = ref(null);

function formatDate(data) {
    const date = new Date(data);
    const formatter = new Intl.DateTimeFormat("en-US", {
        month: "long", // 或 'short'
        day: "numeric",
        year: "numeric",
    });
    return formatter.format(date);
}

const curData = ref({})
const getDetailData = () => {
    VE_API.home.locationList({ id:plotId.value }).then((res) => {
        if(res.data.length===0) return
        const resData = res.data[0];
        curData.value = resData
        baseList.value.forEach((item) => {
            if (item.key === "createDate") {
                item.value = formatDate(resData[item.key]);
            } else {
                item.value = resData[item.key];
            }
        });
        plantList.value.forEach((item) => {
            if (item.key === "plantingDate") {
                item.value = formatDate(resData[item.key]);
            } else {
                item.value = resData[item.key];
            }
        });
        detailMap.value.updateMapDate(resData.geom, resData?.locationCode);
    });
};

function getSummary(param) {
  const columns = param.columns;
  const data = param.data;
  const sums = [];

  for (let i = 0; i < columns.length; i++) {
    if (i === 0) {
      sums[i] = 'total';
      continue;
    }

    let sum = 0;
    let count = 0;
    let canSum = true;

    for (let j = 0; j < data.length; j++) {
      const value = Number(data[j][columns[i].property]);
      if (isNaN(value)) {
        canSum = false;
        break;
      }
      sum += value;
      count++;
    }

    if (canSum) {
      let result = sum;
      if (i === 2 || i === 4 || i === 5) { // 假设索引从0开始，所以第3列是索引2，第5列是索引4，第6列是索引5
        result = sum / count;
      }
      const isDecimal = result % 1 !== 0;
      sums[i] = isDecimal ? result.toFixed(2) : result;
    } else {
      sums[i] = '';
    }
  }

  return sums;
}


const isHide = ref(false)
function mapPointFun(){
    isHide.value = true
}
const plotId = ref(null)
onMounted(() => {
    let { id } = route.query;
    plotId.value = id
    getDetailData();
    getTableList();
    eventBus.off('map:point',mapPointFun)
    eventBus.on('map:point',mapPointFun)

    setTimeout(()=>{
        xData.value = ['F-13', 'F-12', 'F-11']
        yData.value = [73890, 73977, 73977]
    })
});
</script>

<style lang="scss" scoped>
.base-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    .common-item {
        display: flex;
        align-items: center;
        flex-direction: column;
        justify-content: center;
        background: #f5f5f5;
        border-radius: 6px;
        .label {
            color: #666666;
        }
    }
    .base-list {
        display: flex;
        width: 100%;
        .base-item {
            flex: 1;
            height: 85px;
            .value {
                font-size: 32px;
            }
            .label {
                margin-top: 5px;
            }
        }
        .base-item + .base-item {
            margin-left: 16px;
        }
    }
    .box-wrap {
        display: flex;
        margin: 16px 0;
        .map-wrap {
            width: 890px;
            position: relative;
            .map {
                width: 100%;
                height: calc(100% - 21px - 12px);
            }
            .big-icon {
                position: absolute;
                bottom: 20px;
                right: 20px;
                cursor: pointer;
            }
        }
        .plant-wrap {
            width: calc(100% - 890px - 10px);
            margin-left: 16px;
            .plant-list {
                display: flex;
                flex-wrap: wrap;
                margin: -8px 0;
                .plant-item {
                    width: 23%;
                    height: 145px;
                    margin: 8px;
                    .value{
                        font-size: 20px;
                    }
                }
            }
        }
    }
    .card-wrap {
        width: 100%;
        display: flex;
        height: calc(100% - 219px - 241px - 90px);
        .table-wrap{
            width: calc(100% - 456px - 16px);
        }
        .table {
            width: 100%;
            height: calc(100% - 31px);
            .edit {
                width: 36px;
                height: 36px;
                border: 1px solid #dddddd;
                border-radius: 8px;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                .icon {
                    width: 13px;
                    height: 16px;
                }
            }
        }
        .info-wrap {
            width: 456px;
            height: 100%;
            margin-left: 16px;
            .tabs-wrap{
                height: calc(100% - 31px);
                ::v-deep {
                    .el-tabs__item.is-active,
                    .el-tabs__item:hover {
                        color: #00a342;
                    }
                    .el-tabs__active-bar {
                        height: 3px;
                        background: #00a342;
                    }
                }
            }
            .line-chart{
                width: 456px;
                height: calc(100vh - 219px - 241px - 311px);
            }
            .info-list {
                width: 100%;
                height: 100%;
                overflow: auto;
                .info-item {
                    color: #00a342;
                    font-size: 17px;
                    line-height: 26px;
                    .icon {
                        width: 19px;
                        height: 14px;
                        margin-right: 8px;
                    }
                }
            }
        }
    }
}

.edit-popup {
    width: 60%;
    height: auto;
    padding: 24px 20px;
    z-index: 2000;
    overflow: hidden;
    .title {
        display: flex;
        align-items: center;
        font-size: 20px;
        margin-bottom: 24px;
        img {
            width: 19px;
            height: 19px;
            margin-right: 12px;
        }
    }
    .content {
        display: flex;
        .map-wrap {
            width: calc(100% - 328px - 14px);
            position: relative;
            .map {
                width: 100%;
                height: 100%;
                clip-path: inset(0px round 8px);
            }
            .delete {
                position: absolute;
                right: 12px;
                top: 12px;
                background: #fff;
                padding: 8px 11px;
                border-radius: 5px;
                font-size: 20px;
                cursor: pointer;
            }
            .close{
                position: absolute;
                right: 62px;
                top: 12px;
                background: #fff;
                padding: 8px 11px;
                border-radius: 5px;
                font-size: 20px;
                cursor: pointer;
            }
            .polygon-info {
                position: absolute;
                left: 12px;
                top: 12px;
                padding: 8px 11px;
                background: #fff;
                border-radius: 4px;
                .info {
                    margin-top: 8px;
                    .text {
                        display: flex;
                        align-items: center;
                        font-size: 12px;
                        color: #666666;
                        .label {
                            width: 78px;
                        }
                        .value {
                            margin-left: 15px;
                            color: #00a342;
                            padding: 4px;
                            min-width: 82px;
                            text-align: center;
                            border-radius: 4px;
                            background: rgba(0, 163, 66, 0.1);
                        }
                    }
                    .text + .text {
                        margin-top: 6px;
                    }
                }
            }
            .operations {
                position: absolute;
                right: 12px;
                bottom: 12px;
                cursor: pointer;
                display: flex;
                flex-direction: column;
                img {
                    width: 36px;
                    height: 36px;
                }
            }
        }
        .map-info {
            margin-left: 14px;
            width: 328px;
            .info-title {
                display: flex;
                align-items: center;
                font-size: 16px;
                margin-bottom: 22px;
                img {
                    width: 18px;
                    height: 18px;
                    margin-right: 8px;
                }
            }
            .button {
                margin-top: 178px;
                padding: 14px;
                width: 100%;
                box-sizing: border-box;
                background: #00a342;
                border-radius: 4px;
                color: #fff;
                text-align: center;
                cursor: pointer;
            }
        }
    }
}

.map-popup {
    width: 60%;
    height: 80%;
    .map-name {
        color: #fff;
        z-index: 20;
        position: absolute;
        top: 13px;
        left: 13px;
        background: rgba(0, 0, 0, 0.6);
        font-size: 16px;
        padding: 8px 24px;
        border-radius: 20px;
        cursor: pointer;
    }
}
</style>
