<template>
    <view>
        <view class="diagnostic-template">
            <view class="templateHeader">
                <block v-if="currentTabClone == '90'">
                    <view class="header-left">
                        <picker v-if="true" @change="bindCountryChange" :value="countryIndex" :range="countries">
                            <label>{{ countries[countryIndex] }}</label>
                            <view class="icon-style">
                                <mp-icon type="outline" icon="arrow" color="#999999" :size="12"></mp-icon>
                            </view>
                        </picker>
                    </view>
                    <view class="header-right"></view>
                </block>
                <block v-else>
                    <view class="header-left">
                        <picker mode="selector" @change="diagMouldChange" :value="id" :range="diagMouldData" range-key="descripts">
                            <label class="tab-diagMould-select">{{ diagMouldData[id].descripts }}</label>
                            <view class="icon-style">
                                <mp-icon type="outline" icon="arrow" color="#999999" :size="12"></mp-icon>
                            </view>
                        </picker>
                    </view>
                    <view class="header-right">
                        <van-search :placeholder="searchPlaceholder" @selectresult="selectedPat" :search="search" />
                    </view>
                </block>
            </view>
            <view class="page-content">
                <view class="content-left">
                    <view class="left-wrap">
                        <view
                            :class="'swiper-tab-list-history ' + (currentlocDiagTempID == item.id ? 'on-history' : '')"
                            :data-current="item.id"
                            @tap="swichNavHistory"
                            v-for="(item, index) in locDiagTemplateList"
                            :key="index"
                        >
                            {{ item.title }}
                        </view>
                    </view>
                </view>
                <view class="content-right">
                    <view class="right-wrap">
                        <view
                            class="row swiper-tab-list-history-diagnos"
                            :data-index="index"
                            :data-current="item.id"
                            @tap="checkItem"
                            v-for="(item, index) in locDiagList"
                            :key="index"
                        >
                            <view :class="'hisDiag-checkbox-diagDesc ' + (item.checked ? 'checkedDesc' : '')">
                                {{ item.diagDesc }}
                            </view>

                            <view class="hisDiag-checkbox-icon">
                                <mp-icon type="field" icon="done" color="#0079FE" :style="'opacity:' + (item.checked ? 1 : 0)"></mp-icon>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <button v-if="canEdit" class="diagnostibutton" :disabled="isLoading" @tap="diagInsuFlag">
            {{ isLoading ? '保存中' : '保存诊断' }}
        </button>
    </view>
</template>

<script>
import Cache from '../../../../../../../utils/cache';
// pages/diagnose/diagnose-component.js
import { $http } from '../../../../../../../config/https.js';
import Util from '../../../../../../../utils/util.js';
export default {
    components: {},
    data() {
        return {
            currentTabClone: 0,
            countries: ['门诊', '急诊', '住院'],
            countryIndex: 0,
            diagMouldData: [],
            id: 0,
            searchPlaceholder: '输入诊断描述查找',
            findDiagDesc: '',
            locDiagTemplateList: [],
            currentlocDiagTempID: '',
            locDiagList: [],
            checkedTempDiag: [],
            userDiagTempList: [],
            locDiagTempList: [],
            saveHisDiagnosFlag: true,
            isLoading: false,
            defaultData: {},
            patID: '',
            select: 0,
            descripts: '',
            search: '',
            currentTabClone: ''
        };
    },
    /**
     * 组件的属性列表
     */
    props: {
        currentTab: {
            type: String
        },
        arryLength: String
    },
    /**
     * 组件的方法列表
     */
    methods: {
        // 组件所在页面的生命周期函数
        handlePageShow: function () {},

        handlePageHide: function () {},
        handlePageResize: function () {},

        // 此处attached的声明会被lifetimes字段中的声明覆盖
        ready: function () {
            this.initData();
        },

        // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
        attached: function () {},

        // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
        attached: function () {},

        initData: function () {
            this.getDiagMoudleType();
        },

        /**
         * 获取诊断模板类型下拉框数据及下诊断默认属性
         */
        getDiagMoudleType: function () {
            let that = this;
            let { locID } = Cache.get('userData');
            let data = {
                params: [
                    {
                        locID: locID
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03050030',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0' && res.result.hasOwnProperty('templetType')) {
                        let { diagCatDefID, diagStatusDefID, diagTypeDefID } = res.result;
                        this.setData(
                            {
                                diagMouldData: res.result.templetType,
                                defaultData: {
                                    diagCatDefID,
                                    diagStatusDefID,
                                    diagTypeDefID
                                }
                            },
                            () => {
                                this.getDiagMoudleData();
                            }
                        );
                    }
                }
            });
        },

        getDiagMoudleData: function () {
            let that = this;
            let { findDiagDesc } = this;
            let { locID } = Cache.get('userData');
            let { admID } = Cache.get('admID');
            let data = {
                params: [
                    {
                        admID: admID,
                        locID: locID,
                        findDesc: findDiagDesc
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03050036',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0' && res.result.length > 0) {
                        let userDiagTemp = [];
                        let locDiagTemp = [];
                        res.result.forEach((element) => {
                            if (element.code === 'User') {
                                userDiagTemp = element.data;
                            }
                            if (element.code === 'Loc') {
                                locDiagTemp = element.data;
                            }
                        });
                        let { diagMouldData, id } = this;
                        let mouldCode = diagMouldData[id].code;
                        if (mouldCode == 'User') {
                            this.setData({
                                currentlocDiagTempID: userDiagTemp[0] ? userDiagTemp[0].id : '',
                                locDiagList: userDiagTemp[0] ? userDiagTemp[0].data : []
                            });
                        }
                        if (mouldCode == 'Loc') {
                            this.setData({
                                currentlocDiagTempID: locDiagTemp[0] ? locDiagTemp[0].id : '',
                                locDiagList: locDiagTemp[0] ? locDiagTemp[0].data : []
                            });
                        }
                        this.setData({
                            userDiagTempList: userDiagTemp,
                            locDiagTempList: locDiagTemp,
                            locDiagTemplateList: userDiagTemp
                        });
                        console.log(this);
                    }
                }
            });
        },

        /**
         * 自定义、历史诊断 `及科室诊断模板切换
         * @param {旧值} newVal
         * @param {新值} oldVal
         */
        diagTabChange: function (newVal, oldVal) {
            this.currentTabClone = this.clone(this.currentTab);
            console.log(`newVal:${newVal}`);
            console.log(`oldVal:${oldVal}`);
            if (newVal !== oldVal) {
                this.setData({
                    currentTabClone: newVal
                });
                console.log(`currentTab:${this.currentTab}==>${typeof this.currentTab}`);
            }
        },

        /**
         * 诊断模板类型下拉框修改
         */
        bindCountryChange: function (e) {
            // console.log('picker country 发生选择改变，携带值为', e.detail.value);
            this.setData({
                countryIndex: e.detail.value
            });
        },

        /**
         * 模板类型切换
         */
        diagMouldChange: function (e) {
            console.log(e.detail.value);
            if (e.detail.value === this.id) {
                return;
            }
            let { diagMouldData, locDiagTempList, userDiagTempList } = this;
            let mouldCode = diagMouldData[e.detail.value].code;
            this.setData({
                id: e.detail.value
            });
            if (mouldCode === 'User') {
                this.setData({
                    locDiagTemplateList: userDiagTempList
                });
                //默认显示第一个
                console.log(userDiagTempList);
                if (userDiagTempList.length > 0 && userDiagTempList[0].data.length > 0) {
                    this.setData({
                        currentlocDiagTempID: userDiagTempList[0].id,
                        locDiagList: userDiagTempList[0].data
                    });
                }
            }
            if (mouldCode === 'Loc') {
                this.setData({
                    locDiagTemplateList: locDiagTempList
                });
                console.log(locDiagTempList);
                if (locDiagTempList.length > 0 && locDiagTempList[0].data) {
                    this.setData({
                        currentlocDiagTempID: locDiagTempList[0].id,
                        locDiagList: locDiagTempList[0].data
                    });
                } else {
                    this.setData({
                        locDiagList: []
                    });
                }
            }
            // console.log(this.data.locDiagList)
        },

        /**
         * 诊断模板列表切换
         * @param {*} value
         */
        swichNavHistory: function (e) {
            let currentTab = e.target.dataset.current;
            let that = this;
            let { currentlocDiagTempID, locDiagTemplateList } = this;
            if (currentlocDiagTempID === currentTab) {
                return false;
            } else {
                this.setData({
                    currentlocDiagTempID: currentTab,
                    locDiagList: locDiagTemplateList.filter((element) => element.id === currentTab)[0].data
                });
                // console.log(this.data.currentHisAdmID);
                //获取诊断列表
                // this.findLocDiagnosList();
            }
        },

        findLocDiagnosList: function () {
            let { locDiagList, currentlocDiagTempID, locDiagList2 } = this;
            // console.log(currentHisAdmID)
            if (parseInt(currentlocDiagTempID) % 2 === 0) {
                // console.log(historyDiagList)
                this.setData({
                    locDiagList: locDiagList
                });
            } else {
                // console.log(historyDiagList2)
                this.setData({
                    locDiagList: locDiagList2
                });
            }
            console.log(this.locDiagList);
        },

        /**
         * 搜索患者
         */
        searchFun: function (value) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve([
                        {
                            text: '彭若谷',
                            value: 1
                        },
                        {
                            text: '刘建安',
                            value: 2
                        }
                    ]);
                }, 200);
            });
        },

        /**
         * 选中患者
         */
        selectedPat: function (e) {
            console.log('select result', e.detail.item.value);
            this.setData({
                patID: e.detail.item.value
            });
        },

        /**
         * 选中诊断
         * @param {*} event
         */
        checkboxChange: function (event) {
            let checkedTempDiag = event.detail;
            this.setData({
                checkedTempDiag: checkedTempDiag.value,
                saveHisDiagnosFlag: checkedTempDiag.value.length > 0 ? false : true
            });
        },

        /**
         * 保存诊断
         */
        saveHisDiagnos: Util.debounce(function () {
            let { checkedTempDiag, locDiagList, defaultData } = this;
            let { diagCatDefID, diagStatusDefID, diagTypeDefID } = defaultData;
            let { locID, userID } = Cache.get('userData');
            let { admID } = Cache.get('patientData');
            if (admID == '' || admID == undefined) {
                uni.showToast({
                    title: '请选择患者',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }
            // debugger
            let diagData = [];
            for (let index = 0; index < locDiagList.length; index++) {
                const item = locDiagList[index];
                if (item.checked) {
                    let diag = {
                        ICDCode: item.ICDCode,
                        ICDID: item.ICDID,
                        catID: diagCatDefID,
                        diagCMark: '',
                        diagCMarkID: item.CMark,
                        diagCode: item.diagCode,
                        diagDesc: item.diagDesc,
                        diagID: item.diagID,
                        diagStatusID: diagStatusDefID,
                        diagTypeID: diagTypeDefID,
                        mainDiagID: 'N'
                    };
                    diagData.push(diag);
                }
            }
            if (diagData.length == 0) {
                this.setData({
                    isLoading: false
                });
                uni.showToast({
                    title: '请选择诊断',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }
            let data = {
                params: [
                    {
                        admID: admID,
                        // "admID":"1286",
                        locID: locID,
                        userID: userID,
                        diagData: diagData
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03050032',
                data: data,
                success: function (res) {
                    this.setData({
                        isLoading: false
                    });
                    let iconCode;
                    if (res.errorCode == '0') {
                        iconCode = 'success';
                    } else {
                        iconCode = 'none';
                    }
                    uni.showToast({
                        title: res.errorMessage,
                        icon: iconCode,
                        duration: 2000
                    });
                    let pages = getCurrentPages(); //获取当前页面js里面的pages里的所有信息。
                    let prevPage = pages[pages.length - 2];
                    prevPage.setData(
                        {
                            // 将我们想要传递的参数在这里直接setData。上个页面就会执行这里的操作。
                            select: 1
                        },
                        () => {
                            uni.navigateBack({});
                        }
                    );
                },
                fail: function () {
                    this.setData({
                        isLoading: false
                    });
                }
            });
        }),

        /**
         * 勾选诊断列表
         */
        checkItem: function (event) {
            let index = event.currentTarget.dataset.index;
            let { locDiagList } = this;
            locDiagList[index].checked = !locDiagList[index].checked;
            this.setData({
                locDiagList
            });
        },

        diagInsuFlag: function (e) {
            this.setData({
                isLoading: true
            });
            var that = this;
            if (this.arryLength == 0) {
                let patientData = Cache.get('patientData');
                let userData = Cache.get('userData');
                let { locDiagList } = this;
                let params = {
                    params: [
                        {
                            admID: patientData.admID,
                            hospID: userData.hospID,
                            diagID: locDiagList[0].diagID,
                            //诊断ID
                            ICDID: locDiagList[0].ICDID,
                            //ICD诊断ID
                            CMark: locDiagList[0].CMark
                        }
                    ]
                };
                $http.post('urlDeault', this, {
                    code: '03100139',
                    data: params,
                    success: function (res) {
                        this.setData({
                            isLoading: false
                        });
                        let errorCode = res.errorCode;
                        if (errorCode == '0') {
                            if (res.result.reasonFlag == 'Y' && res.result.insuFlag == 'N') {
                                uni.showModal({
                                    content: res.result.insuDesc,
                                    success(res) {
                                        if (res.confirm) {
                                            that.saveHisDiagnos();
                                        } else if (res.cancel) {
                                        }
                                    }
                                });
                            } else {
                                that.saveHisDiagnos();
                            }
                        }
                    },
                    fail: function () {
                        this.setData({
                            isLoading: false
                        });
                    }
                });
            } else {
                that.saveHisDiagnos();
            }
        }
    },
    computed: {
        // 是否可编辑：changeDataFlag 为 'N'（已结束/只读查看）时不可编辑
        canEdit() {
            let pd = Cache.get('patientData') || {};
            return pd.changeDataFlag != 'N';
        }
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
        // 处理小程序 ready 生命周期
        this.$nextTick(() => this.ready());
    },
    moved: function () {},
    destroyed: function () {},
    created: function () {},
    watch: {
        currentTab: {
            handler: function (newVal, oldVal) {
                this.currentTabClone = this.clone(this.currentTab);
                console.log(`newVal:${newVal}`);
                console.log(`oldVal:${oldVal}`);
                if (newVal !== oldVal) {
                    this.setData({
                        currentTabClone: newVal
                    });
                    console.log(`currentTab:${this.currentTab}==>${typeof this.currentTab}`);
                }
            },

            immediate: true
        }
    }
};
</script>
<style>
/* @import '../../../Entry.css'; */

.diagnostic-template {
    position: absolute;
    bottom: 0rpx;
    left: 0;
    right: 0;
    top: 0;
    overflow: auto;
}

.tab-diagMould-select {
    font-size: 32rpx;
    align-self: center;
    margin-left: 15rpx;
    margin-top: 26rpx;
    width: 150rpx;
    height: 62rpx;
    /* padding-left: 10rpx; */
    text-align: center;
}

.diag-piciker {
    width: 100%;
    height: 90rpx;
    background-color: #fff;
}

.tab-diagMould {
    display: flex;
    flex-direction: row;
    color: #1890ff;
    font-size: 33rpx;
}

.tab-diagMould-icon {
    margin-top: 24rpx;
}

.swiper-tab-history {
    display: flex;
    flex-direction: column;
    width: 320rpx;
    height: 900rpx;
    background-color: rgba(255, 255, 255, 1);
    padding-left: 10rpx;
}

.swiper-tab-list-history {
    display: flex;
    align-items: center;
    height: 100rpx;
    font-size: 30rpx;
    width: 100%;
    color: #797979;
    padding-left: 10rpx;
}

.on-history {
    color: #1890ff;
    border-left: 5rpx solid #1890ff;
}

.swiper-tab-history-diagnos {
    background-color: rgba(255, 255, 255, 1);
    margin-left: 10rpx;
    padding-left: 15rpx;
    display: flex;
    flex-direction: column;
    width: 100%;
}

.swiper-tab-list-history-diagnos {
    font-size: 30rpx;
    /* display: inline-block; */
    width: calc(100% - 20rpx);
    color: #797979;
    display: flex;
    padding-left: 20rpx;
    border-bottom: 1px solid #eee;
}

.on-history-diagnose {
    color: #1890ff;
}

.hisDiag-checkbox-label {
    /* width: calc(100%-24); */
    width: 360rpx;
}

.hisDiag-checkbox-diagDesc {
    font-size: 32rpx;
    width: 85%;
    float: left;
    line-height: 80rpx;
}

.checkedDesc {
    color: #1890ff;
}

.hisDiag-checkbox-icon {
    width: 15%;
    float: right;
    line-height: 80rpx;
}

.btn2 {
    /* margin-left: 5px; */
    font-size: 14px;
    color: rgb(247, 247, 248);
    width: 210rpx !important;
    font-weight: 521;
    background-color: #0079fe;
}

.pickerStyle .weui-cell > .weui-cell__ft {
    background-color: red;
}

/* .van-search {
  padding: 0 !important;
} */
</style>
