<template>
    <div class="nucleicAcid">
        <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 label="辖市区">
                    <el-select v-model="searchForm.city" placeholder="请选择辖市区" @change="onSubmit" size="medium">
                        <el-option v-for="item in xqList" :key="item.id" :label="item.label" :value="item.id">
                        </el-option>
                    </el-select>
                </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>
        </div>
        <div class="table-wrapper">
            <table-template :tableData="tableData" :tableColumns="tableColumns" :loading="loading"
                :pagination="pagination" @Jump="jumpPage">
                <el-table-column fixed="right" label="操作" width="300" 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>
                        <el-button type="success" size="mini" round @click="generate(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="cardType">
                    <div>
                        <el-radio v-model="form.cardType" :label="0" :disabled="disabled">身份证</el-radio>
                        <el-radio v-model="form.cardType" :label="1" :disabled="disabled">其他证件</el-radio>
                    </div>
                </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="mobile">
                    <el-input placeholder="请输入手机号码" v-model="form.mobile" :disabled="disabled"></el-input>
                </el-form-item>
                <el-form-item label="辖市区" prop="city">
                    <el-select v-model="form.city" placeholder="请选择辖市区" :disabled="this.dialogType == 1"
                        style="width: 100%">
                        <el-option v-for="item in cityList" :key="item.id" :label="item.label" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="街道地址" prop="addressArea">
                    <el-input placeholder="请选择街道地址" v-model="form.addressArea" :disabled="this.dialogType == 1"
                        :readonly="true" @focus="openMap">
                        <i slot="suffix" class="el-input__icon el-icon-location-information" @click="openMap"></i>
                    </el-input>
                </el-form-item>
                <el-form-item label="所属社区" prop="village">
                    <el-select v-model="form.village" @change="changeArea" :disabled="this.dialogType == 1"
                        placeholder="请选择所属社区" style="width: 100%">
                        <el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item.name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属网格" prop="networkType">
                    <el-select v-model="form.networkType" @change="changeNetwork" :disabled="this.dialogType == 1"
                        placeholder="请选择所属网格" style="width: 100%">
                        <el-option v-for="item in netWorkList" :key="item.id" :label="item.networkType"
                            :value="item.networkType">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="详细地址">
                    <el-input placeholder="请输入详细地址" v-model="form.detailAddress"
                        :disabled="this.dialogType == 1"></el-input>
                </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>
        <el-dialog title="选择行政区划" :visible.sync="dialogMap" destroy-on-close width="45%" :close-on-click-modal="false">
            <div class="map">
                <div style="display: flex; align-items: center">
                    <div style="width: 80px">地址：</div>
                    <el-input placeholder="请输入搜索关键词" @keyup.enter.native="onSearch" v-model="addressWord">
                        <i slot="suffix" @click="onSearch" class="el-input__icon el-icon-search"></i>
                    </el-input>
                </div>
                <div style="width: 100%; height: 350px; margin-top: 10px">
                    <TengXunMap ref="TengXunMap" @click="clickMap" :point="point" class="tengxun-box"></TengXunMap>
                </div>
                <div class="location" style="width: 100%; height: 230px; overflow: auto">
                    <el-empty :image-size="100" v-if="addressList.length == 0" description="暂无地点"></el-empty>
                    <div v-for="(item, index) in addressList" :key="index" @click="selectPoint(item)" style="
              font-size: 16px;
              display: flex;
              flex-direction: column;
              width: 100%;
              align-items: flex-start;
              margin-top: 10px;
              cursor: pointer;
            ">
                        {{ item.title }}
                        <div style="font-size: 14px; color: #999">
                            {{ item.address }}
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
        <el-dialog :title='qrcodeName' :visible.sync="dialogQrcode" destroy-on-close width="45%"
            :close-on-click-modal="false">
            <div class="qrCode"
                style="display: flex; flex-direction: column; align-items: center; justify-content: center;">
                <img id="qr-code" :src="url" style="width: 180px; height: 180px" />
                <div class="down" style="margin: 20px;">
                    <el-button type="primary" @click="downQrcode(url)">下载采样码<i
                            class="el-icon-download el-icon--right"></i></el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import TableTemplate from "@/components/Table";
import TengXunMap from "../Components/Map/TengXunMap.vue";
import axios from "axios";
import { searchArea, getGeocoder } from "../../utils/tengxun";
import {
    getListCommunityDeclarationUser,
    addCommunityDeclarationUser,
    getDetailInfo,
    updateCommunityDeclarationUser,
} from "@/api/nucleicAcid";
import { decryptByDES, encryptByDES, changeList } from "@/utils/index";
import QRCode from "qrcode";

export default {
    name: "nucleicAcid",
    components: { TableTemplate, TengXunMap },
    data() {
        return {
            searchForm: {
                name: "",
                idCard: "",
                city: "",
            },
            xqList: [
                {
                    id: "",
                    label: "全部",
                },
                {
                    id: "京口区",
                    label: "京口区",
                },
                {
                    id: "润州区",
                    label: "润州区",
                },
                {
                    id: "丹徒区",
                    label: "丹徒区",
                },
                {
                    id: "镇江新区",
                    label: "镇江新区",
                },
                {
                    id: "镇江高新区",
                    label: "镇江高新区",
                },
                {
                    id: "扬中市",
                    label: "扬中市",
                },
                {
                    id: "丹阳市",
                    label: "丹阳市",
                },
                {
                    id: "句容市",
                    label: "句容市",
                },
            ],
            loading: false,
            tableData: [],
            tableColumns: [
                {
                    key: "code",
                    label: "编号",
                    width: 280,
                },
                {
                    key: "name",
                    label: "姓名",
                    width: 180,
                },
                {
                    key: "idCard",
                    label: "身份证号码",
                    width: 200,
                },
                {
                    key: "mobile",
                    label: "联系方式",
                    width: 180,
                },
                {
                    key: "city",
                    label: "辖市区",
                    width: 180,
                },
                {
                    key: "addressArea",
                    label: "所属街道",
                    width: 200,
                },
                {
                    key: "updateTime",
                    label: "更新时间",
                    width: 200,
                },
            ],
            pagination: {
                total: 0,
                pageSize: 10,
                currentPage: 1,
            },
            dialogFormVisible: false,
            dialogType: "",
            form: {
                appoType: 2,
                userType: 0,
                name: "",
                cardType: null,
                idCard: "",
                mobile: "",
                city: "",
                addressArea: "",
                village: "",
                networkId: "",
                networkMobile: "",
                networkName: "",
                networkType: "",
                detailAddress: "",
                lat: "",
                lng: "",
                code: "",
            },
            rules: {
                name: [{ required: true, message: "请输入姓名", trigger: "change" }],
                cardType: [
                    { required: true, message: "请选择证件类型", trigger: "change" },
                ],
                idCard: [
                    { required: true, message: "请输入证件号码", trigger: "change" },
                ],
                mobile: [
                    { required: true, message: "请输入手机号码", trigger: "change" },
                ],
                city: [{ required: true, message: "请选择辖市区", trigger: "change" }],
                addressArea: [
                    { required: true, message: "请选择街道地址", trigger: "change" },
                ],
                village: [
                    { required: true, message: "请选择所属社区", trigger: "change" },
                ],
                networkType: [
                    { required: true, message: "请选择所属网格", trigger: "change" },
                ],
            },
            dialogMap: false,
            cityList: [
                {
                    id: "京口区",
                    label: "京口区",
                },
                {
                    id: "润州区",
                    label: "润州区",
                },
                {
                    id: "丹徒区",
                    label: "丹徒区",
                },
                {
                    id: "镇江新区",
                    label: "镇江新区",
                },
                {
                    id: "镇江高新区",
                    label: "镇江高新区",
                },
                {
                    id: "扬中市",
                    label: "扬中市",
                },
                {
                    id: "丹阳市",
                    label: "丹阳市",
                },
                {
                    id: "句容市",
                    label: "句容市",
                },
            ],
            addressWord: "",
            point: {
                lat: 32.188478,
                lng: 119.425722,
            },
            addressList: [],
            areaList: [],
            netWorkList: [],
            latitude: "",
            longitude: "",
            dialogQrcode: false,
            qrcodeName: "",
            url: ""
        };
    },
    computed: {
        dialogTitle() {
            return this.dialogType == 0
                ? "新增信息"
                : this.dialogType == 1
                    ? "查看信息"
                    : "编辑信息";
        },
        disabled() {
            return (
                (localStorage.getItem("userName") == "admin" && this.dialogType != 0) ||
                (localStorage.getItem("userName") != "admin" && this.dialogType == 1)
            );
        },
    },
    methods: {
        init() {
            this.loading = true;
            let params = {
                name: this.searchForm.name,
                idCard: this.searchForm.idCard ? encryptByDES(this.searchForm.idCard, "MnuYbhGv") : "",
                city: this.searchForm.city,
                pageNum: this.pagination.currentPage,
                pageSize: this.pagination.pageSize,
            };
            getListCommunityDeclarationUser(params).then((res) => {
                this.loading = false;
                if (res.success) {
                    this.pagination.total = res.data.total;
                    if (res.data.total) {
                        this.tableData = res.data.list.map((item) => {
                            item.idCard = decryptByDES(item.idCard, "MnuYbhGv");
                            return item;
                        });
                    } 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();
        },
        addNucleicAcid() {
            (this.form = {
                appoType: 2,
                userType: 0,
                name: "",
                cardType: null,
                idCard: "",
                mobile: "",
                city: "",
                addressArea: "",
                village: "",
                networkId: "",
                networkMobile: "",
                networkName: "",
                networkType: "",
                detailAddress: "",
                lat: "",
                lng: "",
                code: "",
            }),
                (this.dialogType = 0);
            this.dialogFormVisible = true;
        },
        openMap() {
            // console.log(this.form)
            this.point = {
                lat: this.form.lat ? this.form.lat : 32.188478,
                lng: this.form.lng ? this.form.lng : 119.425722,
            };
            this.addressList = [];
            this.dialogMap = true;
        },
        onSearch() {
            if (this.addressWord) {
                searchArea(this.addressWord)
                    .then((res) => {
                        if (res.statusText === "OK" && res.data.status === 0) {
                            if (res.data.data.length > 0) {
                                this.addressList = res.data.data;
                                this.latitude = res.data.data[0].location.lat;
                                this.longitude = res.data.data[0].location.lng;
                                this.point = {
                                    lat: res.data.data[0].location.lat,
                                    lng: res.data.data[0].location.lng,
                                };
                            }
                        }
                    })
                    .finally(() => { });
            }
        },
        clickMap(evt) {
            this.latitude = evt.lat;
            this.longitude = evt.lng;
            this.point = {
                lat: evt.lat,
                lng: evt.lng,
            };
            const _that = this;
            getGeocoder(`${evt.lat},${evt.lng}`)
                .then((res) => {
                    if (res.statusText === "OK" && res.data.status === 0) {
                        _that.addressList = res.data.result.pois;
                    }
                })
                .finally(() => { });
        },
        selectPoint(item) {
            this.form.lat = item.location.lat;
            this.form.lng = item.location.lng;
            this.getLocationInfo(item.location.lat, item.location.lng);
            this.dialogMap = false;
        },
        // 获取地理位置 网格信息
        getLocationInfo(lat, lng, type) {
            // console.log(lat,lng,type)
            axios({
                url: "/appointment/queryUserArea",
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                },
                params: { lat, lng },
                responseType: "json",
            })
                .then((res) => {
                    if (res.data.code == 201) {
                        this.$message.warning("您当前未定位到镇江市范围内，请重新尝试！");
                    } else {
                        if (res.data.code != 200) {
                            this.$message.error("定位获取失败，请手动选择！");
                            return false;
                        }
                        // 如果存在社区，选择跟社区名字一致的
                        if (type) {
                            this.areaList = res.data.data.list;
                            // 网格更改
                            this.netWorkList = res.data.data.list.find(
                                (el) => el.name == this.form.village
                            ).list;
                        } else {
                            this.areaList = res.data.data.list;
                            // 街道
                            this.form.addressArea = res.data.data.name;
                            const obj = res.data.data.list.find((item) => item.state === 0);
                            this.form.village = obj ? obj.name : res.data.data.list[0].name;
                            this.netWorkList = obj ? obj.list : res.data.data.list[0].list;
                            const obj1 = this.netWorkList.find((item) => item.state === 0);
                            const obj2 = obj1 || this.netWorkList[0];
                            this.form.networkId = obj2.id; // 从网格来
                            this.form.networkMobile = obj2.networkMobile;
                            this.form.networkName = obj2.name;
                            this.form.networkType = obj2.networkType;
                            this.areaList.map((item) => {
                                if (item.name == this.form.village) {
                                    this.form.village = item.name;
                                    // this.form.villageXzqhbId = item.id;
                                    // this.getAreaInfo(item.id)
                                }
                            });
                        }
                    }
                })
                .catch({});
        },
        changeArea(val) {
            this.netWorkList = this.areaList.find((el) => el.name == val).list;
            this.form.networkType = this.netWorkList[0].networkType;
            this.form.networkId = this.netWorkList[0].id;
            this.form.networkMobile = this.netWorkList[0].networkMobile;
            this.form.networkName = this.netWorkList[0].name;
            this.areaList.map((item) => {
                if (item.name == val) {
                    this.form.village = item.name;
                    // this.form.villageXzqhbId = item.id;
                    // this.getAreaInfo(item.id)
                }
            });
        },
        changeNetwork(val) {
            this.netWorkList.map((item) => {
                if (item.networkType == val) {
                    this.form.networkType = item.networkType;
                    this.form.networkId = item.id;
                    this.form.networkMobile = item.networkMobile;
                    this.form.networkName = item.name;
                }
            });
        },
        formUser(type, value) {
            getDetailInfo({ code: value.code }).then((res) => {
                if (res.success) {
                    this.dialogType = type;
                    this.dialogFormVisible = true;
                    this.form = {
                        ...res.data,
                        appoType: 2,
                        userType: 0,
                        name: value.name,
                        idCard: value.idCard,
                        mobile: value.mobile,
                    };
                }
            });
            // console.log("value", value);
        },
        // 关闭dialog
        closeFn() {
            this.dialogFormVisible = false;
        },
        saveFun() {
            if (this.form.cardType == 0 && this.form.mobile.length > 13) {
                this.$message.warning("请输入正确的电话号码");
                return;
            }
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    let params = JSON.parse(JSON.stringify(this.form));
                    if (this.dialogType == 0) {
                        params.idCard = encryptByDES(this.form.idCard, "MnuYbhGv");
                        addCommunityDeclarationUser(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 {
                        if (localStorage.getItem("userName") == "admin") {
                            getDetailInfo({ code: this.form.code }).then((res) => {
                                if (res.success) {
                                    params.name = res.data.name;
                                    params.idCard = res.data.idCard;
                                    params.mobile = res.data.mobile;
                                    updateCommunityDeclarationUser(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 {
                            params.idCard = encryptByDES(this.form.idCard, "MnuYbhGv");
                            updateCommunityDeclarationUser(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 || "修改失败");
                            });
                        }
                    }
                }
            });
        },
        generate(val) {
            console.log("val", val);
            getDetailInfo({ code: val.code }).then((res) => {
                if (res.success) {
                    this.dialogQrcode = true,
                        this.qrcodeName = res.data.name + '的核酸检测码'
                    console.log("res", res);
                    // 加密内容
                    let obj = {
                        // 姓名
                        name: encryptByDES(res.data.name, "zjyyhedj2022covid2019"),
                        // 身份证号
                        cardNo: encryptByDES(
                            decryptByDES(res.data.idCard, "MnuYbhGv"),
                            "zjyyhedj2022covid2019"
                        ),
                        C: res.data.cardType == "1" ? 1 : 0,
                        // 居住地址
                        A: encryptByDES(
                            res.data.addressArea + res.data.village + res.data.detailAddress,
                            "zjyyhedj2022covid2019"
                        ),
                        // 手机号
                        P: encryptByDES(res.data.mobile, "zjyyhedj2022covid2019"),
                    };
                    this.getCode(JSON.stringify(obj));
                }
            });
        },
        getCode(obj) {
            let that = this;
            QRCode.toDataURL(
                obj,
                {
                    errorCorrectionLevel: "H",
                    type: "image/png",
                    quality: 0.5,
                    margin: 1,
                    w: 600,
                    h: 600,
                    color: {
                        dark: "#000",
                        light: "#fff",
                    },
                },
                function (err, url) {
                    if (err) throw err;
                    that.url = url;
                }
            );
        },
        downQrcode(url) {
            console.log('url', url);
            let a = document.createElement("a"); // 生成一个a元素
            let event = new MouseEvent("click"); // 创建一个单击事件
            a.download = this.qrcodeName || "photo"; // 设置图片名称
            a.href = url; // 将生成的URL设置为a.href属性
            a.dispatchEvent(event); // 触发a的单击事件
        }
    },
    created() {
        this.init();
    },
};
</script>

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

</style>