<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="关 键 字">
            <el-input v-model="queryParams.articleTitle" placeholder="请输入用户姓名、手机号" maxlength="20" clearable style="width: 220px"/>
        </el-form-item>
        <el-form-item label="所属位置" prop="placeIdList">
            <el-cascader v-model="queryParams.placeIdList"
            :options="placeOptions" :filterable="true" style="width: 240px" :show-all-levels="false"
            :props="{
                multiple: true,
                emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
                checkStrictly: false,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
                value:'id',label:'label'
            }" clearable collapse-tags >
            </el-cascader>
        </el-form-item>
        <el-form-item label="所属组织" prop="deptIdList">
            <el-cascader v-model="queryParams.deptIdList"
            :options="deptOptions" :filterable="true" placeholder="请选择所属组织" style="width: 240px" :show-all-levels="false"
            :props="{
                multiple: true,
                emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
                checkStrictly: false,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
                value:'id',label:'label'
            }" clearable collapse-tags >
            </el-cascader>
        </el-form-item>
        <el-form-item label="慢性病">
            <el-select v-model="queryParams.chronicList" placeholder="请选择慢性病"  multiple style="width: 220px" clearable collapse-tags>
                <el-option v-for="item in chronicOptions"
                    :key="item.chronicId"
                    :label="item.chronicName"
                    :value="item.chronicId"
                ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="饮食医嘱">
            <el-select v-model="queryParams.doctorAdvice" placeholder="请选择饮食医嘱"  multiple style="width: 220px" clearable collapse-tags>
                <el-option v-for="item in doctorAdviceOptions"
                    :key="item.doctorAdvice"
                    :label="item.doctorAdviceName"
                    :value="item.doctorAdvice"
                ></el-option>
            </el-select>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
        </el-form>


        <el-table v-loading="loading" :data="tableListData" height="800" ref="multipleTable">
            <el-table-column label="用户姓名" align="center" prop="nickName" :show-overflow-tooltip="true" >
            </el-table-column>
            <el-table-column label="用户手机号" align="center" prop="mobile" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="位置信息" align="center" prop="placeFullName" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="饮食医嘱" align="center" prop="doctorAdvice" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span v-if="scope.row.doctorAdvice==1">禁食</span>
                    <span v-if="scope.row.doctorAdvice==2">流食</span>
                    <span v-if="scope.row.doctorAdvice==3">半流食</span>
                    <span v-if="scope.row.doctorAdvice==4">治疗饮食</span>
                </template>
            </el-table-column>
            <el-table-column label="就诊号" align="center" prop="doctorNum" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="住院号" align="center" prop="hospitalNum" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="住院日期" align="center" prop="inpatientDate" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="慢性病" align="center" prop="chronicNames" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="劳动强度" align="center" prop="labourIntensity" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                  <span v-if="scope.row.labourIntensity==1">轻劳动</span>
                  <span v-if="scope.row.labourIntensity==2">中等强度劳动</span>
                  <span v-if="scope.row.labourIntensity==3">重强度劳动</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        @click="handleUpdate(scope.row)"
                    >修改</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        @click="handleDelete(scope.row)"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
        />

        <!-- 对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="980px" append-to-body>
            <el-form ref="form" :model="form"  label-width="90px">
                <el-row justify="center">
                  <table  align="center" width="80%" cellspacing="0">
                    <tr >
                      <td  colspan="4" class="table-title">个人信息</td>
                    </tr>
                    <tr >
                      <td  class="table-label"><i  class="text-red">*</i> <span >用户姓名</span></td>
                      <td  class="table-content"><span >{{form.nickName}}</span></td>
                      <td  class="table-label"><i  class="text-red">*</i> <span >用户编号</span></td>
                      <td  class="table-content"><span >{{form.userId}}</span></td>
                    </tr>
                    <tr >
                      <td  class="table-label"><i  class="text-red">*</i> <span >所属组织</span></td>
                      <td  class="table-content"><span >{{form.orgFullName}}</span></td>
                      <td  class="table-label"><span >用户类别</span></td>
                      <td  class="table-content"><span >{{form.userType==1?'其它':'系统'}}</span></td>
                    </tr>
                    <tr >
                      <td  class="table-label"><span >用户手机号</span></td>
                      <td  class="table-content"><span >{{form.mobile}}</span></td>
                      <td  class="table-label"><span >性别</span></td>
                      <td  class="table-content"><span >{{form.sex==1?'男':'女'}}</span></td>
                    </tr>
                    <tr >
                      <td  class="table-label"><span >位置信息</span></td>
                      <td  class="table-content"><span ></span></td>
                      <td  class="table-label"><span >出生日期</span></td>
                      <td  class="table-content"><span >{{form.birthday}}</span></td>
                    </tr>
                    <tr >
                      <td  colspan="4" class="table-title">健康信息</td>
                    </tr>
                    <tr >
                      <td  class="table-label"><span >就诊号</span></td>
                      <td  class="table-content">
                        <el-input
                          v-model="form.doctorNum"
                          placeholder="请输入就诊号"
                          maxlength="40"
                          show-word-limit
                        />
                      </td>
                      <td  class="table-label"><span >住院号</span></td>
                      <td  class="table-content">
                        <el-input
                          v-model="form.hospitalNum"
                          placeholder="请输入住院号"
                          maxlength="40"
                          show-word-limit
                        />
                      </td>
                    </tr>
                    <tr >
                      <td  class="table-label"><span >身高</span></td>
                      <td  class="table-content">
                        <el-input
                          v-model="form.height"
                          placeholder="请输入住身高"
                          maxlength="3"
                          show-word-limit
                        />
                      </td>
                      <td  class="table-label"><span >体重</span></td>
                      <td  class="table-content">
                        <el-input
                          v-model="form.weight"
                          placeholder="请输入住体重"
                          maxlength="5"
                          show-word-limit
                        />
                      </td>
                    </tr>
                    <tr >
                      <td  class="table-label"><span >血型</span></td>
                      <td  class="table-content">
                        <el-select v-model="form.bloodType" placeholder="请选择血型" style="width: 100%">
                          <el-option v-for="item in this.bloodTypeOptions"
                              :key="item.bloodType"
                              :label="item.bloodTypeName"
                              :value="item.bloodType"
                          ></el-option>
                        </el-select>
                      </td>
                      <td  class="table-label"><span >慢性病</span></td>
                      <td  class="table-content">
                        <el-select v-model="form.chronicList" placeholder="请选择慢性病" @change="$forceUpdate()"  multiple style="width: 100%" clearable collapse-tags>
                            <el-option v-for="item in chronicOptions"
                                :key="item.chronicId"
                                :label="item.chronicName"
                                :value="item.chronicId"
                            ></el-option>
                        </el-select>
                      </td>
                    </tr>
                    <tr >
                      <td  class="table-label"><span >怀孕状态</span></td>
                      <td  class="table-content">
                        <el-select v-model="form.pregnantStatus" placeholder="请选择怀孕状态" style="width: 100%">
                          <el-option v-for="item in this.pregnantOptions"
                              :key="item.pregnantStatus"
                              :label="item.pregnantStatusName"
                              :value="item.pregnantStatus"
                          ></el-option>
                        </el-select>
                      </td>
                      <td  class="table-label"><span >怀孕日期</span></td>
                      <td  class="table-content">
                        <el-date-picker
                            v-model="form.pregnancyDate"
                            type="date"
                            align="right"
                            unlink-panels
                            value-format="yyyy-MM-dd" style="width: 100%"
                             >
                        </el-date-picker>
                      </td>
                    </tr>
                    <tr >
                      <td  class="table-label"><span >是否住院</span></td>
                      <td  class="table-content">
                        <el-select v-model="form.ifHospitalized" placeholder="请选择是否住院"  style="width: 100%">
                            <el-option v-for="item in this.ifHospitalizedOptions"
                                :key="item.ifHospitalized"
                                :label="item.ifHospitalizedName"
                                :value="item.ifHospitalized"
                            ></el-option>
                        </el-select>
                      </td>
                      <td  class="table-label"><span >住院日期</span></td>
                      <td  class="table-content">
                        <el-date-picker
                            v-model="form.inpatientDate"
                            type="date"
                            align="right"
                            unlink-panels
                            value-format="yyyy-MM-dd" style="width: 100%"
                             >
                        </el-date-picker>
                      </td>
                    </tr>
                    <tr >
                      <td  class="table-label"><span >劳动强度</span></td>
                      <td  class="table-content">
                        <el-select v-model="form.labourIntensity" placeholder="请选择劳动强度" style="width: 100%">
                          <el-option v-for="item in this.labourIntensityOptions"
                              :key="item.labourIntensity"
                              :label="item.labourIntensityName"
                              :value="item.labourIntensity"
                          ></el-option>
                        </el-select>
                      </td>
                      <td  class="table-label"><span >过敏源</span></td>
                      <td  class="table-content">
                        <el-input
                          v-model="form.allergen"
                          placeholder="请输入过敏源"
                          maxlength="40"
                          show-word-limit
                        />
                      </td>
                    </tr>
                    <tr >
                      <td  class="table-label"><span >饮食医嘱</span></td>
                      <td  class="table-content">
                        <el-select v-model="form.doctorAdvice" placeholder="请选择饮食医嘱"   style="width: 100%" >
                            <el-option v-for="item in doctorAdviceOptions"
                                :key="item.doctorAdvice"
                                :label="item.doctorAdviceName"
                                :value="item.doctorAdvice"
                            ></el-option>
                        </el-select>
                      </td>
                      <td  class="table-label"><span >体重控制目标</span></td>
                      <td  class="table-content">
                        <el-select v-model="form.weightControl" placeholder="请选择"   style="width: 100%" >
                            <el-option v-for="item in weightControlOptions"
                                :key="item.weightControl"
                                :label="item.weightControlName"
                                :value="item.weightControl"
                            ></el-option>
                        </el-select>
                      </td>
                    </tr>
                    <tr >
                      <td  class="table-label"><span >BMI(kg/m²)</span></td>
                      <td  class="table-content">{{form.bmi}}</td>
                      <td  colspan="2"></td>
                    </tr>
                  </table>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
  import { deptTreeSelect } from '@/api/system/user'
  import { dictHealthChronicApi,getHealthSciencePageApi,addHealthScienceApi,editHealthScienceApi,delHealthScienceApi,getHealthInfoPageApi,getHealthInfoDetailApi,editHealthInfoApi,delHealthInfoApi } from "@/api/healthCenter/index";
  import { imgUpLoadTwo } from '@/api/system/upload'
  import { decryptWithSM4,encryptWithSM4 } from '@/utils/sm';

export default {
    name: "",
    dicts: [],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            //表格数据
            tableListData: [],
            title:"",
            // 是否显示弹出层
            open: false,
            dateRange:[new Date(),new Date()],
            chronicOptions:[],
            doctorAdviceOptions:[{"doctorAdvice":"1","doctorAdviceName":"禁食"},
            {"doctorAdvice":"2","doctorAdviceName":"流食"},
            {"doctorAdvice":"3","doctorAdviceName":"半流食"},
            {"doctorAdvice":"4","doctorAdviceName":"治疗饮食"},
            ],
            bloodTypeOptions:[
              {"bloodType":"1","bloodTypeName":"A型"},
              {"bloodType":"2","bloodTypeName":"B型"},
              {"bloodType":"3","bloodTypeName":"AB型"},
              {"bloodType":"4","bloodTypeName":"O型"},
              {"bloodType":"5","bloodTypeName":"Rh阳型"},
              {"bloodType":"6","bloodTypeName":"Rh阴型"}
            ],//血型选项
            weightControlOptions:[
              {"weightControl":"1","weightControlName":"减重"},
              {"weightControl":"2","weightControlName":"增重"}
            ],//体重控制目标
            ifHospitalizedOptions:[
              {"ifHospitalized":"1","ifHospitalizedName":"是"},
              {"ifHospitalized":"2","ifHospitalizedName":"否"}
            ],//是否住院
            pregnantOptions:[
              {"pregnantStatus":"0","pregnantStatusName":"保密"},
              {"pregnantStatus":"1","pregnantStatusName":"未怀孕"},
              {"pregnantStatus":"2","pregnantStatusName":"孕妇(早期)"},
              {"pregnantStatus":"3","pregnantStatusName":"孕妇(中期)"},
              {"pregnantStatus":"4","pregnantStatusName":"孕妇(晚期)"},
              {"pregnantStatus":"5","pregnantStatusName":"乳母"}
            ],//怀孕状态
            labourIntensityOptions:[
              {"labourIntensity":"1","labourIntensityName":"轻劳动"},
              {"labourIntensity":"2","labourIntensityName":"中等强度劳动"},
              {"labourIntensity":"3","labourIntensityName":"重强度劳动"}
            ],//劳动强度
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                articleTitle: undefined,//标题
                deptIdList:[],//组织
                chronicList:[],  //慢性病
                placeIdList:[], //位置
                doctorAdvice:[],//饮食医嘱
                articleType:null //类型
            },
            form: {
                nickName:null,
                userId:null,
                orgFullName:null,
                userType:null,
                mobile:null,
                sex:1,
                birthday:null,
                doctorNum:null,
                hospitalNum:null,
                height:null,
                weight:null,
                bloodType:null,
                chronicList:[],
                pregnantStatus:null,
                pregnancyDate:null,
                ifHospitalized:null,
                inpatientDate:null,
                labourIntensity:null,
                allergen:null,
                doctorAdvice:null,
                weightControl:null,
            },//详情
        };
    },
    created() {
        this.getDeptTree()
        this.getList()
        this.getChronicList()
    },
    computed: {
        //图片上传1张后，隐藏上传框
        uploadDisabled() {
            return this.checkUrlList.length > 0
        },
    },
    methods: {
        /** 查询部门下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then((response) => {
                this.deptOptions = this.filterTree(response.data)
            })
        },
        filterTree(nodes) {
            return nodes
                .map((node) => {
                    if (node.children) {
                        node.children = this.filterTree(node.children)
                    }
                    return node
                })
                .filter((node) => node.status !== '1')
        },
        //慢性病类型
        getChronicList() {
            dictHealthChronicApi({}).then((response) => {
                this.chronicOptions = response.data;
                console.log("this.chronicOptions",this.chronicOptions)
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [new Date(),new Date()]
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                articleTitle: "",//标题
                deptIdList:[],
                chronicList:[],  //慢性病
                placeIdList:[], //位置
                doctorAdvice:[],
                articleType:null //类型
            }
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 查询列表 */
        getList() {
            this.loading = true;
            let param = {
                "pageNum":this.queryParams.pageNum,
                "pageSize":this.queryParams.pageSize,
                "articleTitle":this.queryParams.articleTitle,
                "deptIds":this.queryParams.deptIdList.join(",")||"",
                "doctorAdvices":this.queryParams.doctorAdvice.join(",")||"",
                "chronicIds":this.queryParams.chronicList.join(",")||""
            }
            // if(this.queryParams.chronicList.length>0){
            //     this.queryParams.chronicIds = this.queryParams.chronicList.join(",")
            // }else{
            //     this.queryParams.chronicIds = ""
            // }
            console.log("param",param);
            getHealthInfoPageApi(param).then(response => {
                this.tableListData = response.rows;
                console.log("this.tableListData",this.tableListData);
                this.tableListData.forEach(item=>{
                  this.$set(item,"mobile",decryptWithSM4(item.mobile))
                })
                this.total = Number(response.total);
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.fileList=[]
            this.checkUrlList=[]
            this.checkUrlNameList=[]
            this.form = {
                articleTitle:null,
                summary:null,
                chronicIdList:[],
                coverPhoto:null,
                articleType:1,
                articleContent: null,
            };
            this.resetForm("form");
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "新增";
        },
        handleUpdate(row) {
            this.form = Object.assign({}, row);
            getHealthInfoDetailApi(this.form).then(response => {
              this.form=response.data;
              console.log("this.form",this.form);
                this.form.chronicList=this.form.chronicIds!=null?this.form.chronicIds.split(","):[];
                if(this.form.coverPhoto){
                    this.fileList=[{url:this.form.coverPhoto}];
                    this.checkUrlList=[this.form.coverPhoto];
                }else{
                    this.fileList=[];
                    this.checkUrlList=[];
                }
                this.open = true;
                this.title = "修改健康档案";
            });

        },
        /** 提交按钮 */
        submitForm: function() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    console.log("this.form",this.form)
                    if(this.form.chronicList.length>0){
                        this.form.chronicIds = this.form.chronicList.join(",")
                    }else{
                        this.form.chronicIds = ""
                    }
                    if (this.form.userId != undefined) {
                        editHealthInfoApi(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        handleDelete(row) {
            this.$modal.confirm('是否确认删除数据项？').then(function() {
                console.log("row",row)
                return delHealthInfoApi(row);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
        },
        openImg(row) {
          this.dialogImageUrl = row.coverPhoto;
          this.dialogVisible = true;
        },
        // 图片上传
        imgUpLoad(param, name, index) {
            // console.log(param,'image')
            param.type = 'canteen'
            imgUpLoadTwo(param).then((res) => {
                if (res.code == 200) {
                    this.checkUrlList.push(res.data.url)
                    this.checkUrlNameList.push(res.data.name)
                } else {
                    this.$modal.msgError(res.msg)
                }
            })
            .catch((error) => {
                this.$modal.msgError(error)
            })
        },
        handleAvatarSuccess(res, file) {
            console.log('success')
        },
        handleRemove(file, fileList) {
            let sum = 0
            this.checkUrlNameList.forEach((item, index) => {
                if (item == file.name) {
                    sum = index
                }
            })
            this.checkUrlNameList.splice(sum, 1)
            this.checkUrlList.splice(sum, 1)
        },
        //图片点击查看
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url
            this.dialogVisible = true
        },
        //日期
        formatDate(date) {
            // 格式化为 YYYY-MM-DD
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        getDecryptWithSM4(obj){
          return decryptWithSM4(obj);
        },
        getEncryptWithSM4(obj){
          return encryptWithSM4(obj);
        },
    }
};
</script>
<style lang="scss" scoped>
    .remind-question{
        width: 100%;
        height: 50px;
        font-size: 22px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .remind-title{
        width: 100%;
        height: 40px;
        font-size: 16px;
        font-weight: bold;
        color: #000;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    table td, table th{
        border-left: 1px solid #dfe6ec;
        border-right: 1px solid #dfe6ec;
        border-top: 1px solid #dfe6ec;
    }
    .table-title {
        height: 45px;
        background-color: #f8f8f9;
    }
    .table-label{
        height: 45px;
        width: 110px;
        min-width: 100px;
        background-color: #f8f8f9;
    }
    .table-content{
        min-width: 250px;
    }
    //隐藏图片上传框的css
    ::v-deep.disabled {
        .el-upload--picture-card {
            display: none;
        }
    }
</style>
