<template>
  <div>
    <el-card>
      <div slot="header">体检收费</div>
      <div style="display: flex; width: 100%;">
        <!-- 查询条件 与列表  -->
        <div class="queryDivClass">
          <!-- 查询条件 -->
          <div style="height: 80px;">
            <div style="display:flex;">
              <div>
                <span>登记日期：</span>
                <el-date-picker v-model="query.startDate" type="date" placeholder="起始日期" size="small" style="width:90px;"/>
                <span>至</span>
                <el-date-picker v-model="query.endDate" type="date" placeholder="截止日期" size="small" style="width:90px;"/>
              </div>
              <div style="margin-left:10px;">
                <el-button type="primary" class="btnClass" @click="Query" size="small" style="width:95px;">查询</el-button>
              </div>
            </div>
            <div style="display:flex;margin-top:10px;">
              <el-radio-group v-model="query.chargeFlag" @input="Query" size="mini" style="margin-top:8px;">
                <el-radio label="N">未收费</el-radio>
                <el-radio label="Y">已收费</el-radio>
                <el-radio label="B">已退费</el-radio>
              </el-radio-group>
              <div v-if="query.chargeFlag != 'N'" style="margin-left:20px;">
                <span>发票号</span>
                <el-input placeholder="发票/收据号" v-model="query.invoiceNo" size="small" style="width: 100px;" clearable
                  @change="Query('invoiceNo')" />
              </div>
            </div>
          </div>
          <!-- 列表 -->
          <div class="prListDivClass">
            <el-table :data="patientList" border highlight-current-row ref="patientList"
              :height="(window.pageHeight > 600 ? (window.pageHeight - 230) : 370)" @row-click="rowClick" size="small">
              <!--  
                <el-table-column prop="patientRegisterId" label="体检记录ID" />
              -->
              <el-table-column prop="customerOrgParentName" label="单位" width="180">
                <template slot-scope="scope">
                  <div>{{ scope.row.customerOrgParentName ? scope.row.customerOrgParentName : scope.row.customerOrgName }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="patientName" label="姓名" />
              <el-table-column prop="sexId" label="性别" />
              <el-table-column prop="age" label="年龄" />
              <el-table-column prop="patientRegisterNo" label="条码号" width="150" />
              <el-table-column prop="patientNo" label="档案号" />
              <el-table-column prop="medicalTimes" label="体检次数" />
              <el-table-column prop="isVip" label="是否VIP">
                <template slot-scope="scope">
                  <div>{{ scope.row.isVip == "Y" ? "是" : "否" }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="salesman" label="介绍人" />
              <el-table-column prop="invoiceNo" label="发票号" />
              <el-table-column prop="invoiceOrgName" label="发票抬头" />
              <!--
              <el-table-column prop="chargeId" label="介绍人" />
              <el-table-column prop="chargeBackId" label="介绍人" />
              -->
              <el-table-column prop="email" label="邮箱" width="180" />
              <el-table-column prop="idNo" label="身份证" width="150" />
              <el-table-column prop="mobileTelephone" label="手机" width="100" />
              <el-table-column prop="telephone" label="电话" width="100" />
              <el-table-column prop="address" label="地址" width="300" />

            </el-table>
          </div>
        </div>
        <!-- 收费操作  -->
        <div class="queryDivClass" style="margin-left:5px;">
          <!-- 查询信息  -->
          <div style="height: 40px;">
            <div style="display: flex; flex-wrap: wrap;margin-top:40px; height:40px; width: 100%;">
              <div class="query">
                <span>条码号</span>
                <el-input placeholder="条码号" v-model="query.patientRegisterNo" size="small" style="width: 140px;" clearable
                  @change="Query('patientRegisterNo')" />
              </div>
              <div class="query">
                <span>档案号</span>
                <el-input placeholder="档案号" v-model="query.patientNo" size="small" style="width: 100px;" clearable
                  @change="Query('patientNo')" />
              </div>
              <div class="query">
                <span>姓名</span>
                <el-input placeholder="姓名" v-model="query.patientName" size="small" style="width: 100px;" disabled
                  @change="Query" />
              </div>
            </div>
          </div>
          <!-- 收费信息  -->
          <div class="prListDivClass">
            <!-- charge  -->
            <div style="height:148px;">
              <el-form ref="form" :model="form" label-width="80px" :rules="rules" size="small"
                :disabled="query.chargeFlag != 'N'">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="发票号" prop="invoiceNo">
                      <el-input v-model="form.invoiceNo" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="开票抬头" prop="invoiceOrgName">
                      <el-input v-model="form.invoiceOrgName" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="折扣" prop="discount">
                      <el-input v-model="form.discount" @input="discountToDetails" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="应收金额" prop="total">
                      <el-input v-model="form.total" @input="totalToDetails" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-if="query.chargeFlag == 'N'">
                  <el-col :span="12">
                    <el-form-item label="预收金额" prop="preTotal">
                      <el-input v-model="form.preTotal" disabled/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="找零" prop="balance">
                      <el-input v-model="form.balance" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <!-- charge_pay  -->
            <div>
              <div style="margin-top:5px;font-size:10px;">{{ query.chargeFlag == 'B' ? '退' : '收' }}费方式：</div>
              <el-table :data="chargePays" border highlight-current-row size="small"
                :height="window.pageHeight > 600 ? (window.pageHeight - 270 - 146) / 2 : 92">
                <el-table-column prop="payModeId" :label="(query.chargeFlag == 'B' ? '退' : '收') + '费方式'" width="180">
                  <template slot-scope="scope">
                    <div>{{ dddw(dict.payMode, "id", scope.row.payModeId, "displayName") }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="chargeMoney" label="金额">
                  <template slot-scope="scope">
                    <el-input type="number" v-model="scope.row.chargeMoney" size="small" @input="inputMoney"
                      :disabled="query.chargeFlag == 'B'" />
                  </template>
                </el-table-column>
                <el-table-column prop="cardRegisterId" label="会员卡">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.cardRegisterId" placeholder="请选择" size="small" filterable clearable
                      :disabled="scope.row.payModeId == '05' && query.chargeFlag != 'B' ? false : true">
                      <el-option v-for="item in cardRegister" :key="item.id" :label="item.cardNo" :value="item.id" />
                    </el-select>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- asbitem  -->
            <div>
              <div style="margin-top:5px; font-size:10px;">{{ query.chargeFlag == 'N' ? '待收' : (query.chargeFlag == 'Y' ?
                '已收' : '已退') }}费项目：</div>
              <el-table :data="asbItemsForFee" border highlight-current-row
                :height="window.pageHeight > 600 ? (window.pageHeight - 270 - 146) / 2 : 92" size="small"
                @selection-change="handleSelectionChange" ref="asbItemsForFeeTable">
                <el-table-column type="selection" align="center" v-if="query.chargeFlag == 'N'" />
                <el-table-column label="组合项目" width="120" prop="asbitemName" />
                <el-table-column label="标准价格" prop="standardPrice" width="80" align="center" />
                <el-table-column label="折扣" prop="discount" width="60" align="center">
                  <template slot-scope="scope">
                    <el-input type="number" v-model="scope.row.discount" v-if="query.chargeFlag == 'N'"
                      :disabled="scope.row.isCharge == 'Y' ? true : false" size="small"
                      @input="changeDiscount(scope.row)" />
                    <div v-if="query.chargeFlag != 'N'">{{ scope.row.discount }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="数量" prop="amount" width="50" align="center" />
                <el-table-column label="实收价格" prop="chargePrice" width="80" align="center">
                  <template slot-scope="scope">
                    <el-input type="number" v-model="scope.row.chargePrice" v-if="query.chargeFlag == 'N'"
                      :disabled="scope.row.isCharge == 'Y' ? true : false" size="small" @input="changePrice(scope.row)" />
                    <div v-if="query.chargeFlag != 'N'">{{ scope.row.chargePrice }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="total" label="金额" width="70" v-if="false" />
                <el-table-column prop="standardPrice" label="标准金额" width="80" v-if="false" />
                <el-table-column label="支付方式" prop="payTypeFlag" width="100" align="center">
                  <template slot-scope="scope">
                    <div>{{ dddw(dict.payType, "id", scope.row.payTypeFlag, "displayName") }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="checkCompleteFlag" label="状态" align="center">
                  <template slot-scope="scope">
                    <div>{{ dddw(dict.checkCompleteFlag, "id", scope.row.checkCompleteFlag, "displayName") }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="creatorName" label="登记人" align="center" />
                <el-table-column prop="creationTime" label="登记日期" width="90" align="center">
                  <template slot-scope="scope">
                    <div v-if="scope.row.creationTime">{{ moment(scope.row.creationTime).format('yyyy-MM-DD') }}</div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <div class="btnDivClass">
          <div class="btnListClass">
            <el-button type="primary" class="btnClass" @click="btnCharge"
              :disabled="query.chargeFlag == 'N' ? false : true">收费</el-button>
          </div>
          <div class="btnListClass">
            <el-button type="danger" class="btnClass" @click="btnChargeBack"
              :disabled="query.chargeFlag == 'Y' ? false : true">退费</el-button>
          </div>
          <div class="btnListClass">
            <el-button type="success" class="btnClass" @click="chargePrint('0007', false, form.id)"
              :disabled="query.chargeFlag == 'B' ? true : false">打印</el-button>
          </div>
          <div class="btnListClass">
            <el-button type="success" class="btnClass" @click="chargePrint('0007', true, form.id)"
              :disabled="query.chargeFlag == 'B' ? true : false">打印预览</el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script>
import moment from 'moment';
import { mapState, mapActions } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { tcdate, dddw, arrayExistObj, deepCopy } from "../../utlis/proFunc";

import PatientRegisterQuery from "../../components/patientRegister/patientRegisterQuery.vue";
import PatientRegisterRefuseList from "../../components/patientRegister/PatientRegisterRefuseList.vue";

export default {
  components: {
    PatientRegisterQuery,
    PatientRegisterRefuseList,
  },
  props:["patientRegisterNo"],
  data() {
    return {
      query: {
        chargeFlag: 'N',  // N:未收费，Y：已收费，B：已退费
        dateRange: null,
        startDate: null,
        endDate: null,
        patientRegisterNo: '',
        patientNo: '',
        invoiceNo: '',
        patientName: '',
      },//查询条件
      patientList: [],//人员列表
      formInit:{},
      form: {
        id: null,
        patientRegisterId: null,
        invoiceNo: '',
        invoiceOrgName: '',
        chargeFlag: '0',
        discount: 100,
        total: 0,  //应收金额
        preTotal: 0,  //预收金额
        balance: 0,  //找零
      },  //收费主表
      rules: {
        invoiceNo: [
          { required: true, message: "请填写发票/收据号", trigger: "blur" },
        ],
        total: [
          { required: true, message: "请填写应收金额", trigger: "blur" },
        ],
      },

      // pickerOptions: {
      //   shortcuts: [
      //     {
      //       text: "最近一周",
      //       onClick(picker) {
      //         const end = new Date();
      //         const start = new Date();
      //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      //         picker.$emit("pick", [start, end]);
      //       },
      //     },
      //     {
      //       text: "最近一个月",
      //       onClick(picker) {
      //         const end = new Date();
      //         const start = new Date();
      //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      //         picker.$emit("pick", [start, end]);
      //       },
      //     },
      //     {
      //       text: "最近三个月",
      //       onClick(picker) {
      //         const end = new Date();
      //         const start = new Date();
      //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      //         picker.$emit("pick", [start, end]);
      //       },
      //     },
      //   ],
      // },
      chargePays: [],  //收支方式
      chargePaysInit: [],  //收支方式(初始状态)
      asbItemsForFee: [],  //待收费项目
      selectedData: [],    //选中项目
      cardRegister: [{ id: '00000000-0000-0000-0000-000000000000', cardNo: '0001' }],      //当前客户的会员卡
      cardRegisterAll: [],   //所有客户的会员卡
    };
  },

  created() {
    this.formInit = Object.assign({},this.form) 
    this.dictInit();    
  },

  //挂载完成
  mounted() {
    if(this.patientRegisterNo){
      this.Query('patientRegisterNo');
    }else{
      this.Query();
    }    
  },

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

  methods: {
    ...mapActions(["getCustomerOrgGroup"]),

    dddw, moment,

    //查询人员列表数据
    Query(type) {
      let url = '', ltype = type,body = {};
      

      // {
      //   "skipCount": 2147483647,
      //   "sorting": "string",
      //   "patientName": "string",
      //   "patientNo": "string",
      //   "patientRegisterNo": "string",
      //   "invoiceNo": "string",
      //   "startDate": "string",
      //   "endDate": "string",
      //   "maxResultCount": 0
      // }
              
      if(this.patientRegisterNo){
        this.query.patientRegisterNo = this.patientRegisterNo
        ltype = 'patientRegisterNo'
      }
      

      console.log('query', ltype, this.query,this.patientRegisterNo);

      if (ltype == 'patientRegisterNo') {
        if (!this.query.patientRegisterNo) return;
        body = { patientRegisterNo: this.query.patientRegisterNo };
      } else if (ltype == 'patientNo') {
        if (!this.query.patientNo) return;
        body = { patientNo: this.query.patientNo };
      } else if (ltype == 'invoiceNo' && this.query.chargeFlag != 'N') {
        if (!this.query.invoiceNo) return;
        body = { invoiceNo: this.query.invoiceNo };
      } else {
        if (this.query.startDate && this.query.endDate) {
          body.startDate = moment(this.query.startDate).format("yyyy-MM-DD")
          body.endDate = moment(this.query.endDate).format("yyyy-MM-DD")
          if(body.startDate > body.endDate){
            this.$message.warning("起始日期不能大于截止日期，数据校验不通过！")
            return
          }
        }
      }

      switch (this.query.chargeFlag) {
        case 'Y':
          //已收费
          url = '/api/app/patientregister/getpatientregisterchargelist';
          break;
        case 'B':
          //已退费
          url = '/api/app/patientregister/getpatientregisterchargebacklist';
          break;
        default:
          //未收费
          url = '/api/app/patientregister/getpatientregisternotchargedlist'
          break;
      }

      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      postapi(url, body).then(res => {
        console.log(url,body,res)
        if (res.code != - 1) {
          this.patientList = res.data.items;
          //this.patientList.length == 1 && this.query.chargeFlag == 'N'
          if (this.patientList.length > 0) {
            // this.query.patientRegisterNo = this.patientList[0].patientRegisterNo;
            // this.query.patientName = this.patientList[0].patientName;
            // this.query.patientNo = this.patientList[0].patientNo;
            this.$nextTick(() =>{
              setTimeout(() => {
                this.$refs['patientList'].setCurrentRow(this.patientList[0]) 
                this.rowClick(this.patientList[0])
              }, 20)
            })            
          }else{
            this.asbItemsForFee = []
            this.form = Object.assign({},this.formInit)
          }
        }
        loading.close();
      })
      .catch((err) => {
        loading.close();
      });

    },

    //人员列表点击
    rowClick(row) {
      this.query.patientRegisterNo = row.patientRegisterNo;
      this.query.patientName = row.patientName;
      this.query.patientNo = row.patientNo;

      this.chargePays = deepCopy(this.chargePaysInit);
      console.log(this.chargePays, this.chargePaysInit);

      if (this.query.chargeFlag == 'B') {
        this.form.chargeFlag = '1';
      } else {
        this.form.chargeFlag = '0';
      }

      if (row.chargeId) {
        this.form.id = row.chargeId;
        this.form.invoiceNo = row.invoiceNo;
        this.form.invoiceOrgName = row.patientName;
      } else {
        this.form.id = null;
        this.form.invoiceNo = '';
        this.form.invoiceOrgName = row.patientName;
      }

      //获取个人会员卡信息
      this.getCardRegister(row.idNo);



      switch (this.query.chargeFlag) {
        case 'N':
          this.getAsbItemsForFee(row.patientRegisterId);
          break;
        case 'Y':
          this.getChargePayByChargeId(row.chargeId);
          this.getChargeAsbByChargeid(row.chargeId);
          break;
        default:
          this.getChargeBackPayByChargeBackId(row.chargeBackId);
          this.getChargeAsbByChargeid(row.chargeId);
          break;
      }
    },

    //获取项目列表
    async getAsbItemsForFee(patientRegisterId) {
      //待收费项目列表      
      this.asbItemsForFee = [];

      getapi(`/api/app/registerasbitem/getlistinpatientregisterid?PatientRegisterId=${patientRegisterId}`)
        .then(res => {
          if (res.code == 1) {
            this.asbItemsForFee = res.data;

            for (let i = this.asbItemsForFee.length - 1; i >= 0; i--) {
              if (this.asbItemsForFee[i].isCharge == 'Y' || this.asbItemsForFee[i].payTypeFlag == '1') {
                this.asbItemsForFee.splice(i, 1);
                continue;
              }
              this.asbItemsForFee[i].chargePriceOri = this.asbItemsForFee[i].chargePrice;
              this.asbItemsForFee[i].discount = Math.round(10000 * this.asbItemsForFee[i].chargePrice / this.asbItemsForFee[i].standardPrice) / 100;
              this.asbItemsForFee[i].standTotal = this.asbItemsForFee[i].amount * this.asbItemsForFee[i].standardPrice;
              this.asbItemsForFee[i].total = this.asbItemsForFee[i].amount * this.asbItemsForFee[i].chargePrice;
            }

            //勾选已收费项目
            this.toCharge(patientRegisterId);
          }
        });

    },


    // "chargeId": "3a0d5685-b3a0-0186-0dd4-3b3ac0d2d08c",
    // "asbitemId": "3a0c657d-4e73-9bab-68da-56ab2f088bb1",
    // "asbitemName": "身高体重",
    // "asbitemPrice": 17,
    // "chargePrice": 18,
    // "amount": 1,
    // "registerAsbitemId": "3a0c6589-9b27-68d1-32f6-51082031d11c",
    // "creatorName": "admin",
    // "lastModifierName": null,
    // "lastModificationTime": null,
    // "lastModifierId": null,
    // "creationTime": "2023-08-30T10:49:48.753174",
    // "creatorId": "3a0c4180-107c-0c89-b25b-0bd34666dcec",
    // "id": "3a0d5685-b3bb-8dc2-0d14-56af1ddd11f9"

    // 获取个人充值卡
    getCardRegister(idNo) {
      this.cardRegister = [];

      if(!idNo) return;
      let body = { cardModeId: '0', idNo };      
      postapi(`/api/app/cardregister/getcardregisterlist`, body).then(res => {
        if (res.code != - 1) {
          this.cardRegister = res.data;
        }
      });
    },


    //获取收费单包含的组合项目
    getChargeAsbByChargeid(ChargeId) {
      this.asbItemsForFee = [];
      getapi(`/api/app/chargeasbitem/getchargeasbiteminchargeid?ChargeId=${ChargeId}`).then(res => { 
        if (res.code != - 1) {
          res.data.forEach(e => {
            this.asbItemsForFee.push({
              asbitemName: e.asbitemName,
              standardPrice: e.asbitemPrice,
              chargePrice: e.chargePrice,
              chargePriceOri: e.chargePrice,
              amount: e.amount,
              discount: Math.round(10000 * e.chargePrice / e.asbitemPrice) / 100,
              payTypeFlag: e.payTypeFlag,
              checkCompleteFlag: e.checkCompleteFlag,
              creatorName: e.creatorName,
              creationTime: e.creationTime,
            });
          });
          this.sumTotal(this.asbItemsForFee, this.form);
        }
      });
    },

    //获取收费方式明细
    getChargePayByChargeId(ChargeId) {
      let lfind = -1;
      getapi(`/api/app/chargepay/getchargepayinchargeid?ChargeId=${ChargeId}`).then(res => {
        if (res.code != - 1) {
          res.data.forEach(e => {
            lfind = arrayExistObj(this.chargePays, 'payModeId', e.payModeId);
            if (lfind > - 1) {
              this.chargePays[lfind].chargeMoney = e.chargeMoney;
              this.chargePays[lfind].cardRegisterId = e.cardRegisterId;
            }
          });
        }
      });
    },
    //获取退费方式明细
    getChargeBackPayByChargeBackId(ChargeBackId) {
      let lfind = -1;
      getapi(`/api/app/chargebackpay/getchargebackpayinchargebackid?ChargeBackId=${ChargeBackId}`).then(res => {
        if (res.code != - 1) {
          res.data.forEach(e => {
            lfind = arrayExistObj(this.chargePays, 'payModeId', e.payModeId);
            if (lfind > - 1) {
              this.chargePays[lfind].chargeMoney = e.backMoeny;
              this.chargePays[lfind].cardRegisterId = e.cardRegisterId;
            }
          });
        }
      });
    },

    //待收费数据分析
    toCharge(patientRegisterId) {
      //默认全部选中
      this.selectedData = [...this.asbItemsForFee];
      this.$nextTick(function () {
        this.selectedData.forEach(row => {
          this.$refs['asbItemsForFeeTable'].toggleRowSelection(row)
        })
      });
      this.form.patientRegisterId = patientRegisterId;
    },

    //根据明细算总价与折扣
    sumTotal(details, head) {
      let total = 0, totalOri = 0;

      details.forEach(e => {
        totalOri += Math.round(e.amount * e.chargePriceOri * 100) / 100;   //原始实收价格
        total += Math.round(e.amount * e.chargePrice * 100) / 100;      //当前实收价格
        //console.log(total, e.chargePrice, e.amount)
      });
      total = Math.round(total * 100) / 100;
      totalOri = Math.round(totalOri * 100) / 100;

      head.total = total;
      //head.preTotal = total;
      if (totalOri == 0) {
        head.discount = 100;
      } else {
        head.discount = Math.round(10000 * total / totalOri) / 100;
      }

      //
      this.findBalance()

    },

    //通过折扣计算总价与明细价格
    discountToDetails() {
      let discount = this.form.discount;
      let totalOri = 0, totalCompute = 0, totalPlan = 0;
      let lfind = -1;
      this.selectedData.forEach(e => {
        totalOri += Number(e.amount * e.chargePriceOri);  //原始实收价格
        lfind = arrayExistObj(this.asbItemsForFee, 'id', e.id)
        if (lfind > -1 && e.chargePriceOri != 0) {
          e.chargePrice = Math.round(e.chargePriceOri * discount) / 100;
          e.discount = Math.round(10000 * e.chargePrice / e.standardPrice) / 100;
          totalCompute += Math.round(e.chargePrice * e.amount * 100) / 100;
        }
      });
      totalPlan = Math.round(totalOri * discount) / 100;
      this.form.total = totalPlan;
      //this.form.preTotal = totalPlan;
      //明细和与总金额不符处理
      this.handleBalance(totalPlan, totalCompute);

      this.findBalance()
    },

    //通过总价计算折扣与明细价格
    totalToDetails() {
      let discount = 100;
      let totalOri = 0, totalCompute = 0, totalPlan = Number(this.form.total);
      let lfind = -1;

      this.selectedData.forEach(e => {
        totalOri += Math.round(100 * e.amount * e.chargePriceOri) / 100;  //原始实收价格        
      });

      if (totalOri != 0) {
        discount = Math.round(10000 * totalPlan / totalOri) / 100;
        this.form.discount = discount;
      }
      //
      this.selectedData.forEach(e => {
        lfind = arrayExistObj(this.asbItemsForFee, 'id', e.id);
        if (lfind > -1) {
          e.chargePrice = Math.round(e.chargePriceOri * discount) / 100;
          e.discount = Math.round(10000 * e.chargePrice / e.standardPrice) / 100;
          totalCompute += Math.round(100 * e.chargePrice * e.amount) / 100;
        }
      });
      //this.form.preTotal = totalPlan;
      //明细和与总金额不符处理
      this.handleBalance(totalPlan, totalCompute);

      this.findBalance()
    },

    //明细合计金额与总金额不一致时，处理
    handleBalance(totalPlan, totalCompute) {
      if (totalPlan != totalCompute) {
        for (let i = this.selectedData.length - 1; i = 0; i--) {
          lfind = lfind = arrayExistObj(this.asbItemsForFee, 'id', this.selectedData[i].id);
          if (lfind > -1 && this.selectedData[i].amount == 1) {
            this.asbItemsForFee[lfind].chargePrice = this.asbItemsForFee[lfind].chargePrice + totalPlan - totalCompute;
            this.selectedData[i].chargePrice = this.asbItemsForFee[lfind].chargePrice;
            break;
          }
        }
      }
    },

    //输入预收金额，计算找零
    findBalance() {      
      this.form.balance = Math.round((this.form.preTotal - this.form.total)*100)/100;
    },

    //输入收费方式金额
    inputMoney() {
      // 现金 id = 01
      let cashTotal= Number(0), unCashTotal= Number(0);
      this.chargePays.forEach(e => {
        console.log('e',e)
        if(e.payModeId == '01'){
          cashTotal += Number(e.chargeMoney);
        }else{
          unCashTotal += Number(e.chargeMoney);
        }        
      });
      this.form.preTotal = cashTotal + unCashTotal
      this.findBalance() 
      if (unCashTotal > this.form.total) this.$message.warning(`数据校验失败：输入的非现金金额${unCashTotal}不能超过应收金额${this.form.total}！`);

    },


    //勾选要收费的项目
    handleSelectionChange(v) {
      this.selectedData = v;
      this.sumTotal(this.selectedData, this.form);
    },

    //调整明细折扣
    changeDiscount(row) {
      let total = this.form.total;
      let totalDetailsOri = Math.round(100 * row.amount * row.chargePrice) / 100;
      let totalDetailsCur = 0;

      row.chargePrice = Math.round(row.discount * row.standardPrice) / 100;
      let lfind = arrayExistObj(this.selectedData, 'id', row.id);
      if (lfind > -1) {
        totalDetailsCur = Math.round(100 * row.amount * row.chargePrice) / 100;
        this.form.total = total + totalDetailsCur - totalDetailsOri;
      }
      this.sumTotal(this.selectedData, this.form);

    },

    //调整明细实收价格
    changePrice(row) {
      if (row.chargePriceOri != 0) {
        row.discount = Math.round(10000 * row.chargePrice / row.standardPrice) / 100;
      }
      this.sumTotal(this.selectedData, this.form);
    },

    //收费
    btnCharge() {
      let body = {};
      let unCashTotal = Number(0) , cashTotal = Number(0);
      let msg = '';
      let chargePays = [];
      let asbitems = [];

      if (this.form.id) {
        this.$message.warning("已收费，不可重复操作！");
        return;
      }

      this.$refs['form'].validate((valid, fields) => {
        if (!valid) {
          msg = fields[Object.keys(fields)[0]][0].message;
          return;
        }
      });

      if (msg) {
        this.$message.warning(msg);
        return;
      }

      this.chargePays.forEach(e => {
        if(e.payModeId == '01'){
          cashTotal += Number(e.chargeMoney);
        }else{
          unCashTotal += Number(e.chargeMoney);
        }        
        if (e.payModeId == '05' && e.chargeMoney) {
          //console.log(e.payModeId,e.chargeMoney,e.cardRegisterId);
          if (!e.cardRegisterId) msg = dddw(this.dict.payMode, "id", e.payModeId, "displayName") + '付费，必需选择会员卡号';
        } else {
          e.cardRegisterId = null;
        }        
      });

      if (msg) {
        this.$message.warning(msg);
        return;
      }

      //规避套现
      if (unCashTotal > this.form.total) {
        this.$message.warning("非现金收款不可大于应收金额！");
        return;
      }

      if (unCashTotal + cashTotal < this.form.total) {
        this.$message.warning("收费方式合计收款不可小于应收金额！");
        return;
      }


      this.chargePays.forEach(e => {
        if (e.chargeMoney) {
          if(e.payModeId == '01'){
            //现金支付，数据库中存找零后的现金
            chargePays.push({
              payModeId: e.payModeId,
              chargeMoney: e.chargeMoney - this.form.balance,
              cardRegisterId: e.cardRegisterId,
            });
          }else{
            chargePays.push({
              payModeId: e.payModeId,
              chargeMoney: e.chargeMoney,
              cardRegisterId: e.cardRegisterId,
            });
          }
        }
      });

      this.selectedData.forEach(e => {
        asbitems.push({
          asbitemId: e.asbitemId,
          chargePrice: e.chargePrice,
          amount: e.amount,
          registerAsbitemId: e.id,
        });
      });

      body = {
        patientRegisterId: this.form.patientRegisterId,
        invoiceNo: this.form.invoiceNo,
        invoiceOrgName: this.form.invoiceOrgName,
        chargePays,
        asbitems,
      };
      // {
      //   "patientRegisterId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //   "invoiceNo": "string",
      //   "invoiceOrgName": "string",
      //   "chargePays": [
      //     {
      //       "payModeId": "string",
      //       "chargeMoney": 0,
      //       "cardRegisterId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
      //     }
      //   ],
      //   "asbitems": [
      //     {
      //       "asbitemId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //       "chargePrice": 0,
      //       "amount": 0,
      //       "registerAsbitemId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
      //     }
      //   ]
      // }
      //console.log('body',body);
      postapi('/api/app/registerasbitem/registerasbitemcharge', body).then(res => {
        if (res.code != -1) {
          
          this.form.id = res.data.chargeId;  //可防止重复提交收费
          
          this.$confirm("操作成功, 是否打印发票?", "提示", {
            confirmButtonText: "是",
            cancelButtonText: "否",
            type: "warning",
          }).then(() => {
            this.chargePrint('0007', false, res.data.chargeId)
            setTimeout(() => { 
              this.Query();
            }, 1000)
          }).catch((err) => {
            if (err == "cancel") {
              //this.$message.info("已取消删除");
              this.Query();
            }
          });
        }
      });

    },

    //退费
    btnChargeBack() {
      let chargeId = this.form.id;
      let msg = '';
      let chargeBackPays = [];
      let total = 0;
      let body = {};

      if (!chargeId) {
        this.$message.warning("请选择待退费的记录！");
        return;
      }

      if (this.form.chargeFlag == '1') {
        this.$message.warning("已退费，不可重复操作！");
        return;
      }


      this.$confirm("是否确定执行退费操作?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      }).then(() => {
        this.chargePays.forEach(e => {
          total += Number(e.chargeMoney);
          if (e.payModeId == '05' && e.chargeMoney) {
            if (!e.cardRegisterId) msg = '请先择会员卡号';
          } else {
            e.cardRegisterId = null;
          }
          return e;
        });

        if (msg) {
          this.$message.warning(msg);
          return;
        }
        if (total != this.form.total) {
          this.$message.warning("退费方式合计金额与退费总金额不符");
          return;
        }

        this.chargePays.forEach(e => {
          if (e.chargeMoney) {
            chargeBackPays.push({
              payModeId: e.payModeId,
              backMoeny: e.chargeMoney,
              cardRegisterId: e.cardRegisterId,
            });
          }
        });

        // {
        //   "chargeId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
        //   "chargeBackPays": [
        //     {
        //       "payModeId": "string",
        //       "backMoeny": 0,
        //       "cardRegisterId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
        //     }
        //   ]
        // }
        body = {
          chargeId, chargeBackPays
        }
        postapi('/api/app/registerasbitem/registerasbitemchargeback', body).then(res => {
          if (res.code != -1) {
            console.log("操作成功！");
            this.form.chargeFlag = '1';     //防止重复提交退费
            this.Query();
          }
        });

      }).catch((err) => {
        if (err == "cancel") {
          this.$message.info("已取消删除");
        }
      });      

    },

    //收费打印
    chargePrint(ReportCode, isPreview, chargeId) {
      console.log('ReportCode, isPreview, chargeId',ReportCode, isPreview, chargeId)
      if (!chargeId) {
        this.$message.info("人员信息尚未保存，不可执行此操作！");
        return;
      }
      if(!this.$peisAPI) {
        this.$message.info("此功能，需要在壳客户端才可运行！")
        return       
      }

      let token = window.sessionStorage.getItem('token');
      let user = window.sessionStorage.getItem('user');
      let toOutShell = {
        ReportCode, token,
        preViewCanPrint: 'Y',
        Parameters: [
          { Name: 'printer', Value: user },
          { Name: 'hisLog', Value: 'pic/hisLog.jpg' },
        ],
      };

      if (isPreview) {
        postapi(`/api/app/printreport/getchargereport?ChargeId=${chargeId}`)
          .then((res) => {
            if (res.code != -1) {
              toOutShell.ReportTable = res.data;
              console.log('JSON.stringify(toOutShell)', JSON.stringify(toOutShell));
              return this.$peisAPI.printPre(JSON.stringify(toOutShell));
            }
          })
          .then(res =>{
            console.log(res)
            if(JSON.parse(res).code < 0){
              this.$message.error(JSON.parse(res).message)
            }
          })
          .catch(err => {
            this.$message.warning(err);
          });
      } else {
        postapi(`/api/app/printreport/getchargereport?ChargeId=${chargeId}`)
          .then((res) => {
            if (res.code != -1) {
              toOutShell.ReportTable = res.data;
              console.log('JSON.stringify(toOutShell)', JSON.stringify(toOutShell));
              return this.$peisAPI.print(JSON.stringify(toOutShell));
            }
          })
          .then(res =>{
            console.log(res)
            if(JSON.parse(res).code < 0){
              this.$message.error(JSON.parse(res).message)
            }
          })
          .catch(err => {
            this.$message.warning(err);
          });

      }
    },

    //数据初始化
    dictInit() {
      
      this.query.startDate = new Date()
      this.query.endDate = this.query.startDate

      //性别（仅档案用）
      getapi("/api/app/sex").then((res) => {
        if (res.code == 1) {
          this.dict.sex = res.data;
        }
      });

      //性别（查询）
      getapi("/api/app/for-sex").then((res) => {
        if (res.code == 1) {
          this.dict.forSex = res.data;
        }
      });

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

      //体检中心
      getapi("/api/app/organization-units/organization-unit-by-is-peis").then(
        (res) => {
          if (res.code == 1) {
            this.dict.organization = res.data;
          }
        }
      );

      //体检单位
      getapi("/api/app/customer-org/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.customerOrg = res.data.items;
        }
      });

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

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

      //婚姻状况
      getapi("/api/app/marital-statuses").then((res) => {
        if (res.code == 1) {
          this.dict.maritalStatus = res.data.items;
        }
      });

      //性激素期
      getapi("/api/app/sex-hormone-term/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.sexHormoneTerm = res.data.items;
        }
      });

      //民族
      getapi("/api/app/nation/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.nation = res.data.items;
        }
      });

      //籍惯 ，出生地
      getapi("/api/app/birth-place/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.birthPlace = res.data.items;
        }
      });

      //套餐
      postapi("/api/app/medicalpackage/getmedicalpackagelist",{}).then((res) => {
        if (res.code == 1) {
          this.dict.medicalPackage = res.data;
        }
      });

      //分组，所有分组，不限单位，不限次数
      getapi("/api/app/customer-org-group").then((res) => {
        if (res.code == 1) {
          this.dict.customerOrgGroupAll = res.data.items;
        }
      });

      //支付方式 /api/app/pay-mode(全部)
      getapi("/api/app/paymode/getlistinisactive").then((res) => {
        if (res.code == 1) {
          this.dict.payMode = res.data;
          //未收费时
          this.chargePaysInit = [];
          this.dict.payMode.forEach(e => {
            this.chargePaysInit.push({ chargeId: null, payModeId: e.id, chargeMoney: 0, cardBillId: null })
          });
          this.chargePays = deepCopy(this.chargePaysInit);
        }
      });

      //体检类别 树结构
      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/asbitem/getasbitemlist",{}).then((res) => {
        if (res.code == 1) {
          this.dict.asbItemAll = res.data;
        }
      });

      console.log("dict", this.dict);
    },

  },

  //监听事件()
  watch: {
    "dataTransOpts.refresh.charge.S":{
      immediate: true, // 立即执行
      // // deep: true, // 深度监听复杂类型内变化
      handler(newVal,oldVal){
        console.log(`watch: 收费 newVal: ${newVal}, oldVal: ${oldVal}, 人员条码号: `,this.patientRegisterNo)
        this.query.patientRegisterNo = this.patientRegisterNo
        this.Query("patientRegisterNo")          
      }
    },
  },
};
</script>
<style scoped>
@import '../../assets/css/global_button.css';
@import '../../assets/css/global_card.css';
@import '../../assets/css/global_dialog.css';
@import '../../assets/css/global_form.css';
@import '../../assets/css/global_input.css';
@import '../../assets/css/global_table.css';
@import '../../assets/css/global.css';


.queryDivClass {
  display: block;
  width: v-bind("(window.pageWidth > 600 ? (window.pageWidth - 110 - 50) / 2 : 200) + 'px'");
  height: v-bind("(window.pageHeight > 600 ? (window.pageHeight - 150) : 450) + 'px'");
}

.query {
  margin-left: 10px;
}

.prListDivClass {
  height: v-bind("(window.pageHeight > 600 ? (window.pageHeight - 250) : 350) + 'px'");
}

.btnDivClass {
  display: block;
  width: 100px;
  margin-left: 10px;
  margin-top: 180px;
}

.btnListClass {
  margin-top: 10px;
}

.btnClass {
  width: 100px;
}
</style>
