<template>
    <view class="page">
        <u-cell-group :border="false">
            <u-cell
                title="姓名"
                :value="this.info.patient ? this.info.patient.name : ''"
            />
            <u-cell
                title="类别"
                :value="type.text"
            />
            <u-cell
                title="病种"
                :value="illnessType.label"
                isLink
                rightIcon="edit-pen"
                @click="openIllnessType"
            />
            <u-cell
                :title="`${type.text}时间`"
                :value="info.treat_at | date"
                isLink
                rightIcon="edit-pen"
                @click="toggleDatePicker('treat_at')"
            />
            <u-cell
                title="划线价"
                :value="info.origin_price"
                isLink
                rightIcon="edit-pen"
                @click="openModal('划线价', 'origin_price', 'number')"
            />
            <u-cell
                title="实收价"
                :value="info.sell_price"
                isLink
                rightIcon="edit-pen"
                @click="openModal('实收价', 'sell_price', 'number')"
            />
            <u-cell
                title="收费情况"
                :value="orderStatus.text"
                isLink
                rightIcon="edit-pen"
                @click="toggleOrderStatus"
            />
            <u-cell
                :title="`${type.text}医师`"
                :value="adminUser.doctor_name"
                :label="`提成金额: ${info.doctor_money}`"
                isLink
                rightIcon="edit-pen"
                @click="opendAdminUser('doctor')"
            />
            <u-cell
                title="邀请人"
                :value="info.inviter ? info.inviter.name : ''"
                :label="`提成金额: ${info.inviter_money}`"
            />
            <u-cell
                title="业务员"
                :value="info.saler ? info.saler.name : ''"
                :label="`提成金额: ${info.saler_money}`"
            />
            <u-cell
                :title="`${type.text}情况`"
                isLink
                rightIcon="edit-pen"
                @click="openEditor"
            >
                <view slot="label">
                    <!-- <rich-text :nodes="info.illness" /> -->
                    <u--text :text="info.content" type="info" wordWrap="anywhere" />
                </view>
            </u-cell>
			<u-cell title="图片资料">
				<view slot="value">
					<cu-image ref="images" @update="updateImages" />
				</view>
			</u-cell>
            <u-cell
                title="下次就诊时间"
                :value="info.next_treat_at | date"
                isLink
                rightIcon="edit-pen"
                @click="toggleDatePicker('next_treat_at', 'datetime')"
            />
            <u-cell title="开启通知">
                <view slot="value">
                    <u-switch v-model="info.is_notified" :activeValue="0" :inactiveValue="1" asyncChange @change="updateSwitch" />
                </view>
            </u-cell>
            <u-cell
                v-if="info.is_notified == 0"
                title="通知医师"
                :value="adminUser.notify_user_name"
                isLink
                rightIcon="edit-pen"
                @click="opendAdminUser('notify_user')"
            />
            <u-cell
                v-if="info.is_notified == 0"
                title="通知时间"
                :value="info.notify_at | date('yyyy-MM-dd')"
                isLink
                rightIcon="edit-pen"
                @click="toggleDatePicker('notify_at', 'date')"
            />
            <!-- <u-cell
                title="通知备注"
                :value="info.notify_remarks"
                isLink
                rightIcon="edit-pen"
                @click="openModal('通知备注', 'notify_remarks', 'text')"
            /> -->
            <u-cell
                title="录入时间"
                :value="info.created_at"
            />
        </u-cell-group>
        <view class="btn">
            <u-button text="病人信息" type="primary" @click="patientDetail" />
            <u-button text="删除病历" type="error" @click="deleteRecord" />
        </view>
        <select-admin-user ref="select-admin-user" @select="selectAdminUser" />
        <u-action-sheet
            :title="type.title"
            :show="type.show"
            :actions="type.options"
            :closeOnClickOverlay="true"
            @close="toggleType"
            @select="selectType"
        />
        <u-datetime-picker
            v-model="datePicker.value"
            :mode="datePicker.mode"
            :show="datePicker.show"
            :closeOnClickOverlay="true"
            :minDate="datePicker.minDate"
            @close="toggleDatePicker"
            @cancel="toggleDatePicker"
            @confirm="selectDatePicker"
        />
        <u-modal
            :show="modal.show"
            :title="modal.title"
            :showCancelButton="true"
            :closeOnClickOverlay="true"
            :asyncClose="false"
            @confirm="confirmModal"
            @cancel="closeModal"
            @close="closeModal"
        >
            <u--input v-if="modal.type == 'text'" v-model="modal.value" border="surround" />
            <u--input v-if="modal.type == 'number'" v-model="modal.value" type="number" border="surround" />
            <u--textarea v-if="modal.type == 'textarea'" v-model="modal.value" :showConfirmBar="false" />
        </u-modal>
        <u-action-sheet
            :title="orderStatus.title"
            :show="orderStatus.show"
            :actions="orderStatus.options"
            :closeOnClickOverlay="true"
            @close="toggleOrderStatus"
            @select="selectOrderStatus"
        />
        <cu-editor ref="editor" @confirm="confirmEditor" />
        <u-picker
            :show="illnessType.show"
            :columns="illnessType.list"
            keyName="label"
            closeOnClickOverlay
            @close="closeIllnessType"
            @cancel="closeIllnessType"
            @confirm="confirmIllnessType"
        />
    </view>
</template>

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

export default {
    components: {SelectAdminUser, CuEditor, CuImage},
    data() {
        return {
            id: '',
            info: {
                patient_id: '',
                type_id: '',
                origin_price: '',
                sell_price: '',
                notify_remarks: '',
                is_notified: 0,
            },
            adminUser: {
                key: '',
                doctor_name: '',
                notify_user_name: ''
            },
            type: {
                text: '',
                title: '类别',
                show: false,
                options: []
            },
            datePicker: {
                show: false,
                mode: 'datetime',
                name: '',
                value: (new Date).getTime(),
                minDate: (new Date('1900/1/1')).getTime()
            },
            modal: {
                type: 'text',
                show: false,
                title: '',
                key: '',
                value: ''
            },
            orderStatus: {
                title: '收费情况',
                show: false,
                text: '',
                options: orderStatus.options,
            },
            illnessType: {
                show: false,
                value: '',
                label: '',
                list: []
            },
        }
    },
    onLoad(e) {
        this.id = e.id
        this.init()
    },
    onPullDownRefresh() {
        this.loadData()
    },
    methods: {
        async init() {
            let res
            // res = await this.$ajax.get('/admin-api/category', { params: { _action: 'getData' } })
            // if (res.status == 0) {
            //     this.type.options = res.data.items
            // }
            await this.loadData()
            res = await this.$ajax.get('/admin-api/api/keywords/list', { params: { type_key: 'illness_type', value: this.info?.type?.key } })
            if (res.status == 0) {
                this.illnessType.list = [res.data]
            }
        },
        async loadData() {
            if (!this.id) {
                return
            }
            uni.showLoading()
            const params = { _action: 'getData' }
            let res = await this.$ajax.get(`/admin-api/record/${this.id}`, { params })
            uni.stopPullDownRefresh()
            if (res.status == 0) {
                this.info = {
                    ...res.data,
                    treat_at: res.data.treat_at ? res.data.treat_at.replaceAll('-', '/') : '',
                    next_treat_at: res.data.next_treat_at ? res.data.next_treat_at.replaceAll('-', '/') : '',
                    notify_at: res.data.notify_at ? res.data.notify_at.replaceAll('-', '/') : '',
                }
                if (res.data.images) {
                    this.$refs['images'].setList(res.data.images.map(value => {
                        return { url: value }
                    }))
                }
                this.type.text = this.info.type ? this.info.type.name : ''
                this.adminUser.doctor_name = this.info.doctor ? this.info.doctor.name : ''
                this.orderStatus.text = orderStatus.map[this.info.order_status]
                this.adminUser.notify_user_name = this.info.notify_user ? this.info.notify_user.name : ''
                if (res.data.illness_type) {
                    const illness = res.data.illness_type
                    this.illnessType.label = illness.name
                    this.illnessType.value = illness.id
                }
            }

        },
        update(key, value) {
            const params = {
                id: this.id,
            }
            params[key] = value
            return this.$ajax.put(`/admin-api/record/${this.id}`, params, {custom: { loading: true }})
        },
        opendAdminUser(name) {
            this.adminUser.key = name
            this.$refs['select-admin-user'].open()
        },
        closeAdminUser() {
            this.adminUser.key = ''
            this.$refs['select-admin-user'].close()
        },
        selectAdminUser(e) {
            const key = this.adminUser.key
            const value = e.id
            this.update(`${key}_id`, value).then(res => {
                this.closeAdminUser()
                if (res.status == 0) {
                    this.info[`${key}_id`] = value
                    this.adminUser[`${key}_name`] = e.name
                }
            })
        },
        toggleType() {
            this.type.show = !this.type.show
        },
        selectType(e) {
            this.update('type_id', e.id).then(res => {
                if (res.status == 0) {
                    this.type.text = e.name
                    this.info.type_id = e.id
                }
            })
        },
        toggleDatePicker(name, mode) {
            if (name) {
                this.datePicker.name = name
                const value = this.info[name]
                if (value) {
                    this.datePicker.value = (new Date(value)).getTime()
                }
            }
            if (mode) {
                this.datePicker.mode = mode
            }
            this.datePicker.show = !this.datePicker.show
        },
        selectDatePicker(e) {
            const value = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
            const key = this.datePicker.name
            this.update(key, value).then(res => {
                if (res.status == 0) {
                    this.info[key] = value
                    this.toggleDatePicker()
                }
            })
        },
        openModal(title, name, type) {
            this.modal.type = type ? type : 'text'
            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
            this.update(key, value).then(res => {
                this.closeModal()
                if (res.status == 0) {
                    this.info[key] = value
                }
            })
        },
        closeModal() {
            this.modal.show = false
        },
        toggleOrderStatus() {
            this.orderStatus.show = !this.orderStatus.show
        },
        selectOrderStatus(e) {
            const key = 'order_status'
            const value = e.value
            const text = e.name
            this.update(key, value).then(res => {
                if (res.status == 0) {
                    this.orderStatus.text = text
                    this.info[key] = value
                }
            })
        },
        openEditor() {
            this.$refs['editor'].open(this.info.content)
        },
        confirmEditor(e) {
            const value = e
            const key = 'content'
            this.update(key, value).then(res => {
                if (res.status == 0) {
                    this.info[key] = value
                }
            })
        },
		updateImages(e) {
			const list = e.map(item => item.url)
			this.update('images', list).then(res => {
				if (res.status == 0) {
					console.log(res)
				}
			})
		},
        updateSwitch(e) {
            this.update('is_notified', e).then(res => {
                if (res.status == 0) {
					this.info.is_notified = e
				}
            })
        },
        deleteRecord() {
            uni.showModal({
                title: '删除病历记录',
                content: '是否确定?',
                success: (result) => {
                    if (result.confirm) {
                        this.handleDelete(this.id)
                    }
                }
            })
        },
        handleDelete(id) {
            uni.showLoading()
            this.$ajax.delete(`/admin-api/record/${id}`).then(res => {
                if (res.status == 0) {
                    uni.showToast({
                        title: '删除成功',
                        icon: 'success'
                    })
                    setTimeout(() => {
                        uni.navigateBack()
                    }, 1000)
                }
            })  
        },
        patientDetail() {
            return uni.navigateTo({ url: `/pages/patient/detail?id=${this.info.patient_id}` })
        },
        openIllnessType() {
            this.illnessType.show = true
        },
        closeIllnessType() {
            this.illnessType.show = false
        },
        confirmIllnessType(e) {
            const item = e.value[0]
            if (!item) {
                return
            }
            this.closeIllnessType()
            this.update('illness_type_id', item.value).then(res => {
                if (res.status == 0) {
                    this.info.illness_type_id = item.value
                    this.illnessType.value = item.value
                    this.illnessType.label = item.label
				}
            })
        }
    }
}
</script>
<style scoped>
    .page {
        padding: 20px;
        background: white;
    }
    .btn {
        padding: 0 10px;
    }
    .btn .u-button {
        margin-top: 20px;
    }
	.text-gray {
		color: gray;
	}
</style>