<template>
  <div class="app-container" ref="layout">
    <el-tabs v-model="queryParams.nodeExecuteStatus" @tab-click="handleClick" style="flex: 1;">
      <el-tab-pane label="未执行" name="UNEXECUTED"></el-tab-pane>
      <el-tab-pane label="已执行" name="EXECUTED"></el-tab-pane>
    </el-tabs>
    <div ref="topform" class="form">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="随访时间" prop="startDate">
          <el-date-picker v-model="intentionalTime" type="daterange" range-separator="至" start-placeholder="开始日期"
            style="width: 300px" value-format="yyyy-MM-dd" end-placeholder="结束日期" @change="chooseTime">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="姓名" prop="patientName">
          <el-input v-model="queryParams.patientName" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="电话" prop="patientPhone">
          <el-input v-model="queryParams.patientPhone" placeholder="请输入电话" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="医院" prop="hospitalAgencyId">
          <el-select v-model="queryParams.hospitalAgencyId" filterable placeholder="请选择医院" style="width: 200px"
            clearable @clear="clearhospitalAgency" @change="changehospitalAgency">
            <el-option v-for="item in hospitalAgencylist" :key="item.id" :label="item.agencyName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="院区" prop="campusAgencyId" v-if="queryParams.hospitalAgencyId">
          <el-select v-model="queryParams.campusAgencyId" filterable placeholder="请选择院区" style="width: 200px" clearable
            @clear="clearcampusAgency" @change="changecampusAgency">
            <el-option v-for="item in campusAgencylist" :key="item.id" :label="item.agencyName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科室" prop="departmentId" v-if="queryParams.hospitalAgencyId">
          <el-select v-model="queryParams.departmentId" filterable placeholder="请选择科室" style="width: 200px" clearable
            @clear="cleardepartment" @change="changedepartment">
            <el-option v-for="item in departmentlist" :key="item.id" :label="item.departmentName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="病区" prop="wardId" v-if="queryParams.hospitalAgencyId">
          <el-select v-model="queryParams.wardId" filterable placeholder="请选择病区" style="width: 200px" clearable>
            <el-option v-for="item in wardlist" :key="item.id" :label="item.departmentName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="就诊类型" prop="suitRange">
          <el-select v-model="queryParams.suitRange" placeholder="请选择就诊类型" clearable @change="change">
            <el-option v-for="item in visitoptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
            <!-- <el-option
            v-for="dict in dict.type.visit_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="就诊流水号" prop="visitSerialNumber">
          <el-input v-model="queryParams.visitSerialNumber" placeholder="请输入就诊流水号" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="门诊/出院时间" prop="intentionalTimeStart">
          <el-date-picker @change="mzchange" v-model="mzTime" type="daterange" range-separator="至"
            start-placeholder="开始日期" style="width: 300px" value-format="yyyy-MM-dd" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="入院时间" prop="intentionalTimeStart">
          <el-date-picker v-model="ryTime" type="daterange" range-separator="至" start-placeholder="开始日期"
            style="width: 300px" value-format="yyyy-MM-dd" end-placeholder="结束日期" @change="rychange">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="诊断" prop="mainDiagnosis">
          <el-input v-model="queryParams.mainDiagnosis" placeholder="请选择诊断" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="主治医生" prop="attendingPhysicianId" v-if="queryParams.hospitalAgencyId">
          <el-select v-model="queryParams.attendingPhysicianId" style="width: 200px" filterable placeholder="请选择主治医生"
            clearable>
            <el-option v-for="item in attendingPhysicianlist" :key="item.userId" :label="item.nickName"
              :value="item.userId">
            </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>
    </div>
    <div ref="table">
      <el-table :max-height="maxTableHeight" v-loading="loading" :data="taskExecuteRecordList"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="姓名" align="center" prop="patientName" width="50"/>
        <el-table-column label="电话" align="center" prop="patientPhone" width="120"/>
        <el-table-column label="性别" align="center" prop="visitSerialNumber" width="50">
          <template slot-scope="scope">
            {{ scope.row.sex == "MALE" ? "男" : "" }}
            {{ scope.row.sex == "FEMALE" ? "女" : "" }}
          </template>
        </el-table-column>
        <el-table-column label="医院" align="center" prop="hospitalAgencyName" width="105"/>
        <el-table-column label="院区" align="center" prop="campusAgencyName" />
        <el-table-column label="科室名称" align="center" prop="departmentName" />
        <el-table-column label="病区名称" align="center" prop="wardName" />

        <el-table-column label="门诊/住院号" align="center" prop="inHospitalNumber"   width="120" :show-overflow-tooltip="true"/>
        <el-table-column label="就诊流水号" align="center" prop="visitSerialNumber" width="120"  :show-overflow-tooltip="true"/>
        <el-table-column label="诊断" align="center" prop="mainDiagnosis" width="120"  :show-overflow-tooltip="true"/>
        <el-table-column label="手术名称" align="center" prop="surgicalName" />
        <el-table-column label="主治医生" align="center" prop="attendingPhysicianName" width="80"/>
        <el-table-column label="就诊类型" align="center" prop="suitRange" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.suitRange == "OUTPATIENT_SERVICE" ? "门诊" : "" }}
              {{ scope.row.suitRange == "IN_THE_HOSPITAL" ? "在院" : "" }}
              {{ scope.row.suitRange == "DISCHARGE" ? "出院" : "" }}
            </span>
          </template></el-table-column>
        <el-table-column label="入院时间" align="center" prop="admissionTime" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.admissionTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="门诊/出院时间" align="center" prop="visitOrDischargeTime" width="105">
          <template slot-scope="scope">
            <span>{{
      parseTime(scope.row.visitOrDischargeTime, "{y}-{m}-{d}")
    }}</span>
          </template>
        </el-table-column>
        <el-table-column label="随访时间" align="center" prop="executeTime"  width="80">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.executeTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>

        <el-table-column label="随访模板" align="center" prop="templateName" width="110">
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="scope">
            <el-button v-if="queryParams.nodeExecuteStatus == 'UNEXECUTED'" size="mini" type="text"
              icon="el-icon-bank-card" @click="handleUpdate(scope.row)">处理</el-button>
            <el-button v-if="queryParams.nodeExecuteStatus == 'EXECUTED'" size="mini" type="text"
              icon="el-icon-notebook-2" @click="handleadtail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>

<script>

import { manualFollowUpList } from "@/api/system/followup"
import { usergetList } from "@/api/unitconfig/patientConfiguration";

import { getAge } from "@/utils/age";
import {
  selectAgencyList, getAgencyList
} from "@/api/manage/selectAgencyList";
export default {
  name: "Followup22",
  dicts: ["visit_type"],
  data() {
    return {
      maxTableHeight: undefined,
      // 随访时间
      intentionalTime: [],
      // 门诊
      mzTime: [],
      // 入院
      ryTime: [],
      //医院list
      hospitalAgencylist: [],
      // 院区list
      campusAgencylist: [],
      //科室list
      departmentlist: [],
      //病区list
      wardlist: [],
      // 主治医生
      attendingPhysicianlist: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 患者管理任务执行记录表格数据
      taskExecuteRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nodeExecuteStatus: 'UNEXECUTED',
        followStartTime: null,
        followEndTime: null,
        clinicalStartTime: null,
        clinicalEndTime: null,
        admissionEndTime: null,
        admissionStartTime: null,
        mainDiagnosis: null,

        visitSerialNumber: null,
        attendingPhysicianId: null,
        patientId: null,
        suitRange: null,
        manageRouteId: null,
        manageRouteNodeId: null,
        patientName: null,
        startDate: null,
        endDate: null,
        manageRouteName: null,
        manageRouteNodeName: null,
        taskContent: null,
        executeTime: null,
        executePerson: null,
        executeType: null,
        executeRemark: null,
        hospitalAgencyId: null,
        campusAgencyId: null,
        departmentId: null,
        wardId: null,
      },
      // 表单参数
      form: {},
      visitoptions: [
        {
          value: 'IN_THE_HOSPITAL',
          label: '在院'
        }, {
          value: 'OUTPATIENT_SERVICE',
          label: '门诊'
        }, {
          value: 'DISCHARGE',
          label: '出院'
        },
      ],
      // 表单校验
      // rules: {
      //   patientId: [
      //     { required: true, message: "患者表id不能为空", trigger: "blur" },
      //   ],
      // },
    };
  },
  created() {
    this.getList();
    this.selectAgencyinfo();
  },
  mounted() {
    this.getMaxTableHeight()
    this.screenChange()
  },
  methods: {
    handleClick(tab, event) {
      this.intentionalTime = [],
        this.mzTime = [],
        this.ryTime = [],
        this.queryParams.dischargeStartTime = null
      this.queryParams.dischargeEndTime = null
      this.queryParams.clinicalStartTime = null
      this.queryParams.clinicalEndTime = null
      this.queryParams.followStartTime = null
      this.queryParams.followEndTime = null
      this.queryParams.admissionEndTime = null
      this.queryParams.admissionStartTime = null
      this.queryParams.mainDiagnosis = null
      this.queryParams.visitSerialNumber = null
      this.queryParams.attendingPhysicianId = null
      this.queryParams.suitRange = null
      this.queryParams.patientName = null
      this.queryParams.hospitalAgencyId = null
      this.queryParams.campusAgencyId = null
      this.queryParams.departmentId = null
      this.queryParams.wardId = null
      this.queryParams.patientPhone = null
      this.getList();
    },
    change(e) {
      if (e == 'DISCHARGE') {
        this.queryParams.clinicalStartTime = null
        this.queryParams.clinicalEndTime = null

      } else if (e == 'OUTPATIENT_SERVICE') {
        this.queryParams.dischargeStartTime = null
        this.queryParams.dischargeEndTime = null
      } else {

        this.queryParams.dischargeStartTime = null
        this.queryParams.dischargeEndTime = null
        this.queryParams.clinicalStartTime = null
        this.queryParams.clinicalEndTime = null
      }
      console.log(e)
      // DISCHARGE
      // 出院
      // OUTPATIENT
      // 门诊

    },
    //主治医生
    usergetListinfo() {
      usergetList({
        hospitalAgencyId: this.queryParams.hospitalAgencyId,
        postName: 'DOCTOR'
      }).then(res => {
        this.attendingPhysicianlist = res.data
      })
    },
    //获取下级单位
    getAgencyListinfo(nodeType, id) {
      let query = {
        nodeType: nodeType,
      }
      if (nodeType == 'HOSPITAL') {
        query.hospitalId = id
      } else if (nodeType == 'CAMPUS') {
        query.campusId = id
      } else if (nodeType == 'DEPARTMENT') {
        query.departmentId = id
      }
      getAgencyList(query).then(res => {
        if (nodeType == 'HOSPITAL') {
          this.campusAgencylist = res.data.campusList
          this.departmentlist = res.data.departmentList
        } else if (nodeType == 'CAMPUS') {
          this.departmentlist = res.data.departmentList
        }
        this.wardlist = res.data.wardList
      })
    },
    //选中医院获取院区
    changehospitalAgency(id) {
      this.getAgencyListinfo('HOSPITAL', id)
      this.queryParams.campusAgencyId = null
      this.queryParams.departmentId = null
      this.queryParams.wardId = null
      this.queryParams.attendingPhysicianId = null
      // })
      //医生
      this.usergetListinfo();
    },
    //选中院区获取科室
    changecampusAgency(id) {
      this.getAgencyListinfo('CAMPUS', id)
      this.queryParams.departmentId = null
      this.queryParams.wardId = null
      // })
    },
    //选中科室获取病区
    changedepartment(id) {
      this.getAgencyListinfo('DEPARTMENT', id)
      // let query = {
      //   nodeType: 'WARD',
      //   parentDepartmentId: id,
      // }
      // getDepartmentList(query).then(res => {
      //   this.wardlist = res.data
      this.queryParams.wardId = null
      // })
    },
    //清空医院
    clearhospitalAgency() {
      this.queryParams.campusAgencyId = null
      this.queryParams.departmentId = null
      this.queryParams.wardId = null
      this.queryParams.attendingPhysicianId = null
    },
    //清空院区
    clearcampusAgency() {
      this.queryParams.departmentId = null
      this.queryParams.wardId = null
      this.getAgencyListinfo('HOSPITAL', this.queryParams.hospitalAgencyId)
    },
    //清空科室
    cleardepartment() {
      this.queryParams.wardId = null
      if (this.queryParams.departmentId) {
        this.getAgencyListinfo('DEPARTMENT', this.queryParams.departmentId)
      } else if (this.queryParams.campusAgencyId) {
        this.getAgencyListinfo('CAMPUS', this.queryParams.campusAgencyId)
      } else if (this.queryParams.hospitalAgencyId) {
        this.getAgencyListinfo('HOSPITAL', this.queryParams.hospitalAgencyId)
      }
    },
    //获取医院list
    selectAgencyinfo() {
      let query = {
        agencyStatus: "ON",
        nodeType: "HOSPITAL",
      };
      selectAgencyList(query).then((res) => {
        this.hospitalAgencylist = res.data;
      });
    },
    /** 查询患者管理任务执行记录列表 */
    getList() {
      this.loading = true;
      manualFollowUpList(this.queryParams).then((response) => {
        this.taskExecuteRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        nodeExecuteStatus: 'UNEXECUTED',
        id: null,
        patientId: null,
        manageRouteId: null,
        manageRouteNodeId: null,
        patientName: null,
        manageRouteName: null,
        manageRouteNodeName: null,
        taskContent: null,
        executeTime: null,
        executePerson: null,
        executeType: null,
        executeRemark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    // 随访时间
    chooseTime() {
      if (this.intentionalTime == null) {
        this.intentionalTime = [];
        this.queryParams.followStartTime = null
        this.queryParams.followEndTime = null
      } else {
        this.queryParams.followStartTime = this.intentionalTime[0]
        this.queryParams.followEndTime = this.intentionalTime[1]
      }
    },
    // 门诊
    mzchange() {
      if (this.mzTime == null) {
        this.mzTime = [];
        this.queryParams.clinicalStartTime = null
        this.queryParams.clinicalEndTime = null
      } else {
        console.log(this.queryParams, '-----')
        if (!this.queryParams.suitRange || this.queryParams.suitRange == 'IN_THE_HOSPITAL') {
          this.queryParams.clinicalStartTime = this.mzTime[0]
          this.queryParams.clinicalEndTime = this.mzTime[1]
          this.queryParams.dischargeStartTime = this.queryParams.clinicalStartTime
          this.queryParams.dischargeEndTime = this.queryParams.clinicalEndTime
        } else if (this.queryParams.suitRange == 'DISCHARGE') {
          this.queryParams.dischargeStartTime = this.mzTime[0]
          this.queryParams.dischargeEndTime = this.mzTime[1]


          this.queryParams.clinicalStartTime = null
          this.queryParams.clinicalEndTime = null

        } else if (this.queryParams.suitRange == 'OUTPATIENT_SERVICE') {
          this.queryParams.dischargeStartTime = null
          this.queryParams.dischargeEndTime = null
          this.queryParams.clinicalStartTime = this.mzTime[0]
          this.queryParams.clinicalEndTime = this.mzTime[1]
        }
      }
    },
    // 入院
    rychange() {
      if (this.ryTime == null) {
        this.ryTime = [];
        this.queryParams.admissionStartTime = null
        this.queryParams.admissionEndTime = null
      } else {
        this.queryParams.admissionStartTime = this.ryTime[0]
        this.queryParams.admissionEndTime = this.ryTime[1]
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        nodeExecuteStatus: 'UNEXECUTED',
        followStartTime: null,
        followEndTime: null,
        clinicalStartTime: null,
        clinicalEndTime: null,
        admissionEndTime: null,
        admissionStartTime: null,
        mainDiagnosis: null,
        visitSerialNumber: null,
        attendingPhysicianId: null,
        patientId: null,
        suitRange: null,
        manageRouteId: null,
        manageRouteNodeId: null,
        patientName: null,
        startDate: null,
        endDate: null,
        manageRouteName: null,
        manageRouteNodeName: null,
        taskContent: null,
        executeTime: null,
        executePerson: null,
        executeType: null,
        executeRemark: null,
        hospitalAgencyId: null,
        campusAgencyId: null,
        departmentId: null,
        wardId: null,
      },
        this.handleQuery();
      this.intentionalTime = [];
      this.mzTime = [];
      this.ryTime = [];
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加患者管理任务执行记录";
    },
    /** 处理按钮操作 */
    handleUpdate(row) {
      console.log(row)
      this.$router.push({
        path: "/task/followupsee",
        query: {
          patientId: row.patientId,
          taskType: row.taskType,
          templateId: row.templateId,
          cardNo: row.cardNo,
          patientName: row.patientName,
          manageRouteName: row.manageRouteName,
          manageRouteNodeName: row.routeNodeName,
          patientPhone: row.patientPhone,
          sex: row.sex,
          birthDate: row.birthDate,
          familyMemberPhone: row.familyMemberPhone,
          address: row.address,
          patientSource: row.patientSource,
          createTime: row.createTime,
          age: row.birthDate ? getAge(row.birthDate) : "",
          manageRouteId: row.manageRouteId,
          manageRouteNodeId: row.manageRouteNodeId,
          visitRecordId: row.visitRecordId,

          departmentId: row.departmentId,
          departmentName: row.departmentName,
          diseaseTypeId: row.diseaseTypeId ? row.diseaseTypeId : null,
          diseaseTypeName: row.diseaseTypeName ? row.diseaseTypeName : null,
        },
      });

    },
    // 详情
    handleadtail(row) {
      this.$router.push({
        path: "/task/followupdetails",
        query: {
          patientId: row.patientId,
          taskType: row.taskType,
          templateId: row.templateId,
          manageRouteId: row.manageRouteId,
          manageRouteNodeId: row.manageRouteNodeId,

          visitRecordId: row.visitRecordId,
          taskExecuteRecordId: row.taskExecuteRecordId,
          routeHandleRemark: row.routeHandleRemark ? row.routeHandleRemark : null,
        },
      });
      console.log(row)


    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateTaskExecuteRecord(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTaskExecuteRecord(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // handleClick(tab, event) {
    //   this.intentionalTime = [];
    //   this.queryParams.startDate = null;
    //   this.queryParams.endDate = null;
    //   // this.signTime = []
    //   // this.queryParams.signTimeStart = null
    //   // this.queryParams.signTimeEnd = null
    //   this.getList();
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(
          '是否确认删除患者管理任务执行记录编号为"' + ids + '"的数据项？'
        )
        .then(function () {
          return delTaskExecuteRecord(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/taskExecuteRecord/export",
        {
          ...this.queryParams,
        },
        `taskExecuteRecord_${new Date().getTime()}.xlsx`
      );
    },
    // 获取表格最高高度
    getMaxTableHeight() {
      const windowInnerHeight = window.innerHeight // 屏幕可视高度
      const layoutDiv = this.$refs.layout
      const formDiv = this.$refs.topform
      this.maxTableHeight =
        windowInnerHeight - 134 - 54 -
        this.getBoxPadding(layoutDiv) -
        this.getBoxHeight(formDiv)
    },
    // 屏幕resize监听
    screenChange() {
      // 屏幕resize监听事件：一旦屏幕宽高发生变化，就会执行resize
      window.addEventListener('resize', this.getMaxTableHeight, true)
      // 将屏幕监听事件移除
      // 这步是必须的。离开页面时不移除，再返回，或者进入到别的有相同元素的页面会报错
      // 或者将这里的方法直接写在beforeDestroy函数中也可以
      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', this.getMaxTableHeight, true)
      })
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-table__body-wrapper::-webkit-scrollbar {
width: 8px; /*滚动条宽度*/
height: 6px; /*滚动条高度*/
background: #C1C1C1;
border-radius: 10px; /*滚动条的背景区域的圆角*/

// box-shadow: 0px 1px 3px #232335 inset;


}
::v-deep .el-table {
  overflow: auto;
}

.app-container {
  padding-top: 0 !important;
}
</style>
