<template>
  <van-nav-bar :title="$t('inventoryCount.name')" left-text="" left-arrow @click-left="onClickLeft" @click-right="onClickRight">
    <!-- <template #right> {{ $t("common.add") }} </template> -->
  </van-nav-bar>
  <div style="display:flex">
    <van-dropdown-menu>
      <van-dropdown-item v-model="req.warehouseId" :options="warehouseList" @change="changeWarehouseId" />
    </van-dropdown-menu>
    <van-search v-model="req.keyword" style="flex:1" :placeholder="$t('common.pleaseEnterKeywords')" @search="onRefresh" />
  </div>

  <van-tabs v-model:active="active" @change="handleChangeTab">
    <van-tab :title="'物资盘点'" name="first"></van-tab>
    <van-tab :title="'盘点记录'" name="second"></van-tab>
    <van-tab :title="'历史记录'" name="three"></van-tab>
  </van-tabs>
  <div style="padding:0 16px" v-if="active!='three'">
    <table class="table">
      <thead>
        <tr>
          <th style="width:70%;text-align: left;">物品信息</th>
          <th style="width:30%">本次盘点累计</th>
        </tr>
      </thead>
    </table>
  </div>
  <div style="overflow-y:auto"
       :style="{height:active!='three'? !deviceStore.isIosSysteme?'calc(100vh - 258px)':'calc(100vh - 278px)':!deviceStore.isIosSysteme?'calc(100vh - 194px)':'calc(100vh - 214px)'}">
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <div class="list">
        <van-list v-model:loading="loading" :finished="finished" :finished-text="$t('common.noMore')" @load="getList" style="margin-bottom: 60px">
          <commonList :data="listData" @onClick="toDtl" :config="listConfig" v-if="active=='three'">
            <template #inventoryResult="{ row }">
              <div>
                <span v-if="row.result == 0">正常</span>
                <span style="color: red" v-else>异常</span>
              </div>
            </template>
          </commonList>
          <div v-else style="margin-bottom:10px">
            <div v-for="(row,index) in listData" :key="row.id" class="main-box">
              <div style="display:flex;align-items:center">
                <div style="width:70%">
                  <div>
                    仓库名称：{{row.warehouseName}}
                  </div>
                  <div style="margin-top:3px">
                    物品编码：{{row.productCustomCode}}
                  </div>
                  <div style="margin-top:3px">
                    物品名称：{{row.productName}}
                  </div>
                  <div style="margin-top:3px">
                    物品规格：{{row.productSpec}}
                  </div>
                  <div style="margin-top:3px">
                    可用库存：{{row.quantity}}
                  </div>
                </div>
                <div style="width:30%;color:red;text-align:center">
                  {{row.checkQuantity}}
                </div>
              </div>

              <!-- style="border-bottom:1px solid #f1f1f1;" -->
              <div>
                <div style="padding:0 6px">
                  <div style="text-align:center;color:#b7b0b0;margin-bottom:10px" @click="row.isArrow =!row.isArrow">
                    <span>在线盘点登记</span>
                    <van-icon :name="!row.isArrow ?'arrow-down':'arrow-up'" style="margin-left:5px" />
                  </div>
                  <div v-show="row.isArrow" style="margin-top:5px;margin-bottom:10px">
                    <div style="display:flex;margin-bottom:8px ;align-items:center">
                      <van-field v-model="row.addQuantity" type="digit" label="" class="aa" placeholder="请输入临时盘点数量"
                                 style="background-color:#f7f7f7;" />
                      <van-button type="success" size="small" style="width:60px;margin-left:10px" @click="handleStag(row,index)">暂存</van-button>
                    </div>
                    <div>
                      <table class="tableTwo">
                        <thead>
                          <tr>
                            <th>时间</th>
                            <th style="width:70px">盘点数量</th>
                            <th style="width:50px">操作</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr v-for="(sonRow,sonIndex) in row.stockCheckRegisterList" :key="sonIndex">
                            <td>
                              {{sonRow.createTime}}
                            </td>
                            <td>
                              {{sonRow.checkQuantity}}
                            </td>
                            <td>
                              <span style="color:#409EFF;cursor:pointer" v-if="sonRow.status !=2" @click="handleDelete(row,index,sonRow)">删除</span>
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </van-list>
      </div>
    </van-pull-refresh>
  </div>
  <div style="padding:0 16px;margin-top:5px;" v-if="active!='three'">
    <van-button type="primary" round block @click="onSubmit()" style="height:30px">提交</van-button>
  </div>

</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import commonList from "@/components/common-list.vue";
import { showSuccessToast, showFailToast } from "vant";
import { parseTime } from "@/utils/ruoyi";
import useDeviceStore from "@/store/device";
const deviceStore = useDeviceStore();
const proxy = getCurrentInstance().proxy;
const onClickLeft = () => proxy.$router.push("/main/working");
const req = ref({
  pageNum: 1,
  keyword: "",
  warehouseId: "",
  isCheckRegister: "",
});
const warehouseId = ref("");
const warehouseList = ref([{ text: "全部仓库", value: "" }]);
const active = ref("first");
const finished = ref(false);
const onRefresh = () => {
  req.value.pageNum = 1;
  finished.value = false;
  getList("refresh");
};
const loading = ref(false);
const listData = ref([]);
const getList = (type) => {
  loading.value = true;
  proxy
    .post(requestUrl.value, req.value)
    .then((res) => {
      if (active.value != "three") {
        res.data.rows.map((x) => {
          x.addQuantity = "";
          if (x.stockCheckRegisterList && x.stockCheckRegisterList.length > 0) {
            x.checkQuantity = x.stockCheckRegisterList.reduce(
              (total, x) => (total += Number(x.checkQuantity)),
              0
            );
          } else {
            x.checkQuantity = 0;
          }
        });
      }

      listData.value =
        type === "refresh"
          ? res.data.rows
          : listData.value.concat(res.data.rows);
      if (req.value.pageNum * 10 >= res.data.total) {
        finished.value = true;
      }
      req.value.pageNum++;
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};
const toDtl = (row) => {
  proxy.$router.push({
    path: "/main/inventoryCountAdd",
    query: {
      id: row.id,
    },
  });
};
const onClickRight = () => {
  proxy.$router.push({
    path: "/main/inventoryCountAdd",
    query: {},
  });
};
const listConfig = ref([
  {
    label: "盘点单号",
    prop: "code",
  },
  {
    label: "仓库名称",
    prop: "warehouseName",
  },
  {
    label: "盘点时间",
    prop: "createTime",
  },
  {
    label: "盘点人",
    prop: "userName",
  },
  {
    label: "盘点物品数",
    prop: "totalNum",
  },
  {
    label: "正常物品数",
    prop: "normalNum",
  },
  {
    label: "异常物品数",
    prop: "anomalyNum",
  },
  {
    type: "slot",
    label: "盘点结论",
    slotName: "inventoryResult",
  },
]);
const requestUrl = ref("/stockCheck/stockProductPage");
const handleChangeTab = (val) => {
  if (val == "first") {
    requestUrl.value = "/stockCheck/stockProductPage";
    req.value.isCheckRegister = "";
  } else if (val == "second") {
    requestUrl.value = "/stockCheck/stockProductPage";
    req.value.isCheckRegister = "1";
  } else {
    requestUrl.value = "/stockCheck/page";
    req.value.isCheckRegister = "";
  }
  req.value.pageNum = 1;
  listData.value = [];
  getList();
};

const changeWarehouseId = (val) => {
  req.value = {
    pageNum: 1,
    keyword: "",
    warehouseId: val,
    isCheckRegister: "",
  };
  listData.value = [];
  getList();
};

const getDict = () => {
  proxy.post("/warehouse/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    warehouseList.value = [
      ...warehouseList.value,
      ...res.data.rows.map((x) => ({ text: x.name, value: x.id })),
    ];
  });
};
getDict();

const getSonList = (query, index) => {
  proxy.post("/stockCheckRegister/list", query).then((res) => {
    listData.value[index].stockCheckRegisterList = res.data;
    listData.value[index].checkQuantity = res.data
      .filter((x) => x.status != 2)
      .reduce((total, y) => (total += Number(y.checkQuantity)), 0);
  });
};

const handleStag = (row, index) => {
  if (Number(row.addQuantity) > 0) {
    let obj = {
      stockId: row.id,
      warehouseId: row.warehouseId,
      productId: row.productId,
      createTime: parseTime(new Date()),
      // quantity: row.quantity,
      checkQuantity: Number(row.addQuantity),
      status: 0,
    };

    proxy.post("/stockCheckRegister/add", obj).then((res) => {
      row.addQuantity = "";
      let query = {
        stockId: row.id,
        warehouseId: row.warehouseId,
        productId: row.productId,
      };
      getSonList(query, index);
      return showSuccessToast("暂存成功");
    });
  } else {
    return showFailToast("数量必须大于0");
  }
};

const handleDelete = (row, index, sonRow) => {
  let query = {
    stockId: row.id,
    warehouseId: row.warehouseId,
    productId: row.productId,
  };
  proxy.post("/stockCheckRegister/delete", { id: sonRow.id }).then((res) => {
    getSonList(query, index);
    return showSuccessToast("删除成功");
  });
};

const onSubmit = () => {
  proxy.post("/stockCheck/submitAll").then(
    (res) => {
      showSuccessToast("操作成功");
      onRefresh();
    },
    (err) => {
      return showFailToast(err.message);
    }
  );
};
</script>

<style lang="scss" scoped>
* {
  font-size: 11px;
}
.list {
  min-height: 100%;
}
.main-box {
  padding: 12px 16px 0 16px;
  background: #fff;
  border-bottom: 1px solid #f1f1f1;
}
.table {
  border-collapse: collapse;
  border-spacing: 0;
  width: 100%;
  border-color: #ebeef5;
  color: #606266;
  thead tr th {
    padding: 6px 2px;
    text-align: center;
    color: #000;
  }
  td {
    text-align: center;
    padding: 6px 2px;
    // height: 40px;
    height: 30px;
  }
}
.tableTwo {
  border-collapse: collapse;
  border-spacing: 0;
  width: 100%;
  background-color: #f7f7f7;
  color: #606266;
  thead tr th {
    text-align: center;
    padding: 6px 2px;
    height: 20px;
    color: #000;
  }
  td {
    text-align: center;
    padding: 6px 2px;
    height: 30px;
  }
}

:deep(.van-dropdown-menu__bar) {
  box-shadow: none !important;
  height: 54px !important;
}

:deep(.van-field.aa) {
  padding: 5px 10px;
}
</style>
