<template>
    <div class="app-container">
        <div class="interval">
            <div class="package-item">
                <div class="time">{{ list.signTime }}
                </div>
                <div class="name">
                    {{ list.packageName }}
                </div>
                <el-tag v-if="list.serviceStatus == 'INTENTIONAL_SIGNING'" class="type" size="mini">意向签约</el-tag>
                <el-tag v-if="list.serviceStatus == 'SERVICE_CENTER'" class="type" size="mini">服务中</el-tag>
                <el-tag v-if="list.serviceStatus == 'SERVICE_END'" class="type" size="mini">服务结束</el-tag>
            </div>
        </div>
        <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="患者姓名">{{ list.patientName }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ list.sex == 'MALE' ? '男' : '' }}{{
                    list.sex == 'FEMALE' ? '女' : '' }}</el-descriptions-item>
                <!-- <el-descriptions-item label="年龄">{{ list.age }}</el-descriptions-item> -->
                <el-descriptions-item label="电话">{{ list.patientPhone }}</el-descriptions-item>
                <el-descriptions-item label="就诊方式">{{
                    list.visitMethod == 'OUTPATIENT_SERVICE' ? '门诊' : list.visitMethod ==
                        'BE_IN_HOSPITAL' ?
                        '住院' : ''
                }}
                </el-descriptions-item>
                <el-descriptions-item label="诊断">{{ list.signDiagnosis }}</el-descriptions-item>
                <el-descriptions-item label="住院/门诊号">{{ list.inHospitalNumber }}</el-descriptions-item>
                <el-descriptions-item label="医院">{{ list.hospitalAgencyName }}</el-descriptions-item>
                <el-descriptions-item label="科室">{{ list.departmentName }}</el-descriptions-item>
                <!-- <el-descriptions-item label="出院/门诊时间">{{ list.patientName }}</el-descriptions-item> -->
                <!-- <el-descriptions-item label="注册时间">{{ list.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="110px" class="demo-ruleForm"
                :inline="true" style="padding-left:40px">
                <el-form-item label="健康管理师" prop="healthManageId">
                    <el-select v-model="signPackage.healthManageId" filterable placeholder="请选择健康管理师"
                        style="width:300px" clearable>
                        <el-option v-for="item in attendingPhysicianlist" :key="item.userId" :label="item.nickName"
                            :value="item.userId">
                        </el-option>
                    </el-select>
                </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="110px" class="demo-ruleForm"
                :inline="true" style="padding-left:40px">
                <el-form-item label="选择服务包" prop="packageName">
                    <el-input v-model="signPackage.packageName" disabled></el-input>
                </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="110px">
                    <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" :picker-options="pickerOptions" type="date"
                        :clearable='false' value-format="yyyy-MM-dd" @change="changestarttime" placeholder="选择日期"
                        style="width:150px">
                    </el-date-picker>
                    至
                    <el-input v-model="signPackage.serviceEndTime" style="width:150px" disabled></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="110px" class="demo-ruleForm"
                :inline="true" style="padding-left:40px">
                <el-form-item label="专病管理路径" prop="routeId">
                    <specialDiseaseRoute @on-template="onroute" :routeId="signPackage.routeId"
                        v-if="signPackage.servicePackageId" :servicePackageId="signPackage.servicePackageId"
                        :routeName="signPackage.routeName">
                    </specialDiseaseRoute>
                </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="110px" 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:200px">
                            <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码" style="width:200px"></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" style="margin-left:70px" :data="upload.data" ref="upload"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :headers="upload.headers"
                :on-success="handleSuccess" :auto-upload="false" list-type="picture-card">
                <i class="el-icon-plus"></i>
            </el-upload>
        </div>
    </div>
</template>

<script>
import {
    getByRecordId
} from '@/api/manage/continueSigning.js'
import {
    addsign
} from '@/api/manage/newSigning.js'
import {
    getById
} from '@/api/manage/signRecord.js'
import { getAge } from "@/utils/age";
import { obtainendtime } from "@/utils/obtainendtime";
import { getToken } from '@/utils/auth'
import { usergetList } from "@/api/unitconfig/patientConfiguration";
import specialDiseaseRoute from '../components/specialDiseaseRoute'
export default {
    dicts: ['hardware_type'],
    components: { specialDiseaseRoute },
    name: "newSigning",
    data() {
        return {
            signPackage: {
                packageName: undefined,
                packagePrice: undefined,
                serviceCycle: undefined,
                serviceStartTime: undefined,
                serviceEndTime: '',
                healthManageId: "",
                healthManageName: "",
                packagePaymentStatus: '',
                routeId: '',
                routeName: '',
            },
            pickerOptions: {
                disabledDate: (time) => {
                    if (this.signPackage.serviceEndTime != "") {
                        return time.getTime() > new Date(this.signPackage.serviceEndTime).getTime();
                    }
                },
            },
            list: {},
            form: {
                signCategory: 'reSign',
                record: {
                    patientId: undefined,
                    patientPhone: undefined,
                },
                devices: [
                    {
                        snCode: undefined,
                        hardwareType: undefined,
                    }
                ],
                informeds: [],
                route: {
                    routeId: undefined,
                    routeName: ''
                },
            },
            rules: {
                routeId: [
                    { required: true, message: '请选择专病管理路径', trigger: 'change' }
                ],
                healthManageId: [
                    { required: true, message: '请选择健康管理师', trigger: 'change' }
                ],
                packageName: [
                    { 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'
            },
            attendingPhysicianlist: [],
        };
    },
    created() {
        this.info();
        this.usergetListinfo();
    },
    methods: {
        //主治医生
        usergetListinfo() {
            usergetList({
                postName: 'HEALTH_MANAGE_MASTER'
            }).then(res => {
                this.attendingPhysicianlist = res.data
            })
        },
        onroute(item) {
            this.signPackage.routeId = item.routeId
            this.signPackage.routeName = item.routeName
        },
        //签约详情
        info() {
            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) : "";
            getByRecordId(this.$route.query.patientSignRecordId).then(res => {
                this.list = res.data
                this.signPackage.packagePaymentStatus = res.data.packagePaymentStatus
                this.signPackage.healthManageId = res.data.healthManageId
                this.signPackage.healthManageName = res.data.healthManageName
                this.signPackage.routeId = res.data.routeId
                this.signPackage.routeName = res.data.routeName
                // this.signPackage.packageName = this.list.packageName
                // this.signPackage.packageId = this.list.servicePackageId
                // this.signPackage.serviceCycle = this.list.serviceCycle
                // this.signPackage.serviceStartTime = this.list.serviceStartTime
                // this.signPackage.serviceEndTime = this.list.serviceEndTime
                // this.signPackage.packagePrice = this.list.packagePrice
                this.form.devices = this.list.signDevices
                this.form.record = this.list
                this.list.age = this.list.birthDate ? getAge(this.list.birthDate) : ''
                getById(res.data.servicePackageId).then(resp => {
                    this.signPackage = { ...this.signPackage, ...resp.data }
                    this.signPackage.serviceStartTime = `${year}-${month}-${day}`
                    this.signPackage.servicePackageId = resp.data.id
                    this.signPackage.serviceEndTime = obtainendtime(this.signPackage.serviceStartTime, this.signPackage)
                })
            })
        },
        //选择开始时间
        changestarttime(item) {
            this.signPackage.serviceEndTime = obtainendtime(item, this.signPackage)
        },
        //续约
        signupload() {
            const files = this.$refs.upload.uploadFiles
            if (files.length > 0) {
                this.$refs.upload.submit();
            } else {
                this.uploadsave();
            }
        },
        //文件上传完成
        handleSuccess(response, file, fileList) {
            this.form.informeds = []
            fileList.forEach(e => {
                this.form.informeds.push({
                    informedFilePath: e.response.imgUrl,
                })
            })
            this.uploadsave();
        },
        uploadsave() {
            if (this.signPackage.healthManageId && this.attendingPhysicianlist?.length > 0) {
                this.signPackage.healthManageName = this.attendingPhysicianlist.find(e => e.userId == this.signPackage.healthManageId)?.nickName
            }
            this.form.signPackage = this.signPackage
            this.form.route.routeId = this.signPackage.routeId
            this.form.route.routeName = this.signPackage.routeName
            addsign(this.form).then(res => {
                this.$confirm('续约成功, 是否返回上一页?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }).then(() => {
                    this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews }) => {
                        this.$router.push({
                            path: "/patient/signRecord",
                        });
                    })
                }).catch(() => {
                    this.$modal.msgSuccess("续约成功");
                });
            })
        },
        //新增硬件
        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.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews }) => {
                this.$router.push({
                    path: "/patient/signRecord",
                });
            })
        },
    }
};
</script>

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

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

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

    .interval {
        width: 20%;
        background-color: #fff;
        border-radius: 8px 0 0 8px;
        border-right: 1px solid #e5e5e5;

        .package-item {
            border-left: 2px solid #1890ff;
            background-color: #D2E9FC;
            width: 100%;
            height: 120px;
            position: relative;
            padding: 25px 14px;

            .type {
                position: absolute;
                right: 10px;
                top: 20px;
                font-size: 12px;
            }

            .name {
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                height: 40px;
                line-height: 40px;
                font-size: 18px;
                font-weight: 600;
            }

            .time {
                line-height: 20px;
                height: 20px;
                font-size: 14px;
            }
        }
    }

    .header {
        background-color: #fff;
        width: 78%;
        border-radius: 0 8px 8px 0;
        position: relative;
    }

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

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