<template>
    <div>
        <el-card class="!border-none mb-4" shadow="never">
            <el-form
                class="mb-[-16px]"
                :model="queryParams"
                inline
            >
            <el-form-item label="用户ID" prop="user_id">
    <el-input class="w-[280px]" v-model="queryParams.user_id" clearable placeholder="请输入用户ID" />
</el-form-item>
                <el-form-item label="土地ID" prop="land_id">
    <el-input class="w-[280px]" v-model="queryParams.land_id" clearable placeholder="请输入土地ID" />
</el-form-item>
                <el-form-item label="种植种类" prop="kind">
    <el-input class="w-[280px]" v-model="queryParams.kind" clearable placeholder="请输入种植种类" />
</el-form-item>
                <el-form-item label="种植品牌" prop="breed">
    <el-input class="w-[280px]" v-model="queryParams.breed" clearable placeholder="请输入种植品牌" />
</el-form-item>
                <el-form-item label="种植人员" prop="user">
    <el-input class="w-[280px]" v-model="queryParams.user" clearable placeholder="请输入种植人员" />
</el-form-item>
                <el-form-item label="生长状态" prop="status">
    <el-select class="w-[280px]" v-model="queryParams.status" clearable placeholder="请选择生长状态">
        <el-option label="全部" value=""></el-option>
        <el-option 
            v-for="(item, index) in dictData.plant_status"
            :key="index" 
            :label="item.name"
            :value="item.value"
        />
    </el-select>
</el-form-item>
                <el-form-item label="播种时间" prop="plant_date">
    <daterange-picker
        v-model:startTime="queryParams.start_time"
        v-model:endTime="queryParams.end_time"
    />
</el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none" v-loading="pager.loading" shadow="never">
            <div class="mt-4">
                <el-table :data="pager.lists" @selection-change="handleSelectionChange" style="width: 100%">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="ID" prop="id" width="80" show-overflow-tooltip />
                    <!-- <el-table-column label="用户信息" width="200">
                        <template #default="{ row }">
                            <el-tag class="mr-2" type="info">ID: {{ row.user_id }}</el-tag>
                            <el-tag class="mr-2" type="info">账户: {{ row.account }}</el-tag>
                        </template>
                    </el-table-column> -->
                    <el-table-column label="所属土地" width="200">
                        <template #default="{ row }">
                            <el-tag class="mr-2" type="info">ID: {{ row.land_id }}</el-tag>
                            <el-tag class="mr-2" type="info">名称: {{ row.title }}</el-tag>
                        </template>
                    </el-table-column> 
                    <el-table-column label="种植种类" prop="kind" show-overflow-tooltip />
                    <el-table-column label="种植品牌" prop="breed" show-overflow-tooltip />
                    <el-table-column label="种植面积" prop="area" show-overflow-tooltip />
                    <el-table-column label="种植人员" prop="user" show-overflow-tooltip />
                    <el-table-column label="生长状态" align="center" prop="status">
    <template #default="{ row }">
        <dict-value :options="dictData.plant_status" :value="row.status" />
    </template>
</el-table-column>
                    <el-table-column label="溯源二维码" width="150" align="center" prop="qr_code">
    <template #default="{ row }">
                            <el-image
                                v-if="
                                    row.qr_code !== null &&
                                    row.qr_code !== undefined &&
                                    row.qr_code !== ''
                                "
                                style="width: 100px; height: 100px"
                                :src="row.qr_code"
                            />
    </template>
</el-table-column>
                    <el-table-column label="播种时间" width="180" align="center" prop="plant_date">
    <template #default="{ row }">
                            <span>{{
                                row.plant_date
                                    ? timeFormat(row.plant_date, 'yyyy-mm-dd hh:MM:ss')
                                    : ''
                            }}</span>
    </template>
</el-table-column>
                    <el-table-column label="操作" width="340" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button
                                v-perms="['land.land_plant/edit']"
                                type="primary"
                                link
                                @click="handleEdit(row)"
                            >
                                编辑
                            </el-button>
                            <el-button
                                v-perms="['land.land_plant/suyuan']"
                                type="primary"
                                link
                                @click="handleSuyuan(row)"
                            >
                                溯源信息
                            </el-button>
                            <el-button type="primary" link @click="handleDetail(row)">
                                种植图片
                            </el-button>
                            <el-button
                                v-perms="['land.land_plant_action/lists']"
                                type="primary"
                                link
                            >
                                <router-link
                                    :to="{
                                        path: getRoutePath('land.land_plant_action/lists'),
                                        query: {
                                            plant_id: row.id
                                        }
                                    }"
                                >
                                种植操作
                                </router-link>
                            </el-button>
                            <el-button
                                v-perms="['land.land_plant/delete']"
                                type="danger"
                                link
                                @click="handleDelete(row.id)"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="flex mt-4 justify-end">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
        <edit-popup v-if="showEdit" ref="editRef" :dict-data="dictData" @success="getLists" @close="showEdit = false" />
    </div>

    <el-dialog v-model="dialogPicVisible" title="种植图片" center>
        <div style="display: inline-block; margin: 12px" v-for="img in detailData.picData" :key="img">
            <el-image
                style="width: 200px; height: 200px"
                :src="img"
                :zoom-rate="1.2"
                :max-scale="5"
                :min-scale="0.2"
                :preview-src-list="detailData.picData"
                :initial-index="4"
                fit="cover"
                center
            />
        </div>
    </el-dialog>

    <el-dialog v-model="dialogSuyuanVisible" title="溯源信息">
        <div class="overflow-y-auto" style="height: 500px">
            <el-carousel indicator-position="outside">
                <el-carousel-item v-for="(value, index) in suyuanData.categoryData.pic" :key="index" class="text-center">
                    <el-image
                        style="width: auto; height: 100%"
                        :src="suyuanData.categoryData.pic[index]"
                    />
                </el-carousel-item>
            </el-carousel>
            <el-tag size="large" type="info">品类信息</el-tag>
            <el-card class="box-card mb-4">
                <div class="mb-2 text-xl text-tx-gray">
                    商品名称：{{ suyuanData.categoryData.kind }}
                </div>
                <div class="mb-2 text-xl text-tx-gray">
                    收获日期：{{ suyuanData.categoryData.harvest_date }}
                </div>
                <div class="mb-2 text-xl text-tx-gray">
                    生长周期：{{ suyuanData.categoryData.group_day }} 天
                </div>
                <div class="mb-2 text-xl text-tx-gray">
                    生产地址：{{ suyuanData.categoryData.land_address }}
                </div>
            </el-card>
            <div v-for="(value, index) in suyuanData.landActionType" :key="index">
                <el-tag size="large" type="info">{{ suyuanData.landActionType[index] }}</el-tag>
                <el-card class="box-card mb-4">
                    <div
                        v-for="(data, item) in suyuanData.landActionData[index]"
                        :key="item"
                        class="mb-2 text-xl text-tx-gray"
                    >
                        {{ data.item ?? '' }}：{{ data.value ?? '' }}
                    </div>
                </el-card>
            </div>
        </div>
    </el-dialog>
</template>

<script lang="ts" setup name="landPlantLists">
import { usePaging } from '@/hooks/usePaging'
import { getRoutePath } from '@/router'
import { useDictData } from '@/hooks/useDictOptions'
import { apiLandPlantLists, apiLandPlantDelete, apiSuyuanDetail } from '@/api/land_plant'
import { timeFormat } from '@/utils/util'
import feedback from '@/utils/feedback'
import EditPopup from './edit.vue'

const { query } = useRoute()
const editRef = shallowRef<InstanceType<typeof EditPopup>>()
// 是否显示编辑框
const showEdit = ref(false)

let land_id = query.land_id
if (typeof land_id == 'undefined') {
    land_id = ''
}

// 查询条件
const queryParams = reactive({
    user_id: '',
    land_id: land_id,
    kind: '',
    breed: '',
    user: '',
    status: '',
    plant_date: '',
    start_time: '',
    end_time: '',
})

// 选中数据
const selectData = ref<any[]>([])

// 表格选择后回调事件
const handleSelectionChange = (val: any[]) => {
    selectData.value = val.map(({ id }) => id)
}

// 获取字典数据
const { dictData } = useDictData('plant_status')

// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
    fetchFun: apiLandPlantLists,
    params: queryParams
})

const dialogPicVisible = ref(false)
const dialogSuyuanVisible = ref(false)
const detailData = reactive({
    picData: [] as any[]
})

// 详情
const handleDetail = (data: any) => {
    detailData.picData = []
    const picList = JSON.parse(data.pic)
    for (const key in picList) {
        detailData.picData.unshift(picList[key])
    }
    dialogPicVisible.value = true
}


interface actionData {
    [key: string]: any
}

const actionMap = reactive<actionData>({
    '1': {
        kind: '肥料种类',
        breed: '肥料品牌',
        dosage: '肥料用量',
        start_date: '开始日期',
        end_date: '结束日期',
        area: '施肥面积',
        user: '参与人',
        pic: '施肥图片',
        remark: '备注信息'
    },
    '2': {
        kind: '除草剂种类',
        breed: '除草剂品牌',
        dosage: '除草剂用量',
        start_date: '开始日期',
        end_date: '结束日期',
        area: '作业面积',
        user: '参与人',
        pic: '除草图片',
        remark: '备注信息'
    },
    '3': {
        type: '灌溉类型',
        start_date: '开始日期',
        end_date: '结束日期',
        area: '灌溉面积',
        user: '参与人',
        pic: '灌溉图片',
        remark: '备注信息'
    },
    '4': {
        kind: '杀虫剂种类',
        breed: '杀虫剂品牌',
        dosage: '杀虫剂用量',
        start_date: '开始日期',
        end_date: '结束日期',
        area: '作业面积',
        user: '参与人',
        pic: '杀虫图片',
        remark: '备注信息'
    },
    '5': {
        user: '参与人',
        pic: '收获图片',
        remark: '备注信息'
    }
})

const irrigateMap = reactive<actionData>({
    '1': '喷灌',
    '2': '滴灌',
    '3': '沟灌'
})

const landActionData = reactive({
    gridData: [{}]
})

const suyuanData = reactive({
    categoryData: {
        kind: '',
        group_day: '',
        harvest_date: '',
        land_address: '',
        pic: ''
    },
    landActionType: [''],
    landActionData: [reactive<actionData>({})]
})

// 溯源详情
const handleSuyuan = (data: any) => {
    detailData.picData = []
    apiSuyuanDetail({
        id: data.id
    })
        .then((res: any) => {
            dialogSuyuanVisible.value = true
            console.log(res)
            suyuanData.categoryData.kind = res.kind ?? ''
            suyuanData.categoryData.group_day = res.group_day ?? ''
            suyuanData.categoryData.harvest_date = res.harvest_date ?? ''
            suyuanData.categoryData.land_address = res.land_address ?? ''
            suyuanData.categoryData.pic = res.pic ?? []
            landActionData.gridData = [{}]
            for (const key in res.actions) {
                landActionData.gridData = [{}]
                const type = res.actions[key]['type']
                const typeText = res.actions[key]['type_text'] as string
                const detail = res.actions[key]['detail']
                for (const key in actionMap[type]) {
                    const item = actionMap[type][key] ?? '-'
                    for (const dkey in detail) {
                        if (dkey == key) {
                            if (type == 3 && key == 'type') {
                                detail[key] = irrigateMap[detail[key]]
                            }
                            landActionData.gridData.push({
                                item: item,
                                value: detail[key] ?? '-'
                            })
                        }
                    }
                }
                landActionData.gridData.splice(0, 1)
                suyuanData.landActionType.push(typeText)
                suyuanData.landActionData.push(landActionData.gridData)
            }
            suyuanData.landActionType.splice(0, 1)
            suyuanData.landActionData.splice(0, 1)
        })
        .catch((err: any) => {
            console.log('err', err)
        })
}

// 添加
const handleAdd = async () => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('add')
}

// 编辑
const handleEdit = async (data: any) => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('edit')
    editRef.value?.setFormData(data)
}

// 删除
const handleDelete = async (id: number | any[]) => {
    await feedback.confirm('确定要删除？')
    await apiLandPlantDelete({ id })
    getLists()
}

getLists()
</script>

