<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" label-width="90">
      <el-row>
        <el-col :span="6">
          <el-form-item label="项目号" prop="xmNo">
            <el-input v-model="queryParams.xmNo" placeholder="请输入项目号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="订单编号" prop="sapNo">
            <el-input v-model="queryParams.sapNo" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单据号" prop="billNo">
            <el-input v-model="queryParams.billNo" placeholder="请输入单据号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="库存状态" prop="isChuku">
            <el-select v-model="queryParams.isChuku" placeholder="请选择" clearable>
              <el-option v-for="dict in storeStatusList" :key="dict.id" :label="dict.statusName" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="物料号" prop="wlNo">
            <el-input v-model="queryParams.wlNo" placeholder="请输入物料号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目描述" prop="xmMs">
            <el-input v-model="queryParams.xmMs" placeholder="请输入项目描述" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="存放位置" prop="pcode">
            <el-input v-model="queryParams.pcode" placeholder="请输入存放位置" clearable @keyup.enter="handleQuery" />

          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入库类型" prop="operationTypeRK">
            <el-select v-model="operationTypeRK" placeholder="请选择入库类型" clearable
              @change="changeOperationType($event, 'operationTypeRK')">
              <el-option v-for="dict in storeTypeList" :key="dict.id" :label="dict.typeName" :value="dict.typeCode" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="所属仓库" prop="warehouseCode">
            <el-cascader v-model="warehouseCode" :options="warehouseOptions" placeholder="请选择所属仓库" style="width: 100%;"
              :props="{ children: 'children', label: 'warehouseName', value: 'warehouseCode' }" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物料描述" prop="wlMs">
            <el-input v-model="queryParams.wlMs" placeholder="请输入物料描述" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商名称" prop="gysMc">
            <el-input v-model="queryParams.gysMc" placeholder="请输入供应商名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出库类型" prop="operationTypeCK">
            <el-select v-model="operationTypeCK" placeholder="请选择出库类型"
              @change="changeOperationType($event, 'operationTypeCK')" clearable>
              <el-option v-for="dict in ckTypeList" :key="dict.id" :label="dict.typeName" :value="dict.typeCode" />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="操作时间" prop="optionTime">
            <el-date-picker v-model="optionTime" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
              format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="searchBtn">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Download" @click="handleExport"
          v-hasPermi="['wisdom:stock:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stockList" show-overflow-tooltip border
      :row-class-name="tableBillRowClassName" 
      ref="infoTableRef" 
      highlight-current-row 
      show-summary
      :summary-method="getSummaries"
      @row-click="(row) => tableInfoRowClick(row, infoTableRef)">
      <el-table-column label="序号" align="center" type="index" width="70" />
      <el-table-column label="操作类型" align="center" prop="bizType" width="100">
        <template #default="scope">
          <dict-tag :options="dictTagData()" :value="scope.row.bizType" />
        </template>
      </el-table-column>
      <el-table-column label="详细类型" align="center" prop="operationTypeName" width="150" />
      <el-table-column label="单据号" align="center" prop="billNo" width="180" />
      <el-table-column label="物料号" align="center" prop="wlNo" width="100" />
      <el-table-column label="物料描述" align="center" prop="wlMs" width="150" />
      <el-table-column label="单位" align="center" prop="dw" />
      <el-table-column label="合同单价" align="center" prop="htDj" />
      <el-table-column label="总计" align="center" prop="totalAmount" />
      <el-table-column label="数量" align="center" prop="realQty" width="120" />
      <el-table-column label="项目号" align="center" prop="xmNo" width="150" />
      <el-table-column label="项目描述" align="center" prop="xmMs" width="150" />
      <el-table-column label="库位码" align="center" prop="pcode" width="120" />
      <el-table-column label="所属大库" align="center" prop="parentWarehouseName" width="120" />
      <el-table-column label="所属小库" align="center" prop="warehouseName" width="120" />
      <el-table-column label="订单编号" align="center" prop="sapNo" width="150" />
      <el-table-column label="供应商名称" align="center" prop="gysMc" width="150" />
      <el-table-column label="理货员" align="center" prop="operatorName" width="150" />
      <el-table-column label="操作时间" align="center" prop="operationTime" width="200" />
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 图片预览 -->
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup name="Record">
import { listStock, getTotal } from "@/api/wisdom/record";
import { listOuttype } from "@/api/information/outtype";  //出库类型
import { warehouseAll } from "@/api/information/warehouseinfo";    //所属仓库
import { materialtypeDict } from "@/api/information/materialtype";    //物资类型
import { warehousingDict } from "@/api/information/warehousingtype";  //入库类型

import { parseTime } from '@/utils/manage';


const { proxy } = getCurrentInstance();


const total = ref(0);
const loading = ref(true);
const showSearch = ref(true);

const dialogVisible = ref(false);
const dialogImageUrl = ref('');

const optionTime = ref([]);

const storeStatusList = ref([
  { id: '0', statusName: "已入库" },
  { id: '1', statusName: "已出库" }
])//库存状态
// 0入库，1出库，2借料出库，3还料入库
const isChukuList = ref([
  { value: 0, label: "已入库", elTagType: "success", elTagClass: null },
  { value: 1, label: "已出库", elTagType: "warning", elTagClass: null },
  { value: 2, label: "借料出库", elTagType: "danger", elTagClass: null },
  { value: 3, label: "已归还", elTagType: "primary", elTagClass: null },
])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    billNo: null,
    isChuku: null,
    startTime: null,
    endTime: null,
    xmNo: null,
    sapNo: null,
    xmMs: "",
    wlNo: "",
    gysNo: "",
    pcode: "",
    gysMc: "",
    cangku: "",
    wlMs: "",
    ids: [],
  },
});

const { queryParams } = toRefs(data);

//出库类型入库类型改变
const operationTypeRK = ref([])	//入库类型
const operationTypeCK = ref([])	//出库类型
function changeOperationType(val, name) {
  if (name == 'operationTypeRK') {
    operationTypeRK.value = val
    operationTypeCK.value = ''
  } else if (name == 'operationTypeCK') {
    operationTypeCK.value = val
    operationTypeRK.value = ''
  }
}

//查询库存单据主列表 
const stockList = ref([]);
function getList() {
  loading.value = true;
  listStock(queryParams.value).then(response => {
    stockList.value = response.rows
    total.value = response.total;
    loading.value = false;
  });
}

//获取所属仓库下拉
const warehouseOptions = ref([]);  //仓库下拉数据
const warehouseCode = ref([]);  //所属仓库下拉数据
function warehouseFun() {
  //所属仓库下拉数据
  // warehouseDict().then(response=>{
  //   warehouseList.value = response.data
  // })
  warehouseAll().then(response => {
    warehouseOptions.value = response.data
  })

}

//获取物资类型下拉
const wzTypeList = ref([]);     //物资类型下拉数据
function materialFun() {
  //获取物资类型下拉数据
  materialtypeDict().then(response => {
    wzTypeList.value = response.data
  })
}

//获取出入库类型下拉
const ckTypeList = ref([]);     //出库类型下拉数据
const storeTypeList = ref([]);  //入库类型下拉数据
function rklxList() {
  //获取入库类型下拉数据
  warehousingDict().then(response => {
    storeTypeList.value = response.data
  })
  //获取出库类型下拉数据
  listOuttype({ pageNum: 1, pageSize: 50 }).then(response => {
    ckTypeList.value = response.rows
  })
}

//导出按钮操作 
function handleExport() {
  // wisdom/stock/export
  let obj = JSON.parse(JSON.stringify(queryParams.value))
  delete obj.pageNum
  delete obj.pageSize
  proxy.download('wisdom/record/export', {
    ...obj
  }, `出入库记录_${parseTime(new Date().getTime(), '{y}年{m}月{d}日 {h}_{i}_{s}')}.xlsx`)
}

//搜索按钮操作 
function handleQuery() {
  //所属仓库
  console.log(warehouseCode.value, optionTime, '====');
  if (warehouseCode.value) {
    queryParams.value.cangku = warehouseCode.value[1]
  }
  //详细类型
  if (operationTypeCK.value?.length > 0 || operationTypeRK.value?.length > 0) {
    queryParams.value.operationType = operationTypeRK.value || operationTypeCK.value
  }
  //操作时间
  if (optionTime.value && optionTime.value.length > 0) {
    queryParams.value.startDate = optionTime.value[0]
    queryParams.value.endDate = optionTime.value[1]
  } else {
    queryParams.value.startDate = ""
    queryParams.value.endDate = ""
  }
  queryParams.value.pageNum = 1;
  getList();
  getSumInfo()
}

// 重置按钮操作 
function resetQuery() {
  proxy.resetForm("queryRef");
  optionTime.value = []
  operationTypeCK.value = ''
  operationTypeRK.value = ''
  warehouseCode.value = ''
  queryParams.value.operationType = ''
  queryParams.value.cangku = ''
  handleQuery();
}

//数据列表
getList();
//所属仓库
warehouseFun()
//物资类型
materialFun()
//出、入库类型下拉数据
rklxList()

const infoTableRef = ref(null);

// 显示预出库的状态
const tableBillRowClassName = ({ row, rowIndex }) => {
  if (row.execStatus == 0) {
    return 'success-row'
  }
  return ''
}

const dictTagData = () => {
  return isChukuList.value.map(item => ({
    ...item,
    value: String(item.value)
  }));
}

function getSummaries(param) {
  const { columns, data } = param;
  // console.log(columns)
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 1) { // 第一列不进行合计操作，通常是序列号或选择框等非数值列。
      sums[index] = '总计'; // 这里可以设置为其他文字或空字符串。
      return;
    } else if (index === 2) { // 第二列是金额列，进行求和操作。
      sums[index] = '总金额：' + totalMoney.value;
      //   }else if(index === 2){
      // 	sums[index] = totalMoney.value
    } else if (index === 3) {
      sums[index] = '共存于：' + pcodeCount.value + '个库位'
    } else if (index === 4) {
      sums[index] = '总数：' + sumQty.value
    }
  })
  return sums
}

// 获取总计
const totalMoney = ref(null)
const pcodeCount = ref(null)
const sumQty = ref(null)
function getSumInfo() {
  //统计信息
  let rkInfo = JSON.parse(JSON.stringify(queryParams.value))
  delete rkInfo.pageNum
  delete rkInfo.pageSize
  getTotal(rkInfo).then(response => {
  	totalMoney.value = response.data.totalAmount
    pcodeCount.value = response.data.locationCount
    sumQty.value = response.data.totalQuantity
  });
}
getSumInfo()
</script>

<style scoped>
:deep(.el-table .success-row) {
  background-color: #f8fdf5 !important;
}
.el-table {
  /* 核心：把 hover 背景色设为和默认行背景色一致 */
  --el-table-row-hover-bg-color: transparent;
  /* 或设为和表格背景色相同（比如白色），更通用 */
  /* --el-table-row-hover-bg-color: #ffffff; */
}

.searchBtn {
  display: flex;
  justify-content: flex-end;
}
</style>