<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :inline="true"
      :model="queryParams"
      label-width="68px"
    >
      <el-form-item label="病区" prop="bmnbbh">
        <el-select v-model="queryParams.bmnbbh" clearable placeholder="请选择病区">
          <el-option
            v-for="item in inpatientAreaList"
            :key="item.DEPT_ID"
            :label="item.DEPT_NAME"
            :value="item.DEPT_ID"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="住院号" prop="zybah">
        <el-input
          v-model="queryParams.zybah"
          clearable
          placeholder="请输入住院号"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          clearable
          placeholder="请输入患者名称"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="床位号" prop="cwh">
        <el-input
          v-model="queryParams.cwh"
          clearable
          placeholder="请输入床位号"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="医嘱日期" prop="sqsj">
        <el-date-picker
          v-model="dates"
          clearable
          end-placeholder="结束日期"
          range-separator="至"
          size="small"
          start-placeholder="开始日期"
          style="width: 350px"
          type="daterange"
          value-format="yyyy-MM-dd"

        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-search"
          size="mini"
          type="cyan"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="patientList"
          :height="tableHeight"
          border stripe tooltip-effect="light" @selection-change="handleSelectionPatientChange" @row-click="handleRowClick"
        >
          <el-table-column align="center" type="selection" width="55"/>
          <el-table-column align="left" fixed="left" label="姓名" min-width="80" prop="patient_name"
                           show-overflow-tooltip
          />
          <el-table-column align="left" fixed="left" label="床位号" min-width="70" prop="bad_number"
                           show-overflow-tooltip
          />
          <el-table-column align="center" label="住院号" min-width="120" prop="visit_num" show-overflow-tooltip/>
          <el-table-column align="center" label="病区" min-width="100" prop="ward_name" show-overflow-tooltip/>
          <el-table-column :formatter="genderFormat" align="center" label="性别" prop="gender" width="50"/>
        </el-table>

        <!--        <pagination-->
        <!--          v-show="total > 0"-->
        <!--          :total="total"-->
        <!--          :page.sync="queryParams.pageNum"-->
        <!--          :limit.sync="queryParams.pageSize"-->
        <!--          @pagination="getList"-->
        <!--        />-->
      </el-col>
      <el-col :span="16" style="height: 500px">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button size="mini" type="primary" @click="handleSubscribe"
            >预约
            </el-button
            >
            <!--            <el-button type="success" :disabled="single" size="mini" @click="handleModification"
                          >改约</el-button
                        >-->
            <el-button size="mini" type="warning" @click="handleExport"
            >打印
            </el-button
            >
          </el-col>

          <el-col :span="4">
            <el-input
              v-model="queryParams.dmmc"
              clearable
              placeholder="请输入项目"
              size="small"
              @keyup.enter.native="handleInExamItemQuery"
            />
          </el-col>
          <el-col :span="6">
            <el-button
              icon="el-icon-search"
              size="mini"
              type="cyan"
              @click="handleInExamItemQuery"
            >搜索
            </el-button
            >
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetInExamItemQuery"
            >重置
            </el-button
            >
          </el-col>
        </el-row>
        <el-table
          ref="multipleTable2"
          v-loading="inExamItemListLoading"
          :data="inExamItemList"
          :height="tableHeight"
          :span-method="objectSpanMethod" border stripe tooltip-effect="light"
          @selection-change="handleSelectionExamItemChange"
          @row-click="handleRowClick2"
        >
          <el-table-column align="center" type="selection" width="45"/>
          <el-table-column align="left" fixed="left" label="姓名" min-width="80" prop="XM" show-overflow-tooltip
                           width="80"
          />
          <el-table-column
            align="left"
            fixed="left"
            label="申请单号"
            min-width="200" prop="apply_num" show-overflow-tooltip
          />
          <el-table-column
            align="left"
            label="项目"
            min-width="240"
            prop="out_exam_item_name" show-overflow-tooltip
          />
          <el-table-column align="left" label="项目类型" min-width="80" prop="exam_type_name" show-overflow-tooltip
          //>
          <el-table-column
            align="left"
            label="项目编码"
            min-width="240"
            prop="item_code" show-overflow-tooltip
          />
          <el-table-column
            align="left"
            label="申请医生" min-width="80"
            prop="apply_doctor_name"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="申请时间"
            prop="created_at"
            show-overflow-tooltip
            width="115"
          />
          <el-table-column :formatter="formatterApplyType" align="center" label="申请类型" prop="SQLX" width="80"/>

          <!-- <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleCancel(scope.row)"
                >取消预约</el-button
              >
            </template>
          </el-table-column> -->
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  patientList,
  examItemList,
  reservation,
  exportExam,
  xtbmList
} from '@/api/resource/hospitalizationSubscribe'

export default {
  name: 'InExamItem',
  data() {
    return {
      // 遮罩层
      loading: false,
      inExamItemListLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 单个时患者项目列表
      singleExamList: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 住院患者表格数据
      patientList: [],
      // 内部检查项目表格数据
      inExamItemList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      //检查类型下拉
      examTypeOption: [],
      // 下拉选择病区列表
      inpatientAreaList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        cwh: null,
        zybah: null,
        sqsj: null,
        bmnbbh: null,
        dmmc: null,
        startDate: null,
        endDate: null
      },
      // 预约数据
      subscribeData: {
        parameters: {
          sourceType: null,
          sourceID: null,
          syncCode: null,
          datasetcode: null,
          keyvalue: null
        },
        D02014: [],
        D02015: []
      },
      // 性别字典
      genderOptions: [],
      // 患者选择数据
      patientData: [],
      // 检查项目选中数据
      examItemData: [],
      // 表单参数
      form: {},
      dates: [],
      dateF: null,
      tableHeight: 600,
      rowIndexs: [],
      _pos: null,
      countTable: 0
    }
  },
  created() {
    var afterDay = new Date()
    afterDay.setDate(afterDay.getDate() - 3)
    this.dateFormat('YYYY-mm-dd', afterDay)
    this.dates[0] = this.dateF
    this.dateFormat('YYYY-mm-dd', new Date())
    this.dates[1] = this.dateF
    this.getInpatientAreaList()
    // this.queryParams.bmnbbh =
    this.getDicts('sys_user_sex').then((response) => {
      this.genderOptions = response.data
    })
  },
  methods: {
    handleRowClick(row, column, event) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    handleRowClick2(row, column, event) {
      this.$refs.multipleTable2.toggleRowSelection(row)
    },
    // 获取列表数据
    getList() {
      this.loading = true
      console.log(JSON.stringify(this.queryParams))
      console.log(this.queryParams)
      patientList(this.queryParams).then((response) => {
        this.patientList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 获取下拉选择病区
    getInpatientAreaList() {
      xtbmList({ bm: '101' }).then((response) => {
        this.inpatientAreaList = response.data
        console.log(this.inpatientAreaList, this.inpatientAreaList[0].bmnbbh)
        this.queryParams.bmnbbh = response.data[0].DEPT_ID
        var afterDay = new Date()
        afterDay.setDate(afterDay.getDate() - 3)
        this.dateFormat('YYYY-mm-dd', afterDay)
        this.queryParams.startDate = this.dateF
        this.dateFormat('YYYY-mm-dd', new Date())
        this.queryParams.endDate = this.dateF

        this.$nextTick(() => {
          this.getList()
        })
      })
    },
    // 性别字典翻译
    genderFormat(row, column) {
      return this.selectDictLabel(this.genderOptions, row.gender)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      console.log(this.dates)
      this.queryParams.startDate = this.dates[0]
      this.queryParams.endDate = this.dates[1]
      this.getList()
    },
    /** 项目名称检索操作 */
    handleInExamItemQuery() {
      let params = this.patientData.map((item) => {
        return {
          name: item.XM,
          applyNum: item.APPLYNUM,
          dmmc: this.queryParams.dmmc
        }
      })
      examItemList(params).then((response) => {
        this.inExamItemList = response.rows
        this.inExamItemListLoading = false
      })
    },
    /** 重置按钮操作 */
    resetQuery() {

      this.resetForm('queryForm')
      this.queryParams.bmnbbh = this.inpatientAreaList[0].BMNBBH
      this.handleQuery()

    },
    resetInExamItemQuery() {
      this.queryParams.dmmc = null
      this.handleInExamItemQuery()
    },
    // 多选框选中患者数据
    handleSelectionPatientChange(selection) {
      this._pos = null
      this.rowIndexs = []
      this.patientData = selection
      this.single = selection.length !== 1
      let params = selection.map((item) => {
        return {
          name: item.patient_name,
          zybah: item.visit_num,
          patientId: item.patient_id
        }
      })
      this.inExamItemListLoading = true
      setTimeout(() => {
        this.inExamItemListLoading = false
      }, 10000)
      examItemList(params).then((response) => {
        this.inExamItemList = response.rows
        if (!this.single) {
          this.singleExamList = this.inExamItemList
        }
        this.inExamItemListLoading = false
        this.$nextTick(() => {
          for (let i = 0; i < this.inExamItemList.length; i++) {
            this.$refs.multipleTable2.toggleRowSelection(this.inExamItemList[i])
            if (i === 0) {
              this.rowIndexs.push(1)
              this._pos = 0
            } else {
              if (this.inExamItemList[i].apply_num === this.inExamItemList[i - 1].apply_num) {
                this.rowIndexs[this._pos] += 1
                this.rowIndexs.push(0)
              } else {
                this.rowIndexs.push(1)
                this._pos = i
              }
            }
          }
        })
      }).finally(_ => {
        this.inExamItemListLoading = false
      })
    },
    // 多选框选中检查项目数据
    handleSelectionExamItemChange(selection) {
      this.examItemData = selection
    },
    // 预约操作
    handleSubscribe() {
      let applynum = null
      let applynums = []
      let flag = false
      var find = false
      this.subscribeData.D02014 = []
      this.subscribeData.D02015 = []
      this.patientData.forEach(patient => {
          this.examItemData.forEach(item => {

            let applyMainInfos = {
              'DE01.00.008.00': item.apply_num,
              'DE02.01.062.47': item.patient_id,
              'DE02.01.039.65': item.patient_name,
              'DE02.01.040.00': patient.gender,
              'DE02.01.026.00': patient.age,
              'DE02.01.010.00': patient.phone,
              'DE05.01.081.00': '2',
              'DE05.01.081.02': patient.visit_num,
              'DE04.30.018.00': item.exam_type_id,
              'DE01.00.600.00': item.is_urgent,
              'DE08.10.025.18': item.apply_dept_id,
              'DE08.10.026.22': item.apply_dept_name,
              'DE02.01.039.34': item.apply_doctor_name,
              'DE02.01.062.68': item.apply_doctor_id,
              'DE07.00.018.00': item.is_pay
            }

            if (applynums.length === 0) {
              this.subscribeData.D02014.push(applyMainInfos)
              applynums.push(item.apply_num)
              for (let i = 0; i < this.examItemData.length; i++) {

                if (this.examItemData[i].apply_num === item.apply_num) {

                  let applyAdditionInfos = {
                    'DE04.30.020.00': this.examItemData[i].in_exam_item_name,
                    'DE04.30.019.00': this.examItemData[i].item_code,
                    'DE08.10.025.20': this.examItemData[i].exam_dept_id,
                    'DE08.10.026.30': this.examItemData[i].exam_dept_name
                  }
                  this.subscribeData.D02015.push(applyAdditionInfos)
                }
              }
              console.log('json1' + JSON.stringify(this.subscribeData))
              reservation(JSON.stringify(this.subscribeData)).then((rsp) => {

                console.log('code' + rsp.code)
                if (rsp.code === 200) {
                  this.msgSuccess('预约成功')
                }
              })
              this.subscribeData.D02014 = []
              this.subscribeData.D02015 = []

            } else {
              for (let i = 0; i < applynums.length; i++) {
                if (applynums[i] == item.apply_num) {
                  find = true
                  break
                }
              }
              if (!find) {
                this.subscribeData.D02014.push(applyMainInfos)
                applynums.push(item.apply_num)

                this.examItemData.forEach(itemj => {

                  if (itemj.apply_num === item.apply_num) {

                    let applyAdditionInfos = {
                      'DE04.30.020.00': itemj.in_exam_item_name,
                      'DE04.30.019.00': itemj.item_code,
                      'DE08.10.025.20': itemj.exam_dept_id,
                      'DE08.10.026.30': itemj.exam_dept_name
                    }
                    this.subscribeData.D02015.push(applyAdditionInfos)
                  }
                })
                console.log('json2' + JSON.stringify(this.subscribeData))
                reservation(JSON.stringify(this.subscribeData)).then((rsp) => {
                  if (rsp.code === 200) {
                    this.msgSuccess('预约成功')
                  }
                })
                this.subscribeData.D02014 = []
                this.subscribeData.D02015 = []
              }
              find = false
            }

            //
            // if (applynum === item.apply_num){
            //  this.subscribeData.D02015.push(applyAdditionInfos);
            //  console.log("applyAdditionInfos"+this.subscribeData.D02015)
            // }

            applynum = item.apply_num

            // }
          })
          // if (flag){
          //   this.msgSuccess("预约成功");
          // }else {
          //   this.msgSuccess("预约失败");
          // }

        }
      )
      //console.log("json"+JSON.stringify(this.subscribeData))

      this.getList()
    },
    /** 取消预约操作 */
    handleCancel(row) {
      this.reset()
      const id = row.id || this.ids
    },
    // 合并姓名相同的行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // console.log("row"+row)
      // console.log("rowIndex"+rowIndex)
      // console.log("columnIndex"+columnIndex)
      // console.log("columnIndex"+columnIndex)
      if (columnIndex === 1) {

        if (rowIndex === row.index) {
          return [row.length, 1]
        } else {
          return [0, 0]
        }
      }

      if (columnIndex === 2 || columnIndex === 0) {
        if (columnIndex === 2 || rowIndex === 1 || columnIndex === 0) {
          let i = this.rowIndexs[rowIndex]
          let j = i > 0 ? 1 : 0
          if (i) {
            return { rowspan: i, colspan: j }
          }
        }
      }

    },
    // 打印按钮操作
    handleExport() {
      const params = []
      this.$confirm('是否确认打印检查项目数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportExam(params)
      }).then(response => {
        this.download(response.msg)
      })
    },

    // 改约按钮操作
    handleModification() {
      let patientInfo = {
        patientId: null,
        visitName: '住院',
        patientName: this.patientData[0].XM,
        gender: this.patientData[0].XB,
        age: this.patientData[0].NL,
        phone: this.patientData[0].LXDH,
        isUrgent: this.singleExamList[0].SQLX == '普' ? 0 : 1
      }
      let exams = this.singleExamList.map(item => {
        return {
          applyNum: item.ID,
          applyDate: item.SQSJ,
          yardId: '101',
          applyDeptName: item.SQKSMC,
          examDeptName: item.ZXKSMC,
          examName: item.ZDY1,
          outExamItemName: item.DMMC,
          reservationDate: '',
          reservationTimeSlot: '',
          isPay: 1,
          applyState: 0,
          ...patientInfo
        }
      })
      let apply = {
        ...patientInfo,
        examItemList: exams
      }
      this.$store.dispatch('apply/setApplyInfo', apply)
      this.$store.dispatch('apply/setFromRouter', 2)
      this.$router.push({ path: '/manualApply' })
    },
    dateFormat(fmt, date) {
      let ret
      const opt = {
        'Y+': date.getFullYear().toString(),        // 年
        'm+': (date.getMonth() + 1).toString(),     // 月
        'd+': date.getDate().toString(),            // 日
        'H+': date.getHours().toString(),           // 时
        'M+': date.getMinutes().toString(),         // 分
        'S+': date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      for (let k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
        }

      }

      this.dateF = fmt
    },
    formatterApplyType(row, column) {
      if (row.is_urgent === 0) {
        return '普'
      } else if (row.is_urgent === 1) {
        return '急'
      }
    },
    loadTable() {
      this.countTable += 2
    }
  }
}
</script>
