<template>
    <div class="base-container">
        <fnHeader :hideSwitch="true" :hideShadow="true" showDate></fnHeader>
        <div class="content">
            <div class="left">
                <div class="btn" @click="goBack">
                    <img src="@/assets/images/common/back-icon.png" alt="" />
                    返回
                </div>
                <chart-box class="left-cont" :name="isAdd ? '新增农事' : '编辑农事'" color="yellow">
                    <template #title-right>
                        <steps v-if="isAdd" :active="active"></steps>
                    </template>
                    <div class="box">
                        <div class="box-item" v-if="active === 0">
                            <div class="box-title">
                                <div>
                                    选择农事类型
                                    <span>(可多选)</span>
                                </div>
                            </div>
                            <div class="list">
                                <div
                                    class="list-item"
                                    @click="handleItem(item, index)"
                                    :class="{ active: item.active }"
                                    v-for="(item, index) in checkData"
                                    :key="index"
                                >
                                    {{ item.name }}
                                    <el-icon size="25" color="#FFD489" v-show="item.active"
                                        ><CircleCheckFilled
                                    /></el-icon>
                                    <div v-show="!item.active" class="round"></div>
                                </div>
                            </div>
                        </div>
                        <template v-else>
                            <el-form class="box-form" ref="formRef" :model="dynamicValidateForm" :rules="rules">
                                <div class="box-item">
                                    <div class="box-title">基本信息</div>
                                    <el-form-item label="农事名称" prop="name">
                                        <el-input v-model="dynamicValidateForm.name" />
                                    </el-form-item>
                                    <el-form-item label="触发条件" prop="conditionRate">
                                        <el-input v-model="dynamicValidateForm.conditionRate" />
                                    </el-form-item>
                                    <el-form-item label="执行时间" prop="executeDate">
                                        <el-date-picker
                                            class="item-input"
                                            style="width: 100%"
                                            value-format="YYYY-MM-DD"
                                            v-model="dynamicValidateForm.executeDate"
                                            type="date"
                                            :clearable="false"
                                            placeholder="选择日期"
                                        />
                                    </el-form-item>
                                </div>
                                <div class="usage-mode box-form">
                                    <el-form-item label="执行分区" prop="regionId">
                                        <div class="mode-select">
                                            <el-select
                                                v-model="dynamicValidateForm.regionId"
                                                placeholder="请选择"
                                                style="width: 100%"

                                                @change="changeRegion"
                                            >
                                            <el-option v-for="(area, index) in areaList" :key="index" :label="area.name" :value="area.id">
                                            </el-option>
                                            </el-select>
                                        </div>
                                    </el-form-item>
                                    <el-form-item label="服务亩数" prop="regionId">
                                        <div class="mode-select">
                                            {{ dynamicValidateForm.area }}亩
                                        </div>
                                    </el-form-item>
                                </div>
                                <div class="usage-mode box-form">
                                    <el-form-item label="施用方式" prop="usageMode">
                                        <div class="mode-select">
                                            <el-select
                                                v-model="dynamicValidateForm.usageMode"
                                                placeholder="请选择"
                                                prop="usageMode"
                                                style="width: 100%"
                                            >
                                                <el-option
                                                    v-for="(usage, uId) in allUsageModeList"
                                                    :key="uId"
                                                    :label="usage"
                                                    :value="usage"
                                                />
                                            </el-select>
                                        </div>
                                    </el-form-item>
                                </div>
                            </el-form>
                            <div
                                class="box-item"
                                v-for="(item, index) in dynamicValidateForm.prescriptionList"
                                :key="index"
                            >
                                <div class="box-title border-none">
                                    {{ item.name }}处方
                                    <div class="add-text" @click="handleAdd(index)">
                                        <el-icon class="icon"><Plus /></el-icon>
                                        添加药物
                                    </div>
                                </div>
                                <div
                                    class="box-item-children"
                                    v-for="(ele, idx) in item.pesticideFertilizerList"
                                    :key="idx + 'id'"
                                >
                                    <div class="index">{{ idx < 10 ? "0" + (idx + 1) : idx + 1 }}</div>
                                    <custom-table
                                        @updateTableData="updateTableData"
                                        :pIndex="index"
                                        :cIndex="idx"
                                        :key="index + '-' + idx"
                                        :pesticideFertilizerList="ele"
                                        :hasFly="dynamicValidateForm.usageMode === '叶面施'"
                                    ></custom-table>
                                    <div class="box-textarea">
                                        <el-input
                                            class="textarea"
                                            v-model="ele.remark"
                                            :rows="1"
                                            type="textarea"
                                            placeholder="用药注意事项备注"
                                        />
                                    </div>
                                    <div class="btn-group">
                                        <div class="delete" @click="handleDelete(index, idx)">删除</div>
                                        <div @click="resetItem(index, idx)">重置</div>
                                    </div>
                                </div>
                            </div>
                            <div class="box-item">
                                <el-input
                                    class="textarea"
                                    v-model="textarea"
                                    type="textarea"
                                    placeholder="用药注意事项备注"
                                />
                            </div>
                        </template>
                    </div>
                    <div class="footer">
                        <el-button v-if="!isAdd" class="button delete" type="danger" plain @click="remove()">删除</el-button>
                        <div class="button" @click="handleOk">{{ active === 0 ? "确定" : (isAdd ? "新增农事" : "下发农事") }}</div>
                    </div>
                </chart-box>
            </div>
            <div class="right">
                <div class="map-header">
                    <div class="title">
                        <img src="@/assets/images/common/area-icon.png" alt="" />
                        执行农事区域
                    </div>
                    <div class="check-btn"><el-checkbox v-model="checkedArea" @change="handleArea" label="全选" size="large" /></div>
                </div>
                <div ref="mapRef" class="map">
                    <div class="map-bg map-btn">查看巡园照片</div>
                    <div class="map-bg map-legend">
                        <div class="legend-item legend-title">
                            <el-checkbox v-model="showMapLegend" @change="handleLegend" label="状态图例" size="large" />
                        </div>
                        <div class="item">
                            <img src="@/assets/images/map/status/status-zc.png" alt="" />
                            正常
                        </div>
                        <div class="item">
                            <img src="@/assets/images/map/status/status-szyc.png" alt="" />
                            生长异常
                        </div>
                        <div class="item">
                            <img src="@/assets/images/map/status/status-bh.png" alt="" />
                            病害异常
                        </div>
                        <div class="item">
                            <img src="@/assets/images/map/status/status-ch.png" alt="" />
                            虫害异常
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { onMounted, ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import fnHeader from "@/components/fnHeader.vue";
import steps from "./components/steps.vue";
import customTable from "./components/table.vue";
import FarmMap from "./farmMap";
import { deepClone } from "@/common/commonFun";
import chartBox from "@/components/chartBox.vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import eventBus from "@/api/eventBus";
let store = useStore();
let farmMap = new FarmMap();

const active = ref(0);

const checkData = ref([
    { value: 1, name: "生长异常", active: true, children: [{ index: 1 }] },
    { value: 3, name: "病虫异常", active: false, children: [{ index: 1 }] },
    { value: 2, name: "营养农事", active: false, children: [{ index: 1 }] },
]);
const handleItem = (item, index) => {
    checkData.value[index].active = !checkData.value[index].active;
    // const curIndex = checkValue.value.indexOf(item.value)
    // if(curIndex===-1){
    //     checkValue.value.push(item.value)
    // }else{
    //     checkValue.value.splice(curIndex,1)
    //     checkList.value[index].active = false
    // }
};

const router = useRouter();
const route = useRoute();
const mapRef = ref();
const farmId = sessionStorage.getItem("farmId");

// 所选蓝色分区的面积
const getArea = (val) => {
    dynamicValidateForm.area = val.toFixed(2);
};
// 是否为新增
const isAdd = ref(true);

const libId = route.query?.libId
onMounted(async () => {

    farmMap.initMap("POINT(113.61448114737868 23.585550924763083)", mapRef.value);
    isAdd.value = route.query?.isAdd;
    if (!isAdd.value) {
        active.value = 1
        getList()
    }
    await getAreaList();
    dynamicValidateForm.regionId = Number(sessionStorage.getItem("regionId")) ? Number(sessionStorage.getItem("regionId")) : areaList.value[0].id;
    // farmMap.initData(farmId, dynamicValidateForm.regionId)
});
eventBus.off("editNsMap:areaVal", getArea)
eventBus.on("editNsMap:areaVal", getArea)

// 农场分区列表
const areaList = ref([]);
const orderIdVal = ref("");
const workItemData = ref({});
const getAreaList = async (callback) => {
   await VE_API.area.list({ farmId }).then(({ data, code }) => {
        areaList.value = data;
        // if (isAdd.value) {
        //     regionId.value = data && data.length && data[0].id
        // } else {
        //     regionId.value = workItemData.value.regionId
        // }
        if (isAdd.value) {
            changeRegion(dynamicValidateForm.regionId);
        }
        callback && callback();
    });
};
const id = route.query?.id
function getList() {
    VE_API.farm.fetchFarmWorkList({ farmId, libId ,id}).then(({data}) => {
        workItemData.value = data[0]
        Object.assign(dynamicValidateForm, workItemData.value)
        dynamicValidateForm.name = workItemData.value.farmWorkName
        for(let item of  workItemData.value.conditionList){
          dynamicValidateForm.conditionRate=item.name + "大于" + (parseFloat(item.value) * 100) + "%";
        }

        farmMap.initData(workItemData.value.farmId, workItemData.value.regionId)
        farmMap.getBlueRegion({gardenId:  workItemData.value.farmId, regionId: workItemData.value.regionId}, (e) => {
            checkedArea.value = workItemData.value.executeBlueZones.length === e
            farmMap.setBlueRegion(workItemData.value.executeBlueZones)
        });
    })
}


const farmObj = ref();
const serviceRegion = ref("");
const getFarmObj = () => {
    VE_API.farm.fetchFarmDetail({ id: farmId }).then(({ data }) => {
        farmObj.value = data;
        if (serviceRegion.value === "") {
            serviceRegion.value = data.district + data.address + data.name;
        }
    });
};

// 切换分区
const checkedArea = ref(false);
const changeRegion = (e) => {
    dynamicValidateForm.area = 0;
    checkedArea.value = false;
    farmMap.initData(farmId, dynamicValidateForm.regionId)
    farmMap.getBlueRegion({ gardenId: farmId, regionId: e });
};

const handleArea = (e) => {
    farmMap.toggleAllArea(e)
}

// 地图图例
const showMapLegend = ref(true);
const handleLegend = (e) => {
    farmMap.toggleLegend(e);
};

const goBack = () => {
    router.go(-1);
};


const remove = () => {
    ElMessageBox.confirm("是否要删除这个农事?", "警告", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        VE_API.farm.deleteFarmWork({ libId }).then(({ code }) => {
            if (code === 0) {
                ElMessage({
                    type: "success",
                    message: "删除成功！",
                });
                setTimeout(() => {
                    router.go(-1);
                }, 500);
            }
        });
    });
};

//确定/下发农事
const handleOk = () => {
    if (active.value) {
        formRef.value.validate((valid) => {
            if (valid) {
                submitForm();
                // const res = tableData.value.getItem
                // console.log('res', res);
            }
        });
    } else {
        active.value = 1;
        const arr = checkData.value.filter((item) => item.active);
        // boxList.value = deepClone(arr);

        dynamicValidateForm.prescriptionList = arr.map((item) => ({
            name: item.name,
            active: item.active,
            pesticideFertilizerList: [
                {
                    key: 1,
                    typeName: "",
                    muUsage: "",
                    muUsage2: "",
                    ratio: "",
                    ratio2: "",
                    remark: "",
                },
            ],
        }));
    }
};
async function submitForm() {
    const executeBlueZones = farmMap.getSelectedBlueRegion();
    if (!executeBlueZones || !executeBlueZones.length) {
        ElMessage({
            message: "请选择执行区域",
            type: "warning",
        });
        return false;
    }
    let data = {
        ...dynamicValidateForm,
        executeBlueZones,
        remark: textarea.value,
        farmId,
    };
    console.log('dddd', data);
    let res = null;
    if (isAdd.value) {
        data.farmWorkType = 1;
        // data.name = name.value;
        // data.condition = condition.value;
        // 新增农事
        res = await VE_API.farm.saveFarmWork(data);
    } else {
        data = {...data, orderStatus: 1,}
        res = await VE_API.farm.confirm(data);
    }
    if (res?.code == 0) {
        ElMessage({
            message: "保存成功",
            type: "success",
        });
        router.go(-1);
    }
}

// 表单
const formRef = ref();

const allUsageModeList = ["叶面施", "根部施"];
let dynamicValidateForm = reactive({
    name: "",
    conditionRate: "",
    executeDate: "",
    usageMode: "",
    regionId: "",
    prescriptionList: [
        {
            name: "",
            pesticideFertilizerList: [
                {
                    key: 1,
                    typeName: "",
                    muUsage: "",
                    muUsage2: "",
                    ratio: "",
                    ratio2: "",
                    remark: "",
                },
            ],
        },
    ],
});

const rules = {
    name: [
        {
            required: true,
            message: "请输入农事名称",
            trigger: "blur",
        },
    ],
    conditionRate: [
        {
            required: true,
            message: "请输入触发条件",
            trigger: "blur",
        },
    ],
    executeDate: [
        {
            required: true,
            message: "请选择执行时间",
            trigger: "blur",
        },
    ],
    usageMode: [
        {
            required: true,
            message: "请选择施用方式",
            trigger: "change",
        },
    ],
    regionId: [
        {
            required: true,
            message: "请选择执行区域",
            trigger: "change",
        },
    ],
};
const textarea = ref("");

// 添加
const handleAdd = (index) => {
    dynamicValidateForm.prescriptionList[index].pesticideFertilizerList.push({
        index: 1,
        name: "",
        pesticideFertilizerList: [
            {
                key: 1,
                typeName: "",
                muUsage: "",
                muUsage2: "",
                ratio: "",
                ratio2: "",
                remark: "",
            },
        ],
    });
};

// 删除
const handleDelete = (index, childIndex) => {
    // if (boxList.value[index].children.length === 1) return ElMessage.warning("最少保留一个处方");
    dynamicValidateForm.prescriptionList[index].pesticideFertilizerList.splice(childIndex, 1);
};

// 重置
function resetItem(index, childIndex) {
    dynamicValidateForm.prescriptionList[index].pesticideFertilizerList[childIndex] = {
        key: 1,
        pesticideFertilizerId: "",
        typeName: "",
        muUsage: "",
        muUsage2: "",
        ratio: "",
        ratio2: "",
        remark: "",
    };
}

function updateTableData(pIndex, cIndex, tableData) {
    dynamicValidateForm.prescriptionList[pIndex].pesticideFertilizerList[cIndex] = {
        ...tableData,
    };
}
</script>

<style lang="scss" scoped>
.base-container {
    width: 100%;
    height: 100vh;
    color: #fff;
    position: relative;
    box-sizing: border-box;
    z-index: 1;
    background: #000;

    .content {
        width: 100%;
        height: calc(100% - 74px);
        display: flex;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 20px;
        .left {
            width: 473px;
            height: 100%;
            box-sizing: border-box;
            .btn {
                display: flex;
                align-items: center;
                justify-content: center;
                border: 1px solid rgba(255, 255, 255, 0.78);
                border-radius: 4px;
                padding: 9px;
                margin-bottom: 13px;
                width: 104px;
                cursor: pointer;
                img {
                    width: 14px;
                    margin-right: 5px;
                }
            }
            .left-cont {
                width: 100%;
                height: calc(100% - 48px - 4px);
                .box {
                    width: 100%;
                    height: calc(100% - 58px);
                    padding: 16px 12px;
                    box-sizing: border-box;
                    overflow-y: auto;
                    .box-item {
                        background: rgba(255, 255, 255, 0.04);
                        border: 1px solid #444444;
                        border-radius: 8px;
                        padding: 16px 12px 8px 12px;
                        box-sizing: border-box;
                        width: 100%;
                        .box-title {
                            font-size: 20px;
                            border-bottom: 1px solid #333333;
                            padding: 0 0 12px 13px;
                            margin-bottom: 21px;
                            position: relative;
                            display: flex;
                            justify-content: space-between;
                            &.border-none {
                                border: none;
                                padding-bottom: 0;
                            }
                            &::before {
                                content: "";
                                position: absolute;
                                left: 0;
                                top: 6px;
                                width: 3px;
                                height: 16px;
                                background: #fff;
                                border-radius: 11px;
                            }
                            span {
                                font-size: 14px;
                                color: #9f9f9f;
                            }
                            .add-text {
                                font-size: 16px;
                                color: #ffd489;
                                display: flex;
                                align-items: center;
                                cursor: pointer;
                                .icon {
                                    margin-right: 3px;
                                }
                            }
                        }
                        .list {
                            .list-item {
                                background: rgba(255, 255, 255, 0.05);
                                border-radius: 8px;
                                font-size: 18px;
                                padding: 16px;
                                display: flex;
                                align-items: center;
                                justify-content: space-between;
                                border: 1px solid transparent;
                                cursor: pointer;
                                &.active {
                                    border-color: #ffd489;
                                    background: rgba(255, 212, 137, 0.05);
                                }
                                .round {
                                    border: 1px solid #cecece;
                                    border-radius: 50%;
                                    width: 20px;
                                    height: 20px;
                                }
                            }
                            .list-item + .list-item {
                                margin-top: 16px;
                            }
                        }

                        .box-item-children {
                            border: 1px solid #444444;
                            border-radius: 8px;
                            padding: 9px;
                            box-sizing: border-box;
                            position: relative;
                            .index {
                                position: absolute;
                                top: 0;
                                left: 0;
                                background: #ffd489;
                                border-radius: 4px 0 4px 0;
                                font-size: 12px;
                                color: #1d1d1d;
                                padding: 0 7px;
                            }
                            .box-textarea {
                                border-radius: 4px;
                                padding: 10px;
                                background: rgba(255, 255, 255, 0.05);
                                margin: 16px 0 20px 0;
                            }
                            .btn-group {
                                display: flex;
                                div {
                                    background: rgba(255, 212, 137, 0.05);
                                    border-radius: 4px;
                                    border: 1px solid #ffd489;
                                    padding: 6px;
                                    flex: 1;
                                    color: #ffd489;
                                    text-align: center;
                                    cursor: pointer;
                                }
                                .delete {
                                    background: rgba(249, 152, 81, 0.05);
                                    border: 1px solid #f99851;
                                    color: #f99851;
                                    margin-right: 12px;
                                }
                            }
                        }
                        .box-item-children + .box-item-children {
                            margin-top: 12px;
                        }
                        .textarea {
                            ::v-deep {
                                .el-textarea__inner {
                                    background: transparent;
                                    box-shadow: none;
                                    color: #fff;
                                    padding: 0;
                                }
                            }
                        }
                    }
                    .box-item + .box-item {
                        margin-top: 16px;
                    }
                }

                // 编辑处方
                .box-form {
                    ::v-deep {
                        .el-form-item {
                            width: 100%;
                        }
                        .el-form-item__label {
                            font-size: 16px;
                            color: #9f9f9f;
                        }
                        .el-input__wrapper {
                            background: transparent;
                            box-shadow: 0 0 0 1px #9f9f9f;
                            .el-input__inner {
                                color: #fff;
                            }
                        }
                    }
                }

                .usage-mode {
                    // display: flex;
                    // align-items: center;
                    color: #9f9f9f;
                    padding: 16px 21px 0px 12px;
                    border: 1px solid #363636;
                    background: rgba(255, 255, 255, 0.04);
                    border-radius: 8px;
                    font-size: 16px;
                    margin: 16px 0;
                    width: 100%;
                    box-sizing: border-box;
                    .usage-title {
                        padding-right: 20px;
                    }
                    .mode-select {
                        flex: 1;
                    }
                    ::v-deep {
                        .el-select__wrapper {
                            background: transparent;
                            box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.6) inset;
                        }
                        .el-select__placeholder,
                        .el-select__caret {
                            // color: #ffd489;
                            color: #fff;
                        }
                    }
                }

                .footer {
                    width: 100%;
                    height: 58px;
                    border-top: 0.5px solid #555555;
                    background: rgba(255, 255, 255, 0.04);
                    display: flex;
                    justify-content: flex-end;
                    align-items: center;

                    .button {
                        font-size: 16px;
                        padding: 8px 58px;
                        background: #ffd489;
                        border-radius: 4px;
                        color: #000;
                        margin-right: 12px;
                        cursor: pointer;
                        &.delete {
                            background: rgba(255, 148, 61, 0.1);
                            color: #FF943D;
                            border: 1px solid #FF943D;
                        }
                    }
                }
            }
        }
        .right {
            width: calc(100% - 473px - 18px);
            margin-left: 18px;
            height: 100%;
            background: #191919;
            border: 0.6px solid #444444;
            padding: 20px;
            box-sizing: border-box;
            border-radius: 8px;
            .map-header {
                display: flex;
                justify-content: space-between;
                .title {
                    font-size: 22px;
                    display: flex;
                    align-items: flex-end;
                    font-family: "PangMenZhengDao";
                    margin-bottom: 16px;
                    img {
                        margin-right: 8px;
                    }
                }
                .check-btn {
                    ::v-deep {
                        .el-checkbox {
                            color: #fff;
                            font-size: 20px;

                        }
                    }
                }
            }
            .map {
                width: 100%;
                clip-path: inset(0px round 4px);
                height: calc(100% - 31px - 16px);
                position: relative;
                .map-bg {
                    position: absolute;
                    z-index: 2;
                    background: rgba(0, 0, 0, 0.6);
                    border-radius: 18px;
                    padding: 7px 16px;
                    right: 20px;
                }
                .map-btn {
                    top: 19px;
                    cursor: pointer;
                }
                .map-legend {
                    bottom: 21px;
                    .item {
                        display: flex;
                        align-items: center;
                        font-size: 14px;
                        img {
                            width: 16px;
                            margin-right: 6px;
                        }
                    }
                .legend-title {
                    border-bottom: 1px solid rgba(102, 102, 102, 0.35);
                }
                    .item + .item {
                        padding-top: 10px
                    }
                }
            }
        }
    }
}
</style>
