<template>
    <view class="page">
        <u-cell-group :border="false">
            <u-cell
                title="姓名"
                :value="info.name"
                isLink
                rightIcon="edit-pen"
                @click="openModal('姓名', 'name')"
            />
            <u-cell
                title="性别"
                :value="info.sex_text"
                isLink
                rightIcon="edit-pen"
                @click="toggleGender"
            />
            <u-cell isLink rightIcon="edit-pen">
                <view slot="icon" @click="handleCall(info.phone)">
                    <u-icon name="phone" />
                </view>
                <view slot="title" @click="handleCall(info.phone)">联系方式</view>
                <view slot="value" @click="openModal('联系方式', 'phone')">{{ info.phone }}</view>
            </u-cell>
            <u-cell
                title="地址"
                :value="info.address"
                clickable
                isLink
                rightIcon="edit-pen"
                @click="openModal('地址', 'address')"
            />
            <u-cell
                title="出生年月"
                :value="info.birthday | date('yyyy-MM-dd')"
                isLink
                rightIcon="edit-pen"
                @click="toggleBirthday('birthday')"
            />
            <u-cell
                title="初诊时间"
                :value="info.treat_at | date('yyyy-MM-dd')"
                isLink
                rightIcon="edit-pen"
                @click="toggleBirthday('treat_at')"
            />
            <u-cell
                title="初诊医生"
                :value="info.doctor?info.doctor.name : ''"
                isLink
                rightIcon="edit-pen"
                @click="opendDoctor('doctor')"
            />
            <u-cell
                title="邀请人"
                :value="info.inviter?info.inviter.name : ''"
                isLink
                rightIcon="edit-pen"
                @click="opendDoctor('inviter')"
            />
            <u-cell
                title="业务员"
                :value="info.saler?info.saler.name : ''"
                isLink
                rightIcon="edit-pen"
                @click="opendDoctor('saler')"
            />
            <u-cell
                title="病情描述"
                isLink
                rightIcon="edit-pen"
                @click="openEditor"
            >
                <view slot="value">
                    <!-- <rich-text :nodes="info.illness" /> -->
                    <text>{{info.illness}}</text>
                </view>
            </u-cell>
			<u-cell title="图片资料">
				<view slot="value">
					<cu-image ref="images" @update="updateImages" />
				</view>
			</u-cell>
            <u-cell title="录入时间" :value="info.created_at"/>
        </u-cell-group>
        <div class="btn">
            <u-button text="添加病历" type="primary" @click="addRecord" />
            <u-button text="病历记录" type="success" @click="listRecord" />
            <u-button text="删除病人" type="error" @click="deletePatient" />
        </div>
        <u-modal
            :show="modal.show"
            :title="modal.title"
            :showCancelButton="true"
            :closeOnClickOverlay="true"
            :asyncClose="true"
            @confirm="confirmModal"
            @cancel="closeModal"
            @close="closeModal"
        >
            <u--input v-model="modal.value" border="surround" />
        </u-modal>
        <u-action-sheet
            title="性别"
            :show="genderSheet.show"
            :actions="gender.options"
            :closeOnClickOverlay="true"
            @close="toggleGender"
            @select="selectGender"
        />
        <u-datetime-picker
            v-model="datePicker.value"
            mode="date"
            :show="datePicker.show"
            :closeOnClickOverlay="true"
            :minDate="datePicker.minDate"
            @close="toggleBirthday"
            @cancel="toggleBirthday"
            @confirm="selectBirthday"
        />
        <select-admin-user ref="select-admin-user" @select="selectDoctor" />
        <cu-editor ref="editor" @confirm="confirmEditor" />
    </view>
</template>

<script>
import gender from '../../enums/gender'
import SelectAdminUser from '../../components/select-admin-user'
import CuEditor from '../../components/cu-editor'
import CuImage from '../../components/cu-image'

export default {
    components: {SelectAdminUser, CuEditor, CuImage},
    data() {
        return {
            id: '',
            info: {
				images: [],
                doctor_id: '',
                doctor: {},
			},
            modal: {
                type: 'text',
                show: false,
                title: '',
                key: '',
                value: ''
            },
            gender: gender,
            genderSheet: {
                show: false,
            },
            datePicker: {
                show: false,
                name: '',
                value: (new Date).getTime(),
                minDate: (new Date('1900/1/1')).getTime()
            },
            adminUser: {
                key: ''
            }
        }
    },
    onLoad(e) {
        this.id = e.id
        this.loadData()
    },
    onPullDownRefresh() {
        this.loadData()
    },
    methods: {
        loadData() {
            if (!this.id) {
                return
            }
            uni.showLoading()
            const params = {_action: 'getData'}
            this.$ajax.get(`/admin-api/patient/${this.id}`, { params }).then(res => {
				uni.stopPullDownRefresh()
                if (res.status == 0) {
                    this.info = {
						...res.data,
						birthday: res.data.birthday ? res.data.birthday.replaceAll('-', '/') : '',
						treat_at: res.data.treat_at ? res.data.treat_at.replaceAll('-', '/') : '',
					}
					if (res.data.images) {
						this.$refs['images'].setList(res.data.images.map(value => {
							return { url: value }
						}))
					}
                    uni.setNavigationBarTitle({ title: this.info.name })
                }
            }).catch(error => {
				uni.stopPullDownRefresh()
			})
        },
        openModal(title, name) {
            this.modal.title = title
            this.modal.key = name
            this.modal.show = true
            this.modal.value = this.info[name]
        },
        confirmModal() {
            const key = this.modal.key
            const value = this.modal.value
            const params = {}
            params[key] = value
			this.update(params).then(res => {
                this.modal.show = false
                if (res.status == 0) {
                    this.info[key] = value
                }
            })
        },
        closeModal() {
            this.modal.show = false
        },
        openEditor() {
            this.$refs['editor'].open(this.info.illness)
        },
        confirmEditor(e) {
			this.update({ illness: e }).then(res => {
                if (res.status == 0) {
                    this.info.illness = e
                }
            })
        },
        toggleGender() {
            this.genderSheet.show = !this.genderSheet.show
        },
        selectGender(e) {
			this.update({ sex: e.value }).then(res => {
                if (res.status == 0) {
                    this.info.sex = e.value
                    this.info.sex_text = e.name
                }
            })
        },
        toggleBirthday(name) {
            if (name) {
                this.datePicker.name = name
                this.datePicker.value = new Date(this.info[name]).getTime()
            }
            this.datePicker.show = !this.datePicker.show
        },
        selectBirthday(e) {
            const time = Math.floor(e.value / 1000)
            const key = this.datePicker.name
            const params = {}
            params[key] = time
			this.update(params).then(res => {
                if (res.status == 0) {
                    this.info[key] = e.value
                    this.toggleBirthday()
                }
            })
        },
        opendDoctor(key) {
            this.adminUser.key = key
            this.$refs['select-admin-user'].open()
        },
        closeDoctor() {
            this.$refs['select-admin-user'].close()
        },
        selectDoctor(e) {
            const key = this.adminUser.key
            const params = {}
            params[`${key}_id`] = e.id
			this.update(params).then(res => {
                if (res.status == 0) {
                    this.info[`${key}_id`] = e.id
                    this.info[key].id = e.id
                    this.info[key].name = e.name
                }
            })
            this.closeDoctor()
        },
		updateImages(e) {
			const list = e.map(item => item.url)
			this.update({ images: list }).then(res => {
				if (res.status == 0) {
					console.log(res)
				}
			})
		},
        addRecord() {
            return uni.navigateTo({ url: `/pages/record/form?patient=${this.id}` })
        },
        listRecord() {
            return uni.navigateTo({ url: `/pages/record/index?patient=${this.id}` })
        },
        deletePatient() {
            uni.showModal({
                title: '删除 ' + this.info.name,
                content: '是否确定?',
                success: (result) => {
                    if (result.confirm) {
                        this.delete(this.info.id)
                    }
                }
            })
        },
		update(data) {
			const params = Object.assign({id: this.id}, data)
			return this.$ajax.put(`/admin-api/patient/${this.id}`, params, { custom: { loading: true } })
		},
        delete(id) {
            uni.showLoading()
            this.$ajax.delete(`/admin-api/patient/${id}`).then(res => {
                if (res.status == 0) {
                    uni.showToast({
                        title: '删除成功',
                        icon: 'success'
                    })
                    setTimeout(() => {
                        uni.navigateBack()
                    }, 1000)
                }
            })
        },
        handleCall(phone) {
            console.log(phone)
            window.open(`tel:${phone}`, '_blank')
            // uni.makePhoneCall({
            //     phoneNumber: phone
            // });
        }
    }
}
</script>

<style scoped>
    .page {
        padding: 20px;
        background: white;
    }
    .u-cell-group {
        background: white;
    }
    .btn {
        padding: 0 10px;
    }
    .btn .u-button {
        margin-top: 20px;
    }
	.page ::v-deep .u-upload__wrap {
		justify-content: flex-end;
	}
	.text-gray {color: gray}
</style>
