<template>
  <div class="layout_display_flex_y">
    <div style="margin-bottom: 6px; background-color: #fff;">
      <el-input v-model="text" class="w-50 m-2" style="width: 320px" placeholder="请输入编码/名称/首拼/五笔" clearable>
        <template #prepend>编码/名称/首拼/五笔 </template>
      </el-input>
      <el-select v-model="groupNo" placeholder="请选择药库" filterable clearable style="width: 240px;margin-left: 3px">
        <el-option v-for="item in ypGroupNameData" :key="item.code" :label="item.name" :value="item.code">
          <span style="float: left">{{ item.label }}</span>
          <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px; ">
                        {{ item.value }}
                    </span>
        </el-option>
      </el-select>
      <el-switch v-model="isSee" inline-prompt active-text="停用可见" inactive-text="停用不可见" active-value="0" inactive-value="1"
                 style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949; margin-left: 5px"/>
      <el-button type="primary" icon="Search" @click="queryYpDict" style="margin-left: 5px">查询</el-button>
      <el-button type="primary" icon="Plus" @click="addYpDict" style="margin-left: 5px">新增</el-button>
      <el-button type="primary" icon="Download" @click="exportData" style="margin-left: 5px">导出</el-button>
    </div>
    <div class="layout_display_flex_y layout_flex_1-y">
      <div class="layout_flex_1-y">
        <el-table :data="drugDictData.slice(pageSize * (currentPage - 1), pageSize * currentPage)" border
                  style="width: 100%" height="100%" stripe highlight-current-row>
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="code" label="药品编码" width="80" />
          <el-table-column prop="serial" label="药品包装" width="70" />
          <el-table-column prop="name" label="药品名称" width="240" show-overflow-tooltip />
          <el-table-column prop="specification" label="药品规格" width="180" show-overflow-tooltip />
          <el-table-column prop="packRetprice" label="药品零售价" width="100" />
          <el-table-column prop="manuFactory" label="生产厂家" width="200" show-overflow-tooltip />
          <el-table-column prop="delFlag" label="状态" width="70">
            <template #default="scope">
              <span v-if="scope.row.delFlag === '1'" style="color:#d12020;">停用</span>
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column prop="ykFlag" label="药库状态" width="80" v-if="isYk">
            <template #default="scope">
              <span v-if="scope.row.ykFlag === '1'" style="color:#d12020;">药库停用</span>
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column prop="pyCode" label="拼音码" width="150" />
          <el-table-column prop="dCode" label="五笔码" width="150" />
          <el-table-column fixed="right" label="操作" min-width="710" width="710" center>
            <template #default="scope">
              <el-button type="primary" size="small" v-if="!scope.row.isEdit"
                         @click="editYpDict(scope.row)">编辑</el-button>
              <el-button :type="scope.row.tempPurchaseFlag === '1' ? 'primary' : 'info'" size="small"
                         v-if="!scope.row.isEdit" @click="tempPurchase(scope.row)">临购</el-button>
              <el-button :type="scope.row.jbFlag === '1' ? 'primary' : 'info'" size="small"
                         v-if="!scope.row.isEdit" @click="baseDrugConfirm(scope.row)">基本</el-button>
              <el-button :type="scope.row.highWarningFlag === '1' ? 'primary' : 'info'" size="small"
                         v-if="!scope.row.isEdit" @click="highWarningDrug(scope.row)">高警示</el-button>
              <el-button :type="scope.row.winningBidderFlag === '1' ? 'primary' : 'info'" size="small"
                         v-if="!scope.row.isEdit" @click="winningBidderDrug(scope.row)">带量中选</el-button>
              <el-button :type="scope.row.focusMonitorFlag === '1' ? 'primary' : 'info'" size="small"
                         v-if="!scope.row.isEdit" @click="focusMonitorDrug(scope.row)">重点监控</el-button>
              <el-button type="primary" size="small" v-if="!scope.row.isEdit"
                         @click="editYpDictName(scope.row)">别名</el-button>
              <el-button :type="scope.row.delFlag === '1' ? 'info' : 'primary'" size="small"
                         @click="stopYpDict(scope.row)">
                <span v-if="scope.row.delFlag === '1'">启用</span>
                <span v-else>停用</span>
              </el-button>
              <el-button :type="scope.row.ykFlag === '1' ? 'info' : 'primary'" size="small"
                         @click="stopYkYpDict(scope.row)" v-show="isYk">
                <span v-if="scope.row.ykFlag === '1'">药库启用</span>
                <span v-else>药库停用</span>
              </el-button>
              <el-button :type="scope.row.returnFlag === '1' ? 'primary' : 'info'" size="small" v-show="scope.row.categoriesFlag === '0'"
                         v-if="!scope.row.isEdit" @click="kfReturnDrug(scope.row)">口服退药</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div>
        <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[15, 30, 45, 60]"
                       :total="drugDictData.length" layout="total, sizes, prev, pager, next, jumper" style="margin-top: 5px"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </div>
  </div>
  <el-dialog v-model="showYpEdit" :close-on-click-modal="false" :close-on-press-escape="false" :title="ypTitle"
      class="yp-edit-dialog" width="80%" destroy-on-close fullscreen>
      <YpZdDict :ypDetail="ypDetail" @closeYpEditFor="closeYpEditAdd" />
  </el-dialog>
  <el-dialog v-model="showYpPrintName" :close-on-click-modal="false" :close-on-press-escape="false"
      :title="ypPrintName" width="80%" destroy-on-close>
      <YpPrintName :ypPrintNameDetail="ypPrintNameDetail" @closeYpPrintNameEditFor="closeYpPrintName" />
  </el-dialog>
</template>
<script setup name="YpDictInfo">
import {nextTick, onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {clone} from '@/utils/clone'
import {Export} from '@/utils/ExportExcel'
import {
  selectYpDict,
  selectYpDictByCode,
  selectYpGroupNameByYfFlag,
  selectYpStorageInfo,
  updateYkYpStopOrUsed,
  updateYpJbFlag,
  updateYpStopOrUsed,
  updateYpTempPurchase,
  updateYpHighWarning,
  updateYpWinningBidder,
  updateYpFocusMonitor,
  updateYpReturnFlag
} from '@/api/yp-dict/yp-dict-info.js'
import YpZdDict from '@/views/yp-dict/YpZdDict.vue'
import YpPrintName from '@/views/yp-dict/YpPrintName.vue'

const text = ref('')
const isSee = ref('1')
const drugDictData = ref([])
const ypTitle = ref('')
const showYpEdit = ref(false)
const ypDetail = ref({})
const ypPrintName = ref('')
const showYpPrintName = ref(false)
const ypPrintNameDetail = ref({})
const ypGroupNameData = ref([])
const groupNo = ref('')
const isYk = ref(false)
const pageSize = ref(30)
const currentPage = ref(1)
const handleSizeChange = (val) => {
    pageSize.value = val
}
const handleCurrentChange = (val) => {
    currentPage.value = val
}


onMounted(() => {
    nextTick(() => {
        queryYpGroupNameByYfFlag('')
        queryYpDict()
    })
})

// 查询所有药库明细
const queryYpGroupNameByYfFlag = (val) => {
    selectYpGroupNameByYfFlag(val, '0')
        .then((res) => {
            ypGroupNameData.value = res
        })
        .catch(() => {
            ypGroupNameData.value = []
        })
}

// 查询
const queryYpDict = () => {
    isYk.value = !!groupNo.value;
    if(groupNo.value === undefined){
      groupNo.value = ''
    }
    selectYpDict(text.value, groupNo.value, isSee.value)
        .then((res) => {
          drugDictData.value = res
        })
        .catch(() => {
            drugDictData.value = []
        })
}

// 新增
const addYpDict = () => {
    if(groupNo.value === undefined || groupNo.value === '') {
      ElMessage({
        type: "warning",
        message: "新增药品账页请选择药库！",
        duration: 2500,
        showClose: true,
      });
      return false
    }

    ypTitle.value = '新增药品账页信息'
    // 新增标识
    ypDetail.value.modeFlag = 'add'
    ypDetail.value.groupNo = groupNo.value
    showYpEdit.value = true
}

const closeYpEditAdd = () => {
    showYpEdit.value = false
    queryYpDict()
}

// 编辑
const editYpDict = (row) => {
    selectYpDictByCode(row.code, row.serial).then((res) => {
        ypTitle.value = '编码：' + row.code + ' 序号：' + row.serial + ' 规格：' + row.specification + ' 名称：' + row.name + ' 账页信息'
        ypDetail.value = res
        // 修改标识
        ypDetail.value.modeFlag = 'edit'
        showYpEdit.value = true
    })
}

// 编辑别名
const editYpDictName = (row) => {
    ypPrintName.value = row.name + "别名"
    showYpPrintName.value = true
    ypPrintNameDetail.value.chargeCode = row.code
}

const closeYpPrintName = () => {
    showYpPrintName.value = false
    queryYpDict()
}

const stopYpDict = (row) => {
    let delFlag
    let title
    if ('1' === row.delFlag) {
        delFlag = '0'
        title = '请确认是否启用<span style="color:#d12020;">' + row.name + '</span>?'
    } else {
        delFlag = '1'
        title = '请确认是否停用<span style="color:#d12020;">(药房也全部停用)</span><span style="color:#d12020;">' + row.name + '</span>?'
    }

    // 查询停用药品是否存在库存
    if('1' !== row.delFlag) {
      selectYpStorageInfo(row.code, '').then((res) => {
        ElMessageBox.confirm(res.msg, {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning',
          distinguishCancelAndClose: true,
          dangerouslyUseHTMLString: true
        }).then(() => {
          callSaveYpDict(title, row, delFlag)
        }).catch((action) => {
          if (action === 'cancel') {
             queryYpDict()
          }
        })
      })
    } else {
      callSaveYpDict(title, row, delFlag)
    }
}

const callSaveYpDict = (title, row, delFlag) => {
  ElMessageBox.confirm(title, {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    type: 'warning',
    distinguishCancelAndClose: true,
    dangerouslyUseHTMLString: true
  }).then(() => {
    updateYpStopOrUsed(row.code, row.serial, delFlag).then((res) => {
      ElMessage({
        type: "success",
        message: res.cg,
        duration: 2500,
        showClose: true,
      });
      queryYpDict()
    })
  }).catch((action) => {
    if (action === 'cancel') {
      queryYpDict()
    }
  })
}

// 设置成临购药品
const tempPurchase = (row) => {
    let flag
    let title
    if ('1' === row.tempPurchaseFlag) {
        flag = ''
        title = '请确认是否停止临购药品<span style="color:#d12020;">' + row.name + '</span>?'
    } else {
        flag = '1'
        title = '请确认是否设置成临购药品<span style="color:#d12020;">' + row.name + '</span>?'
    }

    ElMessageBox.confirm(title, {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        distinguishCancelAndClose: true,
        dangerouslyUseHTMLString: true
    }).then(() => {
        updateYpTempPurchase(row.code, row.serial, flag).then((res) => {
            ElMessage({
                type: "success",
                message: res.cg,
                duration: 2500,
                showClose: true,
            });
            queryYpDict()
        })
    }).catch((action) => {
        if (action === 'cancel') {
            queryYpDict()
        }
    })
}

// 药库药品是否启用/停用操作
const stopYkYpDict = (row) => {
    let delFlag
    let title

    if (!groupNo.value) {
        ElMessage({
            type: "warning",
            message: "请选择药库！",
            duration: 2500,
            showClose: true,
        });
        return
    }

    if ('1' === row.ykFlag) {
        delFlag = '0'
        title = '请确认药库是否启用<span style="color:#d12020;">' + row.name + '</span>?'
    } else {
        delFlag = '1'
        title = '请确认药库是否停用<span style="color:#d12020;">' + row.name + '</span>?'
    }

    // 查询药库停用药品是否存在库存
    if('1' !== row.ykFlag) {
      selectYpStorageInfo(row.code, groupNo.value).then((res) => {
        ElMessageBox.confirm(res.msg, {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning',
          distinguishCancelAndClose: true,
          dangerouslyUseHTMLString: true
        }).then(() => {
          callYkYpStopOrUsed(title, row, delFlag)
        }).catch((action) => {
          if (action === 'cancel') {
            queryYpDict()
          }
        })
      })
    } else {
      callYkYpStopOrUsed(title, row, delFlag)
    }
}

const callYkYpStopOrUsed = (title, row, delFlag) => {
  ElMessageBox.confirm(title, {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    type: 'warning',
    distinguishCancelAndClose: true,
    dangerouslyUseHTMLString: true
  }).then(() => {
    updateYkYpStopOrUsed(groupNo.value, row.code, row.serial, delFlag).then((res) => {
      ElMessage({
        type: "success",
        message: res.cg,
        duration: 2500,
        showClose: true,
      });
      queryYpDict()
    })
  }).catch((action) => {
    if (action === 'cancel') {
      queryYpDict()
    }
  })
}

// 国家基本药物设置
const baseDrugConfirm = (row) => {
    let flag
    let title
    if ('1' === row.jbFlag) {
        flag = ''
        title = '请确认是否取消国家基本药物<span style="color:#d12020;">' + row.name + '</span>?'
    } else {
        flag = '1'
        title = '请确认是否将<span style="color:#d12020;">' + row.name + '</span>设置成国家基本药物?'
    }

    ElMessageBox.confirm(title, {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        distinguishCancelAndClose: true,
        dangerouslyUseHTMLString: true
    }).then(() => {
        updateYpJbFlag(row.code, row.serial, flag).then((res) => {
            ElMessage({
                type: "success",
                message: res.cg,
                duration: 2500,
                showClose: true,
            });
            queryYpDict()
        })
    }).catch((action) => {
        if (action === 'cancel') {
            queryYpDict()
        }
    })
}

// 高警示药品标志维护
const highWarningDrug = (row) => {
  let flag
  let title
  if ('1' === row.highWarningFlag) {
    flag = ''
    title = '请确认是否取消高警示药品<span style="color:#d12020;">' + row.name + '</span>?'
  } else {
    flag = '1'
    title = '请确认是否将<span style="color:#d12020;">' + row.name + '</span>设置成高警示药品?'
  }

  ElMessageBox.confirm(title, {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    type: 'warning',
    distinguishCancelAndClose: true,
    dangerouslyUseHTMLString: true
  }).then(() => {
    updateYpHighWarning(row.code, row.serial, flag).then((res) => {
      ElMessage({
        type: "success",
        message: res.cg,
        duration: 2500,
        showClose: true,
      });
      queryYpDict()
    })
  }).catch((action) => {
    if (action === 'cancel') {
      queryYpDict()
    }
  })
}

// 国家组织药品集中采购中标药品---“带量中选”维护
const winningBidderDrug = (row) => {
  let flag
  let title
  if ('1' === row.winningBidderFlag) {
    flag = ''
    title = '请确认是否取消国家组织药品集中采购中标药品<span style="color:#d12020;">' + row.name + '</span>?'
  } else {
    flag = '1'
    title = '请确认是否将<span style="color:#d12020;">' + row.name + '</span>设置成国家组织药品集中采购中标药品?'
  }

  ElMessageBox.confirm(title, {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    type: 'warning',
    distinguishCancelAndClose: true,
    dangerouslyUseHTMLString: true
  }).then(() => {
    updateYpWinningBidder(row.code, row.serial, flag).then((res) => {
      ElMessage({
        type: "success",
        message: res.cg,
        duration: 2500,
        showClose: true,
      });
      queryYpDict()
    })
  }).catch((action) => {
    if (action === 'cancel') {
      queryYpDict()
    }
  })
}
// 重点监控药品维护
const focusMonitorDrug = (row) => {
  let flag
  let title
  if ('1' === row.focusMonitorFlag) {
    flag = ''
    title = '请确认是否取消重点监控药品<span style="color:#d12020;">' + row.name + '</span>?'
  } else {
    flag = '1'
    title = '请确认是否将<span style="color:#d12020;">' + row.name + '</span>设置成重点监控药品?'
  }

  ElMessageBox.confirm(title, {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    type: 'warning',
    distinguishCancelAndClose: true,
    dangerouslyUseHTMLString: true
  }).then(() => {
    updateYpFocusMonitor(row.code, row.serial, flag).then((res) => {
      ElMessage({
        type: "success",
        message: res.cg,
        duration: 2500,
        showClose: true,
      });
      queryYpDict()
    })
  }).catch((action) => {
    if (action === 'cancel') {
      queryYpDict()
    }
  })
}
// 口服药能否退药标志kfReturnKDrug
const kfReturnDrug = (row) => {
  if('0' !== row.categoriesFlag){
    ElMessage({
      type: "error",
      message: '非口服药不能设置口服药退药标志',
      duration: 2500,
      showClose: true,
    });
    return
  }

  let flag
  let title
  if ('1' === row.returnFlag) {
    flag = ''
    title = '请确认是否取消药品<span style="color:#d12020;">' + row.name + '</span>允许退药?'
  } else {
    flag = '1'
    title = '请确认是否将药品<span style="color:#d12020;">' + row.name + '</span>设置成允许退药?'
  }

  ElMessageBox.confirm(title, {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    type: 'warning',
    distinguishCancelAndClose: true,
    dangerouslyUseHTMLString: true
  }).then(() => {
    updateYpReturnFlag(row.code, row.serial, flag).then((res) => {
      ElMessage({
        type: "success",
        message: res.cg,
        duration: 2500,
        showClose: true,
      });
      queryYpDict()
    })
  }).catch((action) => {
    if (action === 'cancel') {
      queryYpDict()
    }
  })
}

// 导出药品账页信息
const exportData = () => {
  if (drugDictData.value.length === 0) {
    ElMessage({
      message: "没有可以导出的数据！",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
  } else {
    const title = {
      code: "药品编码",
      serial: "药品包装",
      name: "药品名称",
      specification: "药品规格",
      packRetprice: "药品零售价",
      manuFactory: '生产厂家',
      delFlag: "状态",
      ykFlag: "药库状态",
      pyCode: "拼音码",
      dCode: "五笔码",
    };

    const d = clone(drugDictData.value)
    d.forEach(val => {
      if (val.delFlag === '1') {
        val.delFlag = '停用'
      } else {
        val.delFlag = ''
      }
      if (val.ykFlag === '1') {
        val.ykFlag = '药库停用'
      } else {
        val.ykFlag = ''
      }
    });
    Export(d, title, "药品账页信息")
  }
}
</script>

<style lang="scss">
.yp-edit-dialog {
  .el-dialog__body {
    padding: 2px 5px !important;
  }
}
</style>