<template>
  <div class="grid xl:grid-cols-1 dark:!bg-[#060818] bg-white p-3">
    <div class="search bg-white p-3 grid xl:grid-cols-1">
      <el-form ref="advancedFormRef" :model="advancedForm">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="12" :lg="3" :xl="6" class="mb-4">
            <el-form-item :label="$t('warechouse') + ':'">
              <el-select v-model="advancedForm.warehouse_id" clearable class="w-full">
                <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="5" :xl="6" class="mb-4">
            <el-form-item :label="$t('goods_sn') + '/' + 'sku' + ':'">
              <el-input v-model="advancedForm.keyword" clearable :placeholder="$t('place') + $t('content')" class="w-full"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="1" :xl="6" class="mb-4 flex items-end">
            <el-button class="w-full mt-1" @click="advancedSearchEvent"> {{ $t('search') }} </el-button>
          </el-col>
        </el-row>
      </el-form>
      <!--   <div class="flex justify-end">
        <el-button class="mr-3" @click="advancedSearchEvent"> {{ $t('search') }} </el-button>
      </div> -->
    </div>
    <en-table-layout :tableData="tableData.data" ref="table" :loading="loading" @selection-change="handleSelectionChange">
      <template #toolbar>
        <div class="inner-toolbar">
          <div class="toolbar-btns">
            <el-button
              size="small"
              type="primary"
              v-if="checkPermission(['updateWarnStock:update']) && store.state.user.user.founder !== 1"
              @click="handleSubmitGoodsTransfer"
              >设置预警库存</el-button
            >
            <!-- <el-button size="small" type="primary" v-if="store.state.user.user.founder!==1" @click="checkExport">导出</el-button> -->
          </div>
        </div>
      </template>

      <template #table-columns>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="warehouse_name" :label="$t('warechouse_name')"> </el-table-column>
        <!-- <el-table-column label="商品编号" prop="sn">
        </el-table-column>
        <el-table-column prop="type" label="类别">
          <template #default="scope">
            {{ scope.row.product_vo.hire_or_sail=='sail' ? '售卖商品' : '租赁商品'  }}
          </template>
        </el-table-column> -->
        <el-table-column prop="product_name" :label="$t('goods_name')" />
        <el-table-column prop="type" label="sku">
          <template #default="scope">
            {{ scope.row.product_vo ? scope.row.product_vo.sku : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="goods_unit" :label="$t('goods_unit')" />
        <el-table-column prop="actual_stock" :label="$t('actual_stock')">
          <template #default="scope">
            <span :style="Number(scope.row.actual_stock) < Number(scope.row.warning_stock) ? 'color:red' : ''">{{ scope.row.actual_stock }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="usable_stock" :label="$t('usable_stock')" />
        <el-table-column prop="transit_stock" :label="$t('transit_stock')" />
        <el-table-column prop="locked_stock" :label="$t('locked_stock')" />
        <el-table-column prop="warning_stock" :label="$t('warning_stock')" />
        <!--   <el-table-column label="操作" fixed="right" width="300">
          <template #default="scope">
            <el-button type="success1" size="small" v-if="checkPermission(['goodsTransfer:add']) && scope.row.transit_stock>0"
              @click="lookTransit(scope.row)">查看在途</el-button>
          </template>
        </el-table-column> -->
      </template>

      <template #pagination>
        <el-pagination
          v-if="tableData"
          @size-change="handlePageSizeChange"
          @current-change="handlePageCurrentChange"
          :current-page="tableData.page_no"
          :page-sizes="[50, 100]"
          :page-size="tableData.page_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.data_total"
        >
        </el-pagination>
      </template>
    </en-table-layout>
    <el-dialog
      :title="$t('transitDetails')"
      v-model:visible="dialogVisible"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="!rounded-lg"
    >
      <el-table :data="transitDetails" border class="sku-table">
        <el-table-column prop="order_sn" :label="$t('order_sn')" />
        <el-table-column prop="num" :label="$t('transit_num')" />
        <el-table-column prop="end_time" :label="$t('return_date')" />
      </el-table>
    </el-dialog>
    <el-dialog
      :title="$t('setNumber')"
      v-model:visible="numDialogVisible"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="30%"
      class="!rounded-lg"
    >
      <el-form ref="numAddForm" :model="numAddForm" :rules="numAddFormRule" label-width="160px" inline class="change-form">
        <el-form-item :label="$('warningQuantity')" prop="num" class="change-form-item">
          <el-input v-model="numAddForm.num" :placeholder="$('place')"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="numDialogVisible = false">{{ $('cancel') }}</el-button>
        <el-button @click="submitNum" type="primary">{{ $('submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import * as API_GoodsTransfer from '@/api/goodsTransfer';
import * as API_Setting from '@/api/setting';
import * as API_BasicSetting from '@/api/basicSetting';
import { useStore } from 'vuex';
import { useRouter, useRoute } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
/* import EnTableLayout from '@/components/TableLayout/index.vue';
import EnTableSearch from '@/components/TableSearch/index.vue'; */
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const store = useStore();
const router = useRouter();
const route = useRoute();

const warehouseList = ref([]);
const goodstransferType = ref([]);
const loading = ref(false);
const params = reactive({
  page_no: 1,
  page_size: 50,
  company_id: store.state.companId,
});
const advancedForm = reactive({});
const tableData = ref('');
const multipleSelection = ref([]);
const GoodsTransferForm = reactive({});
const dialogVisible = ref(false);
const transitDetails = ref([]);
const numDialogVisible = ref(false);
const numAddForm = reactive({});
const stockListId = ref([]);
const numAddFormRule = reactive({
  num: [
    {
      required: true,
      message: t('place') + t('warningQuantity'),
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (/^(?:[1-9]\d*)$/.test(value) == false) {
          callback(new Error(t('place') + t('integer')));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
});
const selectedRow = ref(null);

const GET_GoodsTransferList = () => {
  loading.value = true;
  API_GoodsTransfer.productStock(params)
    .then((response) => {
      loading.value = false;
      tableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};

const GET_WarehouseList = () => {
  API_BasicSetting.getWarehouseListAll().then((response) => {
    warehouseList.value = response;
  });
};

const GET_DictDataInfo = () => {
  API_Setting.getDictDataInfo('erp_goodstransfer_type').then((res) => {
    goodstransferType.value = res;
  });
};

const submitNum = () => {
  numAddForm.value.validate((valid) => {
    if (valid) {
      API_GoodsTransfer.updateWarnStock({ stock_id: stockListId.value, warn_num: numAddForm.value.num }).then((res) => {
        numDialogVisible.value = false;
        numAddForm.value = {};
        ElMessage.success(t('warning_stock') + t('set_success') + '!');
        GET_GoodsTransferList();
      });
    }
  });
};

const handleDelGoodsTransfer = (row) => {
  ElMessageBox.confirm('确定要删除这些库存吗？', '提示', { type: 'warning' })
    .then(() => {
      const ids = [row.id];
      API_GoodsTransfer.deleteGoodsTransfer({ ids }).then(() => {
        ElMessage.success('删除成功！');
        GET_GoodsTransferList();
      });
    })
    .catch(() => {});
};

const lookTransit = (row) => {
  API_GoodsTransfer.transitDetail(row.id).then((res) => {
    dialogVisible.value = true;
    transitDetails.value = res;
  });
};

const handleSubmitGoodsTransfer = () => {
  if (stockListId.value.length == 0) return ElMessage.error(t('place'));
  numDialogVisible.value = true;
};

const handleSelectionChange = (rows) => {
  stockListId.value = rows.map((el) => el.id);
};

const handlePageSizeChange = (size) => {
  params.page_size = size;
  GET_GoodsTransferList();
};

const handlePageCurrentChange = (page) => {
  params.page_no = page;
  GET_GoodsTransferList();
};

const advancedSearchEvent = () => {
  Object.assign(params, advancedForm);
  params.page_no = 1;
  GET_GoodsTransferList();
};

onMounted(() => {
  GET_GoodsTransferList();
  GET_DictDataInfo();
  GET_WarehouseList();
});

watch(route, () => {
  params.page_no = 1;
  GET_GoodsTransferList();
});
</script>

<!-- <style type="text/scss" lang="scss" scoped>
.search {
  display: flex;
  align-items: center;
  background: #fff;
  overflow: hidden;
  padding: 30px 10px 10px 10px;

  /deep/ .el-form-item {
    .el-form-item__content {
      .el-input {
        width: 200px;
      }
    }
  }

  .el-button {
    margin-top: -19px;
    margin-left: 20px;
  }
}

.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    text-align: center;
  }
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
 -->
