<template>
	<view class="doc-select-wrapper" style="width: 100%;">

		<template v-if="mode === 'radio'">
			<s-radio-group placement="column" @change="value => { changeRadioBox(value) }" :disabled="disabled"
				v-model="radioSelectedValue" mode="normal" :size="19">
				<s-radio shape="circle" :customStyle="{ marginBottom: '10px' }"
					v-for="(item, index) in record.options.children" :key="index" :name="item.options.selectValue">

					<view style="flex: 1;">
						<template style="display: inline;" v-for="(sitem, sindex) in item.options.children">
							<template v-if="sitem.type === 'warpInput'">
								<span :style="{
                                    letterSpacing: record.options.leftLetterSpacing,
                                }" v-html="sitem.options.leftLabel"></span>
								<span @click="clickWarp(sitem)" @blur="blurWarpInput(index, item, sindex, sitem)"
									:ref="index + '-' + sindex + 'warpInput'" style="
                              word-break: break-all;
                              outline: none;
                              padding: 0 20px;
                              display: inline;
                              white-space: pre-wrap;" :style="{
                                  color: sitem.options.color,
                                  letterSpacing: sitem.options.letterSpacing,
                                  padding: '0 20px',
                                  width: sitem.options.width + 'px',
                                  marginLeft: sitem.options.marginLeft + 'px',
                                  marginRight: sitem.options.marginRight + 'px',
                                  borderBottom: sitem.options.showBottomBorder
                                      ? '1px solid #000'
                                      : 'none',
                              }" :contenteditable="disabled ? false : true" v-html="models[sitem.model]"></span>
								<span v-if="sitem.options.showDot">：</span>
								<span :style="{
                                    letterSpacing: sitem.options.rightLetterSpacing,
                                }">{{ sitem.options.rightLabel }}</span>
							</template>

							<template v-else-if="sitem.type === 'documentDatePicker'">

								<!-- 文书日期组件对应的日期选择器弹出框 -->
								<s-datetime-picker @cancel="showDatePicker = false" :style="{
                                    display: 'inline'
                                }" @confirm="e => { confirmDatePicker(e, sitem.model) }" :show="showDatePicker"
									@close="showDatePicker = false" :value="models[sitem.model]" mode="datetime"
									closeOnClickOverlay></s-datetime-picker>


								<span @click="clickDatePickerHandler" class="text-align-center" style="display: inline"
									:style="{
                                        marginLeft: sitem.options.marginLeft + 'px',
                                        marginRight: sitem.options.marginRight + 'px',
                                    }">
									<span :style="{
                                        paddingLeft: sitem.options.paddingWidth + 'px',
                                        paddingRight: sitem.options.paddingWidth + 'px',
                                    }" :class="sitem.options.showBottomBorder ? 'my-border-bottom ' : ''"
										class="d-inline input-text" v-if="includesText('yyyy', sitem)"
										v-text="dealDocumentText('y', sitem)"></span>
									<span class="d-inline" v-if="includesText('yyyy', sitem)">年</span>
									<span :class="sitem.options.showBottomBorder ? 'my-border-bottom ' : ''"
										class="d-inline input-text" v-if="includesText('MM', sitem)" :style="{
                                            paddingLeft: sitem.options.paddingWidth + 'px',
                                            paddingRight: sitem.options.paddingWidth + 'px',
                                        }" v-text="dealDocumentText('m', sitem)"></span>
									<span class="d-inline" v-if="includesText('MM', sitem)">月</span>
									<span :class="sitem.options.showBottomBorder ? 'my-border-bottom ' : ''"
										class="d-inline input-text" v-if="includesText('dd', sitem)"
										v-text="dealDocumentText('d', sitem)" :style="{
                                            paddingLeft: sitem.options.paddingWidth + 'px',
                                            paddingRight: sitem.options.paddingWidth + 'px',
                                        }"></span>
									<span v-if="includesText('dd', sitem)" class="d-inline">日</span>
									<span :class="sitem.options.showBottomBorder ? 'my-border-bottom ' : ''"
										class="input-text d-inline" v-if="includesText('HH', sitem)" :style="{
                                            paddingLeft: sitem.options.paddingWidth + 'px',
                                            paddingRight: sitem.options.paddingWidth + 'px',
                                        }" v-text="dealDocumentText('H', sitem)"></span>
									<span v-if="includesText('HH', sitem)" class="d-inline">时</span>
									<span :class="sitem.options.showBottomBorder ? 'my-border-bottom ' : ''"
										class="input-text d-inline" v-if="includesText('mm', sitem)"
										v-text="dealDocumentText('M', sitem)" :style="{
                                            paddingLeft: sitem.options.paddingWidth + 'px',
                                            paddingRight: sitem.options.paddingWidth + 'px',
                                        }"></span>
									<span v-if="includesText('mm', sitem)" class="d-inline">分</span>
									<span :class="sitem.options.showBottomBorder ? 'my-border-bottom ' : ''"
										class="input-text d-inline" v-if="includesText('ss', sitem)"
										v-text="dealDocumentText('S', sitem)" :style="{
                                            paddingLeft: sitem.options.paddingWidth + 'px',
                                            paddingRight: sitem.options.paddingWidth + 'px',
                                        }"></span>
									<span v-if="includesText('ss', sitem)" class="d-inline">秒</span>
								</span>
							</template>

							<template v-else-if="sitem.type === 'docCheckbox'">
								<DocCheckbox @change="(data) => { docCheckBoxChange(data, sitem) }" :record="sitem"
									:models="models" />
							</template>


						</template>
					</view>

				</s-radio>
			</s-radio-group>
		</template>

		<template v-else-if="mode === 'checkbox'">
			<s-checkbox-group placement="column" @change="value => { changeRadioBox(value) }" :disabled="disabled"
				v-model="checkboxSelectedValue" mode="normal" :size="19">
				<s-checkbox shape="circle" :customStyle="{ marginBottom: '10px' }"
					v-for="(item, index) in record.options.children" :key="index" :name="item.options.selectValue">

					<view style="flex: 1;">
						<template style="display: inline;" v-for="(sitem, sindex) in item.options.children">

							<template v-if="sitem.type === 'warpInput'">
								<span :style="{
                                    letterSpacing: record.options.leftLetterSpacing,
                                }" v-html="sitem.options.leftLabel"></span>
								<span @blur="blurWarpInput(index, item, sindex, sitem)"
									:ref="index + '-' + sindex + 'warpInput'" style="
                              word-break: break-all;
                              outline: none;
                              padding: 0 20px;
                              display: inline;
                              white-space: pre-wrap;" :style="{
                                  color: sitem.options.color,
                                  letterSpacing: sitem.options.letterSpacing,
                                  padding: '0 20px',
                                  width: sitem.options.width + 'px',
                                  marginLeft: sitem.options.marginLeft + 'px',
                                  marginRight: sitem.options.marginRight + 'px',
                                  borderBottom: sitem.options.showBottomBorder
                                      ? '1px solid #000'
                                      : 'none',
                              }" :contenteditable="disabled ? false : true" v-html="models[sitem.model]"></span>
								<span v-if="sitem.options.showDot">：</span>
								<span :style="{
                                    letterSpacing: sitem.options.rightLetterSpacing,
                                }">{{ sitem.options.rightLabel }}</span>
							</template>

							<template v-else-if="sitem.type === 'documentDatePicker'">

								<!-- 文书日期组件对应的日期选择器弹出框 -->
								<s-datetime-picker @cancel="showDatePicker = false" :style="{
                                    display: 'inline'
                                }" @confirm="e => { confirmDatePicker(e, sitem.model) }" :show="showDatePicker"
									@close="showDatePicker = false" :value="models[sitem.model]" mode="datetime"
									closeOnClickOverlay></s-datetime-picker>


								<span @click="clickDatePickerHandler" class="text-align-center" style="display: inline"
									:style="{
                                        marginLeft: sitem.options.marginLeft + 'px',
                                        marginRight: sitem.options.marginRight + 'px',
                                    }">
									<span :style="{
                                        paddingLeft: sitem.options.paddingWidth + 'px',
                                        paddingRight: sitem.options.paddingWidth + 'px',
                                    }" :class="sitem.options.showBottomBorder ? 'my-border-bottom ' : ''"
										class="d-inline input-text" v-if="includesText('yyyy', sitem)"
										v-text="dealDocumentText('y', sitem)"></span>
									<span class="d-inline" v-if="includesText('yyyy', sitem)">年</span>
									<span :class="sitem.options.showBottomBorder ? 'my-border-bottom ' : ''"
										class="d-inline input-text" v-if="includesText('MM', sitem)" :style="{
                                            paddingLeft: sitem.options.paddingWidth + 'px',
                                            paddingRight: sitem.options.paddingWidth + 'px',
                                        }" v-text="dealDocumentText('m', sitem)"></span>
									<span class="d-inline" v-if="includesText('MM', sitem)">月</span>
									<span :class="sitem.options.showBottomBorder ? 'my-border-bottom ' : ''"
										class="d-inline input-text" v-if="includesText('dd', sitem)"
										v-text="dealDocumentText('d', sitem)" :style="{
                                            paddingLeft: sitem.options.paddingWidth + 'px',
                                            paddingRight: sitem.options.paddingWidth + 'px',
                                        }"></span>
									<span v-if="includesText('dd', sitem)" class="d-inline">日</span>
									<span :class="sitem.options.showBottomBorder ? 'my-border-bottom ' : ''"
										class="input-text d-inline" v-if="includesText('HH', sitem)" :style="{
                                            paddingLeft: sitem.options.paddingWidth + 'px',
                                            paddingRight: sitem.options.paddingWidth + 'px',
                                        }" v-text="dealDocumentText('H', sitem)"></span>
									<span v-if="includesText('HH', sitem)" class="d-inline">时</span>
									<span :class="sitem.options.showBottomBorder ? 'my-border-bottom ' : ''"
										class="input-text d-inline" v-if="includesText('mm', sitem)"
										v-text="dealDocumentText('M', sitem)" :style="{
                                            paddingLeft: sitem.options.paddingWidth + 'px',
                                            paddingRight: sitem.options.paddingWidth + 'px',
                                        }"></span>
									<span v-if="includesText('mm', sitem)" class="d-inline">分</span>
									<span :class="sitem.options.showBottomBorder ? 'my-border-bottom ' : ''"
										class="input-text d-inline" v-if="includesText('ss', sitem)"
										v-text="dealDocumentText('S', sitem)" :style="{
                                            paddingLeft: sitem.options.paddingWidth + 'px',
                                            paddingRight: sitem.options.paddingWidth + 'px',
                                        }"></span>
									<span v-if="includesText('ss', sitem)" class="d-inline">秒</span>
								</span>
							</template>

							<template v-else-if="sitem.type === 'docCheckbox'">
								<DocCheckbox @change="(data) => { docCheckBoxChange(data, sitem) }" :record="sitem"
									:models="models" />
							</template>



						</template>
					</view>

				</s-checkbox>
			</s-checkbox-group>
		</template>
		<s-toast ref="sToast"></s-toast>
	</view>
</template>


<script>
	import {
		getEmitModel
	} from "./utils/eventEmit"
	import {
		toChineseNumeral
	} from "./utils/index"
	import DocCheckbox from "./doc-checkbox"
import { log } from "util"
	// import moment from "moment"
	export default {
		data() {
			return {
				// 单选框当前选中的value
				radioSelectedValue: "",

				// 多选框当前选中的值
				checkboxSelectedValue: [],

				// 显示日期选择器
				showDatePicker: false,

				// 转化为moment对应的日期格式
				momentFormatDateList: {
					"yyyy-MM-dd": "{y}年{m}月{d}日",
					"yyyy-MM-dd HH:mm:ss": "{y}年{m}月{d}日 {h}时{i}分{s}秒",
					"yyyy-MM-dd HH:mm": "{y}年{m}月{d}日 {h}时{i}分",
					"MM-dd HH:mm": "{m}月{d}日 {h}时{i}分",
					"yyyy-MM-dd HH": "{y}年{m}月{d}日 {h}时",
					"dd HH:mm": "{d}日 {h}时{i}分",
					"HH:mm": "{h}时{i}分",
					"HH:mm:ss": "{h}时{i}分{s}秒",
					"yyyy-MM": "{y}年{m}月",
					"MM-dd": "{m}月{d}日",
					"yyyy": "{y}年",
					"MM": "{m}月",
					"dd": "{d}日"
				},
			}
		},
		components: {
			DocCheckbox
		},
		props: {
			// 传入的数据
			models: {
				type: Object,
				default: () => {}
			},
			// 当前选项对应的json数据
			record: {
				type: Object,
				default: () => {}
			},
			// 是否禁用输入
			disabled: {
				type: Boolean,
				default: false
			}
		},
		watch: {
			models: {
				handler(val) {

					console.log("models更新", {
						...val
					});
				},
				immediate: true,
				deep: true
			}
		},
		computed: {
			// 文书select选择器的模式
			mode() {
				return this.record.options.mode || null
			},
			// 判断当前选择的日期是否包含了指定字符
			includesText() {
				return (text, item) => {
					if (item.options.displayFormat) {
						if (item.options.displayFormat.search(text) > -1) {
							return true;
						} else {
							return false;
						}
					}
				};
			},
			dealDocumentText() {
				return (type, item) => {
					if (
						(this.models && this.models[this.record.model]) ||
						this.models[item.model]
					) {
						const value =
							this.models[item.model] ||
							this.models[this.record.model][item.model];

						if (value) {
							switch (type) {
								case "y":
									return value.split(" ")[0].split("-")[0];
								case "m":
									return value.split(" ")[0].split("-")[1];
								case "d":
									return value.split(" ")[0].split("-")[2];
								case "H":
									return value.split(" ")[1].split(":")[0];
								case "M":
									return value.split(" ")[1].split(":")[1];
								default:
									return value.split(" ")[1].split(":")[2];
							}
						}
					} else {
						return "";
					}
				};
			},

		},
		methods: {
			clickWarp(item) {
				if (item.options && item.options.isOpenClick) {
					console.log("发送")
					const eventData = getEmitModel('click', item.options.eventKey, item.model, null)
					this.$emit("event-callback", eventData)
				}
			},
			/**
			 * 文书checkbox 变化
			 * @param {*} key 
			 * @param {*} value 
			 */
			docCheckBoxChange(data, item) {
				const {
					key,
					value
				} = data
				this.$emit('change', key, value)

				if (this.record.options.mode === 'radio') {
					this.changeRadioBox(this.radioSelectedValue)
				} else {
					this.changeRadioBox(this.checkboxSelectedValue)
				}
			},
			// 点击日期组件，弹出日期选择框
			clickDatePickerHandler() {
				this.showDatePicker = true
			},
			// 日期组件点击确认后回调
			confirmDatePicker(e, key) {
				this.$emit('change', key, this.parseTime(e.value))
				this.showDatePicker = false

				if (this.record.options.mode === 'radio') {
					this.changeRadioBox(this.radioSelectedValue)
				} else {
					this.changeRadioBox(this.checkboxSelectedValue)
				}
			},
			/**
			 * @param {Object} time 目标时间字符串
			 * @param {Object} cFormat 需要转化成的时间格式
			 */
			parseTime(time, cFormat) {
				if (arguments.length === 0) {
					return null
				}

				// 默认格式
				const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
				let date
				if (typeof time === 'object') {
					date = time
				} else {
					if (('' + time).length === 10) time = this.parseInt(time) * 1000
					date = new Date(time)
				}
				const formatObj = {
					y: date.getFullYear(),
					m: date.getMonth() + 1,
					d: date.getDate(),
					h: date.getHours(),
					i: date.getMinutes(),
					s: date.getSeconds(),
					a: date.getDay()
				}
				const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
					let value = formatObj[key]
					if (key === 'a') {
						.0.return['一', '二', '三', '四', '五', '六', '日'][value - 1]
					}
					if (result.length > 0 && value < 10) {
						value = '0' + value
					}
					return value || 0
				})
				return time_str
			},

			/**
			 * 传入一个section joson，将其中整个段落的文本内容提取出来
			 */
			/**
			 * 传入一个section joson，将其中整个段落的文本内容组合出来，例如：假设传入的包含了一个换行输入框
			 * 那么 label = 前置文本label + 下划线输入内容 + 后置文本label
			 */
			getSectionInputText(sectionJson) {
				let result = "";
				if (sectionJson) {
					if (
						sectionJson.options.children &&
						sectionJson.options.children.length
					) {
						for (let sitem of sectionJson.options.children) {
							if (sitem.type === "warpInput") {
								result += `${sitem.options.leftLabel}${this.models[sitem.model] || ""
                                }${sitem.options.rightLabel}`;
							} else if (sitem.type === "documentDatePicker") {
								// const date = moment(new Date(this.models[sitem.model])).format(this.momentFormatDateList[sitem.options.displayFormat])
								const date = this.parseTime(new Date(this.models[sitem.model]), this.momentFormatDateList[
									sitem.options.displayFormat])
								result += date.toString()
							} else if (sitem.type === 'docCheckbox') {
								const value = this.models[sitem.model]
								if (sitem.options.mode === 'radio') {
									// 单选框直接处理
									if (value) {
										const label = sitem.options.options.find(k => k.value == value).label
										if (label) {
											result += label
										}
									}
								} else {
									// 如果是多选框 models是以逗号分隔的字符串
									if (value) {
										const checkboxValue = value.split(",")
										if (checkboxValue && checkboxValue.length) {
											for (let pitem of checkboxValue) {
												const label = sitem.options.options.find(k => k.value == pitem).label
												result += label
											}
										}
									}

								}


							}
						}
					}
				}
				return result;
			},
			changeRadioBox(value) {
				// 单选
				if (this.record.options.mode === 'radio') {
					const sectionJson = this.record.options.children.find(k => k.options.selectValue === value)
					const sectionLabel = this.getSectionInputText(sectionJson)
					this.$emit('change', `${this.record.model}_label`, sectionLabel)
					this.$emit('change', `${this.record.model}`, value)
				} else {
					this.checkboxSelectedValue = value
					let docLabelList = []
					for (let item of this.checkboxSelectedValue) {
						const sectionJson = this.record.options.children.find(k => k.options.selectValue === item)
						docLabelList.push(this.getSectionInputText(sectionJson))
					}
					const sectionLabel = docLabelList.join("-")
					this.$emit('change', `${this.record.model}`, this.checkboxSelectedValue.join(","))
					this.$emit('change', `${this.record.model}_label`, sectionLabel)
				}
			},
			/**
			 * 当一个下拉选项中换行输入框变化时触发
			 * @param {*} index 当前编辑的
			 * @param {*} model 
			 * @param {*} pitem 
			 */
			blurWarpInput(pindex, pitem, index, item) {
				console.log("item", item);
				const model = item.model
				const dom = this.$refs[pindex + '-' + index + 'warpInput'][0]
				let tempValue = dom.innerText
				if (dom) {
					console.log("pitem", pitem);

					// 开启了数字金额转大写功能
					if (item && item.options && item.options.isToChineseNumber) {
						if (!isNaN(tempValue)) {
							tempValue = toChineseNumeral(tempValue)
						} else {
							this.$refs.sToast.show({
								type: 'default',
								title: '默认主题',
								message: "请输入数字"
							})
						}
					}

					this.$emit('change', model, tempValue)
					console.log("输入值发生变化，更新");
					if (this.record.options.mode === 'radio') {
						this.changeRadioBox(this.radioSelectedValue)
					} else {
						this.changeRadioBox(this.checkboxSelectedValue)
					}
				}
			}
		},
		created() {
			if (this.models[this.record.model]) {
				if (this.record.options.mode === 'radio') {
					this.radioSelectedValue = this.models[this.record.model]
				} else {
					this.checkboxSelectedValue = this.models[this.record.model].split(",")
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.doc-select-wrapper {
		.d-inline {
			display: inline;
		}

		.my-border-bottom {
			border-bottom: 1px solid #333;
		}
	}
</style>