<template>
  <Mask :is-show="isShow" @close="close" title="添加组套" :show-footer="true" :width="1200" :height="800">
    <div class="group">
      <div class="form-info">
        <el-form :model="form" label-width="0" ref="formRef" style="width: 100%;height: 100%">
          <el-descriptions
              :column="2"
              border
              style="width: 100%"
          >
            <el-descriptions-item label="组套名称">
              <el-form-item prop="name">
                <el-input v-model="form.name"/>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="单位">
              <el-form-item prop="unit">
                <el-popover
                    placement="bottom"
                    title="Title"
                    trigger="click"
                >
                  <template #reference>
                    <el-input v-model="form.unit"></el-input>
                  </template>
                  <UnitSelector :units="itemUnitList" v-model="form.unit"></UnitSelector>
                </el-popover>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="原价">
              <el-form-item>
                <el-input v-model="form.purchaseUnitPrice" readonly>
                  <template #prefix>
                    ￥
                  </template>
                </el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="售价">
              <el-form-item prop="unitPrice">
                <el-input v-model="form.unitPrice" readonly>
                  <template #prefix>￥</template>
                </el-input>
              </el-form-item>
            </el-descriptions-item>
          </el-descriptions>
        </el-form>
      </div>
      <div class="top">
        <div class="default-btn" @click="openSearchDialog">添加子项目</div>
      </div>
      <div class="table" style="height: 100%">
        <el-table v-if="list.length>0" :data="list" style="width: 100%;height: 100%">
          <el-table-column label="名称" prop="name" show-overflow-tooltip></el-table-column>
          <el-table-column label="单位" prop="unit" width="100" show-overflow-tooltip></el-table-column>
          <el-table-column label="医保编码" prop="socialCode" show-overflow-tooltip></el-table-column>
          <el-table-column label="原价" prop="purchaseUnitPrice">
            <template #default="scope">
              <el-input v-model="scope.row.purchaseUnitPrice" type="number">
                <template #prefix>￥</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="售价" prop="unitPrice">
            <template #default="scope">
              <el-input v-model="scope.row.unitPrice" type="number">
                <template #prefix>￥</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="number">
            <template #default="scope">
              <el-input v-model="scope.row.number" type="number">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <span @click="removeTableRow(scope.row)" style="color: #ff0000">删除</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <ItemSearch ref="createSearchRef" @confirm="createConfirm"/>
    <template #footer>
      <div class="footer">
        <div class="page">
          <el-pagination background layout="prev, pager, next" v-model:page-count="pageNum"
                         :page-size="pageSize" :total="total" @current-change="changePage"/>
        </div>
        <span class="default-btn" @click="save">保存</span>
      </div>
    </template>
  </Mask>
</template>
<script setup lang="ts">
import {ref, defineExpose, nextTick, watch} from 'vue'
import Mask from "@/components/common/Mask.vue";
import ItemSearch from "@/components/settings/item/ItemSearch.vue";

const createSearchRef = ref<any>('')
import {itemUnitList} from "@/utils/unitList.ts"
import UnitSelector from "@/components/UnitSelector.vue";
import {post} from "@/utils/request.ts";

const isShow = ref<any>(false)
const list = ref<any[]>([])
const id = ref<any>('')
const init = (row: any) => {
  isShow.value = true
  form.value = {...default_form}
  list.value = []
  if (row != null) {
    id.value = row.id
    post("item/getGroup",{id: row.id}).then((res: any)=>{
      form.value={...res.info}
      console.log(form.value)
      list.value = res.list
    })
  }
}

const openSearchDialog = () => {
  nextTick(() => {
    createSearchRef.value?.init("");
  });
}

const createConfirm = (data: any) => {
  let row = {
    id: null,
    name: data.name,
    unit: data.unit,
    number: "1",
    socialCode: data.code,
    purchaseUnitPrice: 0,
    unitPrice: 0,
  }
  list.value.push(row)
  calculateTotalPrices();
}
const emit = defineEmits(['close'])
const close = () => {
  isShow.value = false
  form.value = {name: '', ids: []}
  emit('close')
}
const default_form = {
  id: null,
  name: "",
  unit: "次",
  purchaseUnitPrice: "",
  unitPrice: "",
}
const form = ref<any>(default_form)
const calculateTotalPrices = () => {
  const totalPurchasePrice = list.value.reduce((sum, item) =>
      sum + parseFloat(item.purchaseUnitPrice || 0) * parseFloat(item.number || 1), 0);
  const totalPrice = list.value.reduce((sum, item) =>
      sum + parseFloat(item.unitPrice || 0) * parseFloat(item.number || 1), 0);
  form.value.purchaseUnitPrice = totalPurchasePrice.toFixed(2); // 保留两位小数
  form.value.unitPrice = totalPrice.toFixed(2);
};
const save = () => {
  post("item/saveGroup",{info: form.value,list:list.value}).then(
      ()=>{
        close()
      }
  )
}
const removeTableRow = (row: any) => {
  const index = list.value.findIndex(item => item === row);
  if (index !== -1) {
    list.value.splice(index, 1);
    calculateTotalPrices();
  }
}
const pageNum = ref<any>(1)
const pageSize = ref<any>(20)
const total = ref<any>(0)
const changePage= (value:any) => {
  pageNum.value=value
  calculateTotalPrices()
}
watch(
    () => list.value.map(item => ({
      number: item.number,
      purchaseUnitPrice: item.purchaseUnitPrice,
      unitPrice: item.unitPrice
    })),
    () => {
      calculateTotalPrices();
    },
    {deep: true}
);
defineExpose({init})
</script>
<style scoped lang="scss">
.group{
  height: 100%;
  display: flex;
  flex-direction: column;
  .form-info {
    padding: 24px;
  }
}


.top {
  padding-left: 24px;
}

.table {
  padding: 24px;
  flex: 1;
  min-height: 0;
}

.footer {
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
}

</style>