<template>
    <div class="inStockManage">
        <a-form layout="inline" class="search_form">
            <a-form-item label="姓名">
                <a-input v-model="searchForm.womanName" placeholder="请输入姓名" style="width: 250px"></a-input>
            </a-form-item>
            <a-form-item label="证件号码">
                <a-input v-model="searchForm.womenIdCard" placeholder="请输入证件号码"
                         style="width: 250px;margin-right: 10px"></a-input>
                <a-button class="search_btn ant-table-btn" @click="getIdCardInfo">读卡识别</a-button>
            </a-form-item>
            <a-form-item label="联系电话">
                <a-input v-model="searchForm.telephone" placeholder="请输入联系电话" style="width: 250px"></a-input>
            </a-form-item>
            <a-form-item>
                <a-button type="primary" icon="search" class="search_btn" style="margin-left: 10px" @click="searchList">
                    搜索
                </a-button>
                <a-button class="search_btn ant-table-btn" icon="sync" style="margin-left: 10px"
                          @click="restSearchForm">清空
                </a-button>
            </a-form-item>
            <a-button type="primary" class="search_btn" style="float: right" @click="share">发放二维码</a-button>
            <a-button type="primary" class="search_btn" style="float: right;margin-right: 20px" @click="toAdd">发放登记
            </a-button>
            <div style="clear: both"></div>
        </a-form>
        <div style="margin-top: 16px;margin-bottom: 10px"></div>

        <a-table :dataSource="tableData"
                 :columns="columns"
                 rowKey="id"
                 :loading="loading"
                 :pagination="false"
                 :scroll="{ x: 1}"
        >
            <template slot="expireDateS" slot-scope="record">
                {{ record.expireDate | formatDate }}
            </template>
            <template slot="nowAddress" slot-scope="text, record">
                <a-tooltip placement="top">
                    <template slot="title">
                        <span>  {{ (record.presentCodeName || "") + record.nowAddress }}</span>
                    </template>
                    <span class="ellipsis">{{ (record.presentCodeName || "") + record.nowAddress }}</span>
                </a-tooltip>
            </template>
            <template slot="action" slot-scope="record">
                <a-button class="ant-table-btn" size="small" @click="toDetail(record)">查看</a-button>
                <a-button style="margin-left: 10px" class="ant-table-btn" size="small" @click="updateRecord(record)">修改
                </a-button>
                <a-popconfirm placement="top" @confirm="deleteRecord(record)" cancelText="取消" okText="确认">
                    <template slot="title">
                        <p>确认删除吗？</p>
                    </template>
                    <a-button style="margin-left: 10px" class="ant-table-btn" size="small">删除</a-button>
                </a-popconfirm>
                <a-button class="ant-table-btn" v-if="record.source===1&&record.isSigned===2" size="small"
                          style="margin-left: 10px"
                          @click="uploadConsentInfo(record)">签署同意书
                </a-button>
                <a-button class="ant-table-btn" v-else size="small" style="margin-left: 10px"
                          @click="showConsentInfo(record)">已签同意书
                </a-button>
            </template>
        </a-table>
        <a-modal title="上传知情同意书" :visible="visible" @cancel="onCancel" @ok="onsubmit"
                 :maskClosable="false"
                 width="600px">
            <span>上传知情同意书：</span>
            <a-upload
                    style="display: inline"
                    name="file"
                    list-type="picture-card"
                    accept=".jpg,.png"
                    :multiple="true"
                    :action="uploadAction"
                    :headers="headers"
                    @reject="handleReject"
                    @preview="preview"
                    @change="handleChange"
                    :file-list="fileList"
            >
                <div>
                    <!--<a-icon type="plus"/>-->
                    <div class="ant-upload-text">
                        上传本地文件
                    </div>
                </div>
            </a-upload>
            <div>
                <br/>
                温馨提示:请上传JPG、PNG格式图片，图片大小不超过5M
                <br/>

            </div>
        </a-modal>
        <!--:getContainer="getContainer"-->
        <a-modal title="查看知情同意书" :visible="showVisible" @cancel="showVisible = false" cancelText="关闭" :footer="null"
                 loading="true"
                 :maskClosable="false"
                 width="600px">
            <div v-if="currentRow.source==1">
                <img style="width: 100%" :src="consentUrl" height="100%"/>
            </div>
            <div v-else>
                <div>
                    <div v-html="consentInfo" style="width: 100%">
                    </div>
                    <div style="float: right;margin-right: 50px">
                        <div style="">签名： <img
                                style="width:50px;height: 120px;transform: rotate(-90deg);margin-left: 60px"
                                :src="applySignUrl"/></div>
                        <div>签署日期：<span style="margin-left: 8px">{{ currentRow.parentDate }}</span></div>
                    </div>
                    <div style="clear: both"></div>
                </div>
            </div>
            <br><br>
            <a-button style="margin-left:80%" type="danger" @click="showVisible = false">关闭</a-button>
            <br>
        </a-modal>
        <a-pagination
                v-if="pagination.total > 0"
                :total="pagination.total"
                show-size-changer
                show-quick-jumper
                v-model="pagination.pageIndex"
                :page-size="pagination.pageSize"
                :page-size-options="pagination.pageSizeOptions"
                @showSizeChange="showSizeChange"
                @change="change"
                :showTotal="() => `共 ${pagination.total} 条`"
        />

        <a-modal title="" :visible="qrCodeShow" @cancel="qrCodeShow = false" cancelText="关闭"
                 :footer="null"
                 loading="true"
                 :maskClosable="false"
                 width="600px">
            <div ref="printContent" style="text-align: center;margin-top: 10%">
                <h2>叶酸手机申请领取二维码(使用医站到家APP扫码领取)</h2>
                <img width="80%" :src="qrCodeUrl" style="margin-left: 20px">
                <br>
                <center style="font-size:18px ">{{ unitInfo.unitName }}</center>
                <br> <br>
            </div>
            <center @click="qrCodePrint" style="cursor: pointer">
                <a-button>打印</a-button>
            </center>

        </a-modal>
    </div>
</template>
<script>
import QRCode from 'qrcode'
import {GetUserInfoByCardDevice, isEmptyParams} from "../../utils/common";


const columns = [
    {
        title: '发放日期',
        dataIndex: 'provideDate',
        width: '140px'
    },
    {
        title: '姓名',
        dataIndex: 'womanName',
        width: '100px', ellipsis: true,
    },
    {
        title: '证件类型',
        dataIndex: 'womenCertificateTypeName',
        width: '100px'
    },
    {
        title: '证件号码',
        dataIndex: 'womenIdCard',
        width: '180px'
    },
    {
        title: '发放数量',
        dataIndex: 'provideNumber',
        width: '100px'
    },
    {
        title: '联系电话',
        dataIndex: 'telephone',
        width: '140px'
    },
    {
        title: '发放医生',
        dataIndex: 'provideDoctorName',
        width: '180px'
    },
    {
        title: '类型',
        dataIndex: 'sourceName',
        width: '140px'
    },
    {
        title: '现住址',
        // dataIndex: 'nowAddress',
        key: 'nowAddress',
        ellipsis: true,
        scopedSlots: {customRender: 'nowAddress'},
    },
    {
        title: '操作',
        fixed: 'right',
        align: 'left',
        width: "300px",
        scopedSlots: {customRender: 'action'},
    },
]
export default {
    components: {},
    data() {
        return {
            // 搜索框对象
            searchForm: {
                womenName: "",
                womenIdCard: undefined,
                telephone: ""
            },
            pagination: {
                pageIndex: 1,
                pageSize: 10,
                total: 0,
                pageSizeOptions: ['10', '20', '30', '40', '50'],
            },
            columns,
            tableData: [],
            loading: false,
            visible: false,
            showVisible: false,
            previewVisible: false,
            consentUrl: "",
            applySignUrl: "",
            consentInfo: "",
            headers: {
                Authorization: sessionStorage.getItem("token")
            },
            uploadAction: process.env.VUE_APP_BASE_URL + "/v1/folacin-admin/sys-pictures-info/upload-img",
            fileList: [],
            formData: {
                consentId: "",
                id: ""
            },
            currentRow: {},
            menuId: undefined,
            qrCodeShow: false,
            qrCodeUrl: "",
            unitInfo: {unitName:""},
            printDisplay: 'none'
        }
    },
    created() {
        this.routerParams = this.$route.query;
        if (this.routerParams.menuId) {
            window.sessionStorage.setItem('menuId', this.routerParams.menuId);
            this.menuId = this.routerParams.menuId;
        }
        this.getDataList();
    },
    methods: {
        getIdCardInfo() {
            GetUserInfoByCardDevice().then(res => {
                let {cardno, name, address} = res;
                this.searchForm.womenIdCard = cardno
            })
        },
        searchList() {
            this.pagination.pageIndex = 1;
            this.getDataList();
        },
        getDataList() {
            this.loading = true
            let pars = isEmptyParams(this.searchForm)
            let par = {
                ...pars,
                pageIndex: this.pagination.pageIndex,
                pageSize: this.pagination.pageSize,
                menuId: this.menuId
            }
            this.$api.folviteDistributionManage.fetchFolviteDistributionList(par).then(({data = {}}) => {
                const {dataList = [], total = 0} = data;
                this.tableData = dataList
                this.pagination.total = total
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        },
        // 分页
        showSizeChange(pageNum, pageSize) {
            this.pagination.pageIndex = 1;
            this.pagination.pageSize = pageSize;
            this.getDataList()
        },
        change(pageNum, pageSize) {
            this.pagination.pageIndex = pageNum;
            this.pagination.pageSize = pageSize;
            this.getDataList()
        },
        restSearchForm() {
            this.searchForm = {
                idCar: undefined
            }
            this.searchList()
        },
        toAdd() {
            if (process.env.NODE_ENV == "dev") {
                this.$router.push({path: '/folviteDistribution/add', query: {routerFlag: 'add', menuId: this.menuId}})
            } else {
                let now_location = escape(process.env.VUE_APP_LOCATION + `folviteDistribution/add?menuId=${this.menuId}&menuCode=${this.routerParams.menuName}&routerFlag=add`)
                window.top.postMessage({messageType: 'THIRD_PAGEADD', title: `发放登记`, url: now_location}, '*')
            }
        },
        toDetail(record) {
            if (process.env.NODE_ENV == "dev") {
                let par = {
                    menuId: this.menuId,
                    id: record.id
                }
                this.$router.push({path: '/folviteDistribution/detail', query: par})
            } else {
                let now_location = escape(process.env.VUE_APP_LOCATION + `folviteDistribution/detail?menuId=${this.menuId}&menuCode=${this.routerParams.menuName}&id=${record.id}&source=${record.source}`)
                window.top.postMessage({messageType: 'THIRD_PAGEADD', title: `查看详情`, url: now_location}, '*')
            }
        },
        updateRecord(record) {
            if (process.env.NODE_ENV == "dev") {
                let params = {
                    id: record.id,
                    routerFlag: 'updateRecord',
                    menuId: this.menuId
                }
                this.$router.push({path: '/folviteDistribution/add', query: params})
            } else {
                let now_location = escape(process.env.VUE_APP_LOCATION + `folviteDistribution/add?menuId=${this.menuId}&menuCode=${this.routerParams.menuName}&routerFlag=updateRecord&id=` + record.id)
                window.top.postMessage({
                    messageType: 'THIRD_PAGEADD',
                    title: `叶酸发放登记修改-` + record.womanName,
                    url: now_location
                }, '*')
            }
        },
        deleteRecord(record) {
            this.$api.folviteDistributionManage.fetchFolviteDelete(record.id).then(({data = [], code}) => {
                if (code == 'SUCCESS') {
                    this.$message.success("删除成功！");
                    this.getDataList();
                } else {
                    this.$message.error("删除失败！");
                }
            })
        },
        uploadConsentInfo(row) {
            this.formData.id = row.id;
            this.visible = true;
        },
        showConsentInfo(row) {
            this.currentRow = row;
            this.showVisible = true;
            let par = {
                menuId: this.menuId,
                residentId: row.id
            }
            this.$api.folviteDistributionManage.fetchFolviteDistributionDetail(par).then(({data = [], code}) => {
                this.consentUrl = data.consentUrl;
                this.applySignUrl = data.applySignUrl;
            })
            if (row.source == 2) {
                let par = {
                    menuId: this.menuId
                }
                this.$api.common.fetchConsentInfoShow(par).then(({data}) => {
                    if (this.$api.utils.isNoBlank(data)) {
                        this.consentInfo = data.content;
                    }
                })
            }
        },
        handleChange(info) {
            let fileList = [...info.fileList];
            fileList = fileList.slice(-1);
            let isFail = false;
            fileList = fileList.map(file => {
                if (file.response) {
                    if (file.response.code != 'SUCCESS') {
                        isFail = true;
                        return;
                    }
                    this.consentUrl = file.response.data.trueDownloadUrl;
                    this.formData.consentId = file.response.data.id;
                }
                return file;
            });
            if (isFail) {
                this.formData.consentId = "";
                this.$message.warning("文件上传失败");
                return;
            }
            if (fileList.length == 0) {
                this.formData.consentId = "";
            }
            this.fileList = fileList;
        },
        handleReject(info) {
            this.$message.warning('请上传JPG、PNG格式图片');
            return false;
        },
        preview(val) {
            window.open(val.response.data.trueDownloadUrl)
        },
        onCancel() {
            this.visible = false;
            this.fileList = [];
            this.formData.consentId = null;
        },
        onsubmit() {
            if (this.currentRow.source == 1) {
                this.visible = false;
                return;
            }
            if (this.$api.utils.isBlank(this.formData.consentId)) {
                this.$message.warning('请上传文件');
                return;
            }
            let par = {
                ...this.formData,
                menuId: this.menuId
            }
            this.$api.folviteDistributionManage.fetchFolviteUploadConsent(par).then(res => {
                if (res.code === 'SUCCESS') {
                    this.fileList = [];
                    this.formData.consentId = "";
                    this.searchList();
                    this.visible = false;
                }
            })

        },
        share() {
            this.qrCodeShow = true;
            QRCode.toDataURL(this.unitInfo.id + "", {width: 500, height: 400, margin: 2})
                .then(qrCodeUrl => {
                    this.qrCodeUrl = qrCodeUrl;
                }).catch(err => {
                //  console.error(err);
            });
        },
        qrCodePrint() {
            this.printDisplay = 'block';
            this.$print(this.$refs.printContent);
            // window.print("<H1>HAHA</H1>");
        }
    },
    mounted() {
        let that = this;
        window.addEventListener("message", function (data) {
            that.getDataList();
        });
        let timer = setInterval(res => {
            let unitInfo = JSON.parse(window.sessionStorage.getItem('unitInfo'));
            if (unitInfo) {
                that.unitInfo = unitInfo;
                clearInterval(timer)
            }
        }, 500)
    }
}
</script>
<style lang="less" scoped>
// 文件上传样式
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 6px;
  color: #666;
}

.btn_space {
  margin-right: 5px;
}

/* .search_form {
     margin-top: -16px;
     border: 1px solid rgba(255,77,128, .2);
     border-top: 0px;
     padding: 30px;
 }*/
.ellipsis {
  display: block;
  width: 100%;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

///deep/ .ant-table-tbody{
//  > tr:hover:not(.ant-table-expanded-row) > td,.ant-table-row-hover,.ant-table-row-hover>td{
//    background:darkcyan !important;
//  }
//}
</style>
