<template>
    <div class="new-farming-page" ref="pageRef">
        <custom-header :name="isEdit ? (onlyPrice ? '编辑报价' : '编辑方案') : '查看详情'"></custom-header>
        <div class="new-farming-content" :class="{ 'no-permission': !hasPlanPermission }">
            <el-form
                ref="formRef"
                style="max-width: 600px"
                label-position="left"
                :rules="rules"
                :model="dynamicValidateForm"
                class="demo-dynamic"
            >
                <div class="farm-card">
                    <div class="card-title between common-inputs">
                        <div>{{ detailData?.name }}<span class="type-tag">标准农事</span></div>
                        <el-select v-if="isEdit" size="small" v-model="tagName" placeholder="标记为" style="width: 94px">
                            <el-option
                                v-for="item in tagList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                        <div class="edit-tag tag-text" v-else>{{ statusMap[tagName] }}</div>
                        <!-- <el-tooltip
                            effect="dark"
                            placement="left"
                        >
                            <template #content>
                                <div class="tag-item">全托管</div>
                                <div class="tag-item">飞防托管</div>
                                <div class="tag-item">营养托管</div>
                            </template>
                            <div class="title-tag add-tag">托管用户</div>
                        </el-tooltip> -->
                    </div>
                    <div class="info-content">
                        <el-form-item label-width="70px" class="form-item text-item" label="农事编号">
                            <div class="info-text">
                                {{ detailData?.code }}
                            </div>
                        </el-form-item>
                        <el-form-item v-if="!noPrice" label-width="70px" class="form-item text-item" label="服务亩数">
                            <div class="info-text">
                                {{ detailData?.farm?.mianji ? formatArea(detailData?.farm?.mianji) + "亩" : "--" }}
                            </div>
                        </el-form-item>
                        <el-form-item v-if="!noPrice" label-width="70px" class="form-item text-item" label="服务区域">
                            <div class="info-text">
                                {{ detailData?.farm?.address || "--" }}
                            </div>
                        </el-form-item>
                        <el-form-item
                            v-if="isEdit"
                            label-width="70px"
                            class="form-item"
                            prop="executeDate"
                            label="执行时间"
                        >
                            <el-date-picker
                                class="item-input"
                                style="width: 100%"
                                value-format="YYYY-MM-DD"
                                v-model="dynamicValidateForm.executeDate"
                                type="date"
                                :clearable="false"
                                placeholder="选择日期"
                                :editable="false"
                            />
                        </el-form-item>
                        <el-form-item v-else label-width="70px" class="form-item text-item" label="执行时间">
                            <div class="info-text">
                                {{ detailData?.executeDate }}
                            </div>
                        </el-form-item>
                    </div>
                </div>

                <div class="farm-card" v-if="!onlyPrice">
                    <!-- 农情互动 -->
                    <div class="card-title border-bottom between">
                        <div>农情互动</div>
                        <!-- <span class="del-tag">删除互动</span> -->
                    </div>
                    <div v-if="isEdit" class="interact-form">
                        <div class="interact-form-item" data-interact-field="phenologyId">
                            <div class="form-label">
                                互动阶段
                            </div>
                            <div class="form-input-wrapper two-select">
                                <div class="select-item">
                                    <el-select
                                        style="width: 100%"
                                        v-model="interactFormData.phenologyId"
                                        placeholder="请选择物候期"
                                        @change="handlePhenologyChange"
                                        :editable="false">
                                        <el-option
                                            v-for="item in phenologyList"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                        ></el-option>
                                    </el-select>
                                </div>
                                <div class="select-item">
                                    <el-select style="width: 100%" v-model="interactFormData.reproductiveId" placeholder="请选择物候期" :editable="false">
                                        <el-option
                                            v-for="item in reproductiveList"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                        ></el-option>
                                    </el-select>
                                </div>
                            </div>
                        </div>
                        <div class="interact-form-item" data-interact-field="interactionTime">
                            <div class="form-label">
                                互动日期
                            </div>
                            <div class="form-input-wrapper">
                                <el-date-picker
                                    v-model="interactFormData.interactionTime"
                                    disabled
                                    style="width: 100%"
                                    type="date"
                                    placeholder="请选择日期"
                                    :editable="false"
                                />
                            </div>
                        </div>
                        <div class="interact-form-item" data-interact-field="interactionQuestion">
                            <div class="form-label">
                                互动问题
                            </div>
                            <el-input
                                v-model="interactFormData.interactionQuestion"
                                type="textarea"
                                :rows="3"
                                show-word-limit
                                maxlength="35"
                                placeholder="请设置互动问题"
                                class="question-textarea"
                            />
                        </div>
                    </div>
                    <div v-else class="interact-content">
                        {{ interactFormData?.interactionQuestion }}
                        <!-- <span class="edit-tag" @click="handleEditInteract(detailData)">点击编辑</span> -->
                    </div>
                </div>

                <template v-if="isEdit">
                    <div class="farm-card prescription-content common-inputs">
                        <div class="card-title pb-12 between">
                            药物处方
                            <div class="add-tag" @click="addDomain()">
                                <el-icon color="#2199F8"><Plus /></el-icon>新增药物
                            </div>
                        </div>
                        <el-form-item label-width="82px" class="form-item" prop="usageMode" label="施用方式">
                            <el-select
                                v-model="dynamicValidateForm.prescription.usageMode"
                                placeholder="请选择施用方式"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="(usage, uId) in allUsageModeList"
                                    :key="uId"
                                    :label="usage"
                                    :value="usage"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="dynamicValidateForm.prescription.usageMode === '叶面施'" label-width="82px" class="form-item" prop="executeStyle" label="执行方式">
                            <el-select
                                    class="select-item"
                                    v-model="dynamicValidateForm.executeStyle"
                                    placeholder="执行方式"
                                    @change="handleExecutionMethodChange"
                                >
                                    <el-option
                                        v-for="(item, index) in modeList"
                                        :key="index"
                                        :label="item.name"
                                        :value="item.value"
                                    />
                                </el-select>
                        </el-form-item>

                        <el-form-item v-if="dynamicValidateForm.prescription.usageMode === '根部施'" label-width="82px" class="form-item" prop="executeStyle" label="执行方式">
                            <div class="info-text">人工</div>
                        </el-form-item>
                        
                        <div v-if="dynamicValidateForm.prescription.usageMode !== '人工农事'">
                            <el-form-item
                                v-for="(domain, index) in dynamicValidateForm.prescription.pesticideFertilizerList"
                                :key="index"
                                :prop="'prescription.pesticideFertilizerList.' + index + '.value'"
                                class="prescription-item"
                            >
                                <div class="recipe-item">
                                    <div class="recipe-form">
                                            <div class="form-box">
                                                <div class="form-index">药肥{{ index + 1 }}</div>
                                                <div class="box-item" v-if="domain.typeName">
                                                    <div class="form-l">药肥类型</div>
                                                    <div class="form-r r-text">
                                                        {{ domain.typeName }}
                                                    </div>
                                                </div>
                                                <div class="box-item">
                                                    <div class="form-l">药肥名称</div>
                                                    <div class="form-r">
                                                        <el-select
                                                            filterable
                                                            @change="
                                                                handlePesticideFertilizerChange(index)
                                                            "
                                                            v-model="domain.code"
                                                            placeholder="请选择"
                                                            style="width: 150px"
                                                        >
                                                            <el-option
                                                                v-for="item in pesticideFertilizersOptions"
                                                                :key="item.pesticideFertilizerCode"
                                                                :label="item.defaultName || item.name"
                                                                :value="item.pesticideFertilizerCode"
                                                            />
                                                        </el-select>
                                                    </div>
                                                </div>

                                                <div class="mt-8">
                                                    <div class="box-item sub-item" :data-ratio-index="index">
                                                        <div class="form-l has-sub">
                                                            <div class="main-name">药肥配比</div>
                                                        </div>
                                                        <div class="form-r input-box text-center input-unit">
                                                            <el-input
                                                                v-model="domain.ratio"
                                                                type="number"
                                                                step="0.01"
                                                                style="width: 150px"
                                                                :placeholder="domain.placeholderRatio || '请输入'"
                                                            >
                                                                <template #append>倍</template>
                                                            </el-input>
                                                        </div>
                                                    </div>
                                                    <div class="box-item sub-item" :data-dosage-index="index">
                                                        <div class="form-l has-sub">
                                                            <div class="main-name">单亩用量</div>
                                                        </div>
                                                        <div class="form-r input-box text-center">
                                                            <el-input
                                                                v-model="domain.dosage"
                                                                type="number"
                                                                step="0.01"
                                                                style="width: 150px"
                                                                :placeholder="domain.placeholderDosage || '请输入'"
                                                            >
                                                                <template #append>{{ domain.unit }}</template>
                                                            </el-input>
                                                        </div>
                                                    </div>

                                                    
                                                    <div class="box-item">
                                                        <div class="form-l">药肥品牌</div>
                                                        <div class="form-r">
                                                            <el-input
                                                                v-model="domain.brand"
                                                                placeholder="药肥品牌"
                                                                style="width: 150px"
                                                            />
                                                        </div>
                                                    </div>
                                                    <div class="box-item">
                                                        <div class="form-l">药肥单价</div>
                                                        <div class="form-r">
                                                            <el-input
                                                                style="width: 150px"
                                                                v-model="domain.price"
                                                                type="number"
                                                                step="0.01"
                                                                placeholder="单价"
                                                            >
                                                                <template #append>元/{{ domain.unit }}</template>
                                                            </el-input>
                                                        </div>
                                                    </div>

                                                    

                                                    <div v-if="!noPrice" class="medicine-item">
                                                        <div class="item-total">总计：</div>
                                                        <div class="item-price">
                                                            {{ getPesticideTotal(domain) }}<span class="item-unit">元</span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="input-box mark-box">
                                                    <el-input
                                                        v-model="domain.remark"
                                                        style="width: 100%"
                                                        type="textarea"
                                                        :rows="2"
                                                        placeholder="备注：用药注意事项"
                                                    />
                                                </div>
                                                <div class="action-btn">
                                                    <el-button
                                                        class="btn delete-btn"
                                                        @click.prevent="removeDomain(prescriptionI, domain)"
                                                    >
                                                        删除
                                                    </el-button>
                                                    <el-button
                                                        type="default"
                                                        class="btn"
                                                        @click.prevent="resetItemForm(prescriptionI, index)"
                                                    >
                                                        重置
                                                    </el-button>
                                                </div>
                                            </div>
                                        <!-- </el-form-item> -->
                                    </div>
                                </div>
                            </el-form-item>
                        </div>
                    </div>

                    <div class="farm-card prescription-content">
                        <div class="medicine-box">
                                <div class="form-index">服务报价</div>
                                <div class="box-wrap">
                                    <div class="medicine-item mt-8">
                                        <div class="item-name">单亩价格</div>
                                        <div class="item-val common-inputs">
                                            <el-input
                                                style="width: 150px"
                                                v-model="servicePricePerMu"
                                                type="number"
                                                step="0.01"
                                                placeholder="服务单价"
                                            >
                                                <template #append>元/亩</template>
                                            </el-input>
                                        </div>
                                    </div>
                                    <div v-if="!noPrice" class="medicine-item">
                                        <div class="item-total">总计：</div>
                                        <div class="item-price">
                                            {{ getServiceTotal() }}<span class="item-unit">元</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                    </div>

                    <div class="submit-btn" :class="{ 'center-btn': onlyPrice }">
                        <div v-if="!onlyPrice" class="btn second" @click.prevent="cancelEdit">取消编辑</div>
                        <div class="btn" @click.prevent="submitForm(formRef)">保存</div>
                    </div>
                </template>

                <template v-else>
                    <div class="farm-card prescription-content">
                        <div class="card-title">药物处方</div>
                        <div class="table-item">
                            <div class="form-item">
                                <div class="item-name">施用方式</div>
                                <div class="item-text">{{ dynamicValidateForm?.prescription?.usageMode }}</div>
                            </div>
                            <div class="form-item">
                                <div class="item-name">执行方式</div>
                                <div class="item-text">
                                    {{ dynamicValidateForm?.prescription?.pesticideFertilizerList[0]?.executeStyle === 1 ? '无人机' : '人工' }}
                                </div>
                            </div>
                        </div>
                        <div class="new-wrap" v-if="detailData?.prescription?.pesticideFertilizerList?.length">
                            <div class="new-title">
                                <div class="title-1"><div class="table-name">使用功效</div></div>
                                <div class="title-2"><div class="table-name">药肥名称</div></div>
                                <div class="title-4"><div class="table-name">药肥配比</div></div>
                                <div class="title-5"><div class="table-name">单亩用量</div></div>
                            </div>
                            <div
                                class="new-table-wrap"
                                v-for="(subP, prescriptionI) in detailData?.prescription?.pesticideFertilizerList || []"
                                :key="prescriptionI"
                            >
                                <!-- <div
                                    class="new-prescription"
                                    v-for="(subP, subI) in prescriptionItem.pesticideFertilizerList"
                                    :key="subI"
                                > -->
                                    <div class="new-table">
                                        <div class="line-l">
                                            <div class="line-1 title-1">{{ subP.typeName || '--' }}</div>
                                            <div class="line-2">
                                                {{ subP.name || subP.pesticideFertilizerName }}
                                            </div>
                                        </div>
                                        <div class="line-r">
                                            <div class="line-3">
                                                <div class="sub-line title-4">{{ subP.ratio ? (subP.ratio + '倍') : '--' }}</div>
                                                <div class="sub-line title-5">{{ subP.dosage ? (subP.dosage + subP.unit) : '--' }}</div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="note-text" v-if="subP.remark">{{ subP.remark }}</div>
                                <!-- </div> -->
                            </div>
                        </div>
                    </div>

                    <div class="farm-card prescription-content">
                        <div class="card-title">处方报价</div>

                        <div class="price-bottom" v-if="!noPrice">
                            <div class="info-title-wrap">
                                <div class="sub-title font-bold">药肥费用</div>
                                <div class="info-more">
                                    {{ pesticideCostTotal ? formatArea(pesticideCostTotal) : "--" }}<span class="unit-text">元</span>
                                </div>
                            </div>
                        </div>
                        <div class="info-content-wrap pt-8">
                            <price-table :prescriptionData="dynamicValidateForm.prescription" :area="detailData?.farm?.mianji">
                                <template #bottomContent>
                                    <div class="price-bottom">
                                        <div class="info-title-wrap">
                                            <div class="sub-title font-bold">服务费用</div>
                                            <div class="info-more" v-if="!noPrice">
                                                {{ detailData?.serviceMuPrice ? serviceCostTotal : '--' }}
                                                <span class="unit-text">元</span>
                                            </div>
                                        </div>
                                        <div class="price-info">
                                            <div class="info-l">
                                                单亩价格<span class="main-text">{{
                                                    detailData?.serviceMuPrice
                                                        ? detailData?.serviceMuPrice + "元/亩"
                                                        : "--"
                                                }}</span>
                                            </div>
                                        </div>
                                        <div class="price-total" v-if="!noPrice">
                                            报价合计：<span class="main-val">{{
                                                totalCost ? formatArea(totalCost) : "--"
                                            }}</span
                                            >元
                                        </div>
                                    </div>
                                </template>
                            </price-table>
                        </div>
                    </div>
                    <template v-if="!isDefault">
                        <div class="submit-btn" v-has-permission="'农事规划'">
                            <div class="btn second" @click.prevent="handleCancelAttention">取消关注</div>
                            <div class="btn" @click.prevent="toEditPrescription">编辑处方</div>
                        </div>
                    </template>
                </template>
            </el-form>
        </div>
    </div>

    <!-- 服务报价单 -->
    <price-sheet-popup ref="priceSheetPopupRef"></price-sheet-popup>

    <!-- 互动设置弹窗 -->
    <interact-popup
        ref="interactPopupRef"
        @handleSaveSuccess="handleSaveInteractSuccess"
        @handleDeleteInteract="handleDeleteInteract"
    ></interact-popup>

    <!-- 取消关注提示 -->
    <tip-popup
        v-model:show="showTipPopup"
        type="warning"
        text="您确定要取消关注"
        text2="农事吗？系统将不再为您推送该农事"
        :highlightText="detailData.name"
        :overlayStyle="{ 'z-index': 9999 }"
        buttonText="确认取消关注"
        @confirm="handleBtn"
        :hasClose="true"
        :closeOnClickOverlay="false"
    />
    <!-- 完善信息弹窗 -->
    <popup 
        v-model:show="showCompletePopup" 
        round 
        class="complete-tip-popup"
        closeable
    >
    <img class="tip-icon success-icon" src="@/assets/img/home/right.png" alt="" />
    <div class="tip-text success-text">
        农事信息已完善
    </div>
        <div class="complete-content">
        </div>
        <div class="btn-wrap">
            <div class="btn-item second" @click="handleViewDetail">查看详情</div>
            <div class="btn-item primary" v-if="!allDone" @click="handleCompleteNext">完善下一个农事</div>
            <div class="btn-item primary" v-else @click="handleBackToPlan">回到种植方案</div>
        </div>
    </popup>
</template>

<script setup>
import { onActivated, ref, reactive, onDeactivated, onBeforeUnmount, computed, onMounted, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import customHeader from "@/components/customHeader.vue";
import { useStore } from "vuex";
import { Popup } from "vant";
import { formatArea } from "@/common/commonFun";
import priceSheetPopup from "@/components/popup/priceSheetPopup.vue";
import interactPopup from "@/components/popup/interactPopup.vue";
import priceTable from "../agri_work/components/priceTable.vue";
import tipPopup from "@/components/popup/tipPopup.vue";
import dayjs from "dayjs";
const store = useStore();
const pageRef = ref(null);
const router = useRouter();
const route = useRoute();

// 检查是否有"农事规划"权限
const hasPlanPermission = computed(() => {
    try {
        const userInfoStr = localStorage.getItem("localUserInfo");
        if (!userInfoStr) return false;
        const userInfo = JSON.parse(userInfoStr);
        const permissions = userInfo.agriculturalPermissions || [];
        return permissions.includes("农事规划");
    } catch (error) {
        console.error("解析用户信息失败:", error);
        return false;
    }
});

const tagList = ref([
    { label: "托管农事", value: 2 },
    { label: "特别关注", value: 1 },
    // { label: "取消关注", value: 0 },
]);

const tagName = ref("");

// 互动表单数据
const interactFormData = ref({
    phenologyId: "",
    reproductiveId: "",
    interactionTime: "",
    interactionQuestion: "",
});
const phenologyList = ref([]);
const reproductiveList = ref([]);
// 是否编辑
const isEdit = ref(false);
// 是否只显示价格，不需要农情互动
const onlyPrice = ref(false);
// 是否不显示价格，种植方案没有价格
const noPrice = ref(false);
// 是否标注方案
const isDefault = ref(false);
// 是否在完善信息弹窗中
const isDoingComplete = ref(false);

const showCompletePopup = ref(false);
onActivated(() => {
    isDefault.value = route.query.isDefault == 'true' ? true : false;
    isEdit.value = route.query.isEdit == 'true' ? true : false;
    onlyPrice.value = route.query.onlyPrice == 'true' ? true : false;
    noPrice.value = route.query.noPrice == 'true' ? true : false;
    // enabled为0时，方案不可用，需要完善
    isDoingComplete.value = route.query.enabled == 0 ? true : false;
    // 方案列表中的ids数组
    if (route.query.farmWorkId) {
        getDetail();
    }
    if (isDoingComplete.value) {
        let farmWorkAndArrangeIdIdsArray = (() => {
                const stored = sessionStorage.getItem("farmWorkAndArrangeIds");
                return stored ? JSON.parse(stored) : [];
            })();
        ids.value = farmWorkAndArrangeIdIdsArray;
        if (ids.value.length === 0 || ids.value.length === 1) {
            allDone.value = true;
        }
    }
    nextTick(() => {
        if (pageRef.value) {
            pageRef.value.scrollTop = 0;
        } else {
            window.scrollTo(0, 0);
        }
    });
    // 初始化 prescription 对象
    if (!route.query.farmWorkId) {
        dynamicValidateForm.prescription = {
            usageMode: "",
            pesticideFertilizerList: [
                {
                    code: "",
                    name: "",
                    dosage: "",
                    ratio: "",
                    typeName: "",
                    muPrice: 0,
                    executeStyle: 1,
                    unit: "",
                },
            ],
        };
    }
});

const priceSheetPopupRef = ref(null);
const showPriceSheetPopup = () => {
    priceSheetPopupRef.value.handleShowPopup(detailData.value);
};

const handlePhenologyChange = async (val) => {
    interactFormData.value.reproductiveId = "";
    const { data } = await VE_API.farm.listByPhenologyId({ phenologyId: val });
    if (!data || !Array.isArray(data)) return;
    reproductiveList.value = data;
};

const statusMap = ref({
    0: "",
    1: "特别关注",
    2: "托管农事",
});
const detailData = ref({});
const userInfo = localStorage.getItem('localUserInfo');
const userInfoObj = userInfo ? JSON.parse(userInfo) : {};
const getDetail = async () => {
    const { data, code } = await VE_API.farm.getFarmWorkLib({ id: route.query.farmWorkId, farmId: route.query.farmId, agriculturalId: userInfoObj?.agriculturalId });
    if(code === 0) {
        detailData.value = data;
        dynamicValidateForm.executeDate = data.executeDate;
        dynamicValidateForm.prescription.usageMode = data?.prescription?.usageMode === '其他' ? '根部施' : data?.prescription?.usageMode;
        // 从 prescription 获取数据
        dynamicValidateForm.prescription = data.prescription || {
            usageMode: "",
            pesticideFertilizerList: [],
        };
        dynamicValidateForm.executeStyle = data?.prescription?.pesticideFertilizerList[0]?.executeStyle;
        servicePricePerMu.value = detailData.value.serviceMuPrice || null;
        if (isDoingComplete.value && !isDefault.value) {
            data?.prescription?.pesticideFertilizerList.forEach(item => {
                item.placeholderRatio = item.ratio || '';
                item.placeholderDosage = item.dosage || '';
                if (isNaN(item.ratio)) {
                    item.ratio = null;
                }
                if (isNaN(item.dosage)) {
                    item.dosage = null;
                }
            });
        }
        const pesticideFertilizerCodes = data?.prescription?.pesticideFertilizerList.map(item => item.code);
        getPriceList(data.schemeId, pesticideFertilizerCodes);
        
        // 加载互动表单数据
        if (data.id) {
            // 重置互动表单数据
            interactFormData.value = {
                phenologyId: "",
                reproductiveId: "",
                interactionTime: "",
                interactionQuestion: "",
            };
            // 按照 interactPopup.vue 的方式获取数据
            await getPhenologyList(data.containerSpaceTimeId || route.query.containerSpaceTimeId);
            await getFarmWorkArrangeDetail(route.query.id || route.query.arrangeId);
        }
    }
};

const getPriceList = async (schemeId, pesticideFertilizerCodes) => {
    const { data } = await VE_API.farm.getPriceList({ schemeId, pesticideFertilizerCodes });
    if (!data || !Array.isArray(data)) return;

    dynamicValidateForm.prescription.pesticideFertilizerList.forEach((item) => {
        const priceInfo = data.find((p) => p.pesticideFertilizerCode === item.code);
        if (!priceInfo) return;
        item.price = priceInfo.price ?? item.price;
        item.brand = priceInfo.brand ?? item.brand;
    });

    quotationData.value = {...detailData.value, ...dynamicValidateForm};
};

const showTipPopup = ref(false);
// 取消关注弹窗
const handleCancelAttention = () => {
    showTipPopup.value = true;
};

const handleBtn = () => {
    showTipPopup.value = false;
    // 切换标记
    VE_API.container_farm_work_arrange.toggleFollow({ id: route.query.id, isFollow: 0 }).then((res) => {
        if (res.code === 0) {
            ElMessage.success("操作成功");
            router.back();
        }
    });
};

const toEditPrescription = () => {
    isEdit.value = true;
    nextTick(() => {
        if (pageRef.value) {
            pageRef.value.scrollTo({ top: 0, behavior: "auto" });
        } else {
            window.scrollTo(0, 0);
        }
    });
};

const quotationData = ref({});


// 计算单个药肥的总计：单价 * 单亩用量 * 亩数
const getPesticideTotal = (pesticide) => {
    const price = Number(pesticide.price || 0);
    const dosage = Number(pesticide.dosage || 0); // 单亩用量
    const area = Number(detailData.value.farm?.mianji || 0); // 农场面积
    if (!price || !dosage || !area) return "--";
    const total = (price * dosage * area).toFixed(2);
    return total;
};

function getServiceCost(cost, area) {
    if (!cost || !area) return "--";
    return (parseFloat(cost) * parseFloat(area)).toFixed(2);
}

const handleViewDetail = () => {
    showCompletePopup.value = false;
    isEdit.value = false;
    nextTick(() => {
        if (pageRef.value) {
            pageRef.value.scrollTo({ top: 0, behavior: "auto" });
        } else {
            window.scrollTo(0, 0);
        }
    });
};
const allDone = ref(false);
const handleBackToPlan = () => {
    router.back();
};

const ids = ref([]);
const handleCompleteNext = () => {
    showCompletePopup.value = false;
    
    // 如果数组为空，说明已经全部完成
    if (!ids.value || ids.value.length === 0) {
        allDone.value = true;
        return;
    }
    
    // 找到当前 farmWorkId 在数组中的索引
    const currentFarmWorkId = route.query.farmWorkId;
    const currentIndex = ids.value.findIndex(item => String(item.farmWorkId) === String(currentFarmWorkId));
    
    if (currentIndex === -1) {
        // 如果找不到当前项，说明可能已经被删除或不存在
        allDone.value = true;
        console.log('未找到当前farmWorkId');
        return;
    }
    
    // 如果数组只剩一个（最后一个），标记为全部完成
    if (ids.value.length === 1) {
        // 从数组中删除当前项（已经完成的）
        ids.value.splice(currentIndex, 1);
        // 更新 sessionStorage
        sessionStorage.setItem("farmWorkAndArrangeIds", JSON.stringify(ids.value));
        allDone.value = true;
        return;
    }
    
    // 判断是否是最后一个
    const isLast = currentIndex === ids.value.length - 1;
    
    // 如果是最后一个，标记为全部完成
    if (isLast) {
        // 从数组中删除当前项（已经完成的）
        ids.value.splice(currentIndex, 1);
        // 更新 sessionStorage
        sessionStorage.setItem("farmWorkAndArrangeIds", JSON.stringify(ids.value));
        allDone.value = true;
        return;
    }
    
    // 获取下一个农事：取当前索引+1位置的值
    const nextItem = ids.value[currentIndex + 1];
    
    if (nextItem && nextItem.farmWorkId && nextItem.arrangeId) {
        // 从数组中删除当前项（已经完成的）
        ids.value.splice(currentIndex, 1);
        // 更新 sessionStorage
        sessionStorage.setItem("farmWorkAndArrangeIds", JSON.stringify(ids.value));
        
        router.replace({
            path: "/modify",
            query: {
                id: nextItem.arrangeId,
                farmWorkId: nextItem.farmWorkId,
                farmId: route.query.farmId,
                containerSpaceTimeId: route.query.containerSpaceTimeId,
                schemeId: route.query.schemeId,
                enabled: 0,
                isEdit: true,
                onlyPrice: false,
                noPrice: true,
                isDefault: false,
            },
        });
        setTimeout(() => {
            window.location.reload();
        }, 500);
    } else {
        // 从数组中删除当前项（已经完成的）
        ids.value.splice(currentIndex, 1);
        // 更新 sessionStorage
        sessionStorage.setItem("farmWorkAndArrangeIds", JSON.stringify(ids.value));
        allDone.value = true;
        console.log('没有下一个农事需要完善');
    }
};
const resetForm = (formEl) => {
    if (!formEl) return;
    formEl.resetFields();
};

// 清空所有数据
const clearData = () => {
    // 清空表单
    resetForm(formRef.value);

    // 清空详情数据
    detailData.value = {};

    // 清空表单数据
    dynamicValidateForm.farmWorkName = "";
    dynamicValidateForm.conditionRate = "";
    dynamicValidateForm.purpose = "";
    dynamicValidateForm.executeDate = dayjs().format("YYYY-MM-DD");
    dynamicValidateForm.prescription = {
        id: "",
        usageMode: "",
        farmWorkLibCode: "",
        expertId: "",
        phenology: "",
        soil: "",
        speed: null,
        pesticideFertilizerList: [
            {
                code: "",
                name: "",
                dosage: "",
                ratio: "",
                typeName: "",
                muPrice: 0,
                executeStyle: 1,
                unit: "",
            },
        ],
    };
};

onDeactivated(() => {
    clearData();
});

onBeforeUnmount(() => {
    clearData();
});

const cancelEdit = () => {
    ElMessageBox.confirm("确认要取消编辑吗？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            isEdit.value = false;
            nextTick(() => {
                if (pageRef.value) {
                    pageRef.value.scrollTop = 0;
                } else {
                    window.scrollTo(0, 0);
                }
            });
        })
        .catch(() => {
            console.log("取消编辑");
        });
};

const modeList = ref([
    { name: "无人机", value: 1 },
    { name: "人工", value: 2 },
]);

const handleExecutionMethodChange = (index, val) => {
    // if (val == 1) {
    //     servicePricePerMu.value = detailData.value.uavServicePrice;
    // } else {
    //     servicePricePerMu.value = detailData.value.manualServicePrice;
    // }
};

// 表单
const formRef = ref();
const dynamicValidateForm = reactive({
    farmWorkName: "",
    conditionRate: "",
    purpose: "",
    executeDate: dayjs().format("YYYY-MM-DD"),
    usageMode: "",
    executeStyle: 2,
    executionMethod: 2,
    prescription: {
        id: "",
        usageMode: "",
        farmWorkLibCode: "",
        expertId: "",
        phenology: "",
        soil: "",
        speed: null,
        pesticideFertilizerList: [
            {
                code: "",
                id: "",
                name: "",
                dosage: "",
                ratio: "",
                brand: "",
                price: "",
                typeName: "",
                muPrice: 0,
                executeStyle: 1,
                unit: "",
            },
        ],
    },
});

const rules = {
    farmWorkName: [
        {
            required: true,
            message: "请输入农事名称",
            trigger: "blur",
        },
    ],
    conditionRate: [
        {
            required: false,
            message: "请输入触发条件",
            trigger: "blur",
        },
    ],
    executeDate: [
        {
            required: false,
            message: "请选择执行时间",
            trigger: "blur",
        },
    ],
};

const addDomain = () => {
    if (!dynamicValidateForm.prescription.pesticideFertilizerList) {
        dynamicValidateForm.prescription.pesticideFertilizerList = [];
    }
    dynamicValidateForm.prescription.pesticideFertilizerList.unshift({
        code: "",
        name: "",
        dosage: "",
        ratio: "",
        brand: "",
        price: "",
        typeName: "",
        muPrice: 0,
        id: "",
        executeStyle: 2,
        unit: "",
    });
};

let pesticideFertilizersOptions = ref([]);
VE_API.z_farm_work_order.pesticideFertilizersList().then(({ data }) => {
    pesticideFertilizersOptions.value = data;
});

const allUsageModeList = ["叶面施", "根部施", "人工农事"];

/**
 * 选择药肥的时候修改订单中药肥pesticideFertilizerId 以外其他数据
 * @param index
 */
const handlePesticideFertilizerChange = (index) => {
    const currentItem = dynamicValidateForm.prescription.pesticideFertilizerList[index];
    let obj = pesticideFertilizersOptions.value.filter(
        (item) => currentItem.code === item.pesticideFertilizerCode
    )[0];
    if (obj) {
        dynamicValidateForm.prescription.pesticideFertilizerList[index] = {
            ...currentItem,
            code: obj.pesticideFertilizerCode,
            id: obj.id,
            name: obj.name || obj.defaultName,
            typeName: obj.typeName,
            unit: obj.unit,
            ratio: "", // 清空亩兑水量
            dosage: "", // 清空单亩用量
            executeStyle: obj.executionMethod || 1,
        };
    }
};

const removeDomain = (index) => {
    if (index !== -1 && dynamicValidateForm.prescription.pesticideFertilizerList) {
        dynamicValidateForm.prescription.pesticideFertilizerList.splice(index, 1);
    }
};

const resetItemForm = (index) => {
    if (dynamicValidateForm.prescription.pesticideFertilizerList) {
        dynamicValidateForm.prescription.pesticideFertilizerList[index] = {
            code: "",
            id: "",
            name: "",
            dosage: "",
            ratio: "",
            brand: "",
            price: "",
            typeName: "",
            muPrice: 0,
            executeStyle: 1,
            unit: "",
        };
    }
};

const servicePricePerMu = ref(null);

// 服务费用总计（数值）：亩单价 * 亩数
const serviceCostTotal = computed(() => {
    const price = Number(servicePricePerMu.value || 0);
    const area = Number(detailData.value?.farm?.mianji || detailData.value?.area || 0);
    if (!price || !area) return 0;
    return Number((price * area).toFixed(2));
});

// 显示用的服务费用（字符串或 "--"）
const getServiceTotal = () => {
    const total = serviceCostTotal.value;
    return total ? total.toFixed(2) : "--";
};

// 药肥费用总计：∑(单价 * 单亩用量 * 亩数)
const pesticideCostTotal = computed(() => {
    const list = dynamicValidateForm.prescription?.pesticideFertilizerList || [];
    const area = Number(detailData.value?.farm?.mianji || detailData.value?.area || 0);
    if (!list.length || !area) return 0;

    const sum = list.reduce((acc, item) => {
        const price = Number(item?.price || 0);
        const dosage = Number(item?.dosage || 0);
        if (!price || !dosage) return acc;
        return acc + price * dosage * area;
    }, 0);

    return Number(sum.toFixed(2));
});

// 报价合计 = 药肥费用 + 服务费用
const totalCost = computed(() => {
    const pesticide = Number(pesticideCostTotal.value || 0);
    const service = Number(serviceCostTotal.value || 0);
    if (!pesticide && !service) return '--';
    return Number((pesticide + service).toFixed(2));
});

const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate(async (valid) => {
        if (valid) {
            // 校验标记是否已选择
            if (!validateTagName()) return;

            // 校验农情互动,不通过，直接返回失败
            if (!onlyPrice.value && !validateInteractForm()) return false;

            // 校验药肥的亩兑水量和单亩用量是否填写
            if (!validatePesticideDosage()) return;

            // 保存报价信息前先校验是否填写完整
            if (!validatePriceInfos()) return;

            // 检验服务报价是否填写
            if (!validateServicePrice()) return;
            submit();
        } else {
            console.log("error submit!");
        }
    });
};

// 校验标记是否已选择
const validateTagName = () => {
    if (tagName.value !== 1 && tagName.value !== 2) {
        ElMessage.warning("请选择标记类型");
        return false;
    }
    return true;
};

// 检验服务报价是否填写
const validateServicePrice = () => {
    if (!servicePricePerMu.value) {
        ElMessage.warning("请完善服务报价信息");
        return false;
    }
    return true;
};

// 校验药肥的亩兑水量和单亩用量是否填写
const validatePesticideDosage = () => {
    const list = dynamicValidateForm.prescription?.pesticideFertilizerList || [];
    if (!list.length) return true; // 没有药肥就不校验

    // 找到第一个未填写完整的药肥
    for (let i = 0; i < list.length; i++) {
        const item = list[i];
        // 如果选择了药肥（有 code），就必须填写亩兑水量和单亩用量
        if (item.code) {
            const hasRatio = item.ratio !== undefined && item.ratio !== null && item.ratio !== "";
            const hasDosage = item.dosage !== undefined && item.dosage !== null && item.dosage !== "";
            
            if (!hasRatio || !hasDosage) {
                ElMessage.warning("请完善药物处方信息");
                return false;
            }
        }
    }
    return true;
};

// 校验报价信息是否填写完整
const validatePriceInfos = () => {
    const list = dynamicValidateForm.prescription?.pesticideFertilizerList || [];
    if (!list.length) return true; // 没有药肥就不校验

    // 找到第一个未填写完整的药肥
    const invalidIndex = list.findIndex((item) => {
        // 只要选择了药肥（有 id），就必须填写单价和品牌
        if (!item.id) return false; // 没选择药肥不校验
        const hasPrice = item.price !== undefined && item.price !== null && item.price !== "";
        const hasBrand = !!item.brand;
        return !hasPrice || !hasBrand;
    });

    if (invalidIndex !== -1) {
        ElMessage.warning("请先完善报价信息");
        return false;
    }
    return true;
};

const submit = () => {
    const data = {
        id: route.query.farmWorkId,
        ...dynamicValidateForm,
        serviceMuPrice: servicePricePerMu.value,
        prescription: dynamicValidateForm.prescription
    };
    VE_API.monitor.saveFarmWorkLib(data);
    
    if (!onlyPrice.value) {
        handleSaveInteract();
    }

    // 保存报价信息
    const priceList = {
        schemeId: detailData.value.schemeId,
        pesticideFertilizerInfos: dynamicValidateForm.prescription.pesticideFertilizerList.map(item => {
            return {
                pesticideFertilizerId: item.id,
                price: item.price,
                brand: item.brand,
            }
        }),
    }
    VE_API.farm.updateBatchByScheme(priceList).then(async (res) => {
        if (res.code === 0) {
            await getDetail();
            if (isDoingComplete.value) {
                // 更新 sessionStorage（不删除当前项，保持数组完整）
                sessionStorage.setItem("farmWorkAndArrangeIds", JSON.stringify(ids.value));
                
                showCompletePopup.value = true;
                return;
            }
            ElMessage.success("保存成功");
            if (onlyPrice.value) {
                // router.push(`/task_condition?noReload=true`);
                router.back();
                return;
            }
            isEdit.value = false;
            nextTick(() => {
                if (pageRef.value) {
                    pageRef.value.scrollTop = 0;
                } else {
                    window.scrollTo(0, 0);
                }
            });
        } else {
            // 不需要处方报价信息的农事
            if (priceList.pesticideFertilizerInfos.length === 0) {
                if (onlyPrice.value) {
                    // router.push(`/task_condition?noReload=true`);
                    router.back();
                    return;
                }
                isEdit.value = false;
                getDetail();
                nextTick(() => {
                    if (pageRef.value) {
                        pageRef.value.scrollTop = 0;
                    } else {
                        window.scrollTo(0, 0);
                    }
                });
            }
        }
    }).catch(() => {
    });

    // 切换标记
    VE_API.container_farm_work_arrange.toggleFollow({ id: route.query.id, isFollow: tagName.value });
};

const handleSaveInteractSuccess = () => {
    getDetail();
};

const interactPopupRef = ref(null);
const handleEditInteract = (item) => {
    if (interactPopupRef.value) {
        interactPopupRef.value.showPopup({...item, containerSpaceTimeId: route.query.containerSpaceTimeId,id:route.query.id});
    }
};

// 获取物候期列表
const getPhenologyList = async (containerSpaceTimeId) => {
    if (!containerSpaceTimeId) {
        phenologyList.value = [];
        return;
    }
    const res = await VE_API.monitor.listPhenology({ containerSpaceTimeId });
    if (res.code === 0) {
        phenologyList.value = res.data || [];
    }
};

// 获取互动设置详情
const getFarmWorkArrangeDetail = async (id) => {
    if (!id) return;
    const { data, code } = await VE_API.farm.getFarmWorkArrangeDetail({ id });
    if(code === 0) {
        tagName.value = data.isFollow === 0 ? null : data.isFollow;
        await handlePhenologyChange(data.phenologyId);
        interactFormData.value = {
            phenologyId: data.phenologyId || "",
            reproductiveId: data.reproductiveId || "",
            interactionTime: data.interactionTime || "",
            interactionQuestion: data.interactionQuestion || "",
        };
    }
};

// 格式化日期
const formatInteractDate = (date) => {
    // 如果已经是字符串格式 YYYY-MM-DD，直接返回
    if (typeof date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(date)) {
        return date;
    }
    // 如果是 Date 对象，进行转换
    if (date instanceof Date) {
        let year = date.getFullYear();
        let month = String(date.getMonth() + 1).padStart(2, "0");
        let day = String(date.getDate()).padStart(2, "0");
        return `${year}-${month}-${day}`;
    }
    // 其他情况返回原值
    return date;
};

// 验证互动表单
const validateInteractForm = () => {
    if (!interactFormData.value.phenologyId) {
        ElMessage.warning("请选择互动阶段");
        return false;
    }
    if (!interactFormData.value.reproductiveId) {
        ElMessage.warning("请选择互动阶段");
        return false;
    }
    if (!interactFormData.value.interactionTime) {
        ElMessage.warning("请选择互动时间");
        return false;
    }
    if (!interactFormData.value.interactionQuestion?.trim()) {
        ElMessage.warning("请设置互动问题");
        return false;
    }
    return true;
};

// 保存互动设置
const handleSaveInteract = async () => {

    const paramsObj = {
        id: route.query.id,
        ...interactFormData.value,
        interactionTime: formatInteractDate(interactFormData.value.interactionTime),
    };

    try {
        const res = await VE_API.monitor.updateFarmWorkArrange(paramsObj);
        if (res.code !== 0) {
            ElMessage.error(res.message || "保存农情互动信息失败");
            return false;
        }
        return true;
    } catch (error) {
        console.error("保存互动设置失败:", error);
        ElMessage.error("保存失败，请重试");
        return false;
    }
};

// 删除互动设置
const handleDeleteInteract = () => {
    ElMessageBox.confirm("确定要删除该互动设置吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(async () => {
            if (!detailData.value.id) return;
            const res = await VE_API.monitor.deleteFarmWorkArrange({ id: detailData.value.id });
            if (res.code === 0) {
                ElMessage.success("删除成功");
                // 清空表单数据
                interactFormData.value = {
                    phenologyId: "",
                    interactionTime: "",
                    interactionQuestion: "",
                };
                await getDetail(); // 重新获取详情
            } else {
                ElMessage.error(res.message || "删除失败");
            }
        })
        .catch(() => {
            // 用户取消，不做任何操作
        });
};
</script>

<style lang="scss" scoped>
.new-farming-page {
    height: 100vh;
    position: relative;
    overflow: auto;
    font-size: 14px;
    background: #f2f3f5;
    ::v-deep {
        .custom-header {
            position: fixed;
            top: 0;
            padding-bottom: 1px;
        }
    }
    .step-wrap {
        padding: 12px 0;
    }
    .box-wrap {
        background: #fff;
        padding: 20px 10px 10px;
        border-radius: 6px;
    }
    .new-farming-content {
        margin: 41px 0 62px 0;
        padding: 4px 12px 8px 12px;
        width: 100%;
        box-sizing: border-box;
        &.no-permission{
            margin-bottom: 12px;
        }

        // ::v-deep {
        //     .el-select__input {
        //         color: #2199F8;
        //     }
        //     .el-select__wrapper {
        //         color: #2199F8;
        //         min-height: 30px;
        //         line-height: 28px;
        //         box-shadow: 0 0 0 1px rgba(33, 153, 248, 0.3) inset;
        //     }
        //     .el-select__caret {
        //         color: #2199F8;
        //     }
        //     .el-select__placeholder {
        //         color: #2199F8;
        //     }
        //     .el-radio {
        //         margin-right: 16px;
        //     }
        //     .el-input__wrapper {
        //         box-shadow: 0 0 0 1px rgba(33, 153, 248, 0.3) inset;
        //     }
        //     .el-input__prefix {
        //         color: #2199F8;
        //     }
        //     .el-input__inner {
        //         color: #2199F8;
        //         --el-input-placeholder-color: rgba(33, 153, 248, 0.43);
        //     }
        //     .el-tag.el-tag--info {
        //         --el-tag-text-color: #2199F8;
        //         --el-tag-bg-color: rgba(33, 153, 248, 0.1);
        //     }
        // }
        .farm-info {
            color: rgba(0, 0, 0, 0.6);
            font-size: 14px;
            margin-top: 14px;
            .info-title {
                display: flex;
                align-items: center;
                justify-content: space-between;
                color: rgba(41, 41, 41, 0.3);
                .info-more {
                    display: flex;
                    align-items: center;
                }
            }
        }
        .farm-photo {
            margin-top: 10px;
            .photo-list {
                display: flex;
                align-items: center;
                width: 100%;
                overflow: auto;
                padding-bottom: 10px;
                .photo-item {
                    width: 92px;
                    height: 92px;
                    border-radius: 8px;
                    object-fit: cover;
                }
                .img-item {
                    img {
                        width: 92px;
                        height: 92px;
                        border-radius: 8px;
                        object-fit: cover;
                        margin-right: 12px;
                    }
                }
            }
            .list-text {
                text-align: center;
                color: rgba(0, 0, 0, 0.5);
                padding-top: 2px;
            }
        }
        .submit-btn {
            z-index: 10;
            position: fixed;
            bottom: 0px;
            left: 0;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px;
            background: #fff;
            box-sizing: border-box;
            box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
            border-top: 1px solid rgba(0, 0, 0, 0.1);
            &.center-btn {
                justify-content: center;
            }
            .btn {
                height: 40px;
                border-radius: 25px;
                line-height: 40px;
                width: 110px;
                text-align: center;
                background: linear-gradient(180deg, #70bffe, #2199f8);
                color: #ffffff;
                font-size: 14px;
                &.second {
                    background: #ffffff;
                    border: 1px solid rgba(153, 153, 153, 0.5);
                    color: #666666;
                }
            }
            .btn + .btn {
                margin-left: 12px;
            }
        }
    }
    .card-title {
        font-size: 16px;
        font-weight: bold;
        color: #000;
        display: flex;
        align-items: center;
        &.between {
            justify-content: space-between;
            .del-tag {
                color: #e04c4c;
                border: 1px solid #e04c4c;
                border-radius: 5px;
                padding: 4px 14px;
                font-size: 12px;
                font-weight: normal;
            }
            .title-tag {
                padding: 2px 10px;
                height: 26px;
                line-height: 26px;
            }
        }
        // justify-content: space-between;
        .add-tag {
            font-size: 12px;
            color: #2199f8;
            padding: 0px 11px;
            border: 1px solid #2199F8;
            border-radius: 5px;
            font-weight: normal;
            height: 28px;
            line-height: 28px;
        }
        .type-tag {
            margin-left: 5px;
            font-size: 12px;
            color: #000000;
            padding: 0 10px;
            background: rgba(119, 119, 119, 0.1);
            border-radius: 20px;
            font-weight: normal;
            height: 26px;
            line-height: 26px;
            display: inline-block;
        }
    }
    .pb-12 {
        padding-bottom: 12px;
    }
    .farm-card {
        background: #ffffff;
        border-radius: 8px;
        padding: 12px 12px 0 12px;
        width: 100%;
        box-sizing: border-box;
        margin-top: 10px;
        color: rgba(0, 0, 0, 0.4);
        &.progress {
            display: flex;
            align-items: center;
            padding: 12px;
            .progress-title {
                margin-right: 12px;
            }
            ::v-deep {
                .el-radio {
                    margin-right: 10px;
                }
            }
        }
        &.map-content {
            margin-top: 12px;
        }
        &.prescription-content {
            padding: 12px;
        }
        .border-bottom {
            padding-bottom: 7px;
            border-bottom: 1px solid rgba(245, 245, 245, 0.99);
        }
    }

    .table-item {
        padding: 6px 0 10px 0;
        .form-item {
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #767676;
            height: 24px;
            .item-name {
                width: 80px;
                color: rgba(0, 0, 0, 0.2);
            }
        }
    }

    .new-wrap {
        border-radius: 5px;
        text-align: center;
        border: 1px solid rgba(225, 225, 225, 0.5);
        .new-title {
            background: rgba(241, 241, 241, 0.4);
            border-radius: 5px 5px 0 0;
            border-bottom: 1px solid rgba(225, 225, 225, 0.5);
            display: flex;
            color: #767676;
            // justify-content: space-around;
            padding: 3px 0px;
            font-size: 12px;
            .table-name {
                width: 24px;
                font-size: 12px;
                margin: 0 auto;
            }
        }

        .title-1 {
            width: 46px;
        }
        .title-2 {
            flex: 1;
        }
        .title-3 {
            width: 52px;
        }
        .title-4 {
            width: 56px;
        }
        .title-5 {
            width: 52px;
        }
        .new-table-wrap {
            padding: 5px 0;
            .new-prescription + .new-prescription {
                border-top: 1px solid rgba(225, 225, 225, 0.8);
            }
            // .new-prescription {
                .new-table {
                    display: flex;
                    align-items: center;
                    // border: 1px solid rgba(225, 225, 225, 0.8);
                    background: #fff;
                    border-radius: 5px;
                    color: rgba(0, 0, 0, 0.6);
                    font-size: 11px;
                    .line-l {
                        display: flex;
                        flex: 1;
                        .line-2 {
                            flex: 1;
                            padding: 0 2px;
                        }
                    }
                    .line-r {
                        &.has-border {
                            border-left: 1px solid rgba(225, 225, 225, 0.8);
                        }
                        .line-3 {
                            display: flex;
                            align-items: center;
                        }
                        .sub-line {
                            padding: 10px 0;
                        }
                        .line-4 {
                            display: flex;
                            align-items: center;
                            border-top: 1px solid rgba(225, 225, 225, 0.8);
                        }
                        .execute-line {
                            border-right: 1px solid rgba(225, 225, 225, 0.8);
                        }
                    }
                }
                .note-text {
                    margin: 8px 0 4px 0;
                    color: rgba(0, 0, 0, 0.4);
                    background: #fff;
                    padding: 6px 8px;
                    border-radius: 5px;
                    text-align: left;
                    font-size: 11px;
                }
            // }
            // .new-prescription + .new-prescription {
            //     padding-top: 8px;
            // }
        }
    }

    .info-content-wrap {
        ::v-deep {
            .new-table-wrap {
                padding: 5px 0;
                .new-prescription + .new-prescription {
                    border-top: 1px solid rgba(225, 225, 225, 0.8);
                }
            }
        }
    }
    .price-bottom {
        padding-top: 8px;

        .info-title-wrap {
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: #000;
            .info-more {
                font-size: 18px;
            }
            .unit-text {
                font-size: 12px;
            }
        }
        .price-info {
            padding: 8px 0;
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: rgba(0, 0, 0, 0.2);
            .main-text {
                padding-left: 20px;
                color: rgba(0, 0, 0, 0.8);
            }
            .info-c {
                flex: 1;
                text-align: center;
            }
        }
        .price-total {
            height: 38px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid rgba(33, 153, 248, 0.5);
            background: rgba(33, 153, 248, 0.1);
            color: #000000;
            border-radius: 4px;
            .main-val {
                font-size: 20px;
                font-weight: bold;
                color: #2199f8;
                padding-right: 2px;
            }
        }
    }
    .pt-8 {
        padding-top: 8px;
    }
    .pb-8 {
        padding-bottom: 8px;
    }

    .common-inputs {
        ::v-deep {
            .el-input__wrapper {
                box-shadow: none;
            }
            .el-input-group__append {
                padding: 0 10px;
                background: none;
                box-shadow: none;
            }
            .el-input-group__append {
                color: rgba(33, 153, 248, 0.5);
            }
            .el-input {
                border: 1px solid rgba(33, 153, 248, 0.3);
                border-radius: 5px;
                height: 30px;
                box-sizing: border-box;
            }
            .el-input__wrapper {
                padding: 0 2px 0 10px;
                height: 28px;
                line-height: 28px;
                min-height: 28px;
            }
            .el-input__inner {
                --el-input-inner-height: 28px;
                height: 28px;
                line-height: 28px;
                min-height: 28px;
                color: #2199f8;
                --el-input-placeholder-color: rgba(33, 153, 248, 0.43);
            }

            .el-select__wrapper {
                box-shadow: 0 0 0 1px rgba(33, 153, 248, 0.3) inset;
            }
            .el-select__placeholder,
            .el-select__caret {
                color: #2199f8;
            }
        }
    }

    .medicine-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 32px;
        .item-name {
            color: rgba(0, 0, 0, 0.4);
        }
        .item-val {
            min-width: 142px;
            text-align: center;
            color: #302f2f;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 4px;
            .price-unit {
                font-size: 12px;
                color: rgba(0, 0, 0, 0.4);
                white-space: nowrap;
            }
        }
        .item-total {
            font-size: 16px;
            color: #000;
        }
        .item-price {
            color: #2199f8;
            font-size: 20px;
            font-weight: bold;
            .item-unit {
                font-size: 14px;
                font-weight: normal;
                padding-left: 2px;
                color: #474747;
            }
        }
    }
    .medicine-box {
        // padding-top: 10px;
        border: 1px solid rgba(33, 153, 248, 0.8);
        position: relative;
        border-radius: 6px;
        .item-title {
            padding-left: 5px;
            font-size: 16px;
            color: #000000;
            font-weight: 500;
            padding-bottom: 10px;
        }
        .medicine-item + .medicine-item {
            padding-top: 2px;
        }
        .mt-8 {
            margin-top: 8px;
        }
    }

    .usage-mode-wrap {
        padding: 0 12px;
        margin-top: 12px;
        .info-content {
            padding-top: 14px;
            padding-bottom: 1px;
        }

        .el-form-item--default {
            margin-bottom: 0;
        }
    }

    ::v-deep {
        .el-form-item__label {
            height: 30px;
            line-height: 30px;
            color: rgba(0, 0, 0, 0.4);
        }
        .el-form-item.is-required:not(.is-no-asterisk).asterisk-left > .el-form-item__label:before {
            display: none;
        }
    }
    .interact-content {
        padding: 10px 0;
        line-height: 20px;
        color: #919191;
        font-size: 14px;
    }
    .interact-form {
        padding: 8px 0 20px 0px;

        .interact-form-item {
            display: flex;
            align-items: baseline;
            margin-bottom: 12px;

            &:last-child {
                margin-bottom: 0;
            }

            .form-label {
                width: 70px;
                color: rgba(0, 0, 0, 0.4);
                font-weight: normal;
                margin-right: 10px;
                font-size: 14px;
                flex: none;
            }

            .form-input-wrapper {
                position: relative;
                width: calc(100% - 70px);
                &.two-select {
                    display: flex;
                    gap: 10px;
                    .select-item {
                        flex: 1;
                    }
                }
                ::v-deep {
                    .el-input__inner {
                        caret-color: transparent;
                        padding-right: 40px;
                    }

                    .el-input__suffix {
                        display: none;
                    }
                }
            }

            .question-textarea {
                ::v-deep {
                    .el-textarea__inner {
                        resize: none;
                        line-height: 1.5;
                        min-height: 80px;
                    }
                }
            }
        }

        .interact-buttons {
            display: flex;
            gap: 12px;
            padding-top: 16px;

            .btn-delete,
            .btn-save {
                flex: 1;
                padding: 8px;
                border-radius: 25px;
                font-size: 16px;
                text-align: center;
                cursor: pointer;
                transition: all 0.3s;
                user-select: none;
            }

            .btn-delete {
                background: #ffffff;
                border: 1px solid #ff4d4f;
                color: #ff4d4f;

                &:hover {
                    background: #fff5f5;
                }

                &:active {
                    opacity: 0.8;
                    transform: scale(0.98);
                }
            }

            .btn-save {
                background: #2199f8;
                color: #fff;
                border: none;

                &:hover:not(.disabled) {
                    background: #1a8ae6;
                }

                &:active:not(.disabled) {
                    opacity: 0.9;
                    transform: scale(0.98);
                }

                &.disabled {
                    opacity: 0.6;
                    cursor: not-allowed;
                    pointer-events: none;
                }
            }
        }
    }
    .edit-tag {
        padding-left: 4px;
        color: #2199f8;
    }
    .tag-text {
        font-size: 12px;
        font-weight: normal;
    }
    .info-content {
        padding: 10px 0;
        position: relative;

        .condition-wrap {
            display: flex;
            align-items: center;
            width: 100%;
            .symbol {
                width: 10px;
                // text-align: center;
                // padding: 0 4px;
            }
        }
        .item-input {
            // width: 60%;
            min-width: 140px;
            max-width: 240px;
        }
        .recheck-text {
            padding-left: 6px;
        }
        .info-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
        }
        .info-item + .info-item {
            margin-top: 12px;
        }

        .bottom-map {
            width: 100%;
            height: 250px;
            clip-path: inset(0px round 8px);
        }
        .check-btn {
            position: absolute;
            bottom: 16px;
            right: 6px;
            background: rgba(0, 0, 0, 0.6);
            padding: 0 8px;
            border-radius: 8px;

            ::v-deep {
                .el-checkbox {
                    color: #fff;
                }
            }
        }
        .area-select {
            padding-bottom: 12px;
            .block {
                width: 12px;
                display: inline-block;
            }
        }
    }

    ::v-deep {
        .el-form-item--default {
            margin-bottom: 8px;
            &.text-item {
                margin-bottom: 2px;
                .el-form-item__content {
                    line-height: 24px;
                }
                .el-form-item__label {
                    height: 24px;
                    line-height: 24px;
                }
            }
        }
    }
    .sub-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: rgba(0, 0, 0, 0.6);
        font-size: 14px;
        .add-tag {
            font-size: 12px;
            color: #2199f8;
            padding: 0 8px;
            border: 1px solid #2199f8;
            border-radius: 5px;
            font-weight: normal;
            height: 28px;
            line-height: 28px;
        }
    }
    .font-bold {
        font-weight: 500;
        color: #000000;
    }
    .form-index {
        position: absolute;
        left: 0;
        top: 0;
        padding: 0 6px;
        background: #2199f8;
        border-radius: 5px 0 4px 0;
        height: 18px;
        line-height: 18px;
        font-size: 12px;
        color: #fff;
    }
    .recipe-item {
        width: 100%;
        .recipe-form {
            padding-top: 8px;
            ::v-deep {
                .el-form-item {
                    &:last-child {
                        margin-bottom: 0;
                    }
                }
            }
        }

        .mt-8 {
            margin-top: 8px;
        }

        .box-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: rgba(0, 0, 0, 0.4);
            .r-text {
                color: #302f2f;
                width: 150px;
                text-align: center;
            }
            .form-r {
                width: 150px;
                min-width: 140px;
                max-width: 240px;
            }
        }
        .form-box {
            border: 1px solid rgba(33, 153, 248, 0.8);
            border-radius: 6px;
            padding: 20px 10px;
            width: 100%;
            box-sizing: border-box;
            position: relative;
            // background: rgb(209, 235, 255, 0.3);
            // margin-bottom: 12px;
            .input-box {
                &.mark-box {
                    padding: 8px 0 12px 0;
                }
            }

            // .input-unit {
            //     ::v-deep {
            //         .el-input {
            //             border: 1px solid #dcdfe6;
            //             border-radius: 5px;
            //             height: 32px;
            //             box-sizing: border-box;
            //         }
            //         .el-input__wrapper {
            //             padding: 0 2px 0 10px;
            //             height: 30px;
            //             line-height: 30px;
            //             min-height: 30px;
            //             box-shadow: none;
            //         }
            //         .el-input__inner {
            //             --el-input-inner-height: 30px;
            //             height: 30px;
            //             line-height: 30px;
            //             min-height: 30px;
            //             color: #606266;
            //             --el-input-placeholder-color: #a8abb2;
            //         }
            //         .el-input-group__append {
            //             box-shadow: none;
            //             border: none;
            //             background: none;
            //         }
            //     }
            // }
            // .text-center {
            //     ::v-deep {
            //         .el-input__inner {
            //             text-align: center;
            //         }
            //     }
            // }
            .action-btn {
                display: flex;
                justify-content: flex-end;
                .btn {
                    color: #8f8f8f;
                    border-radius: 25px;
                    padding: 5px 30px;
                }
                .delete-btn {
                    color: rgba(255, 89, 89, 0.9);
                    background: #fff;
                    border: 1px solid rgba(255, 89, 89, 0.9);
                }
            }
            .btn-group {
                padding-top: 12px;
            }
            .sub-item {
                // padding-left: 10px;
                .has-sub {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    .main-name {
                        line-height: 20px;
                    }
                    .sub-name {
                        font-size: 10px;
                        color: rgba(129, 129, 129, 0.5);
                        line-height: 14px;
                    }
                }
                .colunm-sub {
                    display: flex;
                    align-items: center;
                    .sub-name {
                        font-size: 10px;
                        color: rgba(129, 129, 129, 0.5);
                    }
                }
                .r-text {
                    width: 132px;
                    text-align: center;
                    font-size: 14px;
                    color: #474747;
                }
                .price {
                    ::v-deep {
                        .el-input__wrapper {
                            box-shadow: 0 0 0 1px rgba(33, 153, 248, 0.3) inset;
                        }
                        .el-input__inner {
                            color: #2199f8;
                        }
                    }
                }
            }
            .form-title {
                font-size: 14px;
                padding-top: 6px;
                color: #000;
                font-weight: 600;
            }
            .box-item + .box-item {
                margin-top: 8px;
            }
        }
        .form-box + .form-box {
            margin-top: 8px;
        }
        .usageMode-wrap {
            padding-top: 8px;
        }
    }

    // 状况描述样式
    .situation-description {
        width: 100%;
        .description-title {
            font-size: 16px;
            font-weight: bold;
            color: #000;
            margin-bottom: 12px;
        }

        .description-content {
            .description-textarea {
                margin-bottom: 10px;
                width: 100%;
            }

            .upload-section {
                .upload-btn {
                    width: 112px;
                    height: 32px;
                    border-radius: 3px;
                    border: 1px solid #e0e0e0;
                    background: #fff;
                    color: #000;
                    font-size: 14px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-bottom: 8px;

                    .el-icon {
                        margin-right: 6px;
                    }
                }

                .upload-tip {
                    font-size: 12px;
                    color: #999;
                    line-height: 1.4;
                }
            }
        }
    }

    // 专家诊断按钮样式
    .expert-diagnosis-btn {
        width: 180px;
        height: 40px;
        border-radius: 24px;
        background: linear-gradient(180deg, #70bffe 0%, #2199f8 100%);
        color: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 30px auto 0;
    }
}

.complete-tip-popup {
    width: 80%;
    min-width: 294px;
    padding: 28px 20px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .tip-icon {
        margin-bottom: 12px;
        &.create-icon {
            width: 40px;
            height: 40px;
        }
        &.success-icon {
            width: 68px;
            height: 68px;
        }
    }
    .tip-text {
        margin-bottom: 32px;
        text-align: center;
        &.success-text {
            font-size: 24px;
            font-weight: 400;
        }
    }
    .btn-wrap {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        width: 100%;
        .btn-item {
            height: 40px;
            line-height: 40px;
            border-radius: 20px;
            font-size: 16px;
            color: #2199F8;
            text-align: center;
            &.second {
                flex: none;
                width: 92px;
                border: 1px solid #2199F8;
            }
            &.primary {
                flex: 1;
                background: #2199f8;
                color: #fff;
            }
        }
    }
}
</style>
