<template>
  <div class="dark:!bg-[#060818] bg-white p-3">
    <div class="search bg-white p-3">
      <!-- label-width="160px" -->
      <el-form :model="advancedForm" class="advanced-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8" class="mb-4">
            <el-form-item :label="$t('out_warehouse') + ':'">
              <el-select v-model="advancedForm.out_warehouse_id" 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="12" :md="8" :lg="8" :xl="8" class="mb-4">
            <el-form-item :label="$t('to_warehouse') + ':'">
              <el-select v-model="advancedForm.in_warehouse_id" 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="12" :md="8" :lg="8" :xl="8" class="mb-4">
            <el-form-item :label="$t('warehousing_state') + ':'">
              <el-select v-model="advancedForm.status" class="w-full">
                <el-option v-for="item in statusList" :key="item.id" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8" class="mb-4">
            <el-form-item :label="$t('transfer_time') + ':'">
              <el-date-picker
                v-model="advancedForm.purchasePlan_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"
                class="w-full"
                :picker-options="{
                  disabledDate(time) {
                    return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1;
                  },
                }"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8" class="mb-4">
            <el-form-item :label="$t('transfer_sn') + ':'">
              <el-input v-model="advancedForm.sn" placeholder="请输入调拨单号" class="w-full"></el-input>
            </el-form-item>
          </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(['goodsUnderstock:add'])" -->
            <el-button size="small" type="primary" v-if="store.state.user.user.founder !== 1" @click="handleAddGoodsUnderstock">{{ $t('add') }}</el-button>
          </div>
        </div>
      </template>

      <template #table-columns>
        <el-table-column type="selection" width="50" fixed="left" />
        <el-table-column prop="sn" :label="$t('transfer_sn')" min-width="100" show-overflow-tooltip />
        <el-table-column :label="$t('transfer_time')" min-width="100" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.transfer_time }}</template>
        </el-table-column>
        <el-table-column prop="out_warehouse_name" :label="$t('out_warehouse')" min-width="100" show-overflow-tooltip>
          <template #default="scope">
            {{ warehouseName(scope.row.out_warehouse_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="in_warehouse_name" :label="$t('to_warehouse')" min-width="100" show-overflow-tooltip>
          <template #default="scope">
            {{ warehouseName(scope.row.in_warehouse_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="" :label="$t('delivery_method')" min-width="100" show-overflow-tooltip>
          <template #default="scope">
            {{ getTypename(scope.row.send_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" :label="$t('warehousing_state')" min-width="100" show-overflow-tooltip>
          <template #default="scope">{{ get_typeName(scope.row.status) }}</template>
        </el-table-column>
        <el-table-column :label="$t('operate')" width="80" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleSubmitGoodsTransfer(scope.row)">{{ $t('view') }}</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>
  </div>
</template>
  
  <script lang="ts" setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useStore } from 'vuex';
import * as API_GoodsTransfer from '@/api/goodsTransfer';
import * as API_Statistics from '@/api/statistics';
import * as API_Setting from '@/api/setting';
import * as API_BasicSetting from '@/api/basicSetting';
import * as API_Express from '@/api/express';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';

const store = useStore();
const router = useRouter();
const route = useRoute();
const user = computed(() => store.getters.user);

const warehouseList = ref<any[]>([]);
const goodstransferType = ref<any[]>([]);
const loading = ref(false);
const params = ref<any>({
  page_no: 1,
  page_size: 10,
  company_id: store.state.companId,
});
const advancedForm = ref<any>({});
const tableData = ref<any>({});
const multipleSelection = ref<any[]>([]);
const deliveryTypeList = ref<any[]>([]);
const statusList = ref<any[]>([]);

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

const GET_DictDataInfo = () => {
  API_Setting.getDictDataInfo('erp_goodstransfer_type').then((res) => {
    goodstransferType.value = res;
  });
  API_Setting.getPage({ dictType: 'transfer_status' }).then((res) => {
    statusList.value = res.data;
  });
};

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

const GET_ExpressList = () => {
  API_Express.getExpressList(params.value).then((response) => {
    deliveryTypeList.value = response.data;
  });
};

const get_typeName = (val: string) => {
  let name = '';
  statusList.value.map((el) => {
    if (el.value == val) {
      name = el.label;
    }
  });
  return name;
};

const getTypename = (val: string) => {
  let name = '';
  deliveryTypeList.value.map((el) => {
    if (el.id == val) {
      name = el.name;
    }
  });
  return name;
};

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

const handleSuccessGoodsTransfer = (row: any) => {
  API_GoodsTransfer.get_withdraw(row.id).then(() => {
    ElMessage.success('撤销成功！');
    GET_GoodsTransferList();
  });
};

const handleRejectGoodsTransfer = (row: any) => {
  API_GoodsTransfer.rejectGoodsTransfer(row.id, { in_handled_by_id: user.value.uid, in_handled_by_name: user.value.username }).then(() => {
    ElMessage.success('退回成功！');
    GET_GoodsTransferList();
  });
};

const handleSubmitGoodsTransfer = (row: any) => {
  router.push({
    name: 'goodsUnderstockAdd',
    query: { id: row.id, type: 'view' },
  });
  /*  store.dispatch('router/push', {
    name: 'goodsUnderstockDetail',
    params: { id: row.id },
  }); */
};

const handleWithdrawGoodsTransfer = (row: any) => {
  API_GoodsTransfer.withdrawGoodsTransfer(row.id).then(() => {
    ElMessage.success('撤回成功！');
    GET_GoodsTransferList();
  });
};

const handleDeleteGoodsTransfer = () => {
  if (!multipleSelection.value.length) return store.dispatch('message/error', '请先选择！');
  ElMessageBox.confirm('确定要删除这些商品调拨吗？', '提示', { type: 'warning' })
    .then(() => {
      const ids = multipleSelection.value.map((item) => item.id);
      API_GoodsTransfer.deleteGoodsTransfer(ids).then(() => {
        store.dispatch('message/success', '删除成功！');
        GET_GoodsTransferList();
      });
    })
    .catch(() => {});
};

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

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

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

const handleAddGoodsUnderstock = () => {
  router.push({
    name: 'goodsUnderstockAdd',
  });
};

const handleEditGoodsTransfer = (row: any) => {
  /* store.dispatch('router/push', {
    name: 'goodsTransferEdit',
    params: { id: row.id },
  }); */
};

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

const advancedSearchEvent = () => {
  params.value = {
    ...params.value,
    ...advancedForm.value,
  };
  delete params.value.start_time;
  delete params.value.end_time;
  if (advancedForm.value.purchasePlan_time_range) {
    params.value.start_time = parseInt(String(Number(advancedForm.value.purchasePlan_time_range[0]) / 1000));
    params.value.end_time = parseInt(String(Number(advancedForm.value.purchasePlan_time_range[1]) / 1000));
  }
  delete params.value.purchasePlan_time_range;
  params.value.page_no = 1;
  GET_GoodsTransferList();
};

onMounted(() => {
  GET_GoodsTransferList();
  GET_DictDataInfo();
  GET_WarehouseList();
  GET_ExpressList();
});
</script>
  
 <!--  <style 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> -->