<template>
  <Mask :width="1200" :is-show="isShow" @close="exit"
        title="新增" :height="760" :show-footer="true">
    <div class="add-panel" v-loading="isLoading" element-loading-text="正在保存......">
      <div class="top">
        <el-form :model="inventory_order_data" label-position="top" style="height: 100%" :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-select
                    v-model="inventory_order_data.managerUserId"
                    placeholder="选择采购人"
                    clearable
                    style="width: 240px"
                >
                  <el-option
                      v-for="item in managerUserList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                  />
                </el-select>
              </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="发票号" style="margin-bottom: 0">
                <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" style="margin-bottom: 0">
                <el-select style="width: 196px;margin-right: 10px" 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>
                <div class="default-btn"
                     style="
                     height: 32px;
                     width: 32px;
                     line-height: 32px;
                     border: 1px solid rgb(192, 196, 204);
                      background-color: #fff;"
                     @click="addSupplier">
                  <el-icon style="color: rgb(192, 196, 204)">
                    <Plus/>
                  </el-icon>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" :rules="formRules.purchaseDate" style="margin-bottom: 0">
                <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" style="height: 42px"></GoodsSearch>
            <div class="default-btn" @click="goodsSelectCallBack" style="margin-left: 24px">
              <span class="iconfont icon-RectangleCopy"></span>
              搜索
            </div>
          </div>
        </div>
        <div class="table" style="padding: 0 24px;">
          <el-table :data="table_list"
                    style="width: 100%;height: 100%;background: #F9FAFC;border: 1px solid #EAEAEC;border-bottom: none"
                    :header-cell-style="{ backgroundColor:'#F1F5FB'}">
            <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
                    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
                    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="150">
              <template #default="scope">
                <!--              <el-input-->
                <!--                  v-model="scope.row.traceabilityCode"-->
                <!--                  placeholder="商品追溯码"-->
                <!--                  style="width: 100px"-->
                <!--                  size="small"/>-->
                <TraceabilityCodeInput v-model="scope.row.traceabilityCodeList"></TraceabilityCodeInput>
              </template>

            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <!--              <el-button size="small" @click="openCheckoutDetail(scope.row)" type="danger" plain>溯源码</el-button>-->
                <span style="color: #ff0000" @click="removeTableRow(scope.row)">
                      <el-icon>
                <Delete/>
              </el-icon>
                  移除
                  </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="bottom">
        <div class="totalPrice">
          订单总金额：<span style="color: #FF282E;font-size: 12px">￥</span><span
            style="color: #FF282E">{{ inventory_order_data.totalPrice.toFixed(2) }}</span>
        </div>
        <div class="btn">
          <div class="default-btn" @click="exit">关闭</div>
          <div class="default-btn" @click="confirm" style="margin-left: 24px">确认</div>
        </div>
      </div>
    </template>
  </Mask>
  <AddSupplier ref="addSupplierRef" @close="getSupplierList"></AddSupplier>
  <!--  <Mask :is-show="is_add" :top="100">-->
  <!--    <Edit ref="editRef" @close="is_add = false;"/>-->
  <!--  </Mask>-->
<!--  <CheckoutDetail ref="checkoutDetailRef" @confirm="confirmTrace"></CheckoutDetail>-->
</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 AddSupplier from "@/components/inventory/supplier/AddSupplier.vue";
import GoodsSearch from "@/components/inventory/GoodsSearch.vue";
import CheckoutDetail from "@/components/inventory/CheckoutDetail.vue";
import TraceabilityCodeInput from "@/components/inventory/purchase/TraceabilityCodeInput.vue";
import {Plus, Delete} from "@element-plus/icons-vue";

const orderForm = ref()
const checkoutDetailRef = ref<any>(false);
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: "-",
  invoiceCode: "-",
  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 = () => {
  isShow.value = false
  initInventoryOrderData()
  table_list.value = []
  emit('close')
}
const initInventoryOrderData = () => {
  inventory_order_data.value = {
    code: null,
    purchaseDate: getFormattedDate(),
    userId: null,
    supplierId: null,
    remark: null,
    managerUserId: null,
    kindConut: 0,
    totalPrice: 0,
    shippingCode: "-",
    invoiceCode: "-",
    inventoryOrderGoodsList: []
  }
}
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;

    // 添加药品列表验证
    if (table_list.value.length === 0) {
      ElMessage.error('请至少添加一个采购药品')
      return
    }
    //生产批号
    for (let i = 0; i < table_list.value.length; i++) {
      if (!table_list.value[i].productionBatchCode) {
        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
      }
    }
    table_list.value.forEach((item: any) => {
      item.traceabilityCode = JSON.stringify(item.traceabilityCodeList)
    })
    let data = {
      inventoryOrder: JSON.parse(JSON.stringify(inventory_order_data.value)),
      inventoryOrderGoodsList: JSON.parse(JSON.stringify(table_list.value))
    }
    isLoading.value = true
    post("inventory/order/create", data).then((res: any) => {
      isLoading.value = false
      exit()
    })

  } 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 isShow = 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
  })
}
const userInfo = ref<any>({})
const getUserInfo = () => {
  post("manager/user/verify", null).then((res: any) => {
    userInfo.value = res
    inventory_order_data.value.managerUserId = res.id
  })
}
const removeTableRow = (row: any) => {
  //根据row.goodId删除table_list中的数据
  let index = findIndexForTableList(row.goodId);
  if (index != -1) {
    table_list.value.splice(index, 1);
  }
}
const init = (orderInfo: any,goodList: any) => {
  isShow.value = true
  getSupplierList()
  getManagerUserList()
  getUserInfo()

  if (orderInfo){
    inventory_order_data.value = orderInfo
  }
  if (goodList){
    table_list.value = goodList
  }
  getTotalPrice()

}
const managerUserList: any = ref([])
const getManagerUserList = () => {
  post("manager/user/list", {}).then((res: any) => {
    managerUserList.value = res
  })
}
const addSupplierRef = ref()
const addSupplier = () => {
  nextTick(() => {
    addSupplierRef.value?.addInit();
  })
}
defineExpose({init})
</script>
<style scoped lang="scss">
.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;
}

.add-panel {
  height: 602px;
  display: flex;
  flex-direction: column;

  .top {
    height: 204px;
    padding: 24px;
  }

  .table_content {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #F9FAFC;
    min-height: 0;

    .add_goods {
      height: 90px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 800;
      font-size: 18px;
      color: #333333;
      font-style: normal;
      padding: 0 24px;

      .search {
        display: flex;
        align-items: center;
        height: 42px;

      }
    }

    .table {
      flex: 1;
      min-height: 0;
      background: #F9FAFC;
    }
  }
}

.bottom {
  padding: 0 24px;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 400;
  font-size: 22px;
  color: #333333;
  font-style: normal;

  .btn {
    display: flex;
  }
}

.error {
  background-color: #F00;
}

</style>