<template>
  <div class="container-wrapper">
    <div class="top">
      <div class="search">
        <div class="left">
          <el-form :inline="true" :model="searchModel">
            <el-form-item>
              <el-date-picker
                  v-model="selectedDate"
                  type="daterange"
                  range-separator="-"
                  @change="handleDateChange"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
              />
            </el-form-item>
            <el-form-item>
              <el-input
                  v-model="searchModel.code"
                  placeholder="单号"
                  :prefix-icon="Search"
              >
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-input
                  v-model="searchModel.goodsName"
                  placeholder="商品名称"
              >
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-select
                  v-model="searchModel.supplierIds"
                  placeholder="供应商"
                  multiple
              >
                <el-option
                    v-for="item in supplier_list"
                    :key="item"
                    :label="item.name"
                    :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                  v-model="searchModel.managerUserIds"
                  placeholder="采购人"
                  multiple
              >
                <el-option
                    v-for="item in managerUserList"
                    :key="item"
                    :label="item.name"
                    :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="right">
          <div class="default-btn" @click="resetSearch">
            <span class="iconfont icon-RectangleCopy1"></span>
            重置
          </div>
          <div class="default-btn" @click="init">
            <span class="iconfont icon-RectangleCopy"></span>
            搜索
          </div>
        </div>
      </div>
      <div class="addBtn">
        <span class="default-btn" @click="openAdd">新增采购</span>
        <span class="default-btn" @click="openUpload">一键导入</span>
      </div>
    </div>
    <div class="content_list">
      <el-table :data="tableData" style="width: 100%;height: 100%" @row-click="open_edit"
                :header-cell-style="{ backgroundColor: '#F1F5FB' }">
        <el-table-column fixed label="采购单号" show-overflow-tooltip>
          <template #default="scope">
            <div class="link">{{ scope.row.code }}</div>
          </template>
        </el-table-column>
        <el-table-column label="货单号" prop="shippingCode" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="品种" prop="kindCount" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="入库金额" show-overflow-tooltip>
          <template #default="scope">
            ￥{{ scope.row.totalPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="采购人" prop="managerUserName" show-overflow-tooltip></el-table-column>
        <el-table-column label="供应商" prop="supplierName" show-overflow-tooltip></el-table-column>
        <el-table-column prop="purchaseDate" label="采购时间" show-overflow-tooltip>
          <template #default="scope">
            {{ formatDate(scope.row.purchaseDate) }}
          </template>
        </el-table-column>
        <!--          <el-table-column prop="createDatetime" label="入库时间">-->
        <!--            <template #default="scope">-->
        <!--              {{ formatDate(scope.row.purchaseDate) }}-->
        <!--            </template>-->
        <!--          </el-table-column>-->
        <el-table-column label="备注" prop="remark" show-overflow-tooltip>
        </el-table-column>
      </el-table>
    </div>
    <div class="bottom">
      <div class="page_btn_list">
        <el-pagination
            background
            layout="prev, pager, next"
            :page-size="pageSize"
            :current-page="page"
            :total="total"
            @current-change="changePage"
        />
      </div>
    </div>
    <AddOrder ref="addOrderRef" @close="closeAddOrder"/>
    <EditOrder ref="editOrderRef" @close="closeEditOrder" @updateOrderDetail="init"/>
    <UpLoad v-model="show" @initAddOrderData=initAddOrderData></UpLoad>
  </div>
</template>

<script lang="ts" setup>
import {nextTick, onMounted, ref, watch} from "vue";
import {post} from "@/utils/request.ts";
import {useRoute} from "vue-router";
import AddOrder from "@/components/inventory/purchase/AddOrder.vue";
import Mask from "@/components/common/Mask.vue";
import EditOrder from "@/components/inventory/purchase/EditOrder.vue";
import {Plus, Refresh, Search, SemiSelect} from "@element-plus/icons-vue";
import {formatDateArray, getEndOfDay} from "@/utils/dateUtils.ts";
import UpLoad from "@/components/inventory/purchase/Upload.vue";

let tableData = ref([])
let is_edit = ref(false)
const route = useRoute()
let open_code = ref(null)
onMounted(() => {
  init()
  getSupplierList()
  getManagerUserList()
})
const addOrderRef = ref<any>('')
const openAdd = () => {
  nextTick(() => {
    addOrderRef.value.init(null)
  })
}
const editOrderRef = ref<any>('')
let open_edit = (row: any) => {
  nextTick(() => {
    editOrderRef.value?.init(row.code)
  })
}


let init = () => {
  const query = {
    page: page.value,
    pageSize: 20,
    ...searchModel.value
  }
  post("inventory/order/list", {query: query}).then((res: any) => {
    tableData.value = res.list
    total.value = res.total_count
  })

}
const closeAddOrder = () => {
  init()
}
const closeEditOrder = () => {
  open_code.value = null
  is_edit.value = false
  init()
}
//分页
let pageSize = ref(20)
let total = ref(0)
let page = ref(1)
let changePage = (value: number) => {
  page.value = value
  init()
}
// 转成YYYY-MM-DD格式
const formatDate = (isoStr: any) => {
  const date = new Date(isoStr);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}

const selectedDate = ref<any>([])
const handleDateChange = (date: any[]) => {
  selectedDate.value = formatDateArray(date)
  if (selectedDate.value[0] == selectedDate.value[1]) {
    selectedDate.value[1] = getEndOfDay(selectedDate.value[1]); // 输出今天 23:59
  }
  searchModel.value.beginTime = selectedDate.value[0]
  searchModel.value.endTime = selectedDate.value[1]
}
const supplier_list = ref<any>([])
const getSupplierList = () => {
  const query = {
    turn: 1
  }
  post("inventory/supplier/list", {query: query}).then((res: any) => {
    supplier_list.value = res.list
  })
}
const managerUserList: any = ref([])
const getManagerUserList = () => {
  post("manager/user/list", {}).then((res: any) => {
    managerUserList.value = res
  })
}
const searchModel = ref({
  code: "",
  managerUserIds: [],
  supplierIds: [],
  beginTime: null,
  endTime: null,
  goodsName: null
})
const resetSearch = () => {
  searchModel.value = {
    code: "",
    managerUserIds: [],
    supplierIds: [],
    beginTime: null,
    endTime: null,
    goodsName: null
  }
  init()
}
const show = ref(false)
const openUpload = () => {
  show.value = true
}

const initAddOrderData = (initData: any) => {
  const data = {
    invoiceCode: initData.tag.invoice_code,
    shippingCode: initData.tag.shipping_code,
    remark: initData.tag.remark,
    purchaseDate: initData.tag.purchase_date,
  }
  let goodsList = []
  for (let i = 0; i < initData.list.length; i++) {
    let item = initData.list[i]
    let goodsInfo = {
      productionBatchCode: item.info.production_batch_code,
      wholeNumber: item.info.whole_number,
      productionDate: item.info.production_date,
      expiryDate: item.info.expiry_date,
      purchaseUnitPrice: item.info.purchase_unit_price,
      goodId: item.id,
      name: item.goods.name,
      packagingUnit: item.goods.packagingUnit,
      unitPrice: item.goods.unitPrice,
    }
    goodsList.push(goodsInfo)
  }


  nextTick(() => {
    addOrderRef.value?.init(data, goodsList)
  })
}
</script>
<style scoped lang="scss">
@use "@/assets/scss/base.scss";

.container-wrapper {
  box-sizing: border-box;
  padding: 24px 24px 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
  border-radius: 8px;

  .top {
    background: #fff;
    display: flex;
    flex-direction: column;
    margin-bottom: 24px;

    .search {
      display: flex;
      justify-content: space-between;

      .left {
        flex: 1;
        display: flex;
        justify-content: space-between;
        margin-right: 24px;

        .el-form-item {
          margin-right: 5px;
        }
      }

      .right {
        display: flex;
      }

    }

    .addBtn {
      span {
        &:first-child {
          margin-left: 0;
        }
      }
    }
  }

  .content_list {
    width: 100%;
    flex: 1;
    overflow: hidden;
  }

  .bottom {
    width: 100%;
    height: 60px;
    background-color: #FFF;
    box-sizing: border-box;
    padding: 10px;
    position: relative;
    border-top: 1px solid #EEE;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}

.full_screen {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 100;
  background-color: rgba(0, 0, 0, 0.5);
  display: block;

  .content {
    width: 1200px;
    height: 800px;
    background-color: #FFF;
    border-radius: 10px;
    box-sizing: border-box;
    margin: 0 auto;
    margin-top: 100px;
    overflow: hidden;
    padding: 20px;
  }
}

.link {
  color: #409EFF;
  cursor: pointer;
}

.content {
  display: flex;
  flex-direction: column;
  height: 100%;

  .content_list {
    flex: 1;
  }

  .bottom {
    width: 100%;
    height: 60px;
    background-color: #FFF;
    box-sizing: border-box;
    padding: 10px;
    position: relative;
    border-bottom: 1px solid #EEE;

    .page_btn_list {
      position: absolute;
      left: 0;
      top: 10px;
    }
  }

}

:deep(.el-input__wrapper) {
  height: 42px;
  width: 200px;
}

:deep(.el-range-editor.el-input__wrapper) {
  height: 42px;
}

:deep(.el-select__wrapper) {
  height: 42px;
  width: 100px;
}
</style>