<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" :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="发票号">
                <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: 130px;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>
                <el-button type="primary" @click="addSupplier">添加供应商</el-button>
              </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>
          </div>
        </div>
        <el-table :data="table_list" style="width: 100%;flex: 1">
          <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="150">
            <template #default="scope">
              <el-button size="small" @click="openCheckoutDetail(scope.row)" type="danger" plain>溯源码</el-button>
              <el-button size="small" @click="removeTableRow(scope.row)" type="danger" plain>移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </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">
          <el-button type="primary" @click="confirm">确认</el-button>
          <el-button type="primary" @click="exit">关闭</el-button>
        </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 {Search} from "@element-plus/icons-vue";
import TraceabilityCodeInput from "@/components/inventory/purchase/TraceabilityCodeInput.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 () => {
  console.log('table_list.value++++++++++++++',table_list.value)
  // 进行表单验证
  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) => {
      console.log(item.traceabilityCodeList)
      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) {
    console.log(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 = () => {
  isShow.value = true
  getSupplierList()
  getManagerUserList()
  getUserInfo()

}
const managerUserList: any = ref([])
const getManagerUserList = () => {
  post("manager/user/list", {
  }).then((res: any) => {
    managerUserList.value = res
  })
}
// 追溯码代码
const openCheckoutDetail = (row: any) => {
  let goodlist = []
  goodlist.push(row)
  nextTick(() => {
    checkoutDetailRef.value.init(goodlist);
  })
}
//追溯码页面回调
const confirmTrace = (data: any) => {
  let index = findIndexForTableList(data[0].goodId);
  table_list.value[index] = data[0]
  checkoutDetailRef.value.close();
  // table_list.value.forEach((item: any) => {
  //   if(item.goodId === data[0].goodId){
  //     item = data[0]
  //     table_list.value.
  //   }
  // })
}
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;
  padding: 24px 24px 0;
  display: flex;
  flex-direction: column;

  .top {
    height: 180px;
  }

  .table_content {
    flex: 1;
    margin-top: 24px;
    display: flex;
    flex-direction: column;

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

      .search {
        width: 50%;
      }
    }
  }
}

.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;
}

.error {
  background-color: #F00;
}

</style>