import { debounce } from "lodash";
import { getPatientInfoDetail, getSwitch, getPatientCnDrgInfo, getPatientInfo, getFeeDetail, getDiagnosisDictionary } from "../../../../commons/services"
import headerTplFun from '../tpls/header.hbs'
import ybContentTplFun from '../tpls/ybContent.hbs'
import cnContentTplFun from '../tpls/cnContent.hbs'
import feeListTplFun from '../tpls/feeList.hbs'
import mockGroupTplFun from '../tpls/mockGroup.hbs'
import utils from '../../../../commons/utils'
import "../css/index.less";
const isNullOrUndefined = val => val !== null && val !== undefined ? val : '--';

const formaterPatientInfo = (patientInfoDetail, patientCnDrgInfo) => {
    const { patientInfo, forecastInfoList, qualityControlList } = patientInfoDetail;
    const { caseId, inpId, isDrg } = patientInfo || {};
    const { drgCode, drgName, caseTypeName, caseRw, rate, ylzfy, feeSettle, feeProfit } = forecastInfoList[0] || {};
    return {
        hdObj: {
            caseId: isNullOrUndefined(caseId),
            inpId: isNullOrUndefined(inpId),
        },
        ybObj: {
            isDrg: isNullOrUndefined(isDrg),
            drgGroup: drgCode && drgName ? (drgCode + '-' + drgName) : '--',
            caseTypeName: isNullOrUndefined(caseTypeName),
            caseRw: isNullOrUndefined(caseRw),
            rate: isNullOrUndefined(rate),
            ylzfy: isNullOrUndefined(ylzfy),
            feeSettle: isNullOrUndefined(feeSettle),
            feeProfit: isNullOrUndefined(feeProfit),
        },
        cnObj:{
            drgGroup: patientCnDrgInfo.drgCode && patientCnDrgInfo.drgName ? (patientCnDrgInfo.drgCode + '-' + patientCnDrgInfo.drgName) : '--',
            quanZhong: isNullOrUndefined(patientCnDrgInfo.rw),
        },
        qualityControlList,
        isQuality: qualityControlList && qualityControlList.length > 0,
        forecastInfoList
    };
};

/** 转换最大值 */
const calcMaxWidth = arr => {
    let max = 0;
    arr.forEach((item) => {
        max = typeof item === 'number' ? Math.max(max, item.toString().length) : max;
    });
    return max * 10;
};

const getChartOptions = (yAxis, statistics) => {
    return {
      grid: {
        top: 16,
        left: 100,
        height: 60,
        right: calcMaxWidth(statistics),
      },
      xAxis: {
        show: false,
      },
      yAxis: {
        type: 'category',
        axisTick: {
          show: false,
        },
        axisLabel: {
          interval: 0,
        },
        data: yAxis
      },
      series: [
        {
          type: 'bar',
          label: {
            show: true,
            position: 'right',
            color: '#333',
          },
          data: statistics.map((item) => item ?? 0).reverse(),
          barWidth: 18,
          itemStyle: {
            color: '#3367D6',
          },
        }
      ]
    };
};

layui.config({
    base: './static/extend/' //扩展模块所在目录
}).extend({
    drawer: 'drawer/drawer',
    loading: 'loading/loading',
    selectInput: 'selectInput/selectInput',
}).use(['drawer', 'loading', 'selectInput', 'table'], function() {
    $(window).loading('show')
    // 浏览器窗口高度
    const windowHeight = $(window).height()
    const headerDom = $("#header")
    const contentDom = $("#content")
    const pid = utils.getUrlParam('pid')
    const hosCode = utils.getUrlParam('hosCode')
    const params = { pid: '165390800jflyq',hosCode: 'jflyq' }
    let patientInfoDetail = {}
    let patientInfo = {}
    let feeDetail = []

    /**
     * 前置接口初始化
     */
    const fetchArr = [
        getSwitch(params),
        getPatientInfoDetail(params),
        getPatientCnDrgInfo(params),
        getPatientInfo(params),
        getFeeDetail(params)
    ]
    Promise.all(fetchArr).then(function(res){
        const [switchs, infoDetail, cnDrgInfo, patient,fee] = res;
        if (switchs.data.status === '1') {
            $("#navTab").show()
        }
        patientInfoDetail = formaterPatientInfo(infoDetail.data, cnDrgInfo.data)
        patientInfo = patient.data
        feeDetail = fee.data
        headerDom.html(headerTplFun(patientInfoDetail.hdObj))
        contentDom.html(ybContentTplFun(patientInfoDetail.ybObj))
        $(window).loading('hide')
    })

    /**
     * 医保DRG、CN-DRG点击切换
     */
     $("body").on("click", "#navTab span", function(){
        if (!$(this).hasClass('select')) {
            const lang = $(this).attr("lang")
            if (lang === 'yb') {
                contentDom.html(ybContentTplFun(patientInfoDetail.ybObj))
            } else {
                contentDom.html(cnContentTplFun(patientInfoDetail.cnObj))
            }
            $(this).addClass('select').siblings().removeClass('select')
        }
    })

    /**
     * 费用明细
     */
    const tableHeight = windowHeight - 257;//表格高度
    $('body').on("click", "#linkYlzfy", function(){
        const barOptions = getChartOptions(['预估结算金额', 'DRG医疗总费用'], [patientInfoDetail.ybObj.feeSettle, patientInfoDetail.ybObj.ylzfy]);
        const { feeInsCoordinated, feeInsDiag, feeInsOther, feeZiFei, feeZiLi, feeZifu } = patientInfo
        layui.drawer.render({
            title: '费用明细',
            offset: 'r',
            width: "600px",
            closeBtn: true,
            content: `<div class="fee-content">${feeListTplFun({
                feeInsCoordinated: isNullOrUndefined(feeInsCoordinated),
                feeInsDiag: isNullOrUndefined(feeInsCoordinated),
                feeInsOther: isNullOrUndefined(feeInsCoordinated),
                feeZiFei: isNullOrUndefined(feeInsCoordinated),
                feeZiLi: isNullOrUndefined(feeInsCoordinated),
                feeZifu: isNullOrUndefined(feeInsCoordinated),
            })}</div>`,
            success: function(layero, index){
                // 内容区域高度
                $(".fee-content").height(windowHeight-43)

                // 图表渲染
                var barDom = document.getElementById('feechart');
                var barChart = echarts.init(barDom);
                barChart.setOption(barOptions);

                // 表格渲染
                layui.table.render({
                    elem: '#feeMain',
                    height: tableHeight,
                    cols: [[
                        { field: 'itemName', title: '收费类型'},
                        { field: 'totalCost', title: '总费用', width: '40%'},
                        { field: 'costRate', title: '费用占比'}
                    ]],
                    data: feeDetail
                });
                // 设置子表格默认数据
                const [{itemList}] = feeDetail
                layui.table.render({
                    elem: '#feeSub',
                    height: tableHeight,
                    cols: [[
                        { field: 'itemName', title: '项目明细', width: '55%'},
                        { field: 'amount', title: '数量', width: '20%'},
                        { field: 'totalFee', title: '金额', width: '25%'}
                    ]],
                    data: itemList
                });
                // 主表格点击切换子表格数据
                layui.table.on('row(feeMain)', function(obj){
                    let data = obj.data;
                    layui.table.reload("feeSub", {data: data.itemList});
                    obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
                });
            }
        });
    })

    /**
     * 模拟分组
     */
    $("body").on("click", "#mockGroup", function(){
        layui.drawer.render({
            title: false,
            offset: 'r',
            width: "600px",
            content: `<div class="mock-container">${mockGroupTplFun()}</div>`,
            success: function(layero, index){
                $('.mock-content').height(windowHeight - 145)
                layui.selectInput.render({
                    elem: '#simDiagnosis',
                    name: 'simDiagnosis',
                    initValue: '',
                    placeholder: '请选择当前主要诊断',
                    hasSelectIcon: true,
                    remoteSearch: true,
                    parseData: function (data) {
                        return data.map(item => ({
                            name: `${item.value}(${item.key})`,
                            value: `${item.key}-${item.value}`,
                        }))
                    },
                    remoteMethod: debounce(function (value, cb) {
                        getDiagnosisDictionary({
                            search: value, 
                            pageNum: 1,
                            pageSize: 10,
                            systemEnum: 'MR',
                            checkZe: false,
                            type: 'INHOS',
                            ...params,
                         }, function (res) {
                            cb(res.list);
                        })
                    }, 500)
                });
            }
        });
    })
});