<template>
  <my-layout>
    <layout-item class="bg-white">
      <div class="py-5px flex" @keyup.enter="search()">
        <expand-filter-box v-model:can-expand="canExpand" :enable-expand="true" class="flex-grow" :expand="expand">
          <radio-filter v-model="queryForm.onSale" label="药品状态" :list="statusList" />
          <input-filter v-model="queryForm.name" label="药品名称" placeholder="药品名称搜索" :width="240" />
          <input-filter v-model="queryForm.productId" label="药品id" placeholder="药品id搜索" :width="240" />
          <input-filter v-model="queryForm.barcode" label="条形码" placeholder="条形码搜索" :width="240" />
          <input-filter v-model="queryForm.insuranceCode" label="医保编码" placeholder="医保编码搜索" :width="240" />
        </expand-filter-box>
        <div class="flex-shrink-0 flex items-center h-40px pr-15px">
          <el-button v-if="canExpand" text plain @click="expand = !expand">
            <span class="mr-5px">{{ expand ? "收起筛选" : "更多筛选" }}</span>
            <el-icon v-if="expand">
              <ArrowUpBold />
            </el-icon>
            <el-icon v-else>
              <ArrowDownBold />
            </el-icon>
          </el-button>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button plain @click="clear()">清空筛选</el-button>
        </div>
      </div>
    </layout-item>
    <Layout-item class="bg-white mt-10px">
      <div class="flex items-center px-15px py-12px text-14px">
        <div class="mr-15px flex-shrink-0">
          已选择药品：
          <span class="text-red-500">{{ selections.length }}</span>
        </div>
        <el-button class="flex-shrink-0" type="primary" :icon="Upload" @click="setOnSale(true)">上架</el-button>
        <el-button plain class="flex-shrink-0" type="info" :icon="Download" @click="setOnSale(false)">下架</el-button>
        <div class="flex-grow"></div>
        <el-button class="flex-shrink-0" type="primary" @click="editDrug()">新增</el-button>
        <el-button class="flex-shrink-0" type="success" :icon="Share" @click="show()">批量导入</el-button>
      </div>
    </Layout-item>
    <layout-main :scroll="false">
      <el-table v-loading="loading" border ref="tableRef" height="100%" :data="list"
        @selection-change="handleSelectionChange">
        <el-table-column prop="selection" align="center" type="selection" :width="50" />
        <el-table-column prop="index" type="index" label="序号" :width="60">
          <template #default="{$index}">{{ $index + 1 }}</template>
        </el-table-column>
        <el-common-column prop="status" label="状态" :width="100">
          <template #default="{row}">
            <el-text v-if="row.onSale" type="success">已上架</el-text>
            <el-text v-else type="info">已下架</el-text>
          </template>
        </el-common-column>
        <el-common-column prop="product_id" label="货品id" :width="160" />
        <el-common-column prop="name" label="药品" :width="160" />
        <el-common-column prop="specification" label="规格" :width="160" />
        <el-common-column prop="package_amount" label="包装量" :width="160" />
        <el-common-column prop="manufacturer" label="生产厂家" :width="160" />
        <el-common-column prop="barcode" label="条形码" :width="160" />
        <el-common-column prop="insurance_code" label="医保编码" :width="160" />
        <el-common-column prop="dosage" label="单次剂量" :width="160" />
        <el-common-column prop="dosage_unit" label="剂量单位" :width="160" />
        <el-common-column prop="frequency" label="频次" :width="160" />
        <el-common-column prop="administration_method" label="给药方式" :width="160" />
        <el-common-column prop="days" label="用药天数" :width="160" />
        <el-common-column prop="recommended_quantity" label="推荐发药数量" :width="160" />
        <el-common-column label="" :min-width="0" />
        <el-table-column fixed="right" type="action" label="操作" :width="100">
          <template #default="{ row }">
            <el-text type="primary" class="cursor-pointer mr-10px" @click="showDetail(row)">详情</el-text>
            <el-text type="primary" class="cursor-pointer" @click="editDrug(row)">编辑</el-text>
          </template>
        </el-table-column>
      </el-table>
    </layout-main>
    <layout-item>
      <pagination :totalRow="total" :pageSize="pageSize" :currentPage="page" @handle-size-change="changeSize"
        @handle-current-change="changePage" />
    </layout-item>
  </my-layout>
  <import-modal :visible="visible" :width="width" @change="showImportRes($event)" @close="close()" />
  <import-res-modal :memberInfo="memberInfo" :data="csvData" :visible="visibleResModal" :width="widthResModal"
    @close="closeResModal()" @reUpload="show()" @change="search()" />
  <drug-drawer :data="drug" :memberInfo="memberInfo" :visible="showDrawer" @close="showDrawer=false"
    @change="search()" />
  <drug-detail-drawer :data="drug" :visible="detailVisible" @changeSale="changeSale" @edit="editDrug(drug)"
    @close="detailVisible=false" />
</template>
<script setup>
import { computed, onMounted, ref, watch, onUnmounted } from "vue";
import { storeToRefs } from "pinia";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import dayjs from "dayjs";
import { getHlwDrugInfo, setHlwDrugOnSale } from "@/api/hlw";
import useModal from "@/hooks/useModal";
import useElPagination from "@/hooks/useElPagination";
import { memberStore } from "@/store/member";

import { Upload, Download, Share } from "@element-plus/icons-vue";
import { InputFilter, expandFilterBox, RadioFilter } from "@/components/filter-bar";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import pagination from "@/components/pagination/pagination.vue";
import elCommonColumn from "@/components/el-common-column/el-common-column.vue";
import ImportModal from "./import-modal.vue";
import ImportResModal from "./import-res-modal.vue";
import drugDrawer from './drug-drawer.vue'
import drugDetailDrawer from './drug-detail-drawer.vue'

const { list, page, pageSize, total, changePage, changeSize } = useElPagination(getList);
const { memberInfo } = storeToRefs(memberStore());

const statusList = [{ label: '上架', value: 1 }, { label: '下架', value: 0 }];
const queryForm = ref({ onSale: '', name: '', productId: '', barcode: '', insuranceCode: '' })
const params = ref({});
const selections = ref([]);
const tableRef = ref();
const detailVisible = ref(false)
const loading = ref(false);
const csvData = ref({});
const showDrawer = ref(false);
const drug = ref({});
const { close, show, visible, width } = useModal(560);
const { close: closeResModal, show: showResModal, visible: visibleResModal, width: widthResModal } = useModal(1200);
const canExpand = ref(false);
const expand = ref(false);

function changeSale(onSale) {
  drug.value.onSale = onSale
  const index = list.value.findIndex(i => i._id === drug.value._id);
  if (index >= 0) {
    list.value[index].onSale = onSale;
  }
}

function clear() {
  queryForm.value = {};
  params.value = {}
  search();
}

function editDrug(row = {}) {
  drug.value = { ...row };
  showDrawer.value = true;
}

function search() {
  params.value = { ...queryForm.value };
  if (typeof params.value.onSale == 'number') {
    params.value.onSale = Boolean(params.value.onSale);
  }
  page.value = 1;
  getList();
}

function handleSelectionChange(val) {
  selections.value = val.map((i) => i._id);
}

function showDetail(row) {
  drug.value = { ...row };
  detailVisible.value = true;
}

function showInfo(row) {
  info.value = row;
  visible.value = true;
}

function showImportRes(e) {
  csvData.value = e;
  showResModal();
}

async function getList() {
  loading.value = true;
  tableRef.value && tableRef.value.clearSelection();
  const { success, data, message } = await getHlwDrugInfo({ ...params.value, page: page.value, pageSize: pageSize.value });
  if (!success) {
    ElMessage.error(message);
  }
  list.value = data && Array.isArray(data.data) ? data.data : [];
  total.value = data && data.total >= 0 ? data.total : 0;
  loading.value = false;
}

async function setOnSale(onSale) {
  if (selections.value.length === 0) {
    ElMessage.info('请选择药品');
    return;
  }
  await ElMessageBox.confirm(`确定${onSale ? '上架' : '下架'}选中的药品吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  });
  const { success, message } = await setHlwDrugOnSale({ ids: selections.value, onSale, updater: memberInfo.value.anotherName, updaterId: memberInfo.value._id });
  if (success) {
    ElMessage.success(message);
    getList();
  } else {
    ElMessage.error(message);
  }
}

onMounted(() => {
  getList()
});

onUnmounted(() => {
  // timer.value && clearTimeout(timer.value);
  // loadingInstance.value && loadingInstance.value.close();
});

</script>