<template>
  <div class="dark:!bg-[#060818] bg-white p-3">
    <div class="search bg-white p-3">
      <el-form ref="advancedFormRef" :model="advancedForm">
        <el-row>
          <el-col :xs="24" :sm="24" :md="6" :lg="5" :xl="6" class="mb-4 mr-3">
            <el-form-item :label="$t('inventoryDate')">
              <el-date-picker
                class="mt-1"
                v-model="searchTime"
                type="daterange"
                :shortcuts="shortcuts"
                range-separator="-"
                start-placeholder="Start date"
                end-placeholder="End date"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="6" :lg="3" :xl="6" class="mb-4 mr-3">
            <el-form-item :label="$t('warechouse')">
              <el-select v-model="advancedForm.warehouse_id" clearable>
                <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="6" :lg="3" :xl="6" class="mb-4 mr-3">
            <el-form-item :label="$t('inventoryPeople')">
              <el-select v-model="advancedForm.inventory_person_id" clearable>
                <el-option v-for="item in adminList" :key="item.id" :label="item.real_name" :value="item.id" />
              </el-select>
            </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 @click="advancedSearchEvent"> {{ $t('search') }} </el-button>
      </div> -->
    </div>
    <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
      <template #toolbar>
        <div class="inner-toolbar">
          <div class="toolbar-btns">
            <!-- v-if="checkPermission(['goodsInventory:add'])" type="primary" -->
            <el-button size="small" v-if="store.state.user.user.founder !== 1" @click="handleAddGoodsInventory">{{ $t('add') }}</el-button>
          </div>
        </div>
      </template>

      <template #table-columns>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sn" :label="$t('inventorySn')">
          <template #default="scope">
            <span>{{ scope.row.sn }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="inventory_time" :label="$t('inventory_time')">
          <template #default="scope">{{ scope.row.inventory_time }}</template>
        </el-table-column>
        <el-table-column prop="warehouse_name" :label="$t('warechouse')">
          <template #default="scope">{{ warehouseName(scope.row.warehouse_id) }}</template>
        </el-table-column>
        <el-table-column prop="status" :label="$t('warehousing_state')">
          <template #default="scope">{{ statusFilter(scope.row.status) }}</template>
        </el-table-column>
        <el-table-column :label="$t('operate')" fixed="right" width="450">
          <template #default="scope">
            <!-- v-if="checkPermission(['goodsInventoryCheck'])" -->
            <el-button size="small" @click="handleCheckGoodsInventory(scope.row)">{{ $t('view') }}</el-button>
            <!--  && checkPermission(['goodsInventoryEdit']) -->
            <el-button
              v-if="scope.row.status == 'NOT_HANDLE' && store.state.user.user.founder !== 1"
              size="small"
              @click="handleEditGoodsInventory(scope.row)"
              >{{ $t('edit') }}</el-button
            >
            <!--  && checkPermission(['goodsInventory:sync']) -->
            <el-button
              type="mini"
              size="small"
              v-if="scope.row.status == 'NOT_HANDLE' && store.state.user.user.founder !== 1"
              @click="handleSubmitGoodsInventory(scope.row)"
              >{{ $t('synchronous') }}</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="[10, 20, 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 v-model="dialogVisible" width="940px" center>
      <div style="width: 900px">
        <el-button size="mini" type="primary" @click="handlePrintGoodsInventory" class="print no-btn">打印</el-button>
        <div id="deliverySheet"  class="deliverySheet-header">
          <h3>产品库存盘点单</h3>
        </div>
        <div class="tips-t">
          <div>仓库名称编码:{{ goodsInventoryForm.dept_name }}{{ goodsInventoryForm.warehouse_name }}</div>
          <div>日期:{{ goodsInventoryForm.inventory_time }}</div>
          <div>编号:{{ goodsInventoryForm.sn }}</div>
        </div>
        <el-table
          :data="goodsInventoryForm.product_list"
          border
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
          style="width: 100%"
        >
          <el-table-column label="序号" width="179">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="商品编号" width="170">
            <template #default="scope">
              {{ scope.row.product_sn }}
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="170">
            <template #default="scope">
              {{ scope.row.product_name }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号" width="110">
            <template #default="scope">
              {{ scope.row.specification }}
            </template>
          </el-table-column>
          <el-table-column label="单位" width="50">
            <template #default="scope">
              {{ scope.row.unit }}
            </template>
          </el-table-column>
          <el-table-column label="上期盘点库存" width="110">
            <template #default="scope">
              {{ scope.row.stock_num }}
            </template>
          </el-table-column>
          <el-table-column label="本期盘点库存" width="110">
            <template #default="scope">
              {{ scope.row.inventory_num }}
            </template>
          </el-table-column>
        </el-table>
        <div class="tips-t">
          <div>盘点人:{{ goodsInventoryForm.inventory_person }}</div>
        </div>
      </div>
    </el-dialog> -->
  </div>
</template>
  
  <script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import * as API_GoodsInventory from '@/api/goodsInventory';
import Print from 'print-js';
import * as API_Auth from '@/api/auth';
import * as API_Setting from '@/api/setting';
import * as API_BasicSetting from '@/api/basicSetting';
/*  import { Foundation } from '~/ui-utils'; */
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStore } from 'vuex';
const store = useStore();
const router = useRouter();
const route = useRoute();

const warehouseList = ref<any>([]);
const deptList = ref([]);
const loading = ref(false);
const params = ref({
  page_no: 1,
  page_size: 10,
  company_id: store.state.companId,
});
const advancedForm = ref<any>({});
const tableData = ref<any>({});
const dialogVisible = ref(false);
const multipleSelection = ref<any>([]);
const goodsInventoryForm = ref<any>({});
const adminList = ref<any>([]);
const searchTime = ref([]);

onMounted(() => {
  GET_GoodsInventoryList();
  /* GET_DeptList(); */
  GET_WarehouseList();
});

watch(route, () => {
  params.value.page_no = 1;
  GET_GoodsInventoryList();
});

const shortcuts = () => [
  {
    text: 'Last week',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

const GET_WarehouseList = () => {
  API_BasicSetting.getWarehouseListAll().then((response) => {
    warehouseList.value = response;
  });
  API_Auth.getAdministratorList({
    page_no: 1,
    page_size: 9999,
    user_state: 0,
    company_id: store.state.companId,
  }).then((response) => {
    adminList.value = response.data;
  });
};

const handleCheckGoodsInventory = (row) => {
  router.push({
    name: 'goodsInventoryAdd',
    query: {
      id: row.id,
      type: 'view',
    },
  });
};

const handleEditGoodsInventory = (row) => {
  router.push({
    name: 'goodsInventoryAdd',
    query: {
      id: row.id,
      type: 'edit',
    },
  });
};

const handleSubmitGoodsInventory = (row) => {
  API_GoodsInventory.getSyncStock(row.id).then(() => {
    ElMessage.success('处理成功！');
    GET_GoodsInventoryList();
  });
};

const handleAddGoodsInventory = () => {
  router.push({
    name: 'goodsInventoryAdd',
    /*   params: { callback: GET_GoodsInventoryList } */
  });
};

const handlePrintGoodsInventoryDialog = (row) => {
  GET_GoodsInventoryDetail(row.id);
};

const handleDeleteGoodsInventory = () => {
  if (!multipleSelection.value.length) return ElMessage.error('请先选择！');
  ElMessageBox.confirm('确定要删除当前盘点单吗？', '提示', { type: 'warning' })
    .then(() => {
      const ids: any = multipleSelection.value.map((item) => item.id);
      API_GoodsInventory.deleteGoodsInventory(ids).then(() => {
        ElMessage.success('删除成功！');
        GET_GoodsInventoryList();
      });
    })
    .catch(() => {});
};

const statusFilter = (val) => {
  switch (val) {
    case 'NOT_HANDLE':
      return '未处理';
    case 'HAS_HANDLE':
      return '已处理';
  }
};

const warehouseName = (val) => {
  let name = '';
  warehouseList.value.map((el) => {
    if (el.id == val) {
      name = el.name;
    }
  });
  return name;
};

const GET_DeptList = () => {
  /* API_Setting.getDeptList().then((response) => {
    deptList.value = Foundation.buildTree(response, '0');
  }); */
};

const handlePrintGoodsInventory = () => {
  Print({
    printable: 'deliverySheet',
    type: 'html',
    targetStyles: ['*'],
    ignoreElements: ['no-logs', 'goods-image', 'no-btn'],
  });
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

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

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

const GET_GoodsInventoryDetail = (id) => {
  API_GoodsInventory.getGoodsInventoryInfo(id).then((response) => {
    goodsInventoryForm.value = response;
    let str = ''; // Declare str outside the if block
    if (response.product_list && response.product_list.length) {
      response.product_list.forEach(function (i) {
        str += i.product_name + '、';
      });
    }
    goodsInventoryForm.value.illustrate = str;
    dialogVisible.value = true;
  });
};

const searchEvent = (data) => {
  /* params.value = {
    ...params.value,
    sn: data,
  };
  Object.keys(advancedForm.value).forEach((key) => delete params.value[key]);
  params.value.page_no = 1; */
  GET_GoodsInventoryList();
};

const advancedSearchEvent = () => {
  if (searchTime.value) {
    advancedForm.value.start_time = searchTime.value[0];
    advancedForm.value.end_time = searchTime.value[1];
  }
  params.value = {
    ...params.value,
    ...advancedForm.value,
  };
  params.value.page_no = 1;
  GET_GoodsInventoryList();
};

const GET_GoodsInventoryList = () => {
  loading.value = true;
  API_GoodsInventory.getGoodsInventoryList(params.value)
    .then((response) => {
      loading.value = false;
      tableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};
</script>
  
<!--   <style scoped lang="scss">
  .search {
    display: flex;
    align-items: center;
    background: #fff;
    overflow: hidden;
    padding: 30px 10px 10px 10px;
  
    .el-form-item {
      .el-form-item__content {
        .el-input {
          width: 200px;
        }
      }
    }
  
    .el-button {
      margin-top: -19px;
      margin-left: 20px;
    }
  }
  
  .print {
    margin-left: 790px;
  }
  
  .deliverySheet-header {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .tips-t {
    display: flex;
    padding: 30px 0;
  
    div {
      flex: 1;
      text-align: left;
      padding-left: 70px;
    }
  }
  
  .tips-f {
    padding: 20px 0;
  }
  
  .face-image {
    display: block;
    width: 50px;
    height: 50px;
    margin: 0 auto;
  }
  
  .el-dialog__body {
    padding: 10px 20px;
  }
  </style> -->