<template>
  <div class="box">
    <div>
      <div class="middlebox">
        <div class="contenttitle">
          客户报表 /
          <span class="contenttitleBold"
            >阳性结果人员</span
          >
        </div>
      </div>
      <div :style="'display: block;'">
        <div style="background-color: #fff; padding: 15px; border-radius: 8px;display: flex;flex-wrap: wrap;    margin-bottom: 10px;height:35px;margin-top: 7px;">
          <div class="query">
            <span>体检单位：</span>
            <el-input
              placeholder="请选择体检单位" 
              v-model="patientRegister.query.cusOrgOCX"
              style="width: 240px"
              size="small"
              disabled
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="diagnosis.dialogCusOrgOCX = true"
                style="font-size: 20px"
              ></el-button>
            </el-input>
          </div>
          <div class="query">
            <span>诊断：</span>
            <el-input
              placeholder="请选择诊断"
              v-model="patientRegister.query.StatisticsOCX"
              style="width: 200px"
              size="small"
              disabled
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="diagnosis.dialogAsbitemOCX = true"
                style="font-size: 20px"
              ></el-button>
            </el-input>
          </div>
          <div class="query">
            <span>检查状态：</span>
            <el-select
              v-model="completeFlag"
              placeholder="请选择"
              clearable
              style="width: 80px"
              size="small"
            >
              <el-option label="预登记" value="0" />
              <el-option label="正式登记" value="1" />
              <el-option label="部份已检" value="2" />
              <el-option label="已总检" value="3" />
            </el-select>
          </div>
          <div class="query">
            <el-checkbox
              v-model="classification"
              true-label="Y"
              false-label="N"
            />
            <span style="margin-left: 5px">审核状态</span>
          </div>
          <div class="query">
            <span>报表格式：</span>
            <el-select
              v-model="format"
              placeholder="请选择"
              style="width: 80px"
              size="small"
              @change="changeValue"
            >
              <el-option label="标准格式" value="0" />
              <el-option label="精简格式" value="1" />
            </el-select>
          </div>
          <div class="query">
            <el-button @click="btnQuery" size="small" class="commonbutton"
              >查询</el-button
            >
          </div>
          <div class="query">
            <el-button @click="handleExport" size="small" class="commonbutton"
              >导出excel</el-button
            >
          </div>
          <div class="query">
            <el-button @click="onPrint" size="small" class="commonbutton"
              >打印</el-button
            >
          </div>
        </div>
        <div v-show="format == 0" ref="imageDom0">
          <div style="background-color: #fff; padding: 15px; border-radius: 8px;">
             <el-table
              border
              :height="flag
                  ?  window.pageHeight < 600
                    ? 415
                    : window.pageHeight - 185 - 20: ''
              "
              :data="dataList"
              id="projectTableData"
              ref="projectTableData"
              style="width: 100%"
              show-summary
              :summary-method="getSummaries"
            >
              <el-table-column label="阳性结果人员清单">
                <el-table-column :label="`开始时间： ${summary.startDate || ''} 结束时间：${summary.endDate || ''} 男性： ${summary.maleCount} 女性： ${summary.femaleCount}`" align="left">
                                    <template slot-scope="scope">
                    <el-table
                      :data="scope.row.patientRegisters"
                      border
                      :span-method="objectProjectSpanMethod"
                      show-summary
              :summary-method="summarizeRegisterCount"
                    >
                      <el-table-column :label="scope.row.diagnosisName">
                        <el-table-column
                          label="部门名称"
                          prop="departmentName"
                          width="300"
                        ></el-table-column>
                        <el-table-column
                          label="姓名"
                          prop="patientName"
                        ></el-table-column>
                        <el-table-column
                          label="性别"
                          prop="sexName"
                        ></el-table-column>
                        <el-table-column
                          prop="age"
                          label="年龄"
                        >
                        </el-table-column>
                        <el-table-column prop="patientRegisterNo" label="条码号">
                        </el-table-column>
                        <el-table-column
                          prop="patientNo"
                          label="档案号"
                        >
                        </el-table-column>
                        <el-table-column prop="medicalTimes" label="体检次数">
                        </el-table-column>
                        <el-table-column prop="telephone" label="电话">
                        </el-table-column>
                        <el-table-column prop="mobileTelephone" label="手机号">
                        </el-table-column>
                      </el-table-column>
                    </el-table>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div v-show="format == 1" ref="imageDom1">
          <div style="background-color: #fff; padding: 15px; border-radius: 8px;">
            <el-table
              border
              :height="
               flag
                  ? window.pageHeight < 600 ? 415 : window.pageHeight - 185-20: ''
              "
              :data="dataLists"
              id="standardTableData"
              ref="standardTableData"
              style="width: 100%"
              show-summary
              :summary-method="getSummaris"
            >
              <el-table-column label="阳性结果人员清单">
                <el-table-column :label="`开始时间： ${summary.startDate || ''} 结束时间：${summary.endDate || ''}体检人员共计： ${(summary.maleCount+summary.femaleCount)} 男性： ${summary.maleCount} 女性： ${summary.femaleCount}`" align="left">
                                  <el-table-column
                  prop="diagnosisName"
                  label="诊断名称"
                ></el-table-column>
                <el-table-column
                  prop="patientNames"
                  label="人员清单"
                ></el-table-column>
                <el-table-column
                  prop="patientCount"
                  label="人数"
                ></el-table-column>
                <el-table-column prop="percentage" label="占百分比">
                </el-table-column>
                </el-table-column>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <!--通用选单位、体检次数、分组的控件-->
    <el-dialog
      title="体检单位选择"
      :visible.sync="diagnosis.dialogCusOrgOCX"
      :close-on-click-modal="false"
      width="880px"
      height="600px"
    >
      <CusOrgOCX :initDateType="'creationTime'" :useCustomerOrg="true" />
    </el-dialog>
    <!--通用选组合项目的控件-->
    <el-dialog
      title="诊断选择"
      :visible.sync="diagnosis.dialogAsbitemOCX"
      :close-on-click-modal="false"
      width="700px"
      height="600px"
    >
      <StatisticsOCX />
    </el-dialog>
  </div>
</template>
<script>
import moment from "moment";
import { mapState, mapActions } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { exportToExcel } from "../../utlis/Export2Excel";
import html2canvas from "html2canvas";
import printJs from "print-js";
import {
  dddw,
  objCopy,
  arrayReduce,
  arrayExistObj,
  tcdate,
} from "@/utlis/proFunc";
import CusOrgOCX from "../../components/report/CusOrgOCX.vue";
import StatisticsOCX from "../../components/report/StatisticsOCX.vue";

export default {
  components: {
    CusOrgOCX,
    StatisticsOCX,
  },
  data() {
    return {
      dataList: [], //列表数据
      dataLists: [],
      completeFlag: "",
      classification: "Y",
      format: "0",
      mergedColumnes: ["departmentName"],
      spanMaps: {},
      flag: true,
      summary:{
        startDate:"",
        endDate:"",
        femaleCount:"",
        maleCount:""
      }
    };
  },

  created() {
    this.dictInit();
  },

  //挂载完成
  mounted() {
    // this.btnQuery();
  },

  computed: {
    ...mapState(["window", "dict", "patientRegister", "diagnosis"]),
  },

  methods: {
    moment,
    dddw,
    //数据初始化
    dictInit() {
      //体检中心
      getapi("/api/app/organization-units/organization-unit-by-is-peis").then(
        (res) => {
          if (res.code == 1) {
            this.dict.organization = res.data;
          }
        }
      );

      //体检单位树
      getapi("/api/app/customerorg/getbycodeall").then((res) => {
        if (res.code == 1) {
          this.patientRegister.customerOrgTreeAll = res.data;
          tcdate(this.patientRegister.customerOrgTreeAll);
        }
      });

      //体检类别
      getapi("/api/app/medical-type/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.medicalType = res.data;
        }
      });

      //体检类别 树结构
      getapi("/api/app/item-type/by-code-all").then((res) => {
        if (res.code == 1) {
          this.dict.itemTypeTree = res.data;
          tcdate(this.dict.itemTypeTree);
        }
      });   
      postapi("/api/app/Diagnosis/GetSimpleList").then((res) => {
        if (res.code == 1) {
          this.dict.asbItemAll = res.data;
        }
      });
    },
    changeValue(value) {
      if (value == 0) {
        this.$nextTick(() => {
          this.$refs.projectTableData.doLayout();
        });
      } else if (value == 1) {
        this.$nextTick(() => {
          this.$refs.standardTableData.doLayout();
        });
      }
    },
    tableRowClassName({ row, rowIndex }) {
      switch (row.isCharge) {
        case "N":
          return "danger";
        default:
          return "";
      }
    },
    getSummaris(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (index === 1) {
          let num = 0;
          data.forEach((item, index) => {
            num += item.patientCount;
          });
          sums[index] = num + " 人";
        }
      });

      return sums;
    },
    getSummaries(param){
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if(index === 0){
          let num=0
          data.forEach((item,index)=>{
            num+=item.patientRegisters.length
          })
          sums[index] = "合计：" + num + "人";
        }
      })
       return sums
    },
    summarizeRegisterCount(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "小计";
          return;
        }

        const values = data.map((item) => Number(item[column.property]));
        if (index === 1) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] = "共" + values.length + "人";
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    setProjectdates(data) {
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.mergedColumnes.forEach((column) => {
            this.spanMaps[column] = {
              spanArr: [1],
              pos: 0,
              // index:i
            };
          });
        } else {
          this.mergedColumnes.forEach((column) => {
            if (data[i][column] === data[i - 1][column]) {
              this.spanMaps[column].spanArr[this.spanMaps[column].pos] += 1;
              this.spanMaps[column].spanArr.push(0);
            } else {
              this.spanMaps[column].spanArr.push(1);
              this.spanMaps[column].pos = i;
            }
            // this.spanMap[column].index=i
          });
        }
      }
    },
    objectProjectSpanMethod({ row, column, rowIndex, columnIndex }) {
      let index = rowIndex;
      if (index === 0 && columnIndex === 0) {
        for (let i = 0; i < this.dataList.length; i++) {
          if (row.diagnosisName === this.dataList[i].diagnosisName) {
            this.setProjectdates(this.dataList[i].patientRegisters);
          }
        }
      }
      if (this.spanMaps[column.property]) {
        const _row = this.spanMaps[column.property].spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
    ForwardRanking(data){
        for (let i = 0; i < data.length; i++) {
        data[i].patientRegisters.sort(function (a, b) {
          return a.departmentName > b.departmentName ? -1 : 1; //根据名称属性进行排序
        });
      }
      for(let i = 0; i < data.length; i++){
        for(let k=0;k<data[i].patientRegisters.length;k++){
          let diagnosisName=data[i].diagnosisName
          data[i].patientRegisters[k].diagnosisName=diagnosisName
        }
      }
      this.dataList = data;
    },
    //查询
    btnQuery() {
      let body = {},
        customerOrgs = [],
        diagnosisIds = [];
      if (this.diagnosis.dataCusOrgOCX.length > 0) {
        this.diagnosis.dataCusOrgOCX.forEach((e) => {
          let rd = {
            startDate: moment(e.startDate).format("yyyy-MM-DD"),
            endDate: moment(e.endDate).format("yyyy-MM-DD"),
            dateType:
              e.dateType == "summaryDate"
                ? "3"
                : e.dateType == "medicalStartDate"
                ? "2"
                : "1",
          };

          if (e.customerOrgId) {
            rd.customerOrgId = e.customerOrgId;
            if (e.customerOrgId == this.dict.personOrgId) {
              rd.customerOrgRegisterId = null;
              rd.customerOrgGroupId = [];
            } else {
              rd.customerOrgRegisterId = e.customerOrgRegister.id;
              rd.customerOrgGroupId = e.customerOrgGroupIds;
            }
          }
          customerOrgs.push(rd);
        });
      }

      if (this.diagnosis.dataAsbitemOCX.length > 0) {
        this.diagnosis.dataAsbitemOCX.forEach((e) => {
          diagnosisIds.push(e.id);
        });
      }

      body.customerOrgs = customerOrgs;
      body.diagnosisIds = diagnosisIds;
      if (this.completeFlag) body.completeFlag = this.completeFlag;
      body.isAudit = this.classification;

      //console.log('/api/app/peisreport/getregisterasbitemchargestatus',body)
      if (this.format == 0) {
        postapi(
          "/api/customerreport/getpositivepatientregisterreportstandard",
          body
        ).then((res) => {
          if (res.code != -1) {
            this.ForwardRanking(res.data.details)
            this.summary.startDate=res.data.startDate;
          this.summary.endDate=res.data.endDate;
          this.summary.femaleCount=res.data.femaleCount;
          this.summary.maleCount=res.data.maleCount;
            this.$nextTick(() => {
          this.$refs.projectTableData.doLayout();
        });
          }
        });
      } else {
        postapi(
          "/api/customerreport/getpositivepatientregisterreportreduce",
          body
        ).then((res) => {
          if (res.code != -1) {
            this.dataLists = res.data.details;
            this.summary.startDate=res.data.startDate;
          this.summary.endDate=res.data.endDate;
          this.summary.femaleCount=res.data.femaleCount;
          this.summary.maleCount=res.data.maleCount;
            this.$nextTick(() => {
          this.$refs.standardTableData.doLayout();
        });
          }
        });
      }
    },
    onPrint() {
      this.flag = false;
      let index = "";
      if (this.format == 0) {
        index = "imageDom0";
      } else if (this.format == 1) {
        index = "imageDom1";
      }
      this.$nextTick(() => {
        let width = this.$refs[index].style.width;
        let cloneDom = this.$refs[index].cloneNode(true);
        let imageDom = this.$refs[index];
        cloneDom.style.position = "absolute";
        cloneDom.style.top = "0px";
        cloneDom.style.zIndex = "-1";
        cloneDom.style.width = width;
        console.log(cloneDom);
        imageDom.appendChild(cloneDom);
        html2canvas(cloneDom).then((canvas) => {
          // 转成图片，生成图片地址
          const url = canvas.toDataURL("image/png");
          printJs({
            printable: url,
            type: "image",
            documentTitle: "", // 标题
            style: `@media print { @page {size: auto; margin: 0 0 0 0; } body{margin:0 5px}canvas{page-break-after: always;page-break-inside: avoid;
page-break-after: avoid;
page-break-before: avoid;}}`, // 去除页眉页脚
          });
        });
        cloneDom.style.display = "none";
        this.flag = true;
      });
    },
    handleExport() {
      if (this.format == 0) {
                let index = 3;
        let list = [];
        list.push(index);
        for (let i = 0; i < this.dataList.length - 1; i++) {
          index += this.dataList[i].patientRegisters.length + 4;
          list.push(index);
        }
        exportToExcel("#projectTableData", "阳性结果人员清单", true,list);
      } else if (this.format == 1) {
        exportToExcel("#standardTableData", "阳性结果人员清单",false);
      }
    },
  },

  //监听事件
  watch: {
    //触发查询事件
    // "patientRegister.query.times"(newVal, oldVal) {
    //   if (newVal != oldVal) {
    //     //alert('触发查询事件')
    //     this.query();
    //   }
    // },
  },
};
</script>
<style scoped>
@import "../../assets/css/global_button.css";
@import "../../assets/css/global_dialog.css";
@import "../../assets/css/global_table.css";
@import "../../assets/css/global_form.css";
@import "../../assets/css/global_input.css";
@import "../../assets/css/global.css";
.query{
    margin-right: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    color: #232748;
    font-size: 400;
    font-family: "NotoSansSC-Regular";
}
.box {
  display: flex;
  flex-direction: column;
}
::v-deep .el-input__inner {
  /*text-align: center;*/
  padding-left: 5px;
  padding-right: 15px;
}

::v-deep .el-input__icon {
  width: 15px;
  /* 输入框下拉箭头或清除图标 默认 25 */
}

::v-deep .el-input-group__append {
  padding: 0 5px;
  /* 控件默认 0 20px;*/
}

::v-deep .el-icon-search:before {
  color: #00F;
}
.query:last-child{
  margin-right: 0;
}
</style>
