<template>
    <van-form ref='form'
              class='grow flex flex-col' style='min-height: 1px;flex-wrap: nowrap;'>
        <div class='flex flex-col' v-if='fileType?.includes(1)'>
            <div>
                <!--            无选项-->
                <div class='health-cell mt-2' v-for="item in form.contentList.filter(e => e.templateModeTrans == '无')">
                    <div class='no-req-label'>{{ contentTitle }}</div>
                    <van-field
                        v-model='item.templateContent'
                        rows='1'
                        autosize
                        type='textarea'
                        placeholder='请输入'
                        class='input-back mt-2 form-input'
                        :rules='rules.templateContent'
                    />
                </div>
                <!--            更多选项-->
                <div class='health-cell mt-2'>
                    <div class='no-req-label'>更多{{ contentTitle }}</div>
                    <van-field
                        v-model='form.contentSelectName'
                        readonly
                        is-link
                        placeholder='请选择'
                        class='input-back mt-2 form-input'
                        name='contentSelectName'
                        :rules='rules.contentSelectName'
                        @click='showContentSelect= true'
                    >
                        <template #input>
                            <span class='text-end' v-if='form.contentSelectName'>{{ form.contentSelectName }}</span>
                            <span class='text-end' v-if='!form.contentSelectName' style='color: #dfdfe1'>请选择</span>
                        </template>
                    </van-field>
                    <van-popup v-model:show='showContentSelect' position='bottom'>
                        <div class='p-4'>
                            <div class='flex justify-between mb-4 items-center pop-title'>
                                <div class='greyColor' @click='showContentSelect = false' style='font-weight: 400'>取消
                                </div>
                                <div>{{ contentTitle }}（可多选）</div>
                                <div class='blueColor' @click='contentSelectConfirm'>确定</div>
                            </div>
                            <CheckBtn multiple column-2 :options='contentArray' v-model:value='checkContentSelect'
                                      :fieldNames="{text: 'name', value: 'value'}" />
                        </div>
                    </van-popup>
                </div>

                <div v-if='form.contentSelectName' class='mt-2'>
                    <van-button type='primary' plain class='w-full' @click='choiceTel' size='small'>选择内容</van-button>
                </div>

                <div class='health-cell mt-2' v-for="item in form.contentList.filter(e => e.templateModeTrans != '无')">
                    <template v-if='item.templateMode === 5'>
                        <div class='no-req-label'>药物指导</div>
                        <div v-for='(item, index) in form.drugsList' :key='item._id'
                             :style="{marginTop: index == 0 ? '0': '.16rem'}">
                            <div class='text-driver' v-if='index'></div>
                            <DocDrug v-model:value='item.drugsCode' placeholder='拼音码查询药品'
                                     :valueName="selectData.drugsList ? selectData.drugsList[index]?.helpCode : ''"
                                     @change='drugChange($event, item)'
                            />
                            <div class='flex items-center justify-between w-full mt-2'>
                                <van-field
                                    v-model='item.dose'
                                    placeholder='输入'
                                    label='剂量：'
                                    type='digit'
                                    class='input-back form-input'
                                    style='flex: 1'
                                    :rules='rules.dose'
                                />
                                <van-field
                                    v-model='item.doseUnitName'
                                    readonly
                                    placeholder='请选择'
                                    class='input-back ml-2 form-input'
                                    style='width: .8rem'
                                    @click='showDoseUnit= true'
                                    :rules='rules.doseUnitName'
                                />
                            </div>
                            <van-popup v-model:show='showDoseUnit' position='bottom'>
                                <div class='p-4'>
                                    <van-picker
                                        :columns-field-names="{ text: 'name', value: 'value' }"
                                        :columns="store.getDict('CP00081')"
                                        @confirm='doseUnitConfirm($event, item)'
                                        @cancel='showDoseUnit = false'
                                    />
                                </div>
                            </van-popup>
                            <van-field
                                v-model='item.frequencyName'
                                readonly
                                is-link
                                label='频次：'
                                placeholder='请选择'
                                class='input-back mt-2 form-input'
                                @click='showFrequency= true'
                                :rules='rules.frequencyName'
                            />
                            <van-popup v-model:show='showFrequency' position='bottom'>
                                <div class='p-4'>
                                    <van-picker
                                        :columns-field-names="{ text: 'name', value: 'value' }"
                                        :columns="store.getDict('CP00084')"
                                        @confirm='frequencyConfirm($event, item)'
                                        @cancel='showFrequency = false'
                                    />
                                </div>
                            </van-popup>
                            <van-field
                                v-model='item.usageMethodName'
                                readonly
                                is-link
                                label='用法：'
                                placeholder='请选择'
                                class='input-back mt-2 form-input'
                                @click='showUsageMethod= true'
                                :rules='rules.usageMethodName'
                            />
                            <van-popup v-model:show='showUsageMethod' position='bottom'>
                                <div class='p-4'>
                                    <van-picker
                                        :columns-field-names="{ text: 'name', value: 'value' }"
                                        :columns="store.getDict('CP00083')"
                                        @confirm='usageMethodConfirm($event, item)'
                                        @cancel='showUsageMethod = false'
                                    />
                                </div>
                            </van-popup>

                            <div class='mt-2 text-center'>
                                <van-button type='primary' plain class='btn-br' @click='addDrug'>增加</van-button>
                                <van-button plain class='btn-br'
                                            @click='minusDrug(item, index)'
                                            v-if='form?.drugsList?.length > 1'
                                            style='margin-left: .16rem'
                                >删除
                                </van-button>
                            </div>
                        </div>
                    </template>

                    <div class='no-req-label' v-if='item.templateMode != 5'>{{ item.templateModeTrans }}</div>
                    <van-field
                        v-model='item.templateContent'
                        v-if='item.templateMode != 5'
                        rows='1'
                        autosize
                        type='textarea'
                        placeholder='请输入'
                        :name='item.templateContent'
                        :rules="[{ required: true, message: '请输入' }]"
                        class='input-back mt-2 form-input'
                    />
                </div>
            </div>
        </div>
        <div v-if='fileType.includes(2)' class='w-full'>
            <div class='health-cell mt-2'>
                <div class='no-req-label'>音频</div>
                <Mp3 :file='item' v-for='item in _audio' :key='item.annexId'
                     :activeMediaUrl='activeMediaUrl'
                     @play='e => activeMediaUrl = e.annexUrl'
                     remove
                     @onRemove='getMP3RemoveInfo'
                     class='mt-2'
                />
            </div>
        </div>
        <div v-if='fileType.includes(3)' class='w-full'>
            <div class='health-cell mt-2'>
                <div class='no-req-label'>视频</div>
                <Mp4 :files='_video' :activeMediaUrl='activeMediaUrl'
                     @play='e => activeMediaUrl = e.annexUrl'
                     remove
                     @onRemove='getMP4RemoveInfo'
                     class='mt-2'
                />
            </div>
        </div>

    </van-form>
</template>

<script>


import { fetchDataHandle } from '@/utils/common'
import { useStore } from '@/doctor/store'
import DocDrug from '@/doctor/components/docDrug/DocDrug'
import Mp3 from '@/doctor/components/mediaPlay/Mp3.vue'
import Mp4 from '@/doctor/components/mediaPlay/Mp4.vue'
import CheckBtn from '@/doctor/components/checkBtn/CheckBtn'

export default {
    name: 'GuideTextVideo',
    components: { CheckBtn, Mp4, Mp3, DocDrug },
    props: {
        info: {
            default: () => {
                return {}
            }
        },
        //内容标题
        contentTitle: {
            default: () => {
                return '宣教内容'
            }
        },
        // 文件类型 1:文本 2、文字播报 3、视频
        fileType: Array,
        // 分类
        classify: Number
    },
    data() {
        return {
            store: useStore(),
            //更多指导内容
            showContentSelect: false,
            checkContentSelect: [],
            //药物剂量
            showDoseUnit: false,
            //药物频次
            showFrequency: false,
            //药物用法
            showUsageMethod: false,
            form: {},
            selectData: {},
            // 控制音频同一时间只播放一个
            activeMediaUrl: '',
            hideActiveMediaUrl: '',
            rules: {
                templateContent: [{ required: true, message: '请输入' }],
                dose: [{ required: true, message: '请输入' }],
                doseUnitName: [{ required: true, message: '请选择' }],
                frequencyName: [{ required: true, message: '请选择' }],
                usageMethodName: [{ required: true, message: '请选择' }]
            }
        }
    },
    computed: {
        contentArray() {
            let res = []
            res = this.store.getDict('DC00084').filter(item => item.value != 1)
            return res
        },
        // 音频、视频 回显使用
        _video() {
            const annexList = this.selectData.annexList || []
            return annexList.filter(e => e.type === 3).map(e => {
                return {
                    annexFileName: e.annexFileName,
                    trueDownloadUrl: e.annexUrl,
                    annexUrl: e.annexUrl,
                    relativeUrl: e.relativeUrl,
                    fileType: 'mp4',
                    md5Hash: e.annexMd5,
                    id: e.annexId
                }
            })
        },
        _audio() {
            const annexList = this.selectData.annexList || []
            return annexList.filter(e => e.type === 2).map(e => {
                return {
                    annexFileName: e.annexFileName,
                    trueDownloadUrl: e.annexUrl,
                    annexUrl: e.annexUrl,
                    relativeUrl: e.relativeUrl,
                    fileType: 'mp3',
                    md5Hash: e.annexMd5,
                    id: e.annexId
                }
            })
        }
    },
    watch: {
        'info': {
            handler() {
                if (this.info) {
                    this.selectData = fetchDataHandle(this.info || {}, {
                        templateType: 'strToArrNum',
                        fileType: 'strToArrNum'
                    })
                    const annexList = this.selectData.annexList || []
                    this.selectData._video = annexList.filter(e => e.type === 3)
                    this.selectData._audio = annexList.filter(e => e.type === 2)
                    this.form = this.setTemForm(this.selectData)
                } else {
                    this.form = this.setTemForm({})
                }
            },
            immediate: true
        },
        'form.contentSelectName': {
            handler() {
                this.contentSelectChange()
            }
        }
    },
    methods: {
        //指导和宣教赋值
        setTemForm(info = {}) {
            let contentList = []
            let initC = [
                {
                    templateContent: '',
                    templateId: '',
                    templateMode: 1,
                    templateModeTrans: '无'
                }
            ]
            let infoC = info.contentList || []
            //判断父组件的数据里是否存在 无 的选项
            let resList = infoC.filter(item => item.templateMode == 1)
            if (!resList.length) { //不存在无选项
                contentList = [...initC, ...infoC]
            } else {
                contentList = [...infoC]
            }
            const drugsList = info?.drugsList?.length ? info.drugsList.map(e => {
                if (e.id) {
                    e._id = e.id
                    e.doseUnitName = this.store.getDictValue(this.store.getDict('CP00081'), e.doseUnit)
                    e.frequencyName = this.store.getDictValue(this.store.getDict('CP00084'), e.frequency)
                    e.usageMethodName = this.store.getDictValue(this.store.getDict('CP00083'), e.usageMethod)
                }
                return e
            }) : []

            //给更多内容赋值
            let contentSelectName = ''
            let contentSelectNameList = []
            this.checkContentSelect = []
            contentList.forEach(item => {
                if (item.templateMode != 1) {
                    this.checkContentSelect.push(item.templateMode)
                    contentSelectNameList.push(item.templateModeTrans)
                }
                if (contentSelectNameList && contentSelectNameList.length) {
                    contentSelectName = contentSelectNameList.join()
                }
            })

            const form = {
                id: info.id,
                templateType: info.templateType,
                templateName: info.templateName,
                templateMode: info.templateMode || 1,
                fileType: info.fileType || [1],
                templateClassify: info.templateClassify || 1,
                businessType: info.businessType || 1,
                contentList: JSON.parse(JSON.stringify(contentList)),
                contentSelect: contentList.map(e => e.templateMode),
                drugsList: JSON.parse(JSON.stringify(drugsList)),
                annexList: info.annexList || [],
                // 存放上传后返回的id
                _video: JSON.parse(JSON.stringify(info._video || [])),
                _audio: JSON.parse(JSON.stringify(info._audio || [])),
                drugSelect: 1,
                contentSelectName: contentSelectName
            }
            return form
        },
        // 选择的模板内容变化
        contentSelectChange() {
            const cont = this.form.contentList || []
            let val = this.checkContentSelect
            let delValue = []
            cont.forEach(i => {
                if (!val.includes(i.templateMode) && i.templateMode != 1) {
                    delValue.push(i.templateMode)
                }
            })
            if (delValue.length) {
                this.form.contentList = this.form.contentList.filter(e => !delValue.includes(e.templateMode))
                // 药物指导处理
                if (delValue.includes(5)) {
                    this.form.drugsList = []
                }
            }
            const addValue = this.checkContentSelect.filter(e => !cont.find(i => i.templateMode === e))
            if (addValue.length) {
                addValue.forEach(e => {
                    this.form.contentList.push({
                        templateMode: e,
                        templateModeTrans: this.store.getDictValue('DC00084', e),
                        templateContent: undefined,
                        id: undefined
                    })
                })
                // 药物指导处理
                if (addValue.includes(5)) {
                    this.addDrug()
                }
            }
        },
        // 添加药品
        addDrug() {
            this.form.drugsList.push(this.drugItem())
        },
        drugItem() {
            let rowId = 0
            if (this.form.drugsList.length > 0) {
                rowId = Math.max.apply(null, this.form.drugsList.map(item => Number(item._id)))
            }
            return {
                _id: rowId + 1,
                // 药品名称
                drugsName: undefined,
                drugsCode: undefined,
                // 剂量单位,[CP00081]
                doseUnit: 1,
                // 	每次剂量
                dose: undefined,
                // 频次,[CP00084]
                frequency: undefined,
                // 用法,[CP00083]
                usageMethod: undefined,
                // 每日几次
                // dayTime: undefined,
                helpCode: undefined
            }
        },
        drugChange(option, item) {
            item.drugsName = option.chemicalName
            item.helpCode = option.helpCode
        },
        minusDrug(item, index) {
            this.form.drugsList = this.form.drugsList.filter(e => e._id !== item._id)
        },
        getRef() {
            return this.$refs.form
        },
        choiceTel() {
            this.$emit('changeSelect', this.classify)
        },
        contentSelectConfirm() {
            let res = []
            this.contentArray.forEach(item => {
                let selected = this.checkContentSelect.filter(i => i == item.value)
                if (selected && selected.length) {
                    res.push(item.name)
                }
            })
            if (this.checkContentSelect && this.checkContentSelect.length) {
                this.form.contentSelect = this.checkContentSelect.join()
                this.form.contentSelectName = res.join()
            } else {
                this.form.contentSelect = ''
                this.form.contentSelectName = ''
            }
            this.showContentSelect = false

        },
        doseUnitConfirm({ selectedValues, selectedOptions }, item) {
            item.doseUnit = selectedValues[0]
            item.doseUnitName = selectedOptions[0].name
            this.showDoseUnit = false
        },
        frequencyConfirm({ selectedValues, selectedOptions }, item) {
            item.frequency = selectedValues[0]
            item.frequencyName = selectedOptions[0].name
            this.showFrequency = false
        },
        usageMethodConfirm({ selectedValues, selectedOptions }, item) {
            item.usageMethod = selectedValues[0]
            item.usageMethodName = selectedOptions[0].name
            this.showUsageMethod = false
        },
        //删除MP3
        getMP3RemoveInfo(val) {
            this.selectData.annexList.forEach((item, index) => {
                if (item.relativeUrl == val.relativeUrl) {
                    this.selectData.annexList.splice(index, 1)
                }
            })
        },
        //删除MP4
        getMP4RemoveInfo(val) {
            this.selectData.annexList.forEach((item, index) => {
                if (item.relativeUrl == val.relativeUrl) {
                    this.selectData.annexList.splice(index, 1)
                }
            })
        },
        submit() {
            return new Promise((resolve, reject) => {
                if (this.form.contentList && this.form.contentList.length > 1) {
                    this.rules.templateContent[0].required = false
                } else {
                    this.rules.templateContent[0].required = true
                }
                this.$refs.form.validate().then(valid => {
                    /*          if (this.form.fileType.includes(3) && !this.form._video.length) {
                                this.$message.info('请上传视频')
                                return
                              }
                              if (this.form.fileType.includes(2) && !this.form._audio.length) {
                                this.$message.info('请上传音频')
                                return
                              }*/
                    const query = fetchDataHandle({ ...this.form }, {
                        templateType: 'arrToStr',
                        fileType: 'arrToStr'
                    })
                    const annexList = []
                    this._video.forEach(e => {
                        annexList.push({
                            type: 3,
                            annexId: e.annexId,
                            relativeUrl: e.relativeUrl,
                            annexFileName: e.annexFileName
                        })
                    })
                    this._audio.forEach(e => {
                        annexList.push({
                            type: 2,
                            annexId: e.annexId,
                            relativeUrl: e.relativeUrl,
                            annexFileName: e.annexFileName
                        })
                    })
                    query.annexList = annexList
                    const contentList = query.contentList
                    const item = contentList.find(e => e.templateMode == 5)
                    if (item) {
                        const drugsList = query.drugsList
                        let str = ''
                        drugsList.forEach(e => {
                            str = `药品名：${e.drugsName} 剂量：${e.dose} ${this.store.getDictValue('CP00081', e.doseUnit)} 频次：${this.store.getDictValue('CP00084', e.frequency)} 用法：${this.store.getDictValue('CP00083', e.usageMethod)}\n` + str
                        })
                        item.templateContent = str
                    }
                    resolve(query)
                }).catch(e => {
                    reject(e)
                })
            })
        },
        getForm() {
            return new Promise((resolve, reject) => {
                const query = fetchDataHandle({ ...this.form }, {
                    templateType: 'arrToStr',
                    fileType: 'arrToStr'
                })
                const annexList = []
                this._video.forEach(e => {
                    annexList.push({
                        type: 3,
                        annexId: e.annexId,
                        annexUrl: e.annexUrl,
                        relativeUrl: e.relativeUrl,
                        annexFileName: e.annexFileName
                    })
                })
                this._audio.forEach(e => {
                    annexList.push({
                        type: 2,
                        annexId: e.annexId,
                        annexUrl: e.annexUrl,
                        relativeUrl: e.relativeUrl,
                        annexFileName: e.annexFileName
                    })
                })
                query.annexList = annexList
                const contentList = query.contentList
                const item = contentList.find(e => e.templateMode == 5)
                if (item) {
                    const drugsList = query.drugsList
                    let str = ''
                    drugsList.forEach(e => {
                        str = `药品名：${e.drugsName} 剂量：${e.dose} ${this.store.getDictValue('CP00081', e.doseUnit)} 频次：${this.store.getDictValue('CP00084', e.frequency)} 用法：${this.store.getDictValue('CP00083', e.usageMethod)}\n` + str
                    })
                    item.templateContent = str
                }
                resolve(query)
            }).catch(e => {
                console.log('GuideTextVideo', e)
            })
        }
    }
}
</script>

<style lang='less' scoped>

.action-box {
    width: 56px;
    font-size: 20px;

    .svg-icon {
        vertical-align: baseline;
    }
}

.drug-list {
    background-color: #F5F5F5;
}


.health {
    padding: 1px 8px 8px 8px;
    background: #FAFAFA;
    border-radius: 8px;

    .health-cell {
        padding: 8px;
        background: #FFFFFF;
        border-radius: 8px;
    }
}

.no-req-label {
    font-size: 13px;
    color: #595959;
    font-weight: 500;
}

.form-input {
    padding: 8px 12px;
    border-radius: 8px;
}

.input-back {
    background: #FAFAFA;
}

.text-driver {
    border: 1px solid #EEEEEE;
    margin-bottom: 8px;
    margin-top: 8px;
}

.btn-br {
    border-radius: 38px;
    width: 112px;
    padding: 4px 8px;
    height: 26px;
    font-size: 13px;
}

//灰色
.greyColor {
    color: var(--van-text-color-2);
}

//确定按钮颜色
.blueColor {
    color: var(--van-primary-color)
}

.pop-title {
    color: #262626;
    font-size: 16px;
    line-height: 24px;
    font-weight: bold;
}
//:deep(.van-field__error-message) {
//    position: relative!important;
//}
</style>