<template>
  <div style="display: flex">
    <div>
      <div>
        批量调整分组只针对单位体检有效，个人体检将忽略此操作；不能调整已收费或已检的项目及已总检的体检人员。
      </div>
      <div>
        <br /><el-radio v-model="asbitemBatch.operate" label="add">增加项目</el-radio>
        <el-radio v-model="asbitemBatch.operate" label="del">删除项目</el-radio>
      </div>
      <div>
        <br /><el-checkbox v-model="asbitemBatch.isDeleteGroup"
          :disabled="asbitemBatch.operate == 'add' ? true : false">如果删除项目属于分组则删除体检记录信息的分组设置</el-checkbox>
      </div>
      <div>
        <br /><span>直接录入</span>
        <el-select v-model="asbitemBatch.asbItemId" placeholder="快速选择组合项目" size="small" highlight-current-row filterable
          :filter-method="filterMethod" clearable @clear="quickAsb = deepCopy(asbItemQuick)" @change="quickChoosedAsb"
          default-first-option ref="quickAsbOCX" style="width: 150px; text-align: left; padding-right: 15px">
          <el-option v-for="item in quickAsb" :key="item.id" :value="item.id" :label="item.displayName" />
        </el-select>
      </div>
      <div style="display: flex; margin-top: 2px">
        <div style="width: 480px">
          <el-table :data="asbitemBatch.asbitemsTemp" height="240" width="100%" show-summary @row-dblclick="removeAbs"
            size="small" highlight-current-row @row-click="rowClickaAbitemCurr" border>
            <el-table-column label="组合项目" width="150" prop="asbitemName" />
            <el-table-column label="数量" prop="amount" width="60">
              <template slot-scope="scope">
                <el-input type="number" v-model="scope.row.amount" size="small"
                  :disabled="asbitemBatch.operate == 'del' ? true : false" />
              </template>
            </el-table-column>
            <el-table-column label="实收价格" prop="chargePrice" width="90">
              <template slot-scope="scope">
                <el-input type="number" v-model="scope.row.chargePrice" size="small"
                  :disabled="asbitemBatch.operate == 'del' ? true : false" />
              </template>
            </el-table-column>
            <el-table-column label="支付方式" prop="payTypeFlag" width="120">
              <template slot-scope="scope">
                <el-select v-model="scope.row.payTypeFlag" size="small"
                  :disabled="asbitemBatch.operate == 'del' ? true : false">
                  <el-option v-for="item in dict.payType" :key="item.id" :label="item.displayName" :value="item.id" />
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="display: block; width: 110px; margin-left: 10px">
          <div style="margin-top: 5px">
            <el-button class="commonbutton" type="danger" @click="asbitemDel(1)" style="width: 100px">删除</el-button>
          </div>
          <div style="margin-top: 5px">
            <el-button class="commonbutton" type="danger" @click="asbitemDel(0)" style="width: 100px">删除全部</el-button>
          </div>
          <div style="margin-top: 5px">
            <el-button class="commonbutton" type="primary" @click="changePayTypeFlag('0')" style="width: 100px">全个人支付</el-button>
          </div>
          <div style="margin-top: 5px">
            <el-button class="commonbutton" type="primary" @click="changePayTypeFlag('1')" style="width: 100px">全单位支付</el-button>
          </div>
          <div style="margin-top: 5px">
            <el-button class="commonbutton" type="primary" @click="changePayTypeFlag('2')" style="width: 100px">全赠送</el-button>
          </div>
        </div>
      </div>
      <div style="display: flex;margin-top: 5px;margin-right: 10px;justify-content:space-between;">
        <div></div>
        <div>
          <el-button class="commonbutton" type="primary" @click="asbitemBatchHandle">确 定</el-button>
          <el-button class="commonbutton" @click="dialogWin.PatientRegisterEditItemBatch = false">取 消</el-button>
        </div>
      </div>
    </div>

    <!-- 通用进度条 -->
    <el-dialog title="数据处理中……" :visible.sync="elProgress.display" width="600px" height="400" :show-close="false"
      :close-on-click-modal="false" :append-to-body="true">
      <ElProgressOCX />
    </el-dialog>
  </div>
</template>
<script>
import moment from "moment";
import { mapState, mapActions } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";


import {
  dddw,
  arrayReduce,
  arrayExistObj,
  deepCopy,
} from "../../utlis/proFunc";



import ElProgressOCX from "../report/ElProgressOCX.vue";

export default {
  components: {
    ElProgressOCX,
  },
  props: ["multipleSelection"],
  data() {
    return {
      asbitemBatch: {
        operate: "add",
        isDeleteGroup: false,
        asbItemId: "",
        asbitemsTemp: [], //删除或增加项目临时用
        asbitemCurr: {}, //当前选中要删除的项目(批量调整)
      },
      asbitemBatchInit:{},

      asbItemQuick: [], //快速选择未过滤前全部项目
      quickAsb: [], //可供快速选择的组合项目

    };
  },

  // 组件创建完成
  created() {
    this.asbitemBatchInit = deepCopy(this.asbitemBatch)
  },

  //挂载完成
  mounted() {
    // 初始化数据，如：在用组合项目
    this.dictInit()
  },

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

  },
  methods: {
    moment, dddw, deepCopy,

    //快速查询项目
    filterMethod(keyWords) {
      //console.log('filterMethod',this.dict.asbItemQuick)
      if (keyWords) {
        this.quickAsb = [];
        this.asbItemQuick.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.quickAsb.push(item);
          }
        });
      } else {
        this.quickAsb = deepCopy(this.asbItemQuick);
      }
    },

    //快速选择项目
    quickChoosedAsb(v) {
      //过滤已选的的组合项目
      let lfind = -1;
      if (v) {
        lfind = arrayExistObj(this.quickAsb, "id", v);
        if (lfind > -1) {
          this.asbitemBatch.asbitemsTemp.push({
            asbitemId: v,
            asbitemName: this.quickAsb[lfind].displayName, //仅作显示用
            patientRegisterId: null,
            standardPrice: this.quickAsb[lfind].price,
            chargePrice: this.quickAsb[lfind].price,
            payTypeFlag: "1", //默认单位支付
            isCharge: "N",
            amount: 1,
          });
          this.quickAsb.splice(lfind, 1);
          arrayReduce(this.asbItemQuick, { id: v }, "id=id");
        }
      }
      //console.log(v, this.asbitemBatch.asbitemsTemp);
      this.$nextTick(() => {
        this.$refs['quickAsbOCX'].blur(); //total  asbItemId
        this.asbItemId = ''
        this.quickAsb = deepCopy(this.asbItemQuick)
        this.$refs['quickAsbOCX'].focus(); //total  asbItemId       
      });

    },

    //删除临时显示的组合项目
    removeAbs(row) {
      let lfind = arrayExistObj(
        this.asbitemBatch.asbitemsTemp,
        "asbitemId",
        row.asbitemId
      );
      if (lfind > -1) this.asbitemBatch.asbitemsTemp.splice(lfind, 1);
    },

    rowClickaAbitemCurr(row) {
      this.asbitemBatch.asbitemCurr = row;
    },

    btnRemoveAbs() {
      if (!this.asbitemBatch.asbitemCurr.asbitemId) {
        this.$message.warning("请选择要删除的组合项目！");
        return;
      }
      this.removeAbs(this.asbitemBatch.asbitemCurr);
      this.asbitemBatch.asbitemCurr.asbitemId = null;
    },

    removeAllAbs() {
      this.asbitemBatch.asbitemsTemp = [];
    },

    asbitemDel(type) {
      //typ==0 为批量删除
      if (Number(type) == 0) {
        this.asbitemBatch.asbitemsTemp = [];
      } else {
        if (!this.asbitemBatch.asbitemCurr.asbitemId) {
          this.$message.warning("请选中要删除的项目！");
          return;
        }
        //console.log(this.asbitemBatch.asbitemsTemp,this.asbitemBatch.asbitemCurr)
        let lfind = arrayExistObj(
          this.asbitemBatch.asbitemsTemp,
          "asbitemId",
          this.asbitemBatch.asbitemCurr.asbitemId
        );
        if (lfind > -1) {
          this.asbitemBatch.asbitemsTemp.splice(lfind, 1);
          this.asbitemBatch.asbitemCurr.asbitemId = null;
        }
        //console.log(lfind);
      }
    },

    //批量调整支付方式
    changePayTypeFlag(flag) {
      this.asbitemBatch.asbitemsTemp.forEach((e) => {
        e.payTypeFlag = flag;
        return e;
      });
    },

    //批量调整项目(确定按钮)
    async asbitemBatchHandle() {
      let msg = "",
        body = {};
      if (this.asbitemBatch.asbitemsTemp.length == 0) {
        this.$message.warning("没有选择组合项目，不可执行此操作！");
        return;
      }
      if (this.asbitemBatch.operate == "add") {
        this.asbitemBatch.asbitemsTemp.forEach((e, index) => {
          if (!e.amount || !e.chargePrice) {
            msg = "第 " + (index + 1) + " 行，未输入数量或价格！";
          }
        });
        if (msg) {
          this.$message.warning(msg);
          return;
        }

        let createRegisterAsbitemDtos = deepCopy(
          this.asbitemBatch.asbitemsTemp
        );

        createRegisterAsbitemDtos.forEach((e) => {
          delete e.asbitemName;
          return e;
        });
        this.elProgress.display = true;
        this.elProgress.percentage = 0;
        for (let i = 0; i < this.multipleSelection.length; i++) {
          createRegisterAsbitemDtos.forEach((e) => {
            e.patientRegisterId = this.multipleSelection[i].id;
            return e;
          });
          body = {
            medicalCenterId: this.multipleSelection[i].medicalCenterId,
            createRegisterAsbitemDtos,
          };
          try {
            await postapi(
              "/api/app/registerasbitem/createregisterasbitemincustomerorgmany",
              body
            );
          } catch (error) {
            console.log("批量增加项目错误，原因：", error);
          }
          this.elProgress.percentage = Math.floor(
            ((i + 1) * 100) / this.multipleSelection.length
          );
        }
      } else {
        // {
        //   isDeleteGroup: 'N',
        //   patientRegisterId: null,
        //   asbitemIds: [],
        // }
        let asbitemIds = [];
        if (this.asbitemBatch.isDeleteGroup) {
          body.isDeleteGroup = "Y";
        } else {
          body.isDeleteGroup = "N";
        }
        this.elProgress.display = true;
        this.elProgress.percentage = 0;
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.asbitemBatch.asbitemsTemp.forEach((e) => {
            asbitemIds.push(e.asbitemId);
          });

          body.patientRegisterId = this.multipleSelection[i].id;
          body.asbitemIds = asbitemIds;

          try {
            await postapi(
              "/api/app/registerasbitem/deleteregisterasbitemincustomerorgmany",
              body
            );
          } catch (error) {
            console.log("批量删除项目错误，原因：", error);
          }
          this.elProgress.percentage = Math.floor(
            ((i + 1) * 100) / this.multipleSelection.length
          );
        }
      }

      console.log("操作成功！");
      this.dialogWin.PatientRegisterEditItemBatch = false;
      // 操作成功后，刷新列表
      this.patientRegister.query.times++
    },

    // 初始化字典信息
    dictInit() {
      this.asbitemBatch = deepCopy(this.asbitemBatchInit)
      // 获取在用的组合项目
      postapi('/api/app/asbitem/GetBasicList', { isFilterActive: 'Y' }).then(res => {
        if (res.code != -1) {
          this.asbItemQuick = res.data
          this.quickAsb = res.data
        }
      });
    },

  },

  //监听事件
  watch: {
    "dataTransOpts.plus.PatientRegisterEditItemBatch": {
      // immediate: true, // 立即执行
      // deep: true, // 深度监听复杂类型内变化
      handler(newVal, oldVal) {
        console.log(`watch: 刷新在用组合项目 newVal: ${newVal} oldVal:${oldVal}`)
        if(newVal != oldVal) this.dictInit()
      }
    },
  },
};
</script>
<style scoped>
@import "../../assets/css/global_input.css";
@import "../../assets/css/global_table.css";
@import "../../assets/css/global.css";


.box {
  display: flex;
}

.listBtn {
  margin-top: 5px;
  text-align: center;
}

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