<template>
  <div class="edit-panel" v-loading="isLoading" element-loading-text="正在保存......">
    <div class="top">
      <el-form :model="inventory_order_data" label-position="top" :rules="formRules" ref="orderForm">
        <el-row>
          <el-col :span="6">
            <el-form-item label="订单编号">
              <div style="width: 234px;">
                {{ inventory_order_data.code != null ? inventory_order_data.code : "创建后自动生成" }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购人">
              <el-input style="width: 234px;" disabled v-model="userInfo.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="purchaseDate" label="采购日期" :rules="formRules.purchaseDate">
              <el-date-picker
                  v-model="inventory_order_data.purchaseDate"
                  type="date"
                  placeholder="选择一个创建日期"
                  size="default"
                  style="width: 234px;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="shippingCode" label="货单号" :rules="formRules.shippingCode">
              <el-input v-model="inventory_order_data.shippingCode"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item prop="invoiceCode" label="发票号">
              <el-input style="width: 234px;" v-model="inventory_order_data.invoiceCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="supplierId" label="供应商" :rules="formRules.supplierId">
              <el-select style="width: 234px;" v-model="inventory_order_data.supplierId" placeholder="请选择供应商">
                <el-option
                    v-for="item in supplier_list"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" :rules="formRules.purchaseDate">
              <el-input v-model="inventory_order_data.remark"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="table_content">
      <div class="add_goods">
        <span>添加商品</span>
        <div class="search">
          <GoodsSearch @selectCallBack="goodsSelectCallBack"></GoodsSearch>
          <el-button :icon="Search" type="primary">搜索</el-button>
        </div>
      </div>
      <el-table :data="table_list" style="width: 100%" height="300" max-height="550">
        <el-table-column prop="name" label="药品名称" width="180" show-overflow-tooltip/>
        <el-table-column label="售价" prop="unitPrice" width="80">
        </el-table-column>
        <el-table-column label="单位" prop="packagingUnit" width="80">
        </el-table-column>
        <el-table-column label="数量" width="110">
          <template #default="scope">
            <el-input-number
                v-model="scope.row.wholeNumber"
                :min="1"
                size="small"
                controls-position="right"
                style="width: 80px"
                @change="getTotalPrice"
            />
          </template>

        </el-table-column>
        <el-table-column label="进价" width="110">
          <template #default="scope">
            <el-input-number
                v-model="scope.row.purchaseUnitPrice"
                :min="1"
                size="small"
                controls-position="right"
                style="width: 80px"
                @change="getTotalPrice"
            />
          </template>
        </el-table-column>
        <el-table-column label="生产批号" width="150">
          <template #default="scope">
            <el-input
                v-model="scope.row.productionBatchCode"
                placeholder="生产批号"
                style="width: 100px"
                size="small"/>
          </template>

        </el-table-column>
        <el-table-column label="生产日期" width="140">
          <template #default="scope">
            <el-date-picker
                :editable="false"
                v-model="scope.row.productionDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="生产日期"
                size="small"
                @change="checkProductionDate(scope.row)"
                style="width: 100px;"/>
          </template>

        </el-table-column>
        <el-table-column label="有效日期" width="140">
          <template #default="scope">
            <el-date-picker
                :editable="false"
                v-model="scope.row.expiryDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="有效日期"
                size="small" style="width: 100px;"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="small" @click="removeTableRow(scope.row)" type="danger" plain>移除</el-button>
          </template>
        </el-table-column>

      </el-table>
      <div class="totalPrice">
        订单总金额：￥{{ inventory_order_data.totalPrice.toFixed(2) }}
      </div>

    </div>
    <div class="bottom">
      <el-button type="primary" @click="confirm">确认</el-button>
      <el-button type="primary" @click="exit">关闭</el-button>
    </div>
  </div>

  <Mask :is-show="is_add" :top="100">
    <Edit ref="editRef" @close="is_add = false;"/>
  </Mask>

</template>

<script lang="ts" setup>
import {nextTick, onMounted, ref, watch} from 'vue'
import {post} from '@/utils/request.ts'
import Edit from "@/components/inventory/goods/Edit.vue";
import Mask from "@/components/common/Mask.vue";
import {ElMessage} from "element-plus";
import GoodsSearch from "@/components/inventory/GoodsSearch.vue";
import {Search} from "@element-plus/icons-vue";

const orderForm = ref()
const formRules = ref({
  shippingCode: [{required: true, message: '请输入货单号', trigger: 'blur'}],
  purchaseDate: [{required: true, message: '请选择采购日期', trigger: 'change'}],
  supplierId: [{required: true, message: '请选择供应商', trigger: 'change'}],
});
let inventory_order_data = ref({
  code: null,
  purchaseDate: getFormattedDate(),
  userId: null,
  supplierId: null,
  remark: null,
  managerUserId: null,
  kindConut: 0,
  totalPrice: 0,
  shippingCode: null,
  invoiceCode: null,
  inventoryOrderGoodsList: []
})
const checkProductionDate = (row: any) => {
  if (!row.productionDate) {
    ElMessage.error('生产日期不能为空');
    return false;
  }
  const productionDate = new Date(row.productionDate);
  const currentDate = new Date();
  if (productionDate > currentDate) {
    ElMessage.error('生产日期不能晚于当前日期');
    row.productionDate = null; // 清空无效的生产日期
    return false;
  }
  return true;
};

const checkExpiryDate = (row: any) => {
  if (!row.expiryDate) {
    ElMessage.error('有效期不能为空');
    return false;
  }
  const productionDate = new Date(row.productionDate);
  const expiryDate = new Date(row.expiryDate);
  const currentDate = new Date(); // 获取当前日期

  if (expiryDate <= currentDate) {
    ElMessage.error('有效期不能早于当前日期');
    row.expiryDate = null; // 清空无效的有效期
    return false;
  } else if (expiryDate <= productionDate) {
    ElMessage.error('有效期必须晚于生产日期');
    row.expiryDate = null; // 清空无效的有效期
    return false;
  }
  return true;
};

const isLoading = ref(false)
const getTotalPrice = () => {
  let totalPrice = 0;
  table_list.value.forEach((item: any) => {
    totalPrice += item.purchaseUnitPrice * item.wholeNumber
  })
  inventory_order_data.value.totalPrice = totalPrice;
}
const emit = defineEmits(['close'])
let exit = () => {
  emit('close')
}
const table_list: any = ref([])


function getFormattedDate() {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
  const day = String(today.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
}

let confirm = async () => {
  // 进行表单验证
  try {
    await orderForm.value.validate()

    // 验证通过后执行原有逻辑
    inventory_order_data.value.kindConut = table_list.value.length;
    inventory_order_data.value.managerUserId = userInfo.value.id;

    // 添加药品列表验证
    if (table_list.value.length === 0) {
      ElMessage.error('请至少添加一个采购药品')
      return
    }

    // 检查每个药品的有效期
    for (let i = 0; i < table_list.value.length; i++) {
      if (!checkProductionDate(table_list.value[i])) {
        return
      }
      if (!checkExpiryDate(table_list.value[i])) {
        return
      }
    }
    let data = {
      inventoryOrder: JSON.parse(JSON.stringify(inventory_order_data.value)),
      inventoryOrderGoodsList: JSON.parse(JSON.stringify(table_list.value))
    }

    post("inventory/order/create", data).then((res: any) => {
      exit()
      isLoading.value = true
    })

  } catch (error) {
    ElMessage.warning('请填写完整必填项')
  } finally {
    isLoading.value = false
  }
}
const goodsSelectCallBack = (inventory: any) => {
  if (findIndexForTableList(inventory.goodId) != -1) {
    return
  }
  table_list.value.push(inventory);
  setTimeout(() => {
    getTotalPrice()
  }, 200)
}

const findIndexForTableList = (goodId: any) => {
  return table_list.value.findIndex((item: any) => item.goodId === goodId);
}
const removeItem = (row: any) => {
  const index = table_list.value.findIndex((item: any) => item.goodId === row.goodId);
  if (index !== -1) {
    table_list.value.splice(index, 1);
  }

}
const is_add = ref(false)
const editRef = ref<InstanceType<typeof Edit>>();
const supplier_list: any = ref([])
const getSupplierList = () => {
  const query = {
    turn: 1
  }
  post("inventory/supplier/list", {query: query}).then((res: any) => {
    supplier_list.value = res.list
    supplier_list.value = res.list
  })
}
const userInfo = ref({
  id: null,
  name: null,
  username: null,
})
const getUserInfo = () => {
  post("manager/user/verify", null).then((res: any) => {
    userInfo.value = res
  })
}
const removeTableRow = (row: any) => {
  //根据row.goodId删除table_list中的数据
  let index = findIndexForTableList(row.goodId);
  if (index != -1) {
    table_list.value.splice(index, 1);
  }
}
onMounted(() => {
  getSupplierList()
  getUserInfo()
})
</script>
<style scoped lang="scss">
.order_table {
  position: relative;
  width: 100%;
  //background-color: rgb(148.6, 212.3, 117.1);
  background-color: #fff;
  border-radius: 10px;
  box-sizing: border-box;
  padding: 10px;

  tr {
    height: 40px;
  }
}


.link {
  cursor: pointer;
  font-size: 12px;
  color: #2e7eb3;
}


.line {
  margin-right: 10px;

  .item {
    display: inline-block;
    width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    span {
      color: #999;
    }
  }

  .name {
    width: 300px;
  }

  .producer {
    width: 300px;
  }

  .unitPrice, .purchaseUnitPrice {
    width: 160px;
  }
}

.active {
  background-color: red;
}

.bottom {
  margin-top: 10px;
  position: absolute;
  right: 10px;
  bottom: 10px;
}

.error {
  background-color: #F00;
}
.edit-panel{
  margin-top: 24px;
}
.table_content{
  margin-top: 24px;
  background: #F9FAFC;
  .add_goods{
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 800;
    font-size: 18px;
    color: #333333;
    font-style: normal;
    .search{
      display: flex;
      align-items: center;
    }
  }
}
</style>