<template>
	<view>
		<view class="box">
			<block v-if="(type==1||type==0)&&list&&list.west_prescription.length>0">
				<view class="white b-r-8 item m-t-2" v-for="(item,i) in list.west_prescription" :key="i">
					<!-- <view class="flex-row flex-jus-sp flex-ali-center">
						<d-text text="RP" size="24"></d-text>
						<d-text :text="`共${list.west[i].length}种药`" size="24"></d-text>
					</view> -->
					<view class="m-t08 flex-row flex-jus-sp flex-ali-center pr"
						@click="$go('commonDetails?type=1&info='+JSON.stringify(list.west[i])+'&item='+JSON.stringify(item))">
						<view class="flex-row flex-ali-center">
							<d-text :text="'名 称：'"  className="fs-3 color9"></d-text>
							<d-text :text="item.name"  className="fs-3 main-c"></d-text>
						</view>
						<view class="tag tag2">西药(中成)</view>
						<!-- <u-icon name="arrow-right" color="#A7ABB0" size="32"></u-icon> -->
					</view>
					<!-- <view class="m-t08 flex-row flex-jus-sp flex-ali-center"
						>
						<d-text :text="item.clinical_diagnose" color=" #6C7380"></d-text>
					</view> -->
					<view class="flexBox">
						<view class="label">药 品：</view>
						<view class="flex-1 m-t20">
							<view v-for="(it,idx) in list.west[i]"
								:key="it.id">
								<d-text :text="formatWestDrugLine(it)" className="fs-3 main-c"></d-text>
							</view>
						</view>
					</view>
					<view v-if="type!=0" class="m-t-24 btnBox">
						<view @click="handleDel(i, 'west_prescription', 'west')" class="btn left">移除</view>
						<view @click="use(list.west[i],item)" class="btn right">使用</view>
					</view>
					<view v-if="type==0" class="m-t-24 btnBox">
						<view @click="handleDel(i, 'west_prescription', 'west')" class="btn left">移除</view>
						<!-- <view @click="use(list.west[i],item)" class="btn right">编辑</view> -->
					</view>
				</view>
			</block>
			<block v-if="(type==2||type==0)&&list&&list.chin_prescription&&list.chin_prescription.length>0">
				<view class="white b-r-8 item m-t-2" v-for="(item,i) in list.chin_prescription" :key="i">
					<!-- <view class="flex-row flex-jus-sp flex-ali-center">
						<d-text text="RP" size="24"></d-text>
						<d-text :text="`共${getlen(list.chinese[i])}种药`" size="24"></d-text>
					</view> -->
					<view class="m-t08 flex-row flex-jus-sp flex-ali-center pr"
						@click="$go('commonDetails?type=2&info='+JSON.stringify(list.chinese[i])+'&item='+JSON.stringify(item))">
						<view class="flex-row flex-ali-center">
							<d-text :text="'名 称：'"  className="fs-3 color9"></d-text>
							<d-text :text="item.name"  className="fs-3 main-c"></d-text>
						</view>
						<!-- <u-icon name="arrow-right" color="#A7ABB0" size="32"></u-icon> -->
						<view class="tag">中药饮片</view>
					</view>
					<!-- <view class="m-t08 flex-row flex-jus-sp flex-ali-center">
						<d-text :text="item.clinical_diagnose" color=" #6C7380"></d-text>
					</view> -->
					<view class="flexBox">
						<view class="label">药 品：</view>
						<view class="flex-1 m-t20">
							<view v-for="(it,idx) in list.chinese[i]"
								:key="it.id">
								<d-text :text="formatChineseOrGranularDrugLine(it)" className=" fs-3 main-c"></d-text>
							</view>
						</view>
					</view>
					<view v-if="type!=0" class="m-t-24 btnBox">
						<view @click="handleDel(i, 'chin_prescription', 'chinese')" class="btn left">移除</view>
						<view @click="use(list.chinese[i],item)" class="btn right">使用</view>
					</view>
					<view v-if="type==0" class="m-t-24 btnBox">
						<view @click="handleDel(i, 'chin_prescription', 'chinese')" class="btn left">移除</view>
						<!-- <view @click="use(list.chinese[i],item)" class="btn right">编辑</view> -->
					</view>
				</view>
			</block>
			<block v-if="(type==3||type==0)&&list&&list.granular_prescription&&list.granular_prescription.length>0">
				<view class="white b-r-8 item m-t-2" v-for="(item,i) in list.granular_prescription" :key="i">
					<view class="m-t08 flex-row flex-jus-sp flex-ali-center pr"
						@click="$go('commonDetails?type=2&info='+JSON.stringify(list.granular[i])+'&item='+JSON.stringify(item))">
						<view class="flex-row flex-ali-center">
							<d-text :text="'名 称：'"  className="fs-3 color9"></d-text>
							<d-text :text="item.name"  className="fs-3 main-c"></d-text>
						</view>
						<view class="tag tag3">保健食品</view>
						<!-- <u-icon name="arrow-right" color="#A7ABB0" size="32"></u-icon> -->
					</view>
					<!-- <view class="m-t08 flex-row flex-jus-sp flex-ali-center"
						:key="it.id">
						<d-text :text="item.clinical_diagnose" color=" #6C7380"></d-text>
					</view> -->
					<view class="flexBox">
						<view class="label">药 品：</view>
						<view class="flex-1 m-t20">
							<view v-for="(it,idx) in list.granular[i]"
								:key="it.id">
								<d-text :text="formatChineseOrGranularDrugLine(it)" className=" fs-3 main-c"></d-text>
							</view>
						</view>
					</view>
					<view v-if="type!=0" class="m-t-24 btnBox">
						<view @click="handleDel(i, 'granular_prescription', 'granular')" class="btn left">移除</view>
						<view @click="use(list.granular[i],item)" class="btn right">使用</view>
					</view>
					<view v-if="type==0" class="m-t-24 btnBox">
						<view @click="handleDel(i, 'granular_prescription', 'granular')" class="btn left">移除</view>
						<!-- <view @click="use(list.granular[i],item)" class="btn right">编辑</view> -->
					</view>
				</view>
			</block>
		</view>
		<view class="flex-row flex-jus-center"
			v-if="!loading&&((type==1&&list&&list.west_prescription&&list.west_prescription.length==0)||(type==2&&list&&list.chin_prescription&&list.chin_prescription.length==0)||(type==3&&list&&list.granular_prescription&&list.granular_prescription.length==0))">
			<d-empty @click="$go(1,4)"></d-empty>
		</view>
		<d-loading-page :loading="loading"></d-loading-page>
		<view class="bottom">
			<u-button :throttle-time="0"  :custom-style="{ backgroundColor:'#6ACDBB',color:'#fff' }" shape="circle" @click="add">
				新增常用方
			</u-button>
		</view>
	</view>
</template>

<script>
	import mixin from './mixin/mixin.js';
	import {
		getCommonPrescriptionListApi,
		deleteCommonPrescriptionApi
	} from '@/api/reception.js'
	export default {
		mixins: [mixin],
		data() {
			return {
				loading: true,
				list: {
					west_prescription: [],
					west: [],
					chin_prescription: [],
					chinese: [],
					granular_prescription: [],
					granular: []
				},
				type: 0,
				one:false
			}
		},
		onLoad(op) {
			uni.removeStorageSync('add')
			uni.removeStorageSync('addWests')
			uni.setStorageSync('addChineses', [{
				item: [],
				obj: {}
			}])
			uni.setStorageSync('addGranular', [{
				item: [],
				obj: {}
			}])

			this.type = op['type'] || 0;
			console.log(this.type,'type')
			this.loadCommonList()
		},
		onShow() {
			this.one&&this.loadCommonList()
		},
		onHide() {
			this.one = true
		},
		methods: {
			formatWestDrugLine(it) {
				if (!it) return '';
				let name = it.drug_name || '';
				if (it.content) {
					try {
						const raw = typeof it.content === 'string' ? JSON.parse(it.content) : it.content;
						name = raw.drug_name || raw.name || name;
					} catch (e) {}
				}
				return `${name} *${it.number || 1}盒`;
			},
			formatChineseOrGranularDrugLine(it) {
				if (!it) return '';
				if (it.content) {
					try {
						const parsed = typeof it.content === 'string' ? JSON.parse(it.content) : it.content;
						if (Array.isArray(parsed)) {
							return this.getName2(parsed);
						}
						if (parsed && parsed.name) {
							return `${parsed.name} ${parsed.number || 1}${parsed.unit && parsed.unit.name ? parsed.unit.name : 'g'} `;
						}
					} catch (e) {}
				}
				const u = it.unit && it.unit.name ? it.unit.name : 'g';
				return `${it.drug_name || it.name || ''} ${it.number || 1}${u}`;
			},
			handleDel (i, type, type2) {
				uni.showModal({
					title: '提示信息',
					content: '是否移除',
					showCancel: true,
					success: async ({ confirm }) => {
						if (!confirm) return;
						try {
							const res = await deleteCommonPrescriptionApi({
								id: this.list[type][i].id,
								type: type2
							});
							if (res && res.code === 0) {
								this.list[type].splice(i, 1);
								const parallelKey = type2 === 'west' ? 'west' : type2 === 'chinese' ? 'chinese' : 'granular';
								if (this.list[parallelKey] && this.list[parallelKey][i] !== undefined) {
									this.list[parallelKey].splice(i, 1);
								}
								uni.showToast({ title: '移除成功', icon: 'success', mask: true });
							} else {
								this.$toast(res.msg || res.message || '移除失败');
							}
						} catch (e) {
							console.error(e);
							this.$toast('移除失败');
						}
					}
				})
			},
			getName(arr = []) {
				let names = []
				for (let i = 0; i < arr.length; i++) {
					names.push(arr[i]['name'])
				}
				return names.join()
			},
			getName2(arr = []) {
				let names = []
				for (let i = 0; i < arr.length; i++) {
					names.push(arr[i]['name'] + ' ' + arr[i]['number'] + (arr[i]['unit']?arr[i]['unit'].name:'g')+' ')
				}
				return names.join()
			},
			getlen(arr = []) {
				let len = 0
				for (let i = 0; i < arr.length; i++) {
					len += JSON.parse(arr[i].content).length
				}
				return len
			},
			add() {
				let initial = 2;
				if (this.type === 2) initial = 1;
				else if (this.type === 3) initial = 3;
				uni.navigateTo({
					url: `/subPackages/sub_workbench/prescription_v2/index?save_common=1&initial_category=${initial}`
				});
			},
			async loadCommonList() {
				try {
					const storeId = uni.getStorageSync('store_id') || 11001;
					const res = await getCommonPrescriptionListApi(storeId);
					if (res && res.code === 0 && res.result) {
						this.list = res.result;
					} else {
						this.$toast(res.msg || res.message || '加载失败');
						this.list = this.emptyListShape();
					}
				} catch (e) {
					console.error(e);
					this.$toast('加载失败');
					this.list = this.emptyListShape();
				} finally {
					this.$nextTick(() => {
						this.loading = false;
					});
				}
			},
			emptyListShape() {
				return {
					west_prescription: [],
					west: [],
					chin_prescription: [],
					chinese: [],
					granular_prescription: [],
					granular: []
				};
			}
		}
	}
</script>
<style>
	page {
		background-color: #F9FAFB;
	}
</style>
<style scoped lang="scss">
	.box {
		padding: 0 20rpx;
		padding-bottom: calc(env(safe-area-inset-bottom) + 130rpx);
	}

	.item {
		padding: 16rpx 32rpx;
	}

	.bottom {
		position: fixed;
		width: 750rpx;
		height: 110rpx;
		background: #FFFFFF;
		opacity: 1;
		border-top: 2rpx solid #F2F3F5;
		padding-top: 12rpx;
		bottom: env(safe-area-inset-bottom);
		padding-left: 32rpx;
		padding-right: 32rpx;
		z-index: 9999999;
	}
	.pr {
		position: relative;
		.tag {
			position: absolute;
			width: 162rpx;
			right: 0;
			top: 0;
			height: 48rpx;
			line-height: 48rpx;
			font-size: 28rpx;
			border-radius: 48rpx;
			color:#fff;
			text-align: center;
			background: rgba(15, 190, 22, .55);
			&.tag2 {
				background: rgba(15, 163, 190, .55);
			}
			&.tag3 {
				background: #6ACDBB;
			}
		}
	}
	.color3 {
		color: #333
	}
	.color6 {
		color: #666;
	}
	.btnBox {
		display: flex;
		align-items: center;
	border: 1rpx solid rgba(242, 242, 242, 1);
	.btn {
		height: 86rpx;
		line-height: 86rpx;
		text-align: center;
		font-size: 28rpx;
		flex: 1;
	}
	.left {
		border-right: 1rpx solid rgba(242, 242, 242, 1);
		color: #F44336
	}
	.right {
		color: #6ACDBB;
	}
}
.m-t20 {
	margin-top: 20rpx;
}
.flexBox {
	display: flex;
	align-items: flex-start;
	.label {
		color: #999;
		font-size: 28rpx;
		margin-top: 21rpx;
	}
}
.color9 {
	color: #999!important;
}
</style>
