<template>
  <div>
    <!-- flex items-center -->
    <div class="search bg-white pt-2 dark:!bg-[#060818]">
      <el-form ref="advancedFormRef" :model="advancedForm" label-width="130px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="12" :lg="activeName === 'first' ? 12 : 8" :xl="activeName === 'first' ? 12 : 8" class="mb-4 mr-3">
            <el-form-item :label="$t('access_time')">
              <el-date-picker
                class="w-full dark:!bg-[#060818]"
                v-model="advancedForm.goodsExchange_time_range"
                type="daterange"
                align="center"
                :editable="false"
                unlink-panels
                :clearable="true"
                :default-time="['00:00:00', '23:59:59']"
                range-separator="-"
                :start-placeholder="$t('start_time')"
                :end-placeholder="$t('end_time')"
                value-format="timestamp"
                :picker-options="{
                  disabledDate(time) {
                    return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1;
                  },
                  shortcuts: MixinPickerShortcuts,
                }"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" class="mb-4 mr-3">
            <el-form-item :label="$t('warechouse')">
              <el-select v-model="advancedForm.warehouse_id" clearable class="w-full dark:!bg-[#060818]">
                <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="7" :lg="7" :xl="7" class="mb-4 mr-3">
            <el-form-item :label="$t('storage_type')">
              <el-select v-model="advancedForm.type" clearable class="w-full dark:!bg-[#060818]">
                <el-option v-for="item in entryList" :key="item.id" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" class="mb-4 mr-3">
            <el-form-item :label="$t('customer_name')">
              <el-input
                v-model="advancedForm.customer_name"
                class="w-full dark:!bg-[#060818]"
                clearable
                :placeholder="$t('change') + $t('customer_name')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" class="mb-4 mr-3">
            <el-form-item :label="$t('phone')">
              <el-input v-model="advancedForm.customer_phone" class="w-full dark:!bg-[#060818]" clearable :placeholder="$t('change') + $t('phone')"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="flex justify-end mr-8">
        <el-button class="mr-3" @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">
            <el-button size="small" type="primary" v-if="store.state.user.user.founder !== 1" @click="handleAddGoodsExchange">{{
              $t('addInventory')
            }}</el-button>
          </div>
        </div>
      </template>

      <template #table-columns>
        <el-table-column type="selection" width="55" class="dark:!bg-[#060818]" />
        <el-table-column prop="sn" :label="$t('warehousing_sn')">
          <template #default="scope">
            {{ scope.row.sn }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouse_id" :label="$t('warechouse_name')">
          <template #default="scope">
            {{ warehouseName(scope.row.warehouse_id) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('warehousing_type')">
          <template #default="scope">
            <span>{{ entryName(scope.row.type) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('warehousing_time')">
          <template #default="scope">
            <span>{{ scope.row.create_time }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('warehousing_state')">
          <template #default="scope">
            <span>{{ scope.row.has_submit === 'Y' ? $t('inStock') : $t('notStock') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="memo" :label="$t('notes')">
          <template #default="scope">
            <span>{{ scope.row.memo }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('operate')">
          <template #default="scope">
            <!-- v-if="checkPermission(['checkInventory'])" -->
            <el-button class="mr-1 mt-1" size="small" @click="handleAuditGoodsExchange(scope.row)">{{ $t('view') }}</el-button>
            <!-- && checkPermission(['editInventory']) && checkPermission(['goodsExchangeEdit']) -->
            <el-button
              size="small"
              class="!ml-0 mt-1"
              v-if="scope.row.has_submit === 'N' && store.state.user.user.founder !== 1"
              @click="handleEditGoodsExchange(scope.row)"
              >{{ $t('warehousing') }}</el-button
            >
          </template>
        </el-table-column>
      </template>

      <el-pagination
        v-if="tableData.data && tableData.data.length"
        @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>
    </en-table-layout>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watchEffect } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import * as API_GoodsExchange from '@/api/goodsExchange';
import * as API_Setting from '@/api/setting';
import * as API_BasicSetting from '@/api/basicSetting';
import { useStore } from 'vuex';
const store = useStore();
const router = useRouter();
const route = useRoute();

const warehouseList = ref([]);
const deptList = ref([]);
const loading = ref(false);
const params = reactive({
  page_no: 1,
  page_size: 10,
  company_id: store.state.companId,
});
const advancedForm = reactive({});
const tableData = ref('');
const dialogVisible = ref(false);
const multipleSelection = ref([]);
const goodsExchangeForm = reactive({});
const activeName = ref('second');
const entryList = ref([]);
const outList = ref([]);
const advancedFormRef = ref(null);

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

const GET_DeptList = () => {
  API_Setting.getPage({ dictType: 'warehouse_entry_type' }).then((res) => {
    entryList.value = res.data;
  });
  /*   API_Setting.getPage({ dictType: 'out_warehouse_type' }).then((res) => {
    outList.value = res.data;
  }); */
};

const GET_GoodsExchangeList = () => {
  loading.value = true;
  API_GoodsExchange.getWarehouseOut(params)
    .then((response) => {
      loading.value = false;
      tableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};

const GET_WarehouseEntry = () => {
  loading.value = true;
  API_GoodsExchange.getWarehouseEntry(params)
    .then((response) => {
      loading.value = false;
      tableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};

const handleClick = (tab) => {
  activeName.value = tab.name;
  params.page_no = 1;
  GET_WarehouseEntry();
};

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

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

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

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

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

const handleShiftGoodsExchange = () => {
  router.push({
    name: 'goodsExchangeAdd',
    params: { callback: GET_GoodsExchangeList, type: 'first' },
  });
};

const handleAddGoodsExchange = () => {
  router.push({
    name: 'addInventory',
  });
};

const advancedSearchEvent = () => {
  Object.assign(params, advancedForm);
  delete params.start_time;
  delete params.end_time;
  if (advancedForm.goodsExchange_time_range) {
    params.start_time = parseInt(Number(advancedForm.goodsExchange_time_range[0]) / 1000);
    params.end_time = parseInt(Number(advancedForm.goodsExchange_time_range[1]) / 1000);
  }
  delete params.goodsExchange_time_range;
  params.page_no = 1;
  GET_WarehouseEntry();
};

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

const outName = (val) => {
  let name = '';
  outList.value.map((el) => {
    if (el.value === val) {
      name = el.label;
    }
  });
  return name;
};

const entryName = (val) => {
  let name = '';
  entryList.value.map((el) => {
    if (el.value === val) {
      name = el.label;
    }
  });
  return name;
};

onMounted(() => {
  GET_WarehouseEntry();
  GET_DeptList();
  GET_WarehouseList();
});

watchEffect(() => {
  if (route.query.status) {
    params.status = route.query.status;
    advancedForm.status = route.query.status;
  }
  params.page_no = 1;
  GET_WarehouseEntry();
});
</script>
<!-- <style scoped>
::v-deep .custom-select .el-input__inner {
  background-color: #060818 !important;
}
</style> -->