<!--
  * 病例表
  *
  * @Author:    HMM
  * @Date:      2024-01-11 15:18:32
  * @Copyright  gdxz
-->
<template>
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form" style="border-radius: 10px; padding: 10px 10px;">
        <a-row class="smart-query-form-row">
            <a-form-item label="" class="smart-query-form-item">
                <a-input style="width: 200px" v-model:value="queryForm.name" placeholder="请输入关键字" />
            </a-form-item>
            <a-form-item label="" class="smart-query-form-item">
                <a-select style="width: 150px;" @change="provChange" placeholder="选择省份" v-model:value="queryForm.provId"
                    :allowClear="true">
                    <a-select-option :value="prov.id" v-for="prov in provList">{{ prov.name }}</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="" class="smart-query-form-item">
                <a-select style="width: 150px;" placeholder="选择市区" @change="cityChange" v-model:value="queryForm.cityId"
                    :allowClear="true">
                    <a-select-option :value="city.id" v-for="city in cityList">{{ city.name }}</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="" class="smart-query-form-item">
                <a-select style="width: 250px;" placeholder="选择医院" v-model:value="queryForm.hospitalUuid"
                    :allowClear="true">
                    <a-select-option :value="hospital.uuid" v-for="hospital in hospitalList">{{ hospital.name
                    }}</a-select-option>
                </a-select>
            </a-form-item>
            <!-- <a-form-item label="" class="smart-query-form-item">
                <SmartEnumSelect width="150px" v-model:value="queryForm.caseType" enumName="CASETYPE" placeholder="病例类型" />
            </a-form-item> -->
          
            <a-form-item label="" class="smart-query-form-item">
                <a-range-picker :valueFormat="dateFormat"  v-model:value="queryForm.examineTime" :disabled-date="disabledDate"/>
            </a-form-item>
              <a-form-item label="" class="smart-query-form-item">
                <SmartEnumSelect width="100px" v-model:value="queryForm.status" enumName="CASESTATUS" placeholder="病例状态" />
            </a-form-item>
            <a-form-item label="" class="smart-query-form-item">
                <SmartEnumSelect width="100px" v-model:value="queryForm.settlementFlag" enumName="CASESettlementFlag"
                    placeholder="结算状态" />
            </a-form-item>
            <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="queryData">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    查询
                </a-button>
                <!-- <a-button @click="resetQuery" class="smart-margin-left10">
                    <template #icon>
                        <ReloadOutlined />
                    </template>
                    重置
                </a-button> -->

                <span v-privilege="'case-system:case:excle'">
                    <a-popconfirm title="确认导出excel" placement="bottom" ok-text="确认" cancel-text="取消" @confirm="exportExcel">
                        <a-button class="smart-margin-left10" >
                            <template #icon>
                                <DownloadOutlined />
                            </template>
                            导出列表excel
                        </a-button>
                    </a-popconfirm>
                </span>
                <span v-privilege="'case-system:case:exportExpertCaseExceli'">
                    <a-popconfirm title="确认导出结算excel" placement="bottom" ok-text="确认" cancel-text="取消" @confirm="exportSettlementExcel">
                        <a-button class="smart-margin-left10" >
                            <template #icon>
                                <DownloadOutlined />
                            </template>
                           导出结算excel
                        </a-button>
                    </a-popconfirm>
                </span>
                <span v-privilege="'case-system:case:caseplatformCaseSettlementImport'">
                    <a-upload
                    class="smart-margin-left10"
                        name="file"
                        accept=".xls,.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                        :headers="headers"
                        :showUploadList="false"
                        :customRequest="uploadMethod"
                    >
                        <a-button>
                        <upload-outlined></upload-outlined>
                        导入结算excel
                        </a-button>
                    </a-upload>
        </span>
                
            </a-form-item>
        </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card size="small" :bordered="false" :hoverable="true" style="border-radius: 10px;">
        <!---------- 表格操作行 begin ----------->
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
                <a-typography-title :level="5">病例管理</a-typography-title>
                <!-- <a-button @click="showForm()" type="primary" size="small">
                    <template #icon>
                        <PlusOutlined />
                    </template>
                    新建
                </a-button> -->

            </div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
            </div>
        </a-row>
        <!---------- 表格操作行 end ----------->

        <!---------- 表格 begin ----------->
        <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading"
            :pagination="false">
            <template #bodyCell="{ text, record, column }">
                <template v-if="column.dataIndex === 'createTime'">
                    <span>{{ text.substring(0, 11) }}</span>
                </template>
                  <template v-if="column.dataIndex === 'examineTime'">
                    <span >{{ text?text.substring(0, 11):'--' }}</span>
                   
                </template>
                
                 <template v-if="column.dataIndex === 'signStatus'">
                    <a-tag :color="text == 1?'success':'error'" >{{text == 1?'已签署':'未签署'}}</a-tag>
                </template>
                <template v-if="column.dataIndex === 'caseType'">
                    <a-tag :color="$smartEnumPlugin.getColorByValue('CASETYPE', item)" v-for="item in formatJson(record.caseType)">{{
                        $smartEnumPlugin.getDescByValue('CASETYPE', item) }}</a-tag>
                </template>
                <template v-if="column.dataIndex === 'status'">
                    <a-tag :color="$smartEnumPlugin.getColorByValue('CASESTATUS', text)">{{
                        $smartEnumPlugin.getDescByValue('CASESTATUS', text) }}</a-tag>
                </template>
                <template v-if="column.dataIndex === 'settlementFlag'">
                    <a-tag :color="$smartEnumPlugin.getColorByValue('CASESettlementFlag', text)">{{
                        $smartEnumPlugin.getDescByValue('CASESettlementFlag', text) }}</a-tag>
                </template>
                <template v-if="column.dataIndex === 'action'">
                    <div class="smart-table-operate">
                        <a-button @click="showForm(record.id)" type="link" v-privilege="'case-system:case:select'">查看</a-button>
                        <span v-privilege="'case-system:case:examine'">
                            <a-popconfirm title="请选择审核结果" placement="topRight" ok-text="审核通过" cancel-text="审核不通过"
                                @confirm="confirmExamine(record)" @cancel="cancelExamine(record)" v-if="record.status == 0">
                                <a-button type="link">审核</a-button>
                            </a-popconfirm>
                        </span>
                        <a-button v-if="record.status == 2" @click="showReason(record.reason)" type="link" v-privilege="'case-system:case:reason'">原因</a-button>
                        <span v-privilege="'case-system:case:settlement'">
                            <a-popconfirm title="确认结算？" placement="topRight" ok-text="结算" cancel-text="取消"
                                @confirm="settlement(record.id)" v-if="record.status == 1 && record.settlementFlag == 0">
                                <a-button type="link">结算</a-button>
                            </a-popconfirm>
                        </span>
                         <a-button  type="link" :href="record.signLinkPc" v-if="record.signLinkPc && record.signStatus==1" v-privilege="'case-system:case:protocolAddress'">协议地址</a-button>
                    </div>
                </template>
            </template>
        </a-table>
        <!---------- 表格 end ----------->

        <div class="smart-query-table-page">
            <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS"
                :defaultPageSize="queryForm.pageSize" v-model:current="queryForm.pageNum"
                v-model:pageSize="queryForm.pageSize" :total="total" @change="queryData" @showSizeChange="queryData"
                :show-total="(total) => `共${total}条`" />
        </div>

        <CaseplatformCaseForm ref="formRef" @reloadList="queryData" />

        <a-modal v-model:visible="cancelExamineVisible" title="审核不通过" @ok="submitCancelExamine">
            <a-textarea v-model:value="current_reason" placeholder="输入不通过原因" :auto-size="{ minRows: 2, maxRows: 8 }" />
        </a-modal>

        <a-modal v-model:visible="showReasonVisible" title="原因">
            <div style='white-space: pre-wrap;'>{{ show_reason }}</div>
            <template #footer>

            </template>
        </a-modal>

    </a-card>
    <br>
</template>
<script setup>
import dayjs from 'dayjs';
import { reactive, ref, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { caseplatformCaseApi } from '/@/api/business/case/caseplatform-case-api';
import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { smartSentry } from '/@/lib/smart-sentry';
import TableOperator from '/@/components/support/table-operator/index.vue';
import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';
import CaseplatformCaseForm from './caseplatform-case-form.vue';
import { areaApi } from '/@/api/business/area/area-api';
import { statisticsApi } from '/@/api/business/case/statistics-api';
import { employeeApi } from '/@/api/system/employee/employee-api';
// ---------------------------- 表格列 ----------------------------
const dateFormat = 'YYYY-MM-DD HH:mm:ss'
const cancelExamineVisible = ref(false)
const showReasonVisible = ref(false)
const disabledDate=(current)=>{
    return current && current > dayjs().endOf('day');
}
function showReason(reason) {
    showReasonVisible.value = true
    show_reason.value = reason
}

const show_reason = ref()
const current_reason = ref()
const current_caseId = ref()

const columns = ref([
    {
        title: '姓名',
        dataIndex: 'expertName',
        ellipsis: true,
    },
    {
        title: '省份',
        dataIndex: 'expertProvName',
        ellipsis: true,
    },
    {
        title: '城市',
        dataIndex: 'expertCityName',
        ellipsis: true,
    },
    {
        title: '医院',
        dataIndex: 'expertHospitalName',
        ellipsis: true,
    },
    {
        title: '患者',
        dataIndex: 'userName',
        ellipsis: true,
    },
    {
        title: '患者ID',
        dataIndex: 'uid',
        ellipsis: true,
    },
    // {
    //     title: '类型',
    //     dataIndex: 'caseType',
    //     ellipsis: true,
    //     width: 130
    // },
     {
        title: '签署状态',
        dataIndex: 'signStatus',
        ellipsis: true,
        width: 80
    },
     
     {
        title: '签署时间',
        dataIndex: 'examineTime',
        ellipsis: true,
        width: 100
    },
    {
        title: '提交时间',
        dataIndex: 'createTime',
        ellipsis: true,
        width: 100
    },
    {
        title: '病例状态',
        dataIndex: 'status',
        width: 80
    },
    {
        title: '结算状态',
        dataIndex: 'settlementFlag',
        width: 80
    },

    {
        title: '操作',
        dataIndex: 'action',
        fixed: 'right',
        width: 155,
    },
]);

// ---------------------------- 查询数据表单和方法 ----------------------------

const queryFormState = {
    name: undefined, //name
    caseType: undefined, //病例类型
    status: undefined, //0待审核 1审核通过 2审核不通过
    settlementFlag: undefined, //0未结算 1已结算
    pageNum: 1,
    pageSize: 10,
};
const formatJson = (obj) => {
    if(!obj) return [];
    return JSON.parse(obj);

};

const uploadMethod=(file)=>{
   let formData=new FormData();
   formData.append('file', file.file,file.name);
     caseplatformCaseApi.importData(formData).then((res)=>{
    console.log(res);
     message.success(`上传成功`);
     queryData();
  }).catch((err)=>{
    console.log(err);
    message.error(`上传失败`);
  })
}
// 查询表单form
const queryForm = reactive({ ...queryFormState });
// 表格加载loading
const tableLoading = ref(false);
// 表格数据
const tableData = ref([]);
// 总数
const total = ref(0);

// 重置查询条件
function resetQuery() {
    let pageSize = queryForm.pageSize;
    Object.assign(queryForm, queryFormState);
    queryForm.pageSize = pageSize;
    queryData();
}

// 查询数据
async function queryData() {
    tableLoading.value = true;
    try {
        let queryResult = await caseplatformCaseApi.queryPage(queryForm);
        tableData.value = queryResult.data.list;
        total.value = queryResult.data.total;
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        tableLoading.value = false;
    }
}

// 审核
async function examine(caseId, status) {
    SmartLoading.show()
    try {
        await caseplatformCaseApi.examine(caseId, status);
        message.success("操作成功")
    } catch (e) {
        console.log(e)
    } finally {
        SmartLoading.hide()
        queryData()
    }
}

// 结算
async function settlement(caseId) {
    SmartLoading.show()
    try {
        await caseplatformCaseApi.settlement(caseId);
        message.success("操作成功")
    } catch (e) {
        console.log(e)
    } finally {
        SmartLoading.hide()
        queryData()
    }
}

// 审核
async function submitCancelExamine() {
    SmartLoading.show()
    try {
        await caseplatformCaseApi.cancelExamine({ caseId: current_caseId.value, reason: current_reason.value });
        message.success("操作成功")
    } catch (e) {
        console.log(e)
    } finally {
        cancelExamineVisible.value = false
        current_reason.value = undefined
        current_caseId.value = undefined
        SmartLoading.hide()
        queryData()
    }
}

// 导出数据
async function exportExcel() {
    SmartLoading.show()
    try {
        caseplatformCaseApi.exportEasyExcel(queryForm);
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        SmartLoading.hide()
    }
}

// 导出结算数据
async function exportSettlementExcel() {
    SmartLoading.show()
    try {
        caseplatformCaseApi.exportSettlementExcel(queryForm);
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        SmartLoading.hide()
    }
}

function confirmExamine(e) {
    console.log(e)
    console.log(e.id)
    examine(e.id, 1)
}

function cancelExamine(e) {
    cancelExamineVisible.value = true
    current_caseId.value = e.id
}

function provChange(e) {
    console.log(e)
    queryForm.cityId = undefined
    queryForm.hospitalUuid = undefined
    cityList.value = []
    hospitalList.value = []
    if (e) {
        getCity(e)
        getHospitalList({ provId: e })
    }
}

function cityChange(e) {
    console.log(e)
    queryForm.hospitalUuid = undefined
    hospitalList.value = []
    if (e) {
        getHospitalList({ cityId: e })
    }
}

const provList = ref()

// 查询数据
async function getProvList() {
    SmartLoading.show()
    try {
        let queryResult = await employeeApi.getRoleProv();
        provList.value = queryResult.data;
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        SmartLoading.hide()
    }
}

const cityList = ref()

// 查询数据
async function getCity(parent) {
    SmartLoading.show()
    try {
        let queryResult = await areaApi.cityList(parent);
        cityList.value = queryResult.data;
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        SmartLoading.hide()
    }
}

const hospitalList = ref()

// 查询数据
async function getHospitalList(param) {
    SmartLoading.show()
    try {
        let queryResult = await statisticsApi.getHospitalList(param);
        hospitalList.value = queryResult.data;
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        SmartLoading.hide()
    }
}

onMounted(()=>{
    getProvList()
    queryData()
});

// ---------------------------- 添加/修改 ----------------------------
const formRef = ref();

function showForm(data) {
    formRef.value.show(data);
}

</script>
