<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:350px" size="small"
              disabled>
              <el-button slot="append" icon="el-icon-search" @click="report.dialogCusOrgOCX = true"
                style="font-size: 20px"></el-button>
            </el-input>
          </div>
          <div class="query">
            <span>组合项目：</span>
            <el-input placeholder="请选择组合项目" v-model="patientRegister.query.asbitemOCX" style="'width:350px" size="small"
              disabled>
              <el-button slot="append" icon="el-icon-search" @click="report.dialogAsbitemOCX = true"
                style="font-size: 20px"></el-button>
            </el-input>
          </div>
          <div class="query" v-if="!cut">
            <span>报表格式：</span>
            <el-select v-model="registerType" placeholder="请选择" clearable style="width: 80px" size="small">
              <el-option label="按分组包含预登记" value="1" />
              <el-option label="按分组不包含预登记" value="2" />
              <el-option label="按分组实检(只检1项也算全部已检)" value="3" />
            </el-select>
          </div>
          <div class="query" v-if="cut">
            <span>报表格式：</span>
            <el-select v-model="complexregisterType" placeholder="请选择" clearable style="width: 80px" size="small">
              <el-option label="按组合包含预登记" value="1" />
              <el-option label="按组合不包含预登记" value="2" />
              <el-option label="按组合实检" value="3" />
              <el-option label="按组合实检(只检1项也算全部已检)" value="4" />
            </el-select>
          </div>
          <div class="query">
            <el-checkbox v-model="checkbox" true-label="1" false-label="0" @change="bespeak" />
            <span style="margin-left: 5px">显示人员名单</span>
          </div>
          <div class="query">
            <el-checkbox v-model="isPersonalPayment" true-label="Y" false-label="N" />
            <span style="margin-left: 5px">包含个人支付和免费赠送</span>
          </div>
          <div class="query">
            <el-button size="small" @click="onSubmit" class="commonbutton">查询</el-button>
          </div>
          <div class="query">
            <!--旧导出方式 handleExport、btnExport('expUnitSettlement') -->
            <el-button size="small" class="commonbutton" @click="btnExport('expUnitSettlement')">导出excel</el-button>
          </div>
          <div class="query">
            <el-button size="small" @click="onPrint" class="commonbutton">打印</el-button>
          </div>
        </div>
        <div id="expUnitSettlement">
          <div id="expUnitSettlement0" style="background-color: #fff; padding: 15px; border-radius: 8px" ref="imageDom0" v-show="format == 0">
            <div>
              <el-table border :height="flag
                ? window.pageHeight < 600
                  ? 415
                  : window.pageHeight - 185 - 25
                : ''
                " :data="tableData" id="tableData" ref="tableData" style="width: 100%" show-summary
                :summary-method="summarizeRegisterCountes">
                <el-table-column label="单位结算统计">
                  <template slot-scope="scope">
                    <el-table :data="scope.row.groupDetails" border show-summary
                      :summary-method="summarizeRegisterCount">
                      <el-table-column label="分组" prop="customerOrgGroupName"></el-table-column>
                      <el-table-column label="分组价格" prop="customerOrgGroupPrice"></el-table-column>
                      <el-table-column label="人数" prop="patientCount"></el-table-column>
                      <el-table-column label="总金额" prop="sumPrice"></el-table-column>
                    </el-table>
                    <el-table :data="scope.row.addItems" border show-summary :summary-method="summarizeRegisterCount2">
                      <el-table-column label="加做项目" prop="asbitemName"></el-table-column>
                      <el-table-column label="人数" prop="patientCount"></el-table-column>
                      <el-table-column label="标准价格" prop="standardPrice"></el-table-column>
                      <el-table-column label="应收价格" prop="price"></el-table-column>
                      <el-table-column label="标准金额" prop="standardMoney"></el-table-column>
                      <el-table-column label="应收金额" prop="sumPrice"></el-table-column>
                    </el-table>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <div id="expUnitSettlement1" style="background-color: #fff; padding: 15px; border-radius: 8px" ref="imageDom1" v-show="format == 1">
            <div>
              <el-table border :height="flag
                ? window.pageHeight < 600
                  ? 415
                  : window.pageHeight - 185 - 25
                : ''
                " :data="stafftableData" id="stafftableData" ref="stafftableData" style="width: 100%" show-summary
                :summary-method="summarizeRegisterCountes">
                <el-table-column label="单位结算统计">
                  <template slot-scope="scope">
                    <el-table :data="scope.row.groupDetails" border>
                      <el-table-column label="分组">
                        <template slot-scope="scopes">
                          <el-table :data="scopes.row.patients" border show-summary :summary-method="(params) =>
                            summarizeRegisterCounts(
                              params,
                              scopes.row.sumPrice
                            )
                            ">
                            <el-table-column :label="scopes.row.customerOrgGroupName +
                              ' 价格：' +
                              scopes.row.customerOrgGroupPrice
                              ">
                              <el-table-column label="姓名" prop="patientName"></el-table-column>
                              <el-table-column label="条码号" prop="patientRegisterNo"
                                :formatter="forceStringFormatter"></el-table-column>
                              <el-table-column label="档案号" prop="patientNo" :formatter="forceStringFormatter">
                              </el-table-column>
                              <el-table-column label="性别" prop="sexName"></el-table-column>
                              <el-table-column label="年龄" prop="age"></el-table-column>
                            </el-table-column>
                          </el-table>
                        </template>
                      </el-table-column>
                    </el-table>
                    <el-table :data="scope.row.addItems" border style="margin-top: 10px">
                      <el-table-column label="加做项目">
                        <template slot-scope="scopes">
                          <el-table :data="scopes.row.patients" border show-summary :summary-method="(params) =>
                            summarizeRegisterCounts(
                              params,
                              scopes.row.sumPrice
                            )
                            ">
                            <el-table-column :label="scopes.row.asbitemName +
                              ' 价格：' +
                              scopes.row.price
                              ">
                              <el-table-column label="姓名" prop="patientName"></el-table-column>
                              <el-table-column label="条码号" prop="patientRegisterNo" :formatter="forceStringFormatter"></el-table-column>
                              <el-table-column label="档案号" prop="patientNo" :formatter="forceStringFormatter"></el-table-column>
                              <el-table-column label="性别" prop="sexName"></el-table-column>
                              <el-table-column label="年龄" prop="age"></el-table-column>
                            </el-table-column>
                          </el-table>
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div id="expUnitSettlement2" style="background-color: #fff; padding: 15px; border-radius: 8px" ref="imageDom2" v-show="format == 2">
            <div>
              <el-table border :height="flag
                ? window.pageHeight < 600
                  ? 415
                  : window.pageHeight - 185 - 25
                : ''
                " :data="projecttableData" id="projecttableData" ref="projecttableData" style="width: 100%"
                show-summary :summary-method="projectsummarizeRegisterCount">
                <el-table-column label="单位结算统计">
                  <el-table-column label="项目类别" prop="itmeTypeName"></el-table-column>
                  <el-table-column label="组合项目" prop="asbitemName"></el-table-column>
                  <el-table-column label="标准价格" prop="standardPrice"></el-table-column>
                  <el-table-column label="价格" prop="chargePrice"></el-table-column>
                  <el-table-column label="人数" prop="patientCount"></el-table-column>
                  <el-table-column label="标准金额" prop="standardAmount"></el-table-column>
                  <el-table-column label="折扣" prop="discount"></el-table-column>
                  <el-table-column label="金额" prop="chargeAmount"></el-table-column>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div id="expUnitSettlement3" style="background-color: #fff; padding: 15px; border-radius: 8px" ref="imageDom3" v-show="format == 3">
            <div>
              <el-table border :height="flag
                ? window.pageHeight < 600
                  ? 415
                  : window.pageHeight - 185 - 25
                : ''
                " :data="projectcomplextableData" id="projectcomplextableData" ref="projectcomplextableData"
                style="width: 100%" show-summary :summary-method="projectcomplexsummarizeRegisterCountes">
                <el-table-column label="单位结算统计">
                  <template slot-scope="scope">
                    <el-table :data="scope.row.patients" border show-summary :summary-method="(params) =>
                      projectcomplexsummarizeRegisterCounts(
                        params,
                        scope.row.chargeAmount
                      )
                      ">
                      <el-table-column :label="scope.row.asbitemName +
                        ' 价格：' +
                        scope.row.chargePrice
                        ">
                        <el-table-column label="姓名" prop="patientName"></el-table-column>
                        <el-table-column label="条码号" prop="patientRegisterNo" :formatter="forceStringFormatter"></el-table-column>
                        <el-table-column label="档案号" prop="patientNo" :formatter="forceStringFormatter"></el-table-column>
                        <el-table-column label="性别" prop="sexName"></el-table-column>
                        <el-table-column label="年龄" prop="age"></el-table-column>
                      </el-table-column>
                    </el-table>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--通用选单位、体检次数、分组的控件-->
    <el-dialog title="体检单位选择" :visible.sync="report.dialogCusOrgOCX" :close-on-click-modal="false" width="880px"
      height="600px">
      <CusOrgOCX :initDateType="'creationTime'" :useCustomerOrg="true" />
    </el-dialog>
    <!--通用选组合项目的控件-->
    <el-dialog title="组合项目选择" :visible.sync="report.dialogAsbitemOCX" :close-on-click-modal="false" width="700px"
      height="600px">
      <AsbitemOCX />
    </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 FileSaver from 'file-saver';
import html2canvas from "html2canvas";
import printJs from "print-js";
import CusOrgOCX from "../../components/report/CusOrgOCX.vue";
import AsbitemOCX from "../../components/report/AsbitemOCX.vue";
export default {
  components: {
    CusOrgOCX,
    AsbitemOCX,
  },
  data() {
    return {
      tableData: [],
      flag: true,
      format: "0",
      registerType: "2",
      isPersonalPayment: "N",
      stafftableData: [],
      cut: false,
      checkbox: "0",
      projecttableData: [],
      projectcomplextableData: [],
      complexregisterType: "2",
    };
  },
  created() { },
  mounted() {
    if (this.report.dataAsbitemOCX.length > 0) {
      this.cut = true;
      if (this.checkbox == 0) {
        this.format = "2";
      } else {
        this.format = "3";
      }
    } else {
      this.cut = false;
      if (this.checkbox == 0) {
        this.format = "0";
      } else {
        this.format = "1";
      }
    }
  },
  computed: {
    ...mapState(["window", "dict", "patientRegister", "report"]),
  },
  watch: {
    "report.dataAsbitemOCX"(newVal, oldVal) {
      if (newVal.length > 0) {
        this.cut = true;
        if (this.checkbox == 0) {
          this.format = "2";
        } else {
          this.format = "3";
        }
      } else {
        this.cut = false;
        if (this.checkbox == 0) {
          this.format = "0";
        } else {
          this.format = "1";
        }
      }
    },
  },
  methods: {
    bespeak(e) {
      console.log(e);
      if (this.cut) {
        if (e == 0) {
          this.format = "2";
        } else {
          this.format = "3";
        }
      } else {
        if (e == 0) {
          this.format = "0";
        } else {
          this.format = "1";
        }
      }
    },
    onPrint() {
      this.flag = false;
      let index = "";
      if (this.format == 0) {
        index = "imageDom0";
      } else if (this.format == 1) {
        index = "imageDom1";
      } else if (this.format == 2) {
        index = "imageDom2";
      } else if (this.format == 3) {
        index = "imageDom3";
      }
      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;
      });
    },

    // 强制将单元格值转换为字符串
    forceStringFormatter(row, column, cellValue) {
      // 如果 cellValue 存在，则转为字符串；否则返回原值
      return cellValue ? "\u200C" + String(cellValue) : cellValue
    },

    //通用导出
    btnExport(elId) {
      // 获取HTML元素（表格）
      // let table = document.getElementById(elId); //.cloneNode(true)
      this.$nextTick(() => {
        // let refsTable = this.$refs[elId]  //.cloneNode(true) true
        let table = document.getElementById(elId + this.format)
        // console.log('table,refsTable', table, refsTable)

        let tableData = table.innerHTML
        let fileName = moment(new Date()).format('yyyyMMDDHHmmss')

        let blob = new Blob([tableData], { type: "text/plain;charset=utf-8" });

        FileSaver.saveAs(blob, fileName + '.xls');

      })
    },


    onSubmit() {
      let body = {},
        customerOrgs = [],
        asbitemIds = [];
      if (this.report.dataCusOrgOCX.length > 0) {
        this.report.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.report.dataAsbitemOCX.length > 0) {
        this.report.dataAsbitemOCX.forEach((e) => {
          asbitemIds.push(e.id);
        });
      }

      body.customerOrgs = customerOrgs;
      body.registerType = this.registerType;
      if (this.cut) {
        body.asbitemIds = asbitemIds;
        body.registerType = this.complexregisterType;
      }
      body.isPersonalPayment = this.isPersonalPayment;

      if (this.format == 0) {
        postapi(
          "/api/customerreport/getcustomerorgfeesettlementingroupreportreduce",
          body
        ).then((res) => {
          if (res.code != -1) {
            this.tableData = [];
            this.tableData.push(res.data);
          }
        });
      } else if (this.format == 1) {
        postapi(
          "/api/customerreport/getcustomerorgfeesettlementingroupreportdetail",
          body
        ).then((res) => {
          if (res.code != -1) {
            this.stafftableData = [];
            this.stafftableData.push(res.data);
          }
        });
      } else if (this.format == 2) {
        postapi(
          "/api/customerreport/getcustomerorgfeesettlementinasbitemreportreduce",
          body
        ).then((res) => {
          if (res.code != -1) {
            this.projecttableData = [];
            this.projecttableData = res.data.asbtiems;
          }
        });
      } else if (this.format == 3) {
        postapi(
          "/api/customerreport/getcustomerorgfeesettlementinasbitemreportdetail",
          body
        ).then((res) => {
          if (res.code != -1) {
            this.projectcomplextableData = [];
            this.projectcomplextableData = res.data.asbtiems;
          }
        });
      }
    },

    summarizeRegisterCount(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (index === 3) {
          let sum = 0;
          data.forEach((data, index) => {
            sum = (Number(sum) + Number(data.sumPrice)).toFixed(2);
          });
          sums[index] = sum;
          return;
        }
      });

      return sums;
    },

    summarizeRegisterCount2(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (index == 4) {
          let sum = 0;
          data.forEach((data, index) => {
            sum = (Number(sum) + Number(data.standardMoney)).toFixed(2);
          });
          sums[index] = sum;
          return;
        }
        if (index === 5) {
          let sum = 0;
          data.forEach((data, index) => {
            sum = (Number(sum) + Number(data.sumPrice)).toFixed(2);
          });
          sums[index] = sum;
          return;
        }
      });

      return sums;
    },

    summarizeRegisterCounts(param, e) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "共" + data.length + "人";
          return;
        }
        if (index === 3) {
          sums[index] = "小计";
          return;
        }
        if (index === 4) {
          sums[index] = e;
          return;
        }
      });

      return sums;
    },

    summarizeRegisterCountes(param) {
      const { columns, data } = param;
      const sums = [];
      if (data.length > 0) {
        columns.forEach((column, index) => {
          if (index === 0) {
            let sumPrice = 0;
            let groupDetail = data[0].groupDetails;
            let addItem = data[0].addItems;
            for (let i = 0; i < groupDetail.length; i++) {
              sumPrice = (
                Number(sumPrice) + Number(groupDetail[i].sumPrice)
              ).toFixed(2);
            }
            for (let i = 0; i < addItem.length; i++) {
              sumPrice = (
                Number(sumPrice) + Number(addItem[i].sumPrice)
              ).toFixed(2);
            }
            sums[index] = "总计" + sumPrice;
            return;
          }
        });
      }
      return sums;
    },

    projectsummarizeRegisterCount(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 (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return (Number(prev) + Number(curr)).toFixed(2);
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    projectcomplexsummarizeRegisterCounts(param, e) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "共" + data.length + "人";
          return;
        }
        if (index === 3) {
          sums[index] = "小计";
          return;
        }
        if (index === 4) {
          sums[index] = e + "元";
          return;
        }
      });

      return sums;
    },
    projectcomplexsummarizeRegisterCountes(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          let sumPrice = 0;
          for (let i = 0; i < data.length; i++) {
            sumPrice = (
              Number(sumPrice) + Number(data[i].chargeAmount)
            ).toFixed(2);
          }
          sums[index] = "总计" + sumPrice;
          return;
        }
      });
      return sums;
    },

    // 旧的导出方式
    handleExport() {
      if (this.format == 0) {
        exportToExcel("#tableData", "单位体检结算", true, [2]);
      } else if (this.format == 1) {
        let index = 4;
        let list = [2, 4];
        for (
          let i = 0;
          i < this.stafftableData[0].groupDetails.length - 1;
          i++
        ) {
          index += this.stafftableData[0].groupDetails[i].patients.length + 3;
          list.push(index);
        }
        index += 4;
        list.push(index);
        for (let i = 0; i < this.stafftableData[0].addItems.length - 1; i++) {
          index += this.stafftableData[0].addItems[i].patients.length + 3;
          list.push(index);
        }
        exportToExcel("#stafftableData", "单位体检结算", true, list);
      } else if (this.format == 2) {
        exportToExcel("#projecttableData", "单位体检结算", false);
      } else if (this.format == 3) {
        let index = 2;
        let list = [2];
        for (let i = 0; i < this.projectcomplextableData.length - 1; i++) {
          index += this.projectcomplextableData[i].patients.length + 3;
          list.push(index);
        }
        exportToExcel("#projectcomplextableData", "单位体检结算", true, list);
      }
    },


  },
  updated() {
    this.$nextTick(() => {
      this.$refs.tableData.doLayout();
      this.$refs.projecttableData.doLayout();
    });
  },
};
</script>
<style scoped>
@import "../../assets/css/global_button.css";
@import "../../assets/css/global_card.css";
@import "../../assets/css/global_input.css";
@import "../../assets/css/global_table.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;
}

::v-deep .el-input-group {
  width: 75%;
}

.query:last-child {
  margin-right: 0;
}
</style>