<template>
    <div class="app-container">
        <div class="header">
            <div class="btns">
                <el-button @click="goback">取消</el-button>
                <el-button type="primary" @click="signupload">签约</el-button>
            </div>
            <el-descriptions title="签约详情" class="descriptions">
            </el-descriptions>
            <el-descriptions title="患者信息" style="padding:0 30px">
                <el-descriptions-item label="患者姓名">{{ $route.query.patientName }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ $route.query.sex == 'MALE' ? '男' : '' }}{{
                    $route.query.sex == 'FEMALE' ? '女' : '' }}</el-descriptions-item>
                <!-- <el-descriptions-item label="年龄">{{ $route.query.age }}</el-descriptions-item> -->
                <el-descriptions-item label="电话">{{ $route.query.patientPhone }}</el-descriptions-item>
                <el-descriptions-item label="就诊方式">{{
                    $route.query.visitMethod == 'OUTPATIENT_SERVICE' ? '门诊' : $route.query.visitMethod ==
                        'BE_IN_HOSPITAL' ?
                        '住院' : ''
                }}
                </el-descriptions-item>
                <el-descriptions-item label="诊断">{{ $route.query.reviewDiagnosis }}</el-descriptions-item>
                <el-descriptions-item label="住院/门诊号">{{ $route.query.inHospitalNumber }}</el-descriptions-item>
                <el-descriptions-item label="医院">{{ $route.query.hospitalAgencyName }}</el-descriptions-item>
                <el-descriptions-item label="科室">{{ $route.query.departmentName }}</el-descriptions-item>
                <!-- <el-descriptions-item label="出院/门诊时间">{{ $route.query.patientName }}</el-descriptions-item> -->
                <!-- <el-descriptions-item label="注册时间">{{ $route.query.patientName }}</el-descriptions-item> -->
            </el-descriptions>
            <el-descriptions title="健康管理师信息" style="padding:20px 30px 10px" class="descriptions">
            </el-descriptions>
            <el-form :model="signPackage" :rules="rules" ref="signPackage" label-width="100px" class="demo-ruleForm"
                :inline="true" style="padding-left:40px">
                <el-form-item label="健康管理师" prop="healthManageId">
                    <el-input v-model="signPackage.healthManageId"></el-input>
                </el-form-item>
            </el-form>
            <el-descriptions title="服务包信息" style="padding:20px 30px 10px" class="descriptions">
            </el-descriptions>
            <el-form :model="signPackage" :rules="rules" ref="signPackage" label-width="100px" class="demo-ruleForm"
                :inline="true" style="padding-left:40px">
                <el-form-item label="选择服务包" prop="servicePackageId">
                    <el-select v-model="signPackage.servicePackageId" filterable placeholder="请选择服务包" clearable
                        @change="tappackage">
                        <el-option v-for="item in packagelist" :key="item.id" :label="item.packageName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="服务包缴费状态" prop="packagePaymentStatus" label-width="130px">
                    <el-select v-model="signPackage.packagePaymentStatus" filterable placeholder="请选择服务包" clearable>
                        <el-option label="已缴费" value="PAID">
                        </el-option>
                        <el-option label="未缴费" value="UNPAID_FEES">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <el-form :model="signPackage" :rules="rules" ref="signPackage" label-width="80px" class="demo-ruleForm"
                :inline="true" style="padding-left:40px">
                <el-form-item label="签约期限" prop="" label-width="100px">
                    <div>
                        <el-input v-model="signPackage.packageTerm" style="width:130px" disabled
                            placeholder="请输入签约周期"></el-input>
                        <el-select v-model="signPackage.packageTermUnit" style="width:110px" placeholder="周期单位"
                            disabled>
                            <el-option label="年" value="年">年</el-option>
                            <el-option label="月" value="月">月</el-option>
                            <el-option label="日" value="日">日</el-option>
                        </el-select>
                    </div>
                </el-form-item>
                <el-form-item label="服务时长" prop="packageName">
                    <el-date-picker v-model="signPackage.serviceStartTime" type="date" disabled placeholder="开始日期"
                        style="width:150px">
                    </el-date-picker>
                    至
                    <el-input v-model="signPackage.serviceEndTime" style="width:150px" disabled
                        placeholder="结束日期"></el-input>
                </el-form-item>
                <el-form-item label="服务包价格(元)" prop="" label-width="120px">
                    <el-input v-model="signPackage.packagePrice" style="width:150px" disabled
                        oninput="if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)} if(value.length>7){value=value.slice(0,7)}"
                        min="0" placeholder="小数点后两位(元)"></el-input>
                </el-form-item>
            </el-form>
            <el-descriptions title="专病管理信息" style="padding:20px 30px 10px" class="descriptions">
            </el-descriptions>
            <el-form :model="signPackage" :rules="rules" ref="signPackage" label-width="100px" class="demo-ruleForm"
                :inline="true" style="padding-left:40px">
                <el-form-item label="专病管理路径" prop="routeId">
                    <el-input v-model="signPackage.routeId"></el-input>
                </el-form-item>
            </el-form>
            <el-descriptions title="硬件信息" style="padding:20px 30px 10px" class="descriptions">
            </el-descriptions>
            <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm" :inline="true"
                style="padding-left:40px">
                <div v-for="(item, index) in form.devices" :key="index">
                    <el-form-item label="硬件类型" :prop="`devices[${index}].hardwareType`"
                        :rules="rules.devices.hardwareType">
                        <el-select v-model="item.hardwareType" placeholder="请选择硬件类型" clearable style="width:208px">
                            <el-option v-for="dict in dict.type.hardware_type" :key="dict.value" :label="dict.label"
                                :value="dict.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="SN码" :prop="`devices[${index}].snCode`" :rules="rules.devices.snCode">
                        <el-input v-model="item.snCode" placeholder="请输入设备SN码"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button size="mini" @click="delhardware(index)">删除</el-button>
                    </el-form-item>
                </div>
                <el-button class="addbtn" type="primary" size="mini" @click="addhardware">新增硬件</el-button>
            </el-form>
            <el-descriptions title="知情同意书" style="padding:20px 30px 10px" class="descriptions">
            </el-descriptions>
            <el-upload :action="upload.url" list-type="picture-card" style="margin-left:70px" :data="upload.data"
                ref="upload" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :headers="upload.headers"
                :on-success="handleSuccess" :auto-upload="false">
                <i class="el-icon-plus"></i>
            </el-upload>
        </div>
    </div>
</template>

<script>
import {
    addsign
} from '@/api/manage/newSigning.js'
import {
    servicepackageinfo
} from '@/api/manage/signRecord.js'
import { getToken } from '@/utils/auth'
export default {
    dicts: ['hardware_type'],
    name: "newSigning",
    data() {
        return {
            signPackage: {
                packageName: undefined,
                packagePaymentStatus: '',
            },
            form: {
                record: {
                    patientId: undefined,
                    patientPhone: undefined,
                },
                devices: [
                    {
                        snCode: undefined,
                        hardwareType: undefined,
                    }
                ],
                informeds: []
            },
            rules: {
                packagePaymentStatus: [
                    { required: true, message: '缴费状态不能为空', trigger: 'change' }
                ],
                servicePackageId: [
                    { required: true, message: '请选择服务包', trigger: 'change' }
                ],
                devices: {
                    snCode: [
                        { required: true, message: '请输入SN码', trigger: 'change' }
                    ],
                    hardwareType: [
                        { required: true, message: '请选择硬件类型', trigger: 'change' }
                    ],
                },
            },
            upload: {
                data: {
                    type: 'signInformedFileUrl'
                },
                headers: {
                    Authorization: 'Bearer ' + getToken(),
                },
                url: process.env.VUE_APP_BASE_API + '/manage/file/uploadFile'
            },
            packagelist: [],
        };
    },
    created() {
        this.form.record = this.$route.query
        this.signPackage.packagePaymentStatus = this.form.record.paymentStatus
        servicepackageinfo({ departmentId: this.$route.query.departmentId }).then(res => {
            this.packagelist = res.data
        })
    },
    methods: {
        tappackage(id) {
            let item = this.packagelist.find(e => e.id == id)
            this.signPackage = { ...this.signPackage, ...item }
            let datetime = new Date();
            let year = datetime.getFullYear();
            let month = datetime.getMonth() + 1;
            let day = datetime.getDate();
            month >= 1 && month <= 9 ? (month = "0" + month) : "";
            day >= 0 && day <= 9 ? (day = "0" + day) : "";
            this.signPackage.serviceStartTime = `${year}-${month}-${day}`
            if (item.packageTermUnit == '年') {
                const nextdate = new Date(this.signPackage.serviceStartTime);
                nextdate.setFullYear(nextdate.getFullYear() + Number(item.packageTerm));
                nextdate.setDate(nextdate.getDate() - 1);
                let nextYear = nextdate.getFullYear();
                let nextMonth = this.checkMonth(nextdate.getMonth() + 1);// 因日期中的月份表示为0-11，所以要显示正确的月份，需要 + 1
                let nextday = this.checkMonth(nextdate.getDate())
                let nextDate = nextYear + "-" + nextMonth + "-" + nextday; // "2019-05"
                this.signPackage.serviceEndTime = nextDate
            } else if (item.packageTermUnit == '月') {
                const currentDate = new Date(this.signPackage.serviceStartTime);
                currentDate.setMonth(currentDate.getMonth() + Number(item.packageTerm)); // 加一个月
                currentDate.setDate(currentDate.getDate() - 1); // 减一天
                let nextYear = currentDate.getFullYear();
                let nextMonth = this.checkMonth(currentDate.getMonth() + 1);// 因日期中的月份表示为0-11，所以要显示正确的月份，需要 + 1
                let nextday = this.checkMonth(currentDate.getDate())
                let nextDate = nextYear + "-" + nextMonth + "-" + nextday; // "2019-05"
                this.signPackage.serviceEndTime = nextDate
            } else if (item.packageTermUnit == '日') {
                let currentDate = new Date(this.signPackage.serviceStartTime)
                currentDate = new Date(currentDate.setDate(currentDate.getDate() + Number(item.packageTerm)));
                let nextYear = currentDate.getFullYear();
                let nextMonth = this.checkMonth(currentDate.getMonth() + 1);// 因日期中的月份表示为0-11，所以要显示正确的月份，需要 + 1
                let nextday = this.checkMonth(currentDate.getDate())
                let nextDate = nextYear + "-" + nextMonth + "-" + nextday; // "2019-05"
                this.signPackage.serviceEndTime = nextDate
            }
        },
        checkMonth(i) {
            if (i < 10) {
                i = "0" + i;
            }
            return i;
        },
        //签约
        signupload() {
            const files = this.$refs.upload.uploadFiles
            if (files.length > 0) {
                this.$refs.upload.submit();
            } else {
                this.uploadsave();
            }
        },
        uploadsave() {
            if (this.signPackage.servicePackageId) {
                this.signPackage.packageName = this.packagelist.find(e => e.id == this.signPackage.servicePackageId).packageName
            }
            this.form.signPackage = this.signPackage
            addsign(this.form).then(res => {
                this.$confirm('签约成功, 是否返回上一页?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }).then(() => {
                    // this.$router.go(-1);
                    this.$router.push({
                        path: "/patient/signRecord",
                    });
                }).catch(() => {
                    this.$modal.msgSuccess("签约成功");
                });
            })
        },
        //文件上传完成
        handleSuccess(response, file, fileList) {
            this.form.informeds = []
            fileList.forEach(e => {
                this.form.informeds.push({
                    informedFilePath: e.response.imgUrl,
                })
            })
        },
        //新增硬件
        addhardware() {
            this.form.devices.push({
                snCode: '',
                hardwareType: '',
            })
        },
        delhardware(index) {
            this.form.devices.splice(index, 1);
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePictureCardPreview(file) {
        },
        goback() {
            this.$router.go(-1);
        },
    }
};
</script>

<style lang="scss" scoped>
.app-container {
    padding: 14px 0 0;
    background-color: #F2F3F5 !important;
    width: 100%;

    .descriptions {
        padding: 20px 20px 10px;
    }

    .descriptions {
        ::v-deep .el-descriptions-item__label.has-colon::after {
            display: none;
        }
    }

    .header {
        background-color: #fff;
        width: 98%;
        margin: 0 auto;
        border-radius: 8px;
    }

    .btns {
        position: absolute;
        top: 30px;
        right: 30px;
    }

    .addbtn {
        margin-right: 100px;
        float: right;
        transform: translateY(-200%);
    }
}
</style>