<template>
  <div class="layout_container">
    <header>
      <el-input v-model="codgTotal" class="w-50 m-2" style="width: 200px" disabled>
        <template #prepend><span style="color: #d71345;font-weight: bolder">处方发药总数量</span></template>
      </el-input>
      <el-input v-model="quantityJc" class="w-50 m-2" style="width: 200px" disabled>
        <template #prepend><span style="color: #d71345;font-weight: bolder">追溯码检查数量</span></template>
      </el-input>
      <el-divider direction="vertical" />
      <el-button type="primary" icon="Search" @click="checkBarList" style="margin-left: 5px">检查</el-button>
      <el-button type="danger" icon="Remove" @click="drugBarRepeat" style="margin-left: 5px">去重</el-button>
      <el-button type="warning" icon="Filter" @click="matchCodgData" style="margin-left: 5px">匹配</el-button>
      <el-button type="success" icon="Select" @click="saveMatchCodgData" style="margin-left: 5px" v-if="confirmFlag !== 1">保存</el-button>
      <el-button type="success" icon="Select" @click="saveMatchCodgData" style="margin-left: 5px" v-if="chargeFlag === 1">变更</el-button>
      <el-button type="danger" v-show="setlText" disabled :icon="Star"><span style="font-size: 14px">医保病人</span></el-button>
    </header>
    <div class="layout_display_flex_y">
      <div class="layout_flex_1-y">
        <el-table :data="mzCfDetail" border stripe highlight-current-row height="100%">
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column prop="location" label="货柜号" width="80" />
          <el-table-column prop="patientId" label="门诊号" width="90" />
          <el-table-column prop="times" label="就诊次数" width="70" />
          <el-table-column prop="chargeCode" label="药品编码" width="80" />
          <el-table-column prop="chargeName" label="品名" width="240" />
          <el-table-column prop="specification" label="规格" width="200" />
          <el-table-column prop="retprice" label="价格" width="80"/>
          <el-table-column prop="quantity" label="数量" width="80">
            <template #default="scope">
              <el-button type="primary" size="small">{{ scope.row.quantity }}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="factory" label="生产厂家" width="240"/>
          <el-table-column prop="chargeDate" label="收费时间" width="140" />
          <el-table-column prop="deptName" label="科室" width="120" />
        </el-table>
      </div>
      <div style="margin-top: 4px">
        <el-row :gutter="5">
          <el-col :span="3">
            <el-divider content-position="left">追溯码采集信息</el-divider>
            <el-input v-model="codgLine" type="textarea" :rows="36"/>
          </el-col>
          <el-col :span="3">
            <el-divider content-position="left">追溯码检查信息</el-divider>
            <el-input v-model="drugTracCodgAt" type="textarea" :rows="36"/>
          </el-col>
          <el-col :span="18">
            <el-divider content-position="left">追溯码匹配信息</el-divider>
            <div class="layout_display_flex_y">
              <div class="layout_flex_1-y">
                <el-table :data="codgInfo" border stripe highlight-current-row>
                  <el-table-column type="index" label="序号" width="40" fixed/>
                  <el-table-column prop="matchFlag" label="匹配结果" width="105" fixed>
                    <template #default="scope">
                      <el-button v-if="scope.row.matchFlag === '0' " type="success" size="small">下载匹配成功</el-button>
                      <el-button v-else-if="scope.row.matchFlag === '1' " type="success" size="small">平台匹配成功</el-button>
                      <el-button v-else-if="scope.row.matchFlag === '-1' " type="danger" size="small">匹配失败</el-button>
                      <el-button v-else type="primary" size="small">其他</el-button>
                    </template>
                  </el-table-column>
                  <el-table-column prop="matchMessage" label="匹配信息" width="180" fixed show-overflow-tooltip/>
                  <el-table-column prop="drugTracCodg" label="追溯码" width="150" fixed />
                  <el-table-column prop="drugName" label="品名" width="240" fixed/>
                  <el-table-column prop="specification" label="规格" width="160" />
                  <el-table-column prop="manuNo" label="生产批号" width="140"/>
                  <el-table-column prop="manuDate" label="生产日期" width="140"/>
                  <el-table-column prop="expyEnd" label="有效期止" width="140"/>
                  <el-table-column prop="abbrName" label="生产厂家" width="240"/>
                </el-table>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script setup name="YpMzCodgMatch">
import {nextTick, onMounted, ref, watch} from "vue";
import {
  selectMatchCodgInfo,
  selectMzCfDetail,
  selectMzDrugTracCodgData,
  updateMzDrugCodgData,
  updateMzDrugCodgDataNew
} from "@/api/yp-codg/yp-codg-match.js";
import {isEmpty} from "xe-utils";
import {ElMessage, ElMessageBox} from "element-plus";
import {Star} from "@element-plus/icons-vue";

const mzCfData = ref([])
const mzCfDetail = ref([])
const setlText = ref(false)
const codgLine = ref('')
const codgTotal = ref(0)
// 处方匹配的追溯码信息
const codgInfo = ref([])
const confirmFlag = ref(0)
// 已经发药了，变更追溯码信息
const chargeFlag = ref(0)
const emit = defineEmits(['close', 'closeYpMzCodgMatch'])

const props = defineProps({
  ypMzCfData: {
    type: Object,
    default: {}
  }
})
onMounted( () => {
  nextTick(() => {
    mzCfData.value = props.ypMzCfData
    confirmFlag.value = props.ypMzCfData.confirmFlag
    chargeFlag.value = props.ypMzCfData.flag
    setlText.value = props.ypMzCfData.setlId
    queryMzCfDetail()
    queryMzDrugCodgMatch()
  })
})
watch(() => props.ypMzCfData, () => {
  mzCfData.value = props.ypMzCfData
  confirmFlag.value = props.ypMzCfData.confirmFlag
  chargeFlag.value = props.ypMzCfData.flag
  setlText.value = props.ypMzCfData.setlId
})

const queryMzCfDetail = () => {
  selectMzCfDetail(mzCfData.value).then(res => {
    let u = 0
    res.forEach((item) => {
      u = u + item.quantity
    });
    codgTotal.value = u
    mzCfDetail.value = res
  })
}

const queryMzDrugCodgMatch = () => {
  selectMzDrugTracCodgData(mzCfData.value).then(res => {
    if(res.data){
      codgInfo.value = res.data
    }
  })
}

// 去重
const drugBarRepeat = () => {
  let barStr = codgLine.value
  if(!isEmpty(barStr)) {
    let barInfo = barStr.replaceAll('\n', ',').split(',')
    if (barInfo.length > 0) {
      let barData = new Set(barInfo)
      let barList = [...barData]
      let data = ''
      for(let i in barList){
        if(!isEmpty(barList[i])) {
          data += (barList[i] + '\n')
        }
      }
      codgLine.value = data
    }
  }
  // 去重后在进行一起检查
  checkBarList()
}

// 追溯码扫码计数统计
let barFor = false
let barC = 0
// 检查后数量
const quantityJc = ref(0)
// 检验信息
const drugTracCodgAt = ref('')
// 追溯码检查
const checkBarList = () => {
  barFor = false
  barC = 0
  quantityJc.value = 0
  drugTracCodgAt.value = ''

  let sum = 0;
  let str = codgLine.value;
  let infoErr = '错误：\n';
  let infoRep = '重复：\n';
  if(!isEmpty(str)){
    let barInfo = str.replaceAll('\n', ',').split(',')
    if(barInfo.length > 0) {
      for(let i in barInfo){
        if(barInfo[i].length === 20 || barInfo[i].length === 55){
          sum++;
        } else {
          if(barInfo[i] > 0 && barInfo[i].length !== 20 && barInfo[i].length !== 55){
            sum++;
            barFor = true
            infoErr += barInfo[i] + '\n';
          }
        }
      }
      let barInfoCp = [...barInfo]
      let repStr = ''
      for(let i in barInfo){
        let rep = 1;
        // 不能用index的序号去比，因为它已经比过了
        let index = 0;
        if(!(isEmpty(repStr) || repStr.indexOf(barInfo[i]) === -1)){
          continue
        }
        for(let j in barInfoCp){
          if(j > i && barInfo[i] === barInfoCp[j]){
            rep++;
            barFor = true
            if(isEmpty(repStr)){
              repStr = barInfo[i]
            } else if(repStr.indexOf(barInfo[i]) === -1){
              repStr += ',' + barInfo[i]
            }
            index = j
          }
        }
        if(rep > 1){
          infoRep  = infoRep + barInfo[i] + '重复出现：' + rep + '次。 \n'
          rep = 1
        }
      }
    }
  }
  let info = infoErr + '\n' + infoRep
  quantityJc.value = sum
  drugTracCodgAt.value = info

}

// 追溯码匹配
const matchCodgData = () => {
  if(barFor){
    ElMessage({
      type: "warning",
      message: "当前扫码有重复或者错误追溯码信息，请检查！",
      duration: 2500,
      showClose: true,
    });
    return false
  }
  // 匹配追溯码并返回结果
  mzCfData.value.codeLine = codgLine.value
  selectMatchCodgInfo(mzCfData.value).then(res => {
    if(res.data){
      codgInfo.value = res.data
    }
  })

}

// 保存匹配结果
const saveMatchCodgData = () => {
  if(!codgInfo.value){
    ElMessage({
      type: "warning",
      message: '没有匹配信息，请检查！',
      duration: 2500,
      showClose: true,
    });
    return false
  }
  let unMatchCodgInfo = codgInfo.value.filter(codg => {
    return codg.flag === '-1'
  })
  if(unMatchCodgInfo.length > 0){
    ElMessage({
      type: "warning",
      message: '追溯码匹配信息中存在匹配失败数据，请检查！',
      duration: 2500,
      showClose: true,
    });
    return false
  }

  if(codgInfo.value.length > codgTotal.value){
    ElMessage({
      type: "warning",
      message: '追溯码匹配数量不允许超过处方发药总数量，请检查！',
      duration: 2500,
      showClose: true,
    });
    return false
  }
  let tips = "确定保存药品匹配信息？"
  if(chargeFlag.value === 1){
    tips = "确定变更药品匹配信息？【友情提示：已经上传医保的追溯码，请取消上传再变更追溯码信息！】"
  }
  ElMessageBox.confirm(tips, {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    type: 'warning',
    distinguishCancelAndClose: true,
    dangerouslyUseHTMLString: true
  }).then(() => {
    if(chargeFlag.value === 1){
      updateMzDrugCodgDataNew(codgInfo.value).then((res) => {
        if(res.code === 0){
          ElMessage({
            type: "success",
            message: res.message,
            duration: 2500,
            showClose: true,
          });
          emit('closeYpMzCodgMatch', true)
        }
      })
    } else {
      updateMzDrugCodgData(codgInfo.value).then((res) => {
        if(res.code === 0){
          ElMessage({
            type: "success",
            message: res.message,
            duration: 2500,
            showClose: true,
          });
          emit('closeYpMzCodgMatch', true)
        }
      })
    }
  }).catch((action) => {
    if (action === 'cancel') {
      console.log("已取消。。。")
    }
  })

}
</script>