<template>
    <div class="nucleicAcidResult">
        <div class="search-wrapper">
            <el-form :inline="true" :model="searchForm" class="search_form" style="text-align: left">
                <el-form-item label="姓名">
                    <el-input size="medium" v-model="searchForm.name" placeholder="请输入姓名"
                        @keyup.enter.native="onSubmit"></el-input>
                </el-form-item>
                <el-form-item label="身份证号">
                    <el-input size="medium" v-model="searchForm.idCard" placeholder="请输入身份证号"
                        @keyup.enter.native="onSubmit"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="small" @click="onSubmit">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="small" @click="addNucleicAcid">新增</el-button>
                </el-form-item>
                <!-- <el-form-item>
                    <el-button type="primary" size="small" @click="downLoad">下载Excel模板</el-button>
                </el-form-item> -->
                <el-form-item>
                    <el-upload class="mx-2" name="file" action="string" :before-upload="beforeAvatarUpload" :limit="1"
                        accept=".xlsx,.xls" :show-file-list="false" :file-list="fileList" :http-request="uploadFile1">
                        <el-button type="primary" size="small">模板替换</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-upload class="mx-2" name="file" action="string" :before-upload="beforeAvatarUpload" :limit="1"
                        accept=".xlsx,.xls" :show-file-list="false" :file-list="fileList" :http-request="uploadFile">
                        <el-button type="primary" size="small" @click="upload">导入Excel文件</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
        </div>
        <div class="table-wrapper">
            <table-template :tableData="tableData" :tableColumns="tableColumns" :loading="loading"
                :pagination="pagination" @Jump="jumpPage">
                <el-table-column fixed="right" label="操作" width="250" align="center">
                    <template slot-scope="scope">
                        <el-button type="success" size="mini" round @click="formUser(1, scope.row)">查看</el-button>
                        <el-button type="success" size="mini" round @click="formUser(2, scope.row)">编辑</el-button>
                    </template>
                </el-table-column>
            </table-template>
        </div>
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" destroy-on-close width="45%" @close="closeFn">
            <el-form :model="form" label-width="150px" ref="form" :rules="rules">
                <el-form-item label="姓名" prop="name">
                    <el-input placeholder="请输入姓名" v-model="form.name" :disabled="disabled"></el-input>
                </el-form-item>
                <el-form-item label="证件号码" prop="idCard">
                    <el-input placeholder="请输入证件号码" v-model="form.idCard" :disabled="disabled"></el-input>
                </el-form-item>
                <el-form-item label="辖市区" prop="areaName">
                    <el-select v-model="form.areaName" placeholder="请选择辖市区" :disabled="disabled" style="width: 100%"
                        @change="changeArea">
                        <el-option v-for="item in areaList" :key="item.code" :label="item.name" :value="item.name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="采样时间" prop="collectionTime">
                    <el-date-picker v-model="form.collectionTime" type="datetime" placeholder="请选择采样时间"
                        style="width: 100%" :disabled="disabled" value-format="yyyy-MM-dd HH:mm:ss"
                        @change="changeCollectionTime">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="采样机构" prop="checkUnit">
                    <el-input placeholder="请输入采样机构" v-model="form.checkUnit" :disabled="disabled"></el-input>
                </el-form-item>
                <el-form-item label="采样点" prop="address">
                    <el-input placeholder="请输入采样点" v-model="form.address" :disabled="disabled"></el-input>
                </el-form-item>
                <el-form-item label="采样结果" prop="checkResult">
                    <div>
                        <el-radio v-model="form.checkResult" :label="'阴性'" :disabled="disabled">阴性</el-radio>
                        <el-radio v-model="form.checkResult" :label="'阳性'" :disabled="disabled">阳性</el-radio>
                    </div>
                </el-form-item>
                <el-form-item label="出具结果时间" prop="resultTime">
                    <el-date-picker v-model="form.resultTime" type="datetime" placeholder="请选择出具结果时间时间"
                        style="width: 100%" :disabled="disabled" value-format="yyyy-MM-dd HH:mm:ss"
                        @change="changeResultTime">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeFn" v-if="this.dialogType == 1">关 闭</el-button>
                <el-button @click="closeFn" v-if="this.dialogType != 1">取 消</el-button>
                <el-button type="primary" @click="saveFun" v-if="this.dialogType != 1">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import TableTemplate from "@/components/Table";
import { queryCity } from "@/api/antigen.js";
import {
    getList,
    exportAdd,
    TemplateReplace,
    getResultDetail,
    customAdd,
    update
} from "@/api/nucleicAcid";
import { changeList } from "@/utils/index";

export default {
    components: { TableTemplate },
    data() {
        return {
            searchForm: {
                name: '',
                idCard: '',
                city: '',
                code: ''
            },
            pagination: {
                total: 0,
                pageSize: 10,
                currentPage: 1,
            },
            loading: false,
            tableData: [],
            tableColumns: [
                {
                    key: "code",
                    label: "编号",
                    width: 280,
                },
                {
                    key: "name",
                    label: "姓名",
                    width: 180,
                },
                {
                    key: "idCard",
                    label: "身份证号码",
                    width: 200,
                },
                {
                    key: "areaName",
                    label: "采样区县名称",
                    width: 200,
                },
                {
                    key: "address",
                    label: "采样点",
                    width: 200,
                },
                {
                    key: "checkUnit",
                    label: "检测机构",
                    width: 200,
                },
                {
                    key: "checkResult",
                    label: "检测结果",
                    width: 150,
                },
                {
                    key: "resultTime",
                    label: "出具报告时间",
                    width: 200,
                },
            ],
            fileList: [],
            areaList: [],
            dialogFormVisible: false,
            dialogType: "",
            form: {
                name: '',
                idCard: '',
                cityName: '镇江市',
                cityCode: '321100',
                areaName: '',
                areaCode: '',
                collectionTime: '',
                checkUnit: '',
                address: '',
                checkResult: '',
                resultTime: '',
                code: '',
            },
            rules: {
                name: [{ required: true, message: "请输入姓名", trigger: "change" }],
                idCard: [{ required: true, message: "请输入证件号码", trigger: "change" },],
                areaName: [{ required: true, message: "请选择辖市区", trigger: "change" },],
                collectionTime: [{ required: true, message: "请选择采样时间", trigger: "change" },],
                checkUnit: [{ required: true, message: "请输入采样机构", trigger: "change" }],
                address: [{ required: true, message: "请输入采样点", trigger: "change" }],
                checkResult: [{ required: true, message: "请输入采样结果", trigger: "change" }],
                resultTime: [{ required: true, message: "请选择出具结果时间", trigger: "change" },],
            }
        }
    },
    computed: {
        dialogTitle() {
            return this.dialogType == 0
                ? "新增信息"
                : this.dialogType == 1
                    ? "查看信息"
                    : "编辑信息";
        },
        disabled() {
            return (
                this.dialogType == 1
            );
        },
    },
    methods: {
        initArea() {
            queryCity({}).then((res) => {
                console.log(res)
                if (res.code == 200) {
                    this.areaList = res.data
                }
            })
        },
        init() {
            this.loading = true;
            let params = {
                name: this.searchForm.name,
                // idCard: this.searchForm.idCard ? encryptByDES(this.searchForm.idCard, "MnuYbhGv") : "",
                idCard: this.searchForm.idCard,
                city: this.searchForm.city,
                code: this.searchForm.code,
                pageNum: this.pagination.currentPage,
                pageSize: this.pagination.pageSize,
            };
            getList(params).then((res) => {
                console.log('res', res);
                this.loading = false
                if (res.success) {
                    this.pagination.total = res.data.total;
                    if (res.data.total) {
                        this.tableData = res.data.list;
                    } else {
                        this.tableData = [];
                    }
                    if (localStorage.getItem("userName") == "admin") {
                        this.tableData = changeList(this.tableData);
                    }
                } else {
                    this.$message.error(res.msg || "系统错误");
                }
            })
        },
        onSubmit() {
            this.pagination.currentPage = 1;
            this.init();
        },
        jumpPage() {
            this.init();
        },
        downLoad() {
            const a = document.createElement("a")
            a.setAttribute("href", "./static/核酸采样结果导入模板.xls");
            a.setAttribute("download", "核酸采样结果导入模板.xls")
            a.click()
        },
        uploadFile1(param) {
            const File = param.file;
            let formData1 = new FormData();
            formData1.append("file", File);
            const link = document.createElement("a");
            link.style.display = "none";
            TemplateReplace(formData1).then((res) => {
                console.log('res', res);
                this.fileList = [];
                if (res.status == 200) {
                    link.href = window.URL.createObjectURL(
                        new Blob([res.data], {
                            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
                        })
                    );
                    link.setAttribute("download", "");
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    this.init();
                    this.$message.success("替换成功");

                } else {
                    this.init();
                    this.$message.warning(res.msg || "替换失败");
                }
            }).catch(() => {
                this.fileList = []
                this.$message.warning("替换失败");
            });
        },
        upload() {
            this.$message.warning("请先进行模板替换");
        },
        // 上传前对文件的大小的判断
        beforeAvatarUpload(file) {
            
                this.loading = true;
                const extension = file.name.split(".")[file.name.split('.').length - 1] === "xls";
                const extension2 = file.name.split(".")[file.name.split('.').length - 1] === "xlsx";
                const isLt2M = file.size / 1024 / 1024 < 10;
                if (!extension && !extension2) {
                    this.$message({
                        message: "上传模板只能是 xls、xlsx格式!",
                        type: "error",
                    });
                }
                if (!isLt2M) {
                    this.$message({
                        message: "上传模板大小不能超过 10MB!",
                        type: "error",
                    });
                }
                return extension || extension2 || isLt2M;
            
            
        },
        uploadFile(param) {
            const File = param.file;
            let formData1 = new FormData();
            formData1.append("file", File);
            const link = document.createElement("a");
            link.style.display = "none";
            exportAdd(formData1).then((res) => {
                console.log('res', res);
                this.fileList = [];
                if (res.status == 200) {
                    link.href = window.URL.createObjectURL(
                        new Blob([res.data], {
                            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
                        })
                    );
                    link.setAttribute("download", "导入失败数据.xlsx");
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    this.init();
                    this.$message.success("导入成功");

                } else {
                    this.init();
                    this.$message.warning(res.msg || "导入失败");
                }
            }).catch(() => {
                this.fileList = []
                this.$message.warning("导入失败");
            });
        },
        addNucleicAcid() {
            this.form = {
                name: '',
                idCard: '',
                cityName: '镇江市',
                cityCode: '321100',
                areaName: '',
                areaCode: '',
                collectionTime: '',
                checkUnit: '',
                address: '',
                checkResult: '',
                resultTime: '',
                code: '',
            },
                this.dialogType = 0
            this.dialogFormVisible = true;
        },
        formUser(type, value) {
            getResultDetail({ code: value.code }).then((res) => {
                if (res.success) {
                    this.dialogType = type;
                    this.dialogFormVisible = true;
                    this.form = {
                        ...res.data,
                        cityName: '镇江市',
                        cityCode: '321100',
                        code: value.code,
                    };
                }
            });
        },
        // 关闭dialog
        closeFn() {
            this.dialogFormVisible = false;
        },
        changeArea(value) {
            console.log(value);
            this.areaList.map((item) => {
                if (item.name == value) {
                    return this.form.areaCode = item.code
                }
            })
        },
        changeCollectionTime(value) {
            this.form.collectionTime = value
        },
        changeResultTime(value) {
            this.form.resultTime = value
        },
        saveFun() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    let params = JSON.parse(JSON.stringify(this.form));
                    if (this.dialogType == 0) {
                        customAdd(params).then((res) => {
                            if (res.success) {
                                this.$message.success("新增成功");
                                this.dialogFormVisible = false;
                                this.init();
                            } else {
                                this.$message.error(res.msg || "新增失败");
                            }
                        }).catch((err) => {
                            this.$message.error(err.msg || "新增失败");
                        });
                    } else {
                        update(params).then((res) => {
                            if (res.success) {
                                this.$message.success("修改成功");
                                this.dialogFormVisible = false;
                                this.init();
                            } else {
                                this.$message.error(res.msg || "修改失败");
                            }
                        }).catch((err) => {
                            this.$message.error(err.msg || "修改失败");
                        });
                    }
                }
            })
            // this.dialogFormVisible = false;
        }
    },
    created() {
        this.initArea()
        this.init()
    },
}
</script>

<style lang="stylus" scoped>
@import '~@/stylus/common';

</style>