<template>
    <HcNewCard>
        <template #header>
            <div class="w-64">
                <HcDatePicker :dates="weatherTime" clearable @change="weatherTimeUpdate" />
            </div>
            <div class="ml-2">
                <el-button type="primary" @click="searchWeatherClick">搜索</el-button>
            </div>
        </template>
        <template #extra>
            <HcTooltip keys="write_weather_print">
                <el-button :loading="printLoading" hc-btn @click="batchPrint">
                    <HcIcon name="printer" />
                    <span>打印</span>
                </el-button>
            </HcTooltip>
        </template>
        <HcTable
            :column="tableWeatherColumn" :datas="tableWeatherData" :loading="tableWeatherLoading"
            is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
            @selection-change="tableWeatherSelection"
        >
            <template #tempLow="{ row }">{{ row.tempLow }} ~ {{ row.tempHigh }}</template>
            <template #action="{ row }">
                <HcTooltip keys="write_weather_edit">
                    <el-button plain size="small" type="primary" @click="tableWeatherEdit(row)">
                        <HcIcon name="edit" />
                        <span>编辑</span>
                    </el-button>
                </HcTooltip>
            </template>
        </HcTable>
        <template #action>
            <HcPages :pages="searchWeatherForm" @change="pageWeatherChange" />
        </template>
    </HcNewCard>

    <!-- 编辑天气台账 -->
    <hc-new-dialog v-model="showWeatherEditModal" title="编辑天气台账" widths="38rem">
        <el-form
            ref="weatherFormRef" :model="weatherFormModel" :rules="weatherFormRules" label-width="auto"
            size="large"
        >
            <el-form-item label="日期">
                <el-input v-model="weatherFormModel.recordTime" disabled />
            </el-form-item>
            <el-form-item label="天气" prop="weather">
                <el-input v-model="weatherFormModel.weather" placeholder="天气" />
            </el-form-item>
            <el-form-item label="最低温度" prop="tempLow">
                <el-input v-model="weatherFormModel.tempLow" placeholder="最低温度" type="number" />
            </el-form-item>
            <el-form-item label="最高温度" prop="tempHigh">
                <el-input v-model="weatherFormModel.tempHigh" placeholder="最高温度" type="number" />
            </el-form-item>
            <el-form-item label="风力" prop="windLevel">
                <el-input v-model="weatherFormModel.windLevel" placeholder="风力" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button size="large" @click="showWeatherEditModal = false">
                    <HcIcon name="close" />
                    <span>取消</span>
                </el-button>
                <el-button :loading="saveWeatherLoading" hc-btn type="primary" @click="saveWeatherClick">
                    <HcIcon name="save" />
                    <span>提交保存</span>
                </el-button>
            </div>
        </template>
    </hc-new-dialog>
</template>

<script setup>
import { nextTick, ref } from 'vue'
import weatherApi from '~api/ledger/weather'
import queryApi from '~api/data-fill/query'
import { arrToId, deepClone, formValidate, getArrValue } from 'js-fast-way'

//参数
const props = defineProps({
    projectId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
})

//变量
const projectId = ref(props.projectId)
const contractId = ref(props.contractId)

//渲染完成
nextTick(() => {
    searchWeatherClick()
})

//搜索表单
const searchWeatherForm = ref({ recordTime: '', current: 1, size: 20, total: 0 })

//日期时间被选择
const weatherTime = ref(null)
const weatherTimeUpdate = ({ query, arr }) => {
    weatherTime.value = arr
    searchWeatherForm.value.recordTime = query
}

//搜索
const searchWeatherClick = () => {
    searchWeatherForm.value.current = 1
    getTableWeatherData()
}

//分页被点击
const pageWeatherChange = ({ current, size }) => {
    searchWeatherForm.value.current = current
    searchWeatherForm.value.size = size
    getTableWeatherData()
}

//天气台账表头
const tableWeatherColumn = ref([
    { key: 'recordTime', name: '日期' },
    { key: 'weather', name: '天气' },
    { key: 'tempLow', name: '温度 ℃' },
    { key: 'airTemp', name: '平均温度 ℃' },
    { key: 'windLevel', name: '风力' },
    { key: 'action', name: '操作', width: 100 },
])
const tableWeatherData = ref([])

//获取数据
const tableWeatherLoading = ref(false)
const getTableWeatherData = async () => {
    tableWeatherLoading.value = true
    const { error, code, data } = await weatherApi.queryWeatherPage({
        ...searchWeatherForm.value,
        projectId: projectId.value,
        contractId: contractId.value,
    })
    //判断状态
    tableWeatherLoading.value = false
    if (!error && code === 200) {
        tableWeatherData.value = getArrValue(data['records'])
        searchWeatherForm.value.total = data['total'] || 0
    } else {
        tableWeatherData.value = []
        searchWeatherForm.value.total = 0
    }
}

//天气台账编辑
const showWeatherEditModal = ref(false)
const tableWeatherEdit = (row) => {
    weatherFormModel.value = deepClone(row)
    saveWeatherLoading.value = false
    showWeatherEditModal.value = true
}

//天气台账表单
const weatherFormRef = ref(null)
const weatherFormModel = ref({ recordTime: '', weather: '', tempLow: null, tempHigh: null, windLevel: '' })
const weatherFormRules = ref({
    weather: {
        required: true,
        trigger: 'blur',
        message: '请输入天气',
    },
    tempLow: {
        required: true,
        validator: (rule, value, callback) => {
            const tempHigh = weatherFormModel.value?.tempHigh ?? ''
            const val = Number(value)
            const high = Number(tempHigh)
            if (!val) {
                callback(new Error('请输入最低温度'))
            } else if (val > high) {
                callback(new Error('最低温度不能高于最高温度'))
            } else if (val === high) {
                callback(new Error('最低温度和最高温度，不能一致'))
            } else {
                callback()
            }
        },
        trigger: 'blur',
    },
    tempHigh: {
        required: true,
        validator: (rule, value, callback) => {
            const tempLow = weatherFormModel.value?.tempLow ?? ''
            const val = Number(value)
            const low = Number(tempLow)
            if (!val) {
                callback(new Error('请输入最高温度'))
            } else if (val < low) {
                callback(new Error('最高温度不能低于最低温度'))
            } else if (val === low) {
                callback(new Error('最高温度和最低温度，不能一致'))
            } else {
                callback()
            }
        },
        trigger: 'blur',
    },
    windLevel: {
        required: true,
        trigger: 'blur',
        message: '请输入风力',
    },
})

//提交保存
const saveWeatherLoading = ref(false)
const saveWeatherClick = async () => {
    const validate = await formValidate(weatherFormRef.value)
    if (validate) {
        //发起请求
        saveWeatherLoading.value = true
        const { error, code } = await weatherApi.updateWeatherById({
            ...weatherFormModel.value,
            projectId: projectId.value,
            contractId: contractId.value,
        }, false)
        //处理数据
        saveWeatherLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('保存成功')
            showWeatherEditModal.value = false
            getTableWeatherData()
        } else {
            window?.$message?.error('保存失败')
        }
    }
}
//多选
const tableweatherKeys = ref([])
const tableWeatherSelection = (rows) => {
    tableweatherKeys.value = rows.filter((item) => {
        return (item ?? '') !== ''
    })
}

//打印
const printLoading = ref(false)
const batchPrint = async () => {
    const rows = tableweatherKeys.value
    const ids = arrToId(rows)
    //批量下载
    printLoading.value = true
    const { error, code, data } = await queryApi.batchPrint({ ids: ids })
    //处理数据
    printLoading.value = false
    const res = isString(data) ? data ?? '' : ''
    if (!error && code === 200 && res) {
        window.open(res, '_blank')
    }
}
</script>
