<template>
  <div style="display: flex;">
    <div :style="'width:' + (window.pageWidth - 200 - 145) + 'px;'">
      <el-table :data="dataTransOpts.tableM.lis_request" border @row-click="rowClick"
        :height="window.pageHeight < 600 ? 140 : Math.floor((window.pageHeight - 250) * 2 / 5)" size="small"
        highlight-current-row ref="lis_request" :row-class-name="handleRowClassName">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="isPrint" label="打印" min-width="50">
          <template slot-scope="scope">
            <i class="el-icon-printer" v-if="scope.row.isPrint == 'Y'" style="font-size: 20px; color: green" />
          </template>
        </el-table-column>
        <el-table-column prop="patientName" label="姓名" min-width="70" align="center" />
        <el-table-column prop="lisRequestNo" label="条码号" min-width="120" align="center" />
        <el-table-column prop="sampleTypeName" label="标本" min-width="50" align="center" />
        <el-table-column prop="sampleContainerName" label="标本容器" min-width="100" />
        <el-table-column prop="containerColor" label="颜色" width="50" align="center">
          <template slot-scope="scope">
            <div
              :style="`width: 45px;height: 25px;border-radius: 3px;background-color: ${colorTrans(scope.row.containerColor)};`">
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sampleContainerRemark" label="容器说明" min-width="100" />
        <el-table-column prop="asbitemNames" label="检验项目" min-width="120" />
        <el-table-column prop="samplerName" label="采样人" min-width="70" align="center" />
        <el-table-column prop="samplingTime" label="采样时间" min-width="120" align="center" />
        <el-table-column prop="isSignIn" label="是否签收" width="70" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.isSignIn == 'Y' ? '√' : '' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="signInOrder" label="签收顺序" width="70" align="center" />
        <el-table-column prop="signInPerson" label="签收人" min-width="70" align="center" />
        <el-table-column prop="signInTime" label="签收时间" min-width="120" align="center" />
      </el-table>
    </div>
    <div style="margin-left: 10px;width: 110px;">
      <div v-show="checkPagePriv(pagePriv.privs, '全选')" class="listBtn">
        <el-button type="success" class="commonbutton" @click="btnChoose(true)">全选</el-button>
      </div>
      <div v-show="checkPagePriv(pagePriv.privs, '取消全选')" class="listBtn">
        <el-button type="success" class="deleteButton" @click="btnChoose(false)">取消全选</el-button>
      </div>
      <div v-show="checkPagePriv(pagePriv.privs, '打印')" class="listBtn">
        <el-button type="primary" class="commonbutton" @click="btnLisPrint(false)">打印条码</el-button>
      </div>
      <div v-show="checkPagePriv(pagePriv.privs, '预览条码')" class="listBtn">
        <el-button type="danger" class="commonbutton" @click="btnLisPrint(true)">预览条码</el-button>
      </div>
      <!-- 预留
      <div v-show="checkPagePriv(pagePriv.privs, '发送申请')" class="listBtn">
        <el-button type="danger" class="commonbutton" @click="LisRequest(true)">发送申请</el-button>
      </div>
      <div v-show="checkPagePriv(pagePriv.privs, '撤消申请')" class="listBtn">
        <el-button type="danger" class="deleteButton" @click="LisRequest(false)">撤消申请</el-button>
      </div>
      -->
    </div>
  </div>
</template>
<script>
import moment from "moment";
import { mapState } from "vuex";
import { arrayExistObj, dddw, getPagePriv, checkPagePriv, deepCopy, } from "../../utlis/proFunc";
import { getapi, postapi, putapi, deletapi } from "../../api/api";
import LisRequest from "./LisRequest.vue";

export default {
  components: {},
  data() {
    return {
      pagePriv: {
        routeUrlorPageName: 'patientLis', //当前页面归属路由或归属页面权限名称
        privs: [] // 页面权限
      },
      chooseRows: [], // 选中的行
    };
  },

  created() {
    //获取用户当前页面的权限
    let userPriv = window.sessionStorage.getItem('userPriv')
    if (userPriv) this.pagePriv.privs = deepCopy(getPagePriv(this.pagePriv.routeUrlorPageName))

  },

  updated() {

  },

  //挂载完成
  mounted() { 
    this.retrieve_lis_request(this.dataTransOpts.tableS.patient_register.id)
  },

  computed: {
    ...mapState(["window", "dataTransOpts", "dict", "patientRegister"]),
  },
  methods: {
    dddw, moment, checkPagePriv,

    // 扩展定义表格行样式
    handleRowClassName({ row, rowIndex }) {
      // highLightBg 为 'selected'的高亮
      //console.log(rowIndex, row)
      //return row.highLightBg == 'selected' ? 'high-light-bg' : '';
      if (row.choosed) {
        return "current-row";
      } else {
        return "";
      }
    },

    //颜色转换
    colorTrans(intDataColor) {
      let tempColor = '000000' + Number(intDataColor).toString(16)
      let backgroundColor = '#' + tempColor.substring(tempColor.length - 6)
      return backgroundColor
    },

    // 选中行
    rowClick(row) {      
      this.btnChoose(false)
      this.chooseRows = [row]
      this.$refs['lis_request'].setCurrentRow(row);
    },

    // 全选 / 取消全选
    btnChoose(isChooseAll) {
      if (isChooseAll) {
        this.chooseRows = deepCopy(this.dataTransOpts.tableM.lis_request)     
        this.dataTransOpts.tableM.lis_request.forEach(e => {
          e.choosed = true;
          this.$refs['lis_request'].setCurrentRow(e);
        });
      } else {
        this.chooseRows = []
        this.dataTransOpts.tableM.lis_request.forEach(e => {
          e.choosed = false;
        });
        this.$refs['lis_request'].setCurrentRow();
      }
      this.$nextTick(() => {
        this.$refs['lis_request'].doLayout()
      })
      
    },

    //检验申请
    async btnLisRequest(isRequest) {
      if (this.chooseRows.length == 0) {
        this.$message.warning({ showClose: true, message: "请先选择要操作的条码记录！" })
        return
      }
      console.log('btnLisRequest',isRequest)
    },

    // 打印或预览
    async btnLisPrint(isPreview) {
      if (this.chooseRows.length == 0) {
        this.$message.warning({ showClose: true, message: "请先选择要操作的条码记录！" })
        return
      }
      if (!this.$peisAPI) {
        this.$message.warning({ showClose: true, message: "此功能需要在壳客户端中方可运行！" })
        return
      }      

      if (isPreview) {
        this.lisPrint(this.chooseRows[0].lisRequestId,"0002",isPreview)
        return
      }

      // 打印
      for (let i = 0; i < this.chooseRows.length; i++) {
        let e = this.chooseRows[i];
        try {
          let err = await this.lisPrint(e.lisRequestId,"0002",isPreview)
          if(!err){
            let lfind = arrayExistObj(this.dataTransOpts.tableM.lis_request,"lisRequestId",e.lisRequestId)
          if(lfind > -1) this.dataTransOpts.tableM.lis_request[lfind].isPrint = "Y"
          }          
        } catch (error) {
          console.log(`打印条码或更新条码打印状态失败，原因：${error}`)
          this.$message.warning({ showClose: true, message: `打印条码或更新条码打印状态失败，原因：${error}`})
        }
      }
    },

    //单个检验条码打印
    async lisPrint(lisRequestId, ReportCode, isPreview) {
      let err = ""
      let token = window.sessionStorage.getItem("token");
      let user = window.sessionStorage.getItem("user");
      let toOutShell = {
        ReportCode,
        token,
        IsMoreLabel: 'N',
        isBuildImage: 'N',
        IsUploadPdf: 'N',
        preViewCanPrint: "N",
        Parameters: [
          { Name: "printer", Value: user },
          { Name: "hisLog", Value: "pic/hisLog.jpg" },
        ],
        BusinessCode: lisRequestId
      };
      console.log('this.$peisAPI.print', toOutShell)
      if (isPreview) {
        this.$peisAPI.printPre(JSON.stringify(toOutShell))
          .then(res => {
            console.log('this.$peisAPI.printPre', res)
            if (JSON.parse(res).code < 0) {
              this.$message.warning({ showClose: true, message: JSON.parse(res).message });
            }
          })
          .catch((err) => {
            console.log('打印检验条码错误', err)
            this.$message.warning({ showClose: true, message: `${err}` });
          });

      } else {        
        try {
          let lres = await this.$peisAPI.print(JSON.stringify(toOutShell))
          let Jres = JSON.parse(lres)
          if(Jres.code < 0){
            err = Jres.message
            console.log('打印检验条码错误', err)
            this.$message.error({ showClose: true, message: `打印检验条码错误 ${err}` });
          }else{
            // 更新条码打印状态
            // let res = await postapi('/api/app/lisrequest/updatelisrequestisprint',{});
            // if(res.code < 0){
            //   err = res.message
            //   this.$message.error({ showClose: true, message: `更新条码打印状态失败，原因 ${err}` });
            // }
          }
        } catch (error) {
          err = `${error}`
        }
      }
      return err
    },

    // 刷新条码项目
    retrieve_lis_request(patientRegisterId) {
      this.chooseRows = []
      this.dataTransOpts.tableM.lis_request = []
      if (!patientRegisterId) return
      // console.log(`/api/app/registerasbitem/getlistinpatientregisterid?PatientRegisterId=${id}`, res)
      postapi('/api/app/printreport/GetLisRequestReportByPatientRegisterId', { patientRegisterId })
        .then(res => {
          if (res.code > -1) {
            this.dataTransOpts.tableM.lis_request = res.data
            this.btnChoose(true)
          }
        })
    },
  },

  //监听事件
  watch: {
    //人员ID未切换换时 也可以强制刷新数据
    "dataTransOpts.refresh.lis_request.M": {
      // immediate:true,
      handler(newVal, oldVal) {
        console.log(`watch 人员登记 newVal:${newVal} oldVal:${oldVal} registerCheckId: ${this.dataTransOpts.tableS.patient_register.id}`);
        if(newVal != oldVal) this.retrieve_lis_request(this.dataTransOpts.tableS.patient_register.id)
      }
    },
  }
};
</script>
<style scoped>
@import "../../assets/css/global.css";
@import "../../assets/css/global_table.css";

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