<template>
    <div>
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="height: 65px;"
            :disabled="state.disabled">
            <el-form-item label="相关单位" v-if="userType === '0'">
                <el-select v-model="queryParams.unitCode" placeholder="关联单位" filterable clearable @change="queryList">
                    <el-option v-for="item in state.unitData" :key="item.unitCode" :label="item.unitName" 
                        :value="item.unitCode" />
                </el-select>
            </el-form-item>

            <el-form-item label="统计月份">
                <el-config-provider :locale="locale">
                    <el-date-picker v-model="queryParams.sampleTime" type="month" placeholder="统计日期"
                        value-format="YYYY-MM-DD HH:mm:ss" @change="queryList" />
                </el-config-provider>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" class="button" @click="queryList">查询数据</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" class="button" @click="handleDownLoad">下载文件</el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%" :height="tableHeight"
            highlight-current-row @current-change="handleCurrentRowChange"
            :header-cell-style="{ background: '#606266', color: '#FFFFFF' }">
            <el-table-column fixed type="index" width="50" align="center" />
            <el-table-column fixed fit prop="unitname" label="用水单位" header-align="center" width="300" />           
            <el-table-column fit prop="stationName" label="遥测站名称" header-align="center" width="240" />
            <el-table-column label="统计日期" header-align="center" width="120">
                <template #default="scope">
                    {{ tool.dateFormat(scope.row.sampleTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="stationCode" label="遥测站代码" header-align="center" width="120" />
            <el-table-column prop="resultValue" label="设备读数" header-align="center" width="120" />
            <el-table-column label="图片" header-align="center" width="150" resizable="false">
                <template #default="scope">
                    <div style="display: flex; align-items: center">
                        <el-image :src="scope.row.smallJpgUrl" :hide-on-click-modal="true" :close-on-press-escape="true"
                            slot="error">
                            <template #error>
                                <div slot="error" class="image-slot">
                                    <i class="el-icon-picture-outline"
                                        style="font-size: 30px;text-align: center;display: block;width: 120px;"></i>
                                    <span style="color: red;text-align: center;display: block;">无图片信息</span>
                                </div>
                            </template>
                        </el-image>
                    </div>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>
  
<script lang="ts" setup>
import { reactive, toRefs, toRef, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import StationCountAction from "@/api/station/stationcount";
import { StationCountQueryParam, StationCountModel, Dialog, PageResult, TAffiliatedunitQueryParam, TAffiliatedunitModel } from '@/types';
import tool from "@/until/tool";
import zhCn from 'element-plus/lib/locale/lang/zh-cn';
import Moment from "moment";
import TAffAction from "@/api/customermanagement/taffiliatedunit";
import { Result } from "postcss";
import { AxiosResponse } from "axios";
import { stat } from "fs";

let locale = ref(zhCn)

const queryFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
let userId = localStorage.getItem("CustomerId") + '';
const unitCode = localStorage.getItem("UnitCode") + '';
const userType = localStorage.getItem("UserType")?.toString();

const loading = ref(false)
const defaultDate = new Date();

const state = reactive({
    queryParams: {
        page: 1,
        rows: 999,
        sampleTime: Moment(defaultDate.getTime()).format("YYYY-MM-DD HH:mm:ss"),
        unitCode: localStorage.getItem("UnitCode") || ""
    } as StationCountQueryParam,

    pagination: {
        total: 0,
        small: false,
        background: false,
        disabled: false,
    },
    disabled: false,                              //控制查询面板
    unitData: [] as TAffiliatedunitModel[],       //使用单位
    tableData: [] as StationCountModel[],
});

const {
    queryParams,
    tableData
} = toRefs(state);

const tableHeight = ref(document.documentElement.clientHeight - 150);
const currentRow = ref()

const handleCurrentRowChange = (val: StationCountModel | undefined) => {
    currentRow.value = val
}

const handleDownLoad = () => {
    if (!state.queryParams.sampleTime) {
        ElMessage.warning("请选择日期...");
        return;
    }
    if (userType === '1') {
        state.queryParams.unitCode = unitCode;
    } else if (!state.queryParams.unitCode) {
        ElMessage.warning("请选择单位...");
        return;
    }
    state.disabled = true;
    let time = tool.dateFormat(Moment(state.queryParams.sampleTime).format("YYYY-MM-DD HH:mm:ss").toString(), "YYYY-MM-DD HH:mm:ss", "YYYYMMDDHHmmss");

    StationCountAction.DownLoadFile(state.queryParams.unitCode, time).then(result => {
        state.disabled = false;
        if (result.status === 200) {
            let unitModel = state.unitData.find(s => s.unitCode === state.queryParams.unitCode);
            let unitName = unitCode == null || unitCode == undefined ? '' : unitModel?.unitName;

            const blob = new Blob([result.data]);//处理文档流
            const fileName = unitName + '-' + time.substring(0, 6) + '.xlsx';
            const down = document.createElement('a');
            down.download = fileName;
            down.style.display = 'none';
            down.href = URL.createObjectURL(blob);
            document.body.appendChild(down);
            down.click();
            URL.revokeObjectURL(down.href);
            document.body.removeChild(down);
        }
    }).catch(error => {
        let response = Promise.resolve(error) as Promise<Response>;
        response.then(result => {
            if (result.status === 5501) {
                ElMessage.error("导出单位错误");
            } else if (result.status === 5502) {
                ElMessage.error("当前单位没有模板");
            }
            else {
                ElMessage.error(error || "未知异常...");
            }
        }).catch(err => {
            ElMessage.error(err || "未知异常...");
        });
        state.disabled = false;
    })
}

const queryList = () => {
    if (!state.queryParams.sampleTime) {
        ElMessage.warning("请选择日期...");
        return;
    }
    if (userType === '1') {
        state.queryParams.unitCode = unitCode;
    } else if (!state.queryParams.unitCode) {
        ElMessage.warning("请选择单位...");
        return;
    }
    let time = tool.dateFormat(Moment(state.queryParams.sampleTime).format("YYYY-MM-DD HH:mm:ss").toString(), "YYYY-MM-DD HH:mm:ss", "YYYYMMDDHHmmss");

    loading.value = true;
    StationCountAction.QueryStationCountList(state.queryParams.unitCode, time).then(result => {
        if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
                state.tableData = res as StationCountModel[];
            } else {
                ElMessage.error(error || "获取数据异常...");
            }
            loading.value = false;
        }
    }).catch(error => {
        //请求失败时的操作     
        ElMessage.error(error || "获取数据异常...");
        loading.value = false;
    })

};

onMounted(() => {
    window.onresize = function () {
        tableHeight.value = document.documentElement.clientHeight - 150
    }
    //queryList();
    queryUnit();
})

const queryUnit = () => {
    let queryModel = {} as TAffiliatedunitQueryParam;
    TAffAction.QueryTAffiliatedunitList(queryModel).then(result => {
        if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
                const pageData = res as PageResult<TAffiliatedunitModel[]>;
                state.unitData = pageData.list;
            } else {
                ElMessage.error(error);
            }
        }
        loading.value = false;
    }).catch(error => {
        //请求失败时的操作     
        ElMessage.error(error);
        loading.value = false;
    })
}
</script>
  
  <style lang="scss" scoped>
  .button {
      margin: 10px 0;
  }
  </style>