<template>
  <div class="form">
    <van-nav-bar :title="$t('waitInbound.name')" :left-text="$t('common.back')" left-arrow @click-left="onClickLeft" @click-right="onClickRight">
      <template #right>
        <van-button plain type="primary" size="small">多货登记</van-button> </template>
    </van-nav-bar>
    <van-tabs v-model:active="active">
      <van-tab title="入库明细" :name="0" />
      <van-tab title="基本信息" :name="1" />
    </van-tabs>

    <van-form @submit="onSubmit" @failed="onFailed" label-align="top" style="margin-top: 20px">
      <van-cell-group inset v-show="active==1">
        <van-field v-model="formData.businessTypeName" readonly :label="$t('waitInbound.dataSource')" />
        <van-field v-model="formData.businessCode" readonly label="入库单号" />
        <van-field v-model="formData.code" readonly label="物流信息" />
        <van-field v-model="formData.warehouseName" is-link label="仓库名称" readonly :placeholder="'请选择仓库名称'" @click="typeModal = true"
                   :rules="[{ required: true, message: '请选择仓库名称'}]" required />
        <van-field v-model="formData.arrivalRemark" label="到货物流备注" type="textarea" />
        <van-popup v-model:show="typeModal" round position="bottom">
          <van-picker :columns="columns" @cancel="typeModal = false" @confirm="onConfirm" />
        </van-popup>
      </van-cell-group>
      <!-- overflow-x: auto;width:calc(100% - 20px) -->
      <van-cell-group inset v-show="active==0" style="padding:10px;">
        <van-search v-model="keyword" :placeholder="$t('common.pleaseEnterKeywords')" @search="onSearch" style="padding:0px" />
        <table class="table">
          <thead>
            <tr>
              <th style="width:46%;text-align:left;">物品信息</th>
              <th style="width:13%">采购<div style="width:0px;height:0px"></div>数量
              </th>
              <th style="width:13%">本次<div style="width:0px;height:0px"></div>发货
              </th>
              <th style="width:15%">已入库</th>
              <th style="width:13%">累计<div style="width:0px;height:0px"></div>清点
              </th>
            </tr>
          </thead>
        </table>
        <div style="height:calc(100vh - 280px);overflow-y:auto"
             :style="{height:!deviceStore.isIosSysteme?'calc(100vh - 280px)':'calc(100vh - 300px)'}">
          <table class="table" v-if="!keyword">
            <tbody>
              <template v-for="(row,index) in formData.stockWaitDetailsList" :key="row.id">
                <div style="height:10px">
                </div>
                <tr>
                  <td style="text-align:left;width:46%">
                    <div>编码：{{row.productCustomCode}}</div>
                    <div style="margin-top:3px">名称：{{row.productName}}</div>
                    <div style="margin-top:3px">规格：{{row.productSpec}}</div>
                  </td>
                  <td style="width:13%">
                    <div>{{row.purchaseQuantity}}</div>
                  </td>
                  <td style="width:13%">
                    <div>{{row.arrivalQuantity}}</div>
                  </td>
                  <td style="width:15%">
                    <div>{{row.receiptQuantity}}</div>
                  </td>
                  <td style="width:13%">
                    <div style="color:red">{{row.quantity}}</div>
                  </td>
                </tr>
                <tr style="border-bottom:1px solid #f1f1f1;">
                  <td colspan="5" 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="" 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:70px">提交状态</th>
                              <th style="width:50px">操作</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr v-for="(sonRow,sonIndex) in row.stockWaitDetailsCheckList" :key="sonIndex">
                              <td>
                                {{sonRow.createTime}}
                              </td>
                              <td>
                                {{sonRow.quantity}}
                              </td>
                              <td>
                                {{sonRow.status==2?'已提交':'未提交'}}
                              </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>
                  </td>
                </tr>
              </template>
            </tbody>
          </table>

          <table class="table" v-else>
            <tbody>
              <template v-for="(row,index) in formData.stockWaitDetailsListCopy" :key="row.id">
                <div style="height:10px">
                </div>
                <tr>
                  <td style="text-align:left;width:31%">
                    <div>编码：{{row.productCustomCode}}</div>
                    <div>名称：{{row.productName}}</div>
                    <div>规格：{{row.productSpec}}</div>
                  </td>
                  <td style="width:18%">
                    <div>{{row.purchaseQuantity}}</div>
                  </td>
                  <td style="width:18%">
                    <div>{{row.arrivalQuantity}}</div>
                  </td>
                  <td style="width:15%">
                    <div>{{row.receiptQuantity}}</div>
                  </td>
                  <td style="width:18%">
                    <div style="color:red">{{row.quantity}}</div>
                  </td>
                </tr>
                <tr style="border-bottom:1px solid #f1f1f1;">
                  <td colspan="5" 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="" 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:70px">提交状态</th>
                              <th style="width:50px">操作</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr v-for="(sonRow,sonIndex) in row.stockWaitDetailsCheckList" :key="sonIndex">
                              <td>
                                {{sonRow.createTime}}
                              </td>
                              <td>
                                {{sonRow.quantity}}
                              </td>
                              <td>
                                {{sonRow.status==2?'已提交':'未提交'}}
                              </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>
                  </td>
                </tr>
              </template>
            </tbody>
          </table>
        </div>
      </van-cell-group>

      <div style="margin-top: 5px">
        <van-button round block type="primary" native-type="submit" style="height:30px">
          {{$t('common.submit')}}
        </van-button>
      </div>

    </van-form>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from "vue";
import { showSuccessToast, showFailToast } from "vant";
import { useRoute } from "vue-router";
import { parseTime } from "@/utils/ruoyi";
import useDeviceStore from "@/store/device";
const deviceStore = useDeviceStore();
const proxy = getCurrentInstance().proxy;
const active = ref(0);
const route = useRoute();
const typeModal = ref(false);
const formData = ref({});

const getDict = () => {
  proxy.post("/warehouse/page", { pageNum: 1, pageSize: 9999 }).then((res) => {
    columns.value = res.data.rows.map((item) => {
      return {
        text: item.name,
        value: item.id,
      };
    });
  });
};

const getDetails = (id) => {
  proxy.post("/stockWait/detail", { id }).then((res) => {
    res.data.inQuantity = res.data.quantity;
    formData.value = res.data;
  });
};

const columns = ref([]);

const onConfirm = ({ selectedOptions }) => {
  formData.value.warehouseId = selectedOptions[0].value;
  formData.value.warehouseName = selectedOptions[0].text;
  typeModal.value = false;
};

const onClickLeft = () => history.back();

const onSubmit = () => {
  const list = formData.value.stockWaitDetailsList;
  const total = list.reduce((total, x) => (total += Number(x.quantity)), 0);
  if (!(total > 0)) {
    return showFailToast("清点累计不能为0");
  }
  proxy.post("/stockWait/addByWdly", formData.value).then(
    (res) => {
      setTimeout(() => {
        showSuccessToast(proxy.$t("manualInbound.warehousingSuccess"));
        proxy.$router.push("/main/waitInbound");
      }, 500);
    },
    (err) => {
      return showFailToast(err.message);
    }
  );
};

const onFailed = () => {
  return showFailToast("数据未填完整");
};
const businessType = ref([
  { label: "线边回仓", value: "1" },
  { label: "完工入库", value: "2" },
  { label: "采购到货", value: "3" },
  { label: "退货出库", value: "4" },
]);

onMounted(() => {
  if (route.query && route.query.id) {
    proxy
      .post("/stockWait/detailByWdly", { id: route.query.id })
      .then((data) => {
        let res = data.data;
        const json = res.victoriatouristJson
          ? JSON.parse(res.victoriatouristJson)
          : {};
        formData.value = {
          id: route.query.id,
          type: "1",
          businessCode: res.businessCode,
          businessType: res.businessType + "",
          businessTypeName: proxy.dictValueLabel(
            res.businessType,
            businessType.value
          ),
          warehouseId: "",
          code: json.logisticsCompanyName + "( " + json.code + " )",
          stockWaitDetailsList: res.stockWaitDetailsList.map((x) => ({
            ...x,
            arrivalQuantity: x.quantity,
            quantity: x.stockWaitDetailsCheckList
              ? x.stockWaitDetailsCheckList
                  .filter((x) => x.status != 2)
                  .reduce((total, y) => (total += Number(y.quantity)), 0)
              : 0,
            isArrow: false,
            stockWaitDetailsCheckList: x.stockWaitDetailsCheckList || [],
          })),
          stockWaitDetailsListCopy: [],
        };
      });
  }
  getDict();
});

const getSonList = (query, index) => {
  proxy.post("/stockWaitDetailsCheck/list", query).then((res) => {
    if (keyword.value) {
      formData.value.stockWaitDetailsListCopy[index].stockWaitDetailsCheckList =
        res.data;
      formData.value.stockWaitDetailsListCopy[index].quantity = res.data
        .filter((x) => x.status != 2)
        .reduce((total, y) => (total += Number(y.quantity)), 0);
      // 修改数据
      let id = formData.value.stockWaitDetailsListCopy[index].id;
      if (id) {
        let noKeywordIndex = formData.value.stockWaitDetailsList.findIndex(
          (x) => x.id == id
        );
        if (noKeywordIndex != -1) {
          formData.value.stockWaitDetailsList[
            noKeywordIndex
          ].stockWaitDetailsCheckList = res.data;
          formData.value.stockWaitDetailsList[noKeywordIndex].quantity =
            res.data
              .filter((x) => x.status != 2)
              .reduce((total, y) => (total += Number(y.quantity)), 0);
        }
      }
    } else {
      formData.value.stockWaitDetailsList[index].stockWaitDetailsCheckList =
        res.data;
      formData.value.stockWaitDetailsList[index].quantity = res.data
        .filter((x) => x.status != 2)
        .reduce((total, y) => (total += Number(y.quantity)), 0);
    }
  });
};

const handleStag = (row, index) => {
  if (Number(row.addQuantity) > 0) {
    let obj = {
      stockWaitId: formData.value.id,
      stockWaitDetailsId: row.id,
      createTime: parseTime(new Date()),
      quantity: Number(row.addQuantity),
      status: 0,
    };
    // row.stockWaitDetailsCheckList.push(obj);

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

const handleDelete = (row, index, sonRow) => {
  // formData.value.stockWaitDetailsList[index].stockWaitDetailsCheckList.splice(
  //   sonIndex,
  //   1
  // );
  proxy.post("/stockWaitDetailsCheck/delete", { id: sonRow.id }).then((res) => {
    getSonList({ stockWaitDetailsId: row.id }, index);
    return showSuccessToast("删除成功");
  });
};

const onClickRight = () => {
  proxy.$router.push({
    path: "/main/manyGoods",
    query: {
      id: formData.value.id,
      businessTypeName: formData.value.businessTypeName,
      businessCode: formData.value.businessCode,
      code: formData.value.code,
    },
  });
};
const keyword = ref("");
const onSearch = (val) => {
  formData.value.stockWaitDetailsListCopy = [];
  let list = formData.value.stockWaitDetailsList;
  for (let i = 0; i < list.length; i++) {
    const row = list[i];
    if (
      row.productCustomCode.indexOf(val) != -1 ||
      row.productName.indexOf(val) != -1 ||
      row.productSpec.indexOf(val) != -1
    ) {
      formData.value.stockWaitDetailsListCopy.push({ ...row });
    }
  }
};
</script>
<style lang="scss" scoped>
* {
  font-size: 11px;
}
:deep(.van-search__field) {
  display: flex;
  .van-field__label--top {
    width: 20px;
    margin-bottom: 0px;
  }
}
.row {
  display: flex;
  padding: 5px 10px 0 10px;
  justify-content: space-between;
  align-items: center;
  .title {
    flex: 1;
  }
  .delete {
    width: 20px;
    cursor: pointer;
    text-align: center;
  }
}
.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: 30px;
    color: #000;
  }
  td {
    text-align: center;
    padding: 6px 2px;
    height: 30px;
  }
}
</style>