<template>
  <div class="layout_container">
    <header>
      <el-input v-model="inpatientNo" class="w-50 m-2" style="width: 220px" placeholder="请输入姓名/住院号" clearable>
      </el-input>
      <el-select v-model="chargeCode" placeholder="请选择临购药品" filterable clearable
                 remote style="width: 320px;margin-left: 3px" :remote-method="queryTempPurchaseYp">
        <el-option v-for="item in tempPurchaseData" :key="item.chargeCode" :label="item.chargeName"
                   :value="item.chargeCode">
          <span style="float: left">{{ item.chargeName }}</span>
          <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px; ">
                        {{ item.chargeCode }}
                    </span>
        </el-option>
      </el-select>
      <el-select v-model="ztFlag" placeholder="请选择申请进度" clearable style="width: 140px;margin-left: 3px">
        <el-option v-for="item in ztOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker v-model="dateRange" type="daterange" :shortcuts="maxHalfYear" range-separator="至"
                      start-placeholder="开始时间" end-placeholder="结束时间" style="width: 260px;margin-left: 3px">
      </el-date-picker>
      <el-button type="primary" icon="Search" @click="queryYpTempPurchaseData"
                 style="margin-left: 5px">查询
      </el-button>
      <el-button type="primary" icon="Download" @click="exportData" style="margin-left: 5px">导出</el-button>
    </header>
    <div class="layout_main">
      <el-tabs class="el-tabs__fill" v-model="editableTabsValue" type="border-card" @tab-click="handleClick">
        <el-tab-pane key="ypPurchase" label="明细" name="ypPurchaseInfo">
          <div class="layout_container">
            <div class="layout_main layout_el-table">
              <el-table :data="ypPurchaseData.slice(pageSize * (currentPage - 1), pageSize * currentPage)" border
                         stripe highlight-current-row>
                <el-table-column type="index" label="序号" width="60" fixed/>
                <el-table-column prop="chargeCode" label="药品编码" width="90" fixed/>
                <el-table-column prop="serial" label="药品包装" width="70" fixed>
                  <template #default="scope">
                    <span v-if="scope.row.serial === '99'">大包装</span>
                    <span v-else>小包装</span>
                  </template>
                </el-table-column>
                <el-table-column prop="chargeName" label="药品名称" width="220" show-overflow-tooltip fixed/>
                <el-table-column prop="specification" label="药品规格" width="140" show-overflow-tooltip/>
                <el-table-column prop="name" label="患者姓名" width="100"/>
                <el-table-column prop="inpatientNo" label="住院号" width="100"/>
                <el-table-column prop="amount" label="数量" width="70"/>
                <el-table-column prop="manuFactory" label="厂家" width="160" show-overflow-tooltip/>
                <el-table-column prop="useResult" label="使用理由" width="200" show-overflow-tooltip/>
                <el-table-column prop="op" label="申请人" width="100"/>
                <el-table-column prop="applyDate" label="申请时间" width="140"/>
                <el-table-column prop="receptFlag" label="是否接收" width="80">
                  <template #default="scope">
                    <span v-if="scope.row.receptFlag === '1'" style="color:#106898;">已接收</span>
                    <span v-else-if="scope.row.receptFlag === '0'" style="color:#d12020;">拒接收</span>
                    <span v-else></span>
                  </template>
                </el-table-column>
                <el-table-column prop="purchaseFlag" label="是否采购" width="80">
                  <template #default="scope">
                    <span v-if="scope.row.purchaseFlag === '1'" style="color:#106898;">已采购</span>
                    <span v-else-if="scope.row.purchaseFlag === '0'" style="color:#d12020;">拒采购</span>
                    <span v-else></span>
                  </template>
                </el-table-column>
                <el-table-column prop="storageFlag" label="是否入库" width="80">
                  <template #default="scope">
                    <span v-if="scope.row.storageFlag === '1'" style="color:#106898;">已入库</span>
                    <span v-else-if="scope.row.storageFlag === '0'" style="color:#d12020;">拒入库</span>
                    <span v-else></span>
                  </template>
                </el-table-column>
                <el-table-column prop="result" label="采购情况" width="200" show-overflow-tooltip/>
                <el-table-column prop="auditName" label="审核" width="100" />
                <el-table-column prop="purchaseName" label="采购" width="100" />
                <el-table-column prop="storageName" label="入库" width="100" />
                <el-table-column fixed="right" label="操作" min-width="80" width="80" header-align="center"
                                 align="center">
                  <template #default="scope">
                    <el-button type="primary" size="small" v-if="scope.row.permissions === '1'"
                               @click="auditTempPurchase(scope.row)">审核
                    </el-button>
                    <el-button type="primary" size="small" v-if="scope.row.permissions === '0'"
                               @click="editTempPurchase(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="ypPurchaseData.length" layout="total, sizes, prev, pager, next, jumper"
                             style="margin-top: 5px" @size-change="handleSizeChange"
                             @current-change="handleCurrentChange">
              </el-pagination>
            </div>
          </div>
          <el-dialog v-model="showAuditTempPurchase" :close-on-click-modal="false" :before-close="handleClose"
                     :close-on-press-escape="false" :title="auditTempPurchaseName" width="80%" destroy-on-close>
            <TempPurchaseAudit :ypTempPurchaseDetail="ypTempPurchaseDetail"
                               @closeTempPurchaseAudit="closeTempPurchaseAudit"/>
          </el-dialog>
          <el-dialog v-model="showEditTempPurchase" :close-on-click-modal="false" :before-close="handleClose"
                     :close-on-press-escape="false" :title="editTempPurchaseName" width="80%" destroy-on-close>
            <TempPurchaseEdit :ypTempPurchaseEditData="ypTempPurchaseEditData"
                              @closeTempPurchaseEdit="closeTempPurchaseEdit"/>
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane key="ypPurchase" label="申请" name="ypPurchase">
          <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px"
                   class="demo-ruleForm" :size="formSize" status-icon>
            <el-row>
              <el-col :span="6">
                <el-form-item label="药品" prop="chargeCode">
                  <el-select v-model="ruleForm.chargeCode" placeholder="请选择药品" filterable clearable
                             remote style="width: 100%" @change="ypChange" :remote-method="queryTempPurchaseYp">
                    <el-option v-for="item in tempPurchaseData" :key="item.chargeCode"
                               :label="item.chargeName" :value="item.chargeCode">
                      <span style="float: left">{{ item.chargeName }}</span>
                      <span
                          style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">
                          {{ item.chargeCode }}
                        </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="序号" prop="serial">
                  <el-input v-model="ruleForm.serial" maxlength="2" show-word-limit placeholder="序号"
                            disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="规格" prop="specification">
                  <el-input v-model="ruleForm.specification" maxlength="40" show-word-limit
                            placeholder="规格" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="厂家" prop="manuFactory">
                  <el-input v-model="ruleForm.manuFactory" maxlength="32" show-word-limit
                            placeholder="厂家" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="数量" prop="amount">
                  <el-input v-model="ruleForm.amount" maxlength="10" show-word-limit
                            placeholder="请填写数量" autocomplete="off"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="患者姓名" prop="name">
                  <el-input v-model="ruleForm.name" maxlength="40" show-word-limit
                            placeholder="请填写患者姓名"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="住院号" prop="inpatientNo">
                  <el-input v-model="ruleForm.inpatientNo" maxlength="10" show-word-limit
                            placeholder="请填写住院号"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="申请人" prop="op">
                  <el-input v-model="ruleForm.op" maxlength="40" show-word-limit
                            placeholder="申请人" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="18">
                <el-form-item label="使用理由" prop="useResult">
                  <el-input v-model="ruleForm.useResult" show-word-limit placeholder="请填写使用理由"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="申请日期" prop="applyDate">
                  <el-input v-model="ruleForm.applyDate" show-word-limit placeholder="请填写申请日期"
                            disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="温馨提示" prop="desc">
                  <el-input v-model="desc" show-word-limit placeholder="温馨提示" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">
                申请
              </el-button>
              <el-button type="info" @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script setup>
import {ref, onMounted, nextTick} from 'vue'
import {useUserStore} from '@/pinia/user-store'
import {ElMessage} from 'element-plus'
import {Export} from '@/utils/ExportExcel'
import {formatDatetime, getDateRangeFormatDate} from '@/utils/date'
import {maxHalfYear} from '@/data/shortcuts'
import {clone} from '@/utils/clone'
import {selectYpTempPurchase, selectTempPurchaseYp, saveYpTempPurchase} from '@/api/yp-inventory/yp-temp-purchase.js'
import TempPurchaseAudit from '@/views/yp-inventory/TempPurchaseAudit.vue'
import TempPurchaseEdit from '@/views/yp-inventory/TempPurchaseEdit.vue'

const userInfo = useUserStore().userInfo
const editableTabsValue = ref('ypPurchaseInfo')
const userCode = userInfo.code
const userName = userInfo.name
const ypPurchaseData = ref([])
const inpatientNo = ref('')
const chargeCode = ref('')
const ztFlag = ref('')
const dateRange = ref([])
const now = formatDatetime(new Date())
const start = formatDatetime(maxHalfYear[2].value[0])
const end = formatDatetime(maxHalfYear[2].value[1])
const pageSize = ref(30)
const currentPage = ref(1)
const handleSizeChange = (val) => {
  pageSize.value = val
}
const handleCurrentChange = (val) => {
  currentPage.value = val
}
const handleClick = (tab, event) => {
  editableTabsValue.value = tab.props.name
  if (editableTabsValue.value === 'ypPurchaseInfo') {
    queryYpTempPurchaseData()
  }
}
const ztOptions = [
  {value: '1', label: '已接收'}, {value: '2', label: '未接收'},
  {value: '3', label: '已采购'}, {value: '4', label: '未采购'},
  {value: '5', label: '已入库'}, {value: '6', label: '未入库'}]
const desc = ref('科室临购药品在本院出现滞销（90天以上未使用或使用数量低于购进数量的30%以下），导致过期现象，则该药品的损失由申请科室承担，并1年内不能再申请新药。')
const tempPurchaseData = ref([])
const queryData = ref({
  inpatientNo: '',
  chargeCode: '',
  ztFlag: '',
  startTime: '',
  endTime: '',
})

onMounted(() => {
  nextTick(() => {
    queryTempPurchaseYp('')
    queryData.startTime = start;
    queryData.endTime = end + " 23:59:59";
    dateRange.value = [start, end];
    queryYpTempPurchaseData()
  })
})

const showAuditTempPurchase = ref(false)
const auditTempPurchaseName = ref('临购药品审核')
const ypTempPurchaseDetail = ref([])

const showEditTempPurchase = ref(false)
const editTempPurchaseName = ref('临购药品修改')
const ypTempPurchaseEditData = ref([])

const queryYpTempPurchaseData = () => {
  if (dateRange.value) {
    let dateS = getDateRangeFormatDate(dateRange.value)
    queryData.value.startTime = dateS.startTime
    queryData.value.endTime = dateS.endTime
  }
  queryData.value.chargeCode = chargeCode.value
  queryData.value.inpatientNo = inpatientNo.value
  queryData.value.ztFlag = ztFlag.value
  selectYpTempPurchase(queryData.value)
      .then((res) => {
        ypPurchaseData.value = res
      })
      .catch(() => {
        ypPurchaseData.value = []
      })
}

const queryTempPurchaseYp = (text) => {
  selectTempPurchaseYp(text)
      .then((res) => {
        tempPurchaseData.value = res
      })
      .catch(() => {
        tempPurchaseData.value = []
      })

}

const ypChange = async () => {
  await nextTick()
  let dataF = tempPurchaseData.value.filter((item) => {
    return item.chargeCode === ruleForm.value.chargeCode
  })
  if (dataF) {
    ruleForm.value.chargeName = dataF[0].chargeName
    ruleForm.value.serial = dataF[0].serial
    ruleForm.value.specification = dataF[0].specification
    ruleForm.value.manuFactory = dataF[0].manuFactory
  }
}

const formSize = ref('default')
const ruleFormRef = ref()
const ruleForm = ref({
  applyId: '', // 申请id
  chargeName: '', // 药品名称
  chargeCode: '', // 药品code
  serial: '', // 序号
  specification: '', // 规格
  amount: '', // 申请数量
  useResult: '', // 使用理由
  op: userName, // 申请人(要求是临床科主任)
  opId: userCode, // 申请人id
  name: '', // 患者姓名
  inpatientNo: '', // 住院号
  receptFlag: '', // 是否接收(1: 接收)
  purchaseFlag: '', // 是否采购(1: 采购)
  storageFlag: '', // 是否入库(1: 入库)
  applyDate: now, // 申请日期
  auditDate: '', // 审核日期
  result: '', // 未采购原因
  manuFactory: '', // 厂家
  auditId: '', // 审核人id
  auditName: '', // 审核人
  purchaseId: '', // 采购人id
  purchaseName: '', // 采购人
  storageId: '', // 入库人id
  storageName: '', // 入库人
})
const rules = ref({
  chargeCode: [
    {required: true, message: '请选择药品', trigger: 'change'},
  ],
  amount: [
    {required: true, message: '请填写申请数量', trigger: 'blur'},
  ],
  useResult: [
    {required: true, message: '请填写使用理由', trigger: 'blur'},
  ],
  name: [
    {required: true, message: '请填写患者姓名', trigger: 'blur'},
  ],
  inpatientNo: [
    {required: true, message: '请填写住院号', trigger: 'blur'},
  ],
})

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (Number.isNaN(Number.parseFloat(ruleForm.value.amount))) {
        ElMessage({
          type: "warning",
          message: '申请数量不是数值，请检查！',
          duration: 2500,
          showClose: true,
        });
        return
      }
      saveYpTempPurchase(ruleForm.value).then((res) => {
        if (res.cg) {
          ElMessage({
            type: "success",
            message: res.cg,
            duration: 2500,
            showClose: true,
          });

          formEl.resetFields()
          editableTabsValue.value = 'ypPurchaseInfo'
          queryYpTempPurchaseData()
        }
      });
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

const auditTempPurchase = (row) => {
  showAuditTempPurchase.value = true
  ypTempPurchaseDetail.value = row
}

const closeTempPurchaseAudit = (flag) => {
  if (flag) {
    showAuditTempPurchase.value = false
  }
  queryYpTempPurchaseData()
}

const handleClose = (done) => {
  queryYpTempPurchaseData()
  done()
}

const editTempPurchase = (row) => {
  if (row.receptFlag === '1') {
    ElMessage({
      type: "warning",
      message: '临购药品已接收的申请不允许修改，请检查！',
      duration: 2500,
      showClose: true,
    });
    return
  }

  showEditTempPurchase.value = true
  ypTempPurchaseEditData.value = row
}

const closeTempPurchaseEdit = (flag) => {
  if (flag) {
    showEditTempPurchase.value = false
  }
  queryYpTempPurchaseData()
}

// 导出临购药品明细信息
const exportData = () => {
  if (ypPurchaseData.value.length === 0) {
    ElMessage({
      message: "没有可以导出的数据！",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
  } else {
    const title = {
      chargeCode: "药品编码",
      chargeName: "药品名称",
      serial: "药品包装",
      specification: "药品规格",
      name: "患者姓名",
      inpatientNo: "住院号",
      amount: "数量",
      manuFactory: '厂家',
      useResult: "使用理由",
      op: "申请人",
      receptFlag: "是否接收",
      purchaseFlag: "是否采购",
      storageFlag: "是否入库",
      applyDate: "申请日期",
      auditDate: "审核日期",
      result: "采购情况",
    };

    const d = clone(ypPurchaseData.value)
    d.forEach(val => {
      if (val.serial === '99') {
        val.serial = '大包装'
      } else {
        val.serial = '小包装'
      }
      if (val.receptFlag === '1') {
        val.receptFlag = '是'
      } else {
        val.receptFlag = '否'
      }
      if (val.purchaseFlag === '1') {
        val.purchaseFlag = '是'
      } else {
        val.purchaseFlag = '否'
      }
      if (val.storageFlag === '1') {
        val.storageFlag = '是'
      } else {
        val.storageFlag = '否'
      }
    });
    Export(d, title, "临购药品明细信息")
  }
}

</script>