<template>
    <!-- 专家处方 -->
    <div class="work-item" :class="{ dark: prescriptioData?.progress === 0 && ROLETYPE != '3' }">
        <div class="work-info">
            <img
                v-if="prescriptioData?.progress === 0 && ROLETYPE == '3'"
                class="todo-img"
                src="@/assets/img/gallery/todo.png"
            />
            <div class="prescription-box">
                <div class="step-box">
                    <step-box
                        :orderStatus="infoItem.orderStatus"
                        v-if="infoItem.orderStatus || infoItem.orderStatus === 0"
                    ></step-box>
                </div>
                <div class="work-info-conetnt">
                    <div class="info-item">
                        <div class="info-name">农事编号：</div>
                        <div class="info-value">{{ infoItem.orderId }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-name">服务亩数：</div>
                        <div class="info-value">{{ infoItem.area }}亩</div>
                    </div>
                    <div class="info-item">
                        <div class="info-name">服务区域：</div>
                        <div class="info-value">{{ infoItem.serviceRegion }}</div>
                    </div>
                    <div v-if="prescriptioData?.progress === 0 && ROLETYPE == '3'">
                        <div class="info-item">
                            <div class="info-name">触发条件：</div>
                            <div class="info-value">
                                {{ infoItem.farmWorkLibName }}
                                <div class="select-value">
                                    <el-select v-model="infoItem.usageMode" placeholder="请选择" style="width: 80px">
                                        <el-option v-for="num in 9" :key="num" :value="20 + (num - 1) * 5 + '%'">
                                            {{ 20 + (num - 1) * 5 }}%
                                        </el-option>
                                    </el-select>
                                </div>
                            </div>
                        </div>
                        <div class="info-item time-picker">
                            <div class="info-name">执行时间：</div>
                            <div class="info-value">
                                <el-date-picker
                                    style="width: 150px"
                                    value-format="YYYY-MM-DD"
                                    v-model="infoItem.executeDate"
                                    type="date"
                                    :clearable="false"
                                    class="date-info"
                                    placeholder="选择日期"
                                />
                            </div>
                        </div>
                    </div>
                    <div v-else>
                        <div class="info-item">
                            <div class="info-name">触发条件：</div>
                            <div class="info-value">{{ infoItem.farmWorkLibName }}</div>
                        </div>
                        <div class="info-item">
                            <div class="info-name">执行时间：</div>
                            <div class="info-value">{{ infoItem.executeDate }}</div>
                        </div>
                    </div>
                </div>
                <div class="desc">
                    您果园周边 3公里 出现虫害。根据气象模型推算，您的果园出现 卷叶蛾 风险达到90％。手机拍照上传
                    果园照片，自动预测物候期可以确定.
                    <!-- {{ prescriptioData?.expertPrescription }} -->
                </div>
                <!-- v-if="prescriptioData?.progress === 0 && ROLETYPE == '3'" -->
                <div class="prescription-item">
                    <div class="recipe-box">
                        <div class="recipe-title">
                            <div class="recipe-name">药物处方</div>
                            <div class="recipe-btn" @click="addDomain">
                                <el-icon class="icon"><Plus /></el-icon>新增药物
                            </div>
                        </div>
                        <custom-table type="0" @handleDelete="removeDomain" :tableHeader="tableHeader" :tableData="dynamicValidateForm.domains"></custom-table>
                        <!-- <div class="recipe-item">
                            <div class="recipe-form">
                                <el-form
                                    ref="formRef"
                                    style="max-width: 600px"
                                    :model="dynamicValidateForm"
                                    class="demo-dynamic"
                                >
                                    <el-form-item
                                        v-for="(domain, index) in dynamicValidateForm.domains"
                                        :key="domain.key"
                                        :prop="'domains.' + index + '.value'"
                                    >
                                        <div class="form-box">
                                            <div class="form-index">{{ formatIndex(index) }}</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
                                                        @change="handlePesticideFertilizerChange(index)"
                                                        v-model="domain.pesticideFertilizerId"
                                                        placeholder="请选择"
                                                        style="width: 140px"
                                                    >
                                                        <el-option
                                                            v-for="item in pesticideFertilizersOptions"
                                                            :key="item.id"
                                                            :label="item.defaultName"
                                                            :value="item.id"
                                                        />
                                                    </el-select>
                                                </div>
                                            </div>
                                            <div class="form-title">人工方式</div>
                                            <div class="box-item sub-item">
                                                <div class="form-l has-sub">
                                                    <div class="main-name">肥药配比</div>
                                                    <div class="sub-name">(药剂:兑水量)</div>
                                                </div>
                                                <div class="form-r input-box text-center">
                                                    <el-input
                                                        v-model="domain.ratio"
                                                        style="width: 140px"
                                                        placeholder="请输入"
                                                    />
                                                </div>
                                            </div>
                                            <div class="box-item sub-item">
                                                <div class="form-l">施用方式</div>
                                                <div class="form-r">
                                                    <el-select
                                                        v-model="domain.usageMode"
                                                        placeholder="请选择"
                                                        style="width: 140px"
                                                    >
                                                        <el-option
                                                            v-for="(usage, uId) in domain.usageModeList"
                                                            :key="uId"
                                                            :label="usage"
                                                            :value="usage"
                                                        />
                                                    </el-select>
                                                </div>
                                            </div>
                                            <div class="box-item sub-item">
                                                <div class="form-l has-sub">
                                                    <div class="main-name">单亩用量</div>
                                                    <div class="sub-name">(亩数:药剂)</div>
                                                </div>
                                                <div class="form-r input-box text-center">
                                                    <el-input
                                                        v-model="domain.muUsage"
                                                        style="width: 140px"
                                                        placeholder="请输入"
                                                    />
                                                </div>
                                            </div>
                                            <div class="form-title">无人机方式</div>
                                            <div class="box-item sub-item">
                                                <div class="form-l has-sub">
                                                    <div class="main-name">肥药配比</div>
                                                    <div class="sub-name">(药剂:兑水量)</div>
                                                </div>
                                                <div class="form-r input-box text-center">
                                                    <el-input
                                                        v-model="domain.muUsage2"
                                                        style="width: 140px"
                                                        placeholder="请输入"
                                                    />
                                                </div>
                                            </div>
                                            <div class="box-item sub-item">
                                                <div class="form-l has-sub">
                                                    <div class="main-name">单亩用量</div>
                                                    <div class="sub-name">(亩数:药剂)</div>
                                                </div>
                                                <div class="form-r input-box text-center">
                                                    <el-input
                                                        v-model="domain.ratio2"
                                                        style="width: 140px"
                                                        placeholder="请输入"
                                                    />
                                                </div>
                                            </div>
                                            <div class="input-box">
                                                <el-input
                                                    v-model="domain.remark"
                                                    style="width: 100%"
                                                    placeholder="备注：用药注意事项"
                                                />
                                            </div>
                                            <div class="action-btn">
                                                <el-button class="btn delete-btn" @click.prevent="removeDomain(domain)">
                                                    删除
                                                </el-button>
                                                <el-button
                                                    type="primary"
                                                    class="btn"
                                                    @click.prevent="resetItemForm(index)"
                                                >
                                                    重置
                                                </el-button>
                                            </div>
                                        </div>
                                    </el-form-item>
                                </el-form>
                            </div>
                        </div> -->
                    </div>
                </div>
                <!-- <div class="prescription-item" v-else>
                    <div class="sub-title">
                        <div class="sub-name">药物处方</div>
                        <div class="sub-name"><span>施用方式：</span>根部施</div>
                    </div>
                    <custom-table type="0" :tableHeader="tableHeader" :tableData="tableData"></custom-table>
                </div> -->
                <div class="prescription-item" v-if="prescriptioData?.progress === 0">
                    <div class="sub-title">
                        <div class="sub-line"></div>
                        <div class="sub-name">指标动态</div>
                        <div class="sub-line"></div>
                    </div>
                    <div class="prescription-chart">
                        <chart :key="1" type="feature" :chartJson="prescriptioData.indexJson"></chart>
                    </div>
                </div>
                <div class="prescription-item" v-if="prescriptioData?.progress === 0 && ROLETYPE == '3'">
                    <el-button class="one-btn" type="primary" @click="submitForm(formRef)">确认下发</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import eventBus from "@/api/eventBus";
import chart from "./chart.vue";
import { onActivated, onMounted, reactive, ref } from "vue";
import { useStore } from "vuex";
import stepBox from "@/components/common/stepBox.vue";
import customTable from "./table.vue";

const props = defineProps({
    prescriptioData: {
        type: Object,
    },
});

const tableHeader = [
    {
        name: "使用功效",
        props: "typeName",
    },
    {
        name: "肥药名称",
        props: "defaultName",
    },
    {
        name: "执行方式",
        props: "usageMode1",
    },
    {
        name: "药肥配比",
        props: "usageMode",
    },
    {
        name: "单亩用量",
        props: "muUsage",
    },
];

const tableData = ref([
    {
        brand: "",
        defaultDroneRatio: null,
        defaultName: "灌水",
        defaultRatio: null,
        executeStyle: null,
        id: "686142764512972800",
        muPrice: null,
        muUsage: 222,
        muUsage2: null,
        orderId: "686142764492001280",
        pesticideFertilizerCode: "",
        pesticideFertilizerId: "15",
        pesticideFertilizerName: "灌水",
        price: null,
        ratio: 11,
        ratio2: null,
        remark: "",
        typeName: "调节",
        unit: "kg",
        usageMode: "",
        list: [],
    },
]);

const infoItem = ref({});

const store = useStore();
const ROLETYPE = store.state.app.curRole;

// 农事类型--区分表格显示字段等
const workType = ref(false);

let pesticideFertilizersOptions = ref([
    {
        id: "null",
        name: "芸苔素内酯 15000倍",
        typeName: "30",
        defaultRatio: null,
        defaultDroneRatio: null,
        unit: 0,
        defaultName: "调节",
    },
]);
VE_API.order.pesticideFertilizers().then(({ data }) => {
    pesticideFertilizersOptions.value = data;
    tableData.value[0].list = data;
});

onMounted(() => {
    dynamicValidateForm.domains = props.prescriptioData?.pesticideFertilizers.map((item) => ({ ...item }));
    // submit()
    console.log("dynamicValidateForm.domains", dynamicValidateForm.domains);
    infoItem.value = props.prescriptioData;
});

// 表单
const formRef = ref();
const dynamicValidateForm = reactive({
    domains: [
        {
            key: 1,
            typeName: "",
            muUsage: "",
            muUsage2: "",
            ratio: "",
            ratio2: "",
            remark: "",
        },
    ],
});

const addDomain = () => {
    dynamicValidateForm.domains.unshift({
        key: Date.now(),
        muUsage: "",
        muUsage2: "",
        ratio: "",
        ratio2: "",
        remark: "",
    });
    console.log("121323.domains", dynamicValidateForm.domains);
};

const removeDomain = (index) => {
    // const index = dynamicValidateForm.domains.indexOf(item);
    // if (index !== -1) {
        if(dynamicValidateForm.domains.length===1) return ElMessage.warning('至少保留一个处方!')
        dynamicValidateForm.domains.splice(index, 1);
    // }
};

const resetItemForm = (index) => {
    dynamicValidateForm.domains[index] = { typeName: "", muUsage: "", muUsage2: "", ratio: "", ratio2: "", remark: "" };
};

/**
 * 选择药肥的时候修改订单中药肥pesticideFertilizerId 以外其他数据
 * @param index
 */
const handlePesticideFertilizerChange = (index) => {
    let obj = pesticideFertilizersOptions.value.filter(
        (item) => dynamicValidateForm.domains[index].pesticideFertilizerId === item.id
    )[0];
    dynamicValidateForm.domains[index] = {
        ...dynamicValidateForm.domains[index],
        typeName: obj.typeName,
        unit: obj.unit,
        defaultRatio: obj.defaultRatio,
        usageModeList: obj.usageModeList,
        ratio: obj.defaultRatio,
        defaultName: obj.defaultName,
        pesticideFertilizerName: obj.name,
    };
    console.log(dynamicValidateForm.domains);
};

const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            submit();
        } else {
            console.log("error submit!");
        }
    });
};

const submit = () => {
    const data = {
        orderId: props.prescriptioData.orderId,
        orderStatus: 1,
        pesticideFertilizers: dynamicValidateForm.domains,
    };
    VE_API.order.confirm(data).then(({ code }) => {
        if (code == 0) {
            console.log("专家下发处方成功");
            eventBus.emit("discover:submitForm");
            window.location.reload();
        }
    });
};

const formatIndex = (index) => {
    return String(index + 1).padStart(2, "0");
};

const handleTableData = (item) => {
    return [
        {
            typeName: item.typeName,
            defaultName: item.defaultName,
            executeStyle: 1,
            ratio: item.ratio || item.defaultRatio,
            usageMode: item.usageMode,
            muUsage: item.muUsage,
            unit: item.unit,
        },
        {
            typeName: item.typeName,
            defaultName: item.defaultName,
            executeStyle: 2,
            ratio: item.ratio2,
            usageMode: "---",
            muUsage: item.muUsage2,
            unit: item.unit,
        },
    ];
};
</script>

<style lang="scss" scoped>
@import "./boxClass.scss";
.recipe-box {
    .recipe-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
        padding-left: 10px;
        position: relative;
        &::before {
            content: "";
            position: absolute;
            left: 0;
            top: 3px;
            width: 3px;
            height: 15px;
            background: #fff;
            border-radius: 11px;
        }
        .recipe-name {
            color: #fff;
            font-size: 15px;
        }
        .recipe-btn {
            color: #FFD489;
            display: flex;
            align-items: center;
            cursor: pointer;
            .icon{
                margin-right: 3px;
            }
        }
    }
}
.prescription-result {
    position: relative;
    &.has-wrap {
        border: 0.5px solid rgba(33, 153, 248, 0.5);
        border-radius: 4px;
        padding: 8px 10px 10px 10px;
    }
    .result-index {
        position: absolute;
        left: -1px;
        top: -1px;
        padding: 0 8px;
        background: #2199f8;
        color: #fff;
        font-size: 12px;
        border-radius: 4px 0 4px 0;
    }
    .result-title {
        display: flex;
        justify-content: center;
        align-items: center;
        padding-bottom: 8px;
        .title-item {
            display: flex;
            align-items: center;
            .name {
                color: rgba(33, 153, 248, 0.85);
            }
            .value {
                color: rgba(0, 0, 0, 0.4);
            }
        }
        .title-item + .title-item {
            padding-left: 16px;
        }
    }
}
</style>
