<template>
  <div>
    <div class="middlebox">
      <div class="contenttitle">
        体检查询 /
        <span class="contenttitleBold">营业额统计（实收）</span>
      </div>
    </div>
    <div
      style="display: flex;justify-content: space-between; padding: 10px;background-color: #fff;border-radius: 8px;margin-bottom: 10px;">
      <div style="display:block;">
        <div style="display: flex;flex-wrap: wrap;height: 32px;align-items: center;">
          <div class="query">
            <el-select v-model="query.dateType" placeholder="请选择" style="width: 80px" size="small" disabled>
              <el-option label="登记日期" :value="'1'" />
              <el-option label="体检日期" :value="'2'" />
              <el-option label="总检日期" :value="'3'" />
              <el-option label="收费日期" :value="'6'" />
            </el-select>
            <!-- dateType  1 登记，2 体检，3 总检日期-->
            <el-date-picker v-model="query.startDate" type="date" placeholder="起始日期" size="small" style="width:90px;"
              value-format="yyyy-MM-dd" :picker-options="pickerOptions" />
            <span class="spanClass">至</span>
            <el-date-picker v-model="query.endDate" type="date" placeholder="截止日期" size="small" style="width:90px;"
              value-format="yyyy-MM-dd" :picker-options="pickerOptions" />
          </div>
          <div class="query">
            <span class="spanClass">体检单位</span>
            <el-select v-model="query.customerOrgIds" placeholder="请选择体检单位" :filter-method="filterMethod"
              default-first-option clearable filterable style="margin-left: 10px;width:300px;" size="small" multiple
              collapse-tags>
              <el-option v-for="item in customerOrg" :key="item.id" :label="item.displayName" :value="item.id">
                {{ item.displayName }}
              </el-option>
            </el-select>
          </div>
          <div class="query">
            <span class="spanClass">含预登记</span>
            <el-checkbox v-model="query.isPreRegistration" true-label="Y" false-label="N" />
          </div>
          <div class="query">
            <span class="spanClass">含子单位</span>
            <el-checkbox v-model="query.isChild" true-label="Y" false-label="N" @change="btnQuery" />
          </div>
          <div class="query">
            <span class="spanClass">单位次数</span>
            <el-checkbox v-model="query.isCustomerOrgRegister" true-label="Y" false-label="N" @change="btnQuery" />
          </div>
        </div>
        <div style="display: flex;flex-wrap: wrap;margin-top: 2px; height: 32px;align-items: center;">
          <div class="query">
            <span class="spanClass">体检类别</span>
            <el-select v-model="query.medicalTypeIds" placeholder="请选择体检类别" :filter-method="filterMethod"
              default-first-option clearable filterable style="margin-left: 10px;width:200px;" size="small" multiple
              collapse-tags>
              <el-option v-for="item in medicalType" :key="item.id" :label="item.displayName" :value="item.id">
                {{ item.displayName }}
              </el-option>
            </el-select>
          </div>
          <div class="query">
            <span class="spanClass">人员类别</span>
            <el-select v-model="query.personnelTypeIds" placeholder="请选择人员类别" :filter-method="filterMethod"
              default-first-option clearable filterable style="margin-left: 10px;width:200px;" size="small" multiple
              collapse-tags>
              <el-option v-for="item in personnelType" :key="item.id" :label="item.displayName" :value="item.id">
                {{ item.displayName }}
              </el-option>
            </el-select>
          </div>
          <div class="query">
            <span class="spanClass">业务员</span>
            <el-select v-model="query.salesmans" placeholder="请输入业务员姓名" default-first-option clearable filterable
              style="margin-left: 10px" size="small" multiple collapse-tags>
              <el-option v-for="item in dictSalesman" :key="item.id" :label="item.surname" :value="item.surname" />
            </el-select>
          </div>
          <div class="query">
            <span>支付方式：</span>
            <el-select v-model="query.payModeIds" placeholder="请选择" style="margin-left: 10px" filterable clearable
              size="small" multiple collapse-tags>
              <el-option v-for="item in dict.payMode" :key="item.id" :label="item.displayName" :value="item.id" />
            </el-select>
          </div>
        </div>
      </div>
      <div style="display: block;width: 110px;">
        <div>
          <el-button type="primary" class="commonbutton" @click="btnQuery" size="small">查询</el-button>
        </div>
        <div style="margin-top: 5px;">
          <el-button class="commonbutton" @click="btnExport('tableData')" size="small">导出</el-button>
        </div>
      </div>
    </div>
    <div id="tableData">
      <el-table :data="tableData" border :height="window.pageHeight - 192" highlight-current-row size="small"
        row-key="id" :summary-method="getSummaries" show-summary ref="refTable">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="customerOrgName" label="单位名称" min-width="240" />
        <el-table-column v-if="query.isCustomerOrgRegister == 'Y' ? true : false" prop="medicalTimes" label="单位次数"
          min-width="80" align="center" />
        <el-table-column label="收款" align="center">
          <el-table-column prop="chargeCount" label="人数" min-width="80" align="center" />
          <el-table-column prop="chargeTotal" label="金额" min-width="80" align="center" />
        </el-table-column>
        <el-table-column label="退款" min-width="80" align="center">
          <el-table-column prop="refundCount" label="人数" min-width="80" align="center" />
          <el-table-column prop="refundTotal" label="金额" min-width="80" align="center" />
        </el-table-column>
        <el-table-column label="营收金额" min-width="80" align="center">
          <el-table-column prop="turnoverTotal" label="汇总" min-width="80" align="center" />
          <el-table-column v-for="(col, index) in asyncCols" :key="index" :prop="col" :label="col" min-width="80"
            align="center">
            <template slot-scope="scope">
              <el-tooltip class="item" :content="`收款：${scope.row[col + '_p']}  退款：${scope.row[col + '_b']}`"
                placement="top">
                <div v-if="scope.row[col] != 0 ? true : false">{{ scope.row[col] }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { deepCopy } from "../../utlis/proFunc"
import CusOrgOCX from "./CusOrgOCX.vue"
import moment from "moment";
import FileSaver from 'file-saver';

export default {
  components: {
    CusOrgOCX,
  },
  props: ["orgEnable"],
  data() {
    return {
      dialogVisible: false,
      local: {
        completeFlag: []
      },

      customerOrg: [],
      customerOrgAll: [],
      medicalType: [],
      personnelType: [],
      dictSalesman: [],
      query: {
        dateType: '6',
        startDate: '',
        endDate: '',
        customerOrgIds: [],
        medicalTypeIds: [],
        personnelTypeIds: [],
        salesmans: [],
        payModeIds: [],
        // isMedicalTypeId: 'Y',
        isPreRegistration: 'N',
        isChild: 'Y',
        isCustomerOrgRegister: 'N',   // 是否显示单位体检次数
      },
      tableData: [],
      asyncCols: [], // 动态列 
    };
  },

  created() {

  },

  //挂载完成
  mounted() {

    this.dictInit()

  },

  updated() {
    this.$nextTick(() => {
      this.$refs['refTable'].doLayout()
    })
  },

  computed: {
    ...mapState(["pickerOptions", "window", "dict", "patientRegister", "report"]),
  },
  methods: {
    //获取初始数据
    dictInit() {
      let today = moment(new Date()).format("YYYY-MM-DD")
      this.query.startDate = today
      this.query.endDate = today

      //获取单位列表
      getapi("/api/app/customer-org/parent-all").then((res) => {
        if (res.code != -1) {
          this.customerOrgAll = res.data;
          this.customerOrg = deepCopy(this.customerOrgAll);
        }
      });

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

      //人员类别
      getapi("/api/app/personnel-type/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.personnelType = res.data;
          this.personnelType = res.data;
        }
      });

      // 业务员 {
      postapi('/api/identity/users/GetUserListBySaleRole')
        .then(res => {
          if (res.code > -1) {
            this.dictSalesman = res.data
          }
        })

      //支付方式
      getapi("/api/app/pay-mode").then((res) => {
        if (res.code == 1) {
          this.dict.payMode = res.data;
        }
      });
    },

    //通用导出
    btnExport(elId) {
      let table = document.getElementById(elId);
      let tableData = table.innerHTML
      let fileName = moment(new Date()).format('yyyyMMDDHHmmss') + '.xls'
      let blob = new Blob([tableData], { type: "text/plain;charset=utf-8" });
      FileSaver.saveAs(blob, fileName);
    },

    // 单位过滤
    filterMethod(keyWords) {
      if (keyWords) {
        this.customerOrg = [];
        this.customerOrgAll.forEach((item) => {
          if (
            item.displayName.toLowerCase().indexOf(keyWords.toLowerCase()) > -1 ||
            item.simpleCode.toLowerCase().indexOf(keyWords.toLowerCase()) > -1
            // || item.shortName.toLowerCase().indexOf(keyWords.toLowerCase()) > - 1
          ) {
            this.customerOrg.push(item);
          }
        });
      } else {
        this.customerOrg = deepCopy(this.customerOrgAll);
      }
    },

    // 查询
    btnQuery() {
      //let body = deepCopy(this.query)
      postapi("/api/app/CustomerReport/GetCustomerOrgAmountReceivedStatistics", this.query).then(res => {
        if (res.code > -1) {
          // 动态生成新的显示数据
          this.makeDispData(res.data)
        }
      })
    },

    // 动态生成新的显示数据
    makeDispData(orgData) {
      this.tableData = []
      this.asyncCols = []
      // 没有数据返回
      if (!(Array.isArray(orgData) && orgData.length > 0)) return

      orgData.forEach(e => {
        if (this.query.isChild == 'Y') {
          e.customerOrgName = (e.customerOrgName == e.departmentName ? e.customerOrgName : e.customerOrgName + '--' + e.departmentName)
        }
        e.chargeTotal = 0
        e.refundTotal = 0
        e.feeDetail.forEach(c => {
          e.chargeTotal = Number(e.chargeTotal) + Number(c.chargeMoney)
          e.refundTotal = Number(e.refundTotal) + Number(c.refundMoney)
          if (!this.asyncCols.includes(c.payModeName)) {
            this.asyncCols.push(c.payModeName)
          }
          e[c.payModeName] = Math.round((Number(c.chargeMoney) + Number(c.refundMoney)) * 100) / 100
          e[c.payModeName + '_p'] = c.chargeMoney  // 收
          e[c.payModeName + '_b'] = c.refundMoney   // 退
        });
        e.chargeTotal = Math.round(e.chargeTotal * 100) / 100
        e.refundTotal = Math.round(e.refundTotal * 100) / 100
        e.turnoverTotal = Math.round((Number(e.chargeTotal) + Number(e.refundTotal)) * 100) / 100
        this.tableData.push(e)
      });

      this.tableData.forEach(e => {
        this.asyncCols.forEach(col => {
          if (!e[col]) {
            e[col] = 0
          }
        });
      });
      // console.log('this.tableData',this.tableData)
      // console.log('this.asyncCols',this.asyncCols)
    },

    //合计
    getSummaries(param) {
      // console.log('getSummaries param', param)
      // if(!param){
      //   param = {
      //     columns:[{}, {}, {}, {}, {}, {}, {property: 'asbitemMoney'},{property: 'customerOrgGroupDetailMoney'}],
      //     data:this.customerOrgGroupAsbitems
      //   }
      // }

      const { columns, data } = param;
      let count = 7, sumCol = []  //需合计的列      
      const sums = [];

      if (this.query.isCustomerOrgRegister == 'Y') {
        sumCol = [2, 3, 4, 5, 6, 7]
        count = 8
      } else {
        sumCol = [2, 3, 4, 5, 6]
      }
      this.asyncCols.forEach(() => {
        sumCol.push(count++)
      });

      console.log('sumCol', sumCol)
      columns.forEach((column, index) => {
        console.log('column.property, index,data', column.property, index, data)
        //显示合计列
        if (index === 1) {
          sums[index] = '合计';
          return;
        }

        //不合计的列
        if (sumCol.indexOf(index) == -1) {
          sums[index] = '';
          return;
        }

        sums[index] = 0
        data.forEach(e => {
          if (!isNaN(e[column.property])) sums[index] += Number(e[column.property])// * e['amount']
        })
        sums[index] = sums[index].toFixed(2) //+ ' 元';

      });
      // this.groupPrice = sums[7];
      // console.log('getSummaries',sums)
      // if (!this.totalFoucs) this.total = sums[5];
      // if (!this.discountFoucs) this.discount = Number(this.total * 100 / this.totalStand).toFixed(2);
      return sums;
    },

  },
};
</script>
<style scoped>
@import '../../assets/css/global.css';
@import '../../assets/css/global_font.css';

::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 {
  margin-left: 10px;
  font-size: 14px;
  color: #232748;
  font-weight: 400;
  font-family: "NotoSansSC-Regular";
}

.spanClass {
  padding: 0 2px 0 0;
}
</style>
