<template>
  <div class="bg-in-stock">
    <el-form ref="GoodsTransferFormRef" :model="GoodsTransferForm" label-width="120px" :rules="GoodsTransferFormRule" inline>
      <h3>{{$t('transfer_order')}}</h3>
      <el-form-item :label="$t('transfer_time')" prop="transfer_time" class="change-form-item">
        <span v-if="type === 'view'">{{ GoodsTransferForm.transfer_time }}</span>
        <el-date-picker
          v-else
          v-model="GoodsTransferForm.transfer_time"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetime"
          :disabled="type === 'view' || type === 'audit' || type === 'check'"
          :placeholder="$t('change')+$t('date')"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="out_warehouse_id" :label="$t('out_warehouse')">
        <span v-if="type === 'view'">{{ getWarehouse(GoodsTransferForm.out_warehouse_id) }}</span>
        <el-select v-else @change="cleanGoodsList" v-model="GoodsTransferForm.out_warehouse_id" :disabled="type === 'view'">
          <el-option v-for="item in WarehouseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item prop="in_warehouse_id" :label="$t('to_warehouse')">
        <span v-if="type === 'view'">{{ getWarehouse(GoodsTransferForm.in_warehouse_id) }}</span>
        <el-select v-else v-model="GoodsTransferForm.in_warehouse_id" :disabled="type === 'view'">
          <el-option v-for="item in WarehouseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('delivery_method')" prop="send_type">
        <span v-if="type === 'view'">{{ getdeliveryType(GoodsTransferForm.send_type) }}</span>
        <el-select v-else v-model="GoodsTransferForm.send_type" clearable :disabled="type === 'view'">
          <el-option v-for="item in deliveryTypeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('notes')" prop="remark">
        <span v-if="type === 'view'">{{ GoodsTransferForm.remark }}</span>
        <el-input v-else :disabled="type === 'view'" type="textarea" :rows="2" :placeholder="$t('place')" v-model="GoodsTransferForm.remark"> </el-input>
      </el-form-item>
      <div class="mx">
        <h3>{{$t('goods_inventory')}}</h3>
        <el-button class="button" size="small" type="primary" v-if="type !== 'view'" @click="handleSelectWarehouseEntryBatch">选择</el-button>
      </div>
      <div style="display: block">
        <el-table
          :data="GoodsTransferForm.product_list"
          border
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column :label="$t('goods_name')">
            <template #default="scope">
              <span>{{ scope.row.product_vo.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="sku">
            <template #default="scope">
              <span>{{ scope.row.product_vo.sku }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('goods_unit')">
            <template #default="scope">
              <span>{{ scope.row.product_vo.unit }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('inventory_num')">
            <template #default="scope">
              <span>{{ scope.row.usable_stock }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('transfer_num')">
            <template #default="scope">
              <span v-if="type === 'view'">{{ scope.row.num }}</span>
              <el-input
                v-else
                v-model="scope.row.num"
                type="number"
                :min="0"
                :maxlength="20"
                :disabled="type === 'view' || type === 'audit' || type === 'check'"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('operate')" v-if="type !== 'view'">
            <template #default="scope">
              <el-button size="small" type="danger" @click="GoodsTransferForm.product_list.splice(scope.$index, 1)">{{$t('delete')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <div class="footer">
      <el-button v-if="type !== 'view'" type="primary" @click="submitGoodsTransferForm">{{$t('save')}}</el-button>
      <!-- <el-button @click="printIng">{{$t('print')}}</el-button> -->
      <el-button @click="roBack">{{$t('return')}}</el-button>
    </div>
    <el-dialog :title="$t('transfer_goods')" v-model="goodsVisible" width="1000px" @close="closeGoosData">
      <div style="display: flex; align-items: center; justify-content: flex-end; padding: 10px 0">
        <span>{{$t('search_goods')}}:</span><el-input v-model="params.keyWord" style="width: 200px; margin-right: 5px"></el-input>
        <el-button @click="searchGoodEvent"> {{$t('search')}} </el-button>
      </div>
      <el-table :data="goodsData.records" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="product_vo.name" :label="$t('goods_name')"></el-table-column>
        <el-table-column prop="product_vo.sku" label="sku"> </el-table-column>
        <el-table-column prop="" :label="$t('brand')">
          <template #default="scope">
            {{ scope.row.product_vo.brand }}
          </template>
        </el-table-column>
        <el-table-column prop="product_vo.weight" :label="$t('weight')"> </el-table-column>
        <el-table-column prop="product_vo.unit" :label="$t('goods_unit')"> </el-table-column>
      </el-table>
      <el-pagination
        @size-change="goodsPageSizeChange"
        @current-change="goodsPageCurrentChange"
        :current-page="goodsData.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="goodsData.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="goodsData.total"
      >
      </el-pagination>
      <template #footer>
        <el-button @click="closeGoosData">{{$t('cancel')}}</el-button>
        <el-button type="primary" @click="submitGoosData()">{{$t('submit')}}</el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script lang="ts" setup>
import { ref, onMounted, computed,reactive } from 'vue';
import { useStore } from 'vuex';
import * as API_GoodsTransfer from '@/api/goodsTransfer';
import * as API_BasicSetting from '@/api/basicSetting';
import * as API_Setting from '@/api/setting';
import * as API_Auth from '@/api/auth';
import * as API_Express from '@/api/express';
import * as API_GoodsExchange from '@/api/goodsExchange';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const router = useRouter();
const route = useRoute();

const store = useStore();
const user = computed(() => store.getters.user);

const adminList = ref<any[]>([]);
const WarehouseList = ref<any[]>([]);
const inWarehouseList = ref<any[]>([]);
const deptList = ref<any[]>([]);
const deptListAll = ref<any[]>([]);
const goodstransferType = ref<any[]>([]);
const fileList = ref<any[]>([]);
const id = ref<string>('');
const type = ref<string>('');
const deliveryTypeList = ref<any[]>([]);
const GoodsTransferForm = ref<any>({
  out_dept_id: '',
  out_handled_by_id: '',
  product_list: [],
});
const GoodsTransferFormRule = ref({
  transfer_time: {
    required: true,
    message: t('change')+t('transfer_time'),
    trigger: 'change',
  },
  out_warehouse_id: {
    required: true,
    message: t('change')+t('out_warehouse'),
    trigger: 'change',
  },
  in_warehouse_id: {
    required: true,
    message: t('change')+t('to_warehouse'),
    trigger: 'change',
  },
  send_type: {
    required: true,
    message: t('change')+t('delivery_method'),
    trigger: 'change',
  },
});

const getdeliveryType = (value: string) => {
  const type = deliveryTypeList.value.find((type) => type.id === value);
  return type ? type.name : t('unknown');
};

const getWarehouse = (value: string) => {
  const type = WarehouseList.value.find((type) => type.id === value);
  return type ? type.name : t('unknown');
};

const printIng = () => {
  // 打印功能
};
/* 报损商品信息 操作部分 */
const goodsVisible = ref(false);
const goodsData = ref<any>([]);
const params = reactive({
  page_no: 1,
  page_size: 10,
  keyWord: '',
});
/* 关闭报损商品 */
const closeGoosData = () => {
  goodsVisible.value = false;
};
/* 搜索报损商品 */
const searchGoodEvent = () => {
  API_GoodsExchange.getGoodsInfo(params, GoodsTransferForm.value.out_warehouse_id).then((res) => {
    goodsData.value = res;
  });
};
/* 选中的商品列表 */
const goodsList = ref([]);
const handleSelectionChange = (val) => {
  goodsList.value = val.map((el) => {
    return el;
  });
};
const submitGoosData = () => {
  if (goodsList.value.length >= 1) {
    GoodsTransferForm.value.product_list = goodsList.value.map((el) => {
      return el;
    });
    goodsVisible.value = false;
  } else {
    ElMessage.error(t('change')+t('goods_info')+'!');
  }
};
/* 盘点商品分页 */
const goodsPageSizeChange = (size) => {
  params.page_size = size;
  searchGoodEvent();
};

const goodsPageCurrentChange = (page) => {
  params.page_no = page;
  searchGoodEvent();
};

const changeDept = () => {
  GET_WarehouseList({ dept_id: GoodsTransferForm.value.out_dept_id });
  cleanGoodsList();
};

const cleanGoodsList = () => {
  GoodsTransferForm.value.product_list = [];
};

const GET_AdministratorList = () => {
  API_Auth.getAdministratorList({
    page_no: 1,
    page_size: 9999,
    user_state: 0,
  }).then((response) => {
    adminList.value = response.data;
  });
};

const roBack = () => {
  /* const { callback } = store.state.route.params;
  if (typeof callback === 'function') callback();
  store.dispatch('delCurrentViews', {
    view: store.state.route,
    $router: store.state.router,
  }); */
 router.push({ name: 'goodsUnderstock' });
};

const handleSelectWarehouseEntryBatch = async () => {
  if (!GoodsTransferForm.value.out_warehouse_id) {
    ElMessage.error(t('change')+t('out_warehouse')+'!');
    return;
  }
  API_GoodsExchange.getGoodsInfo(params, GoodsTransferForm.value.out_warehouse_id, 'gt').then((res) => {
    goodsData.value = res;
    goodsVisible.value = true;
  });
  /* const goodsData = await store.dispatch('EnwarehouseEntryBatch', {
    goodsApi: `/admin/erp/warehouseOut/getGoodByWarehouse/${GoodsTransferForm.value.out_warehouse_id}`,
    warehouseList: WarehouseList.value,
    selectedIds: id.value ? GoodsTransferForm.value.product_list.map((item: any) => item.id) : GoodsTransferForm.value.product_list.map((item: any) => item.id),
    purchasePlanApiParams: {
      warehouse_id: GoodsTransferForm.value.out_warehouse_id,
    },
  });
  GoodsTransferForm.value.out_warehouse_id = goodsData.warehouse_id;
  if (goodsData.purchasePlans && goodsData.purchasePlans.length) {
    GoodsTransferForm.value.product_list = goodsData.purchasePlans.map((item: any) => {
      item.warehouse_entry_batch_id = item.id;
      return item;
    });
  } */
};
const GoodsTransferFormRef = ref();
const submitGoodsTransferForm = () => {
  GoodsTransferFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const params = { ...GoodsTransferForm.value };
      if (params.product_list.length === 0) {
        ElMessage.error(t('change')+t('goods_info')+'!');
        return;
      }
      if (params.in_warehouse_id === params.out_warehouse_id) {
        ElMessage.error(t('out_warehouse')+t('to_warehouse')+t('consistent')+'！');
        return;
      }
      params.product_list = params.product_list.map((item: any) => ({
        num: item.num,
        goods_id: item.goods_id,
        usable_stock: Number(item.usable_stock),
        product_id: item.product_id,
        product_stock_id: item.id,
      }));
      if (id.value) {
        API_GoodsTransfer.editGoodsTransfer(id.value, params).then(() => {
            ElMessage.success(t('edit_success')+'!');
         /*  const { callback } = store.state.route.params;
          if (typeof callback === 'function') callback();
          store.dispatch('delCurrentViews', {
            view: store.state.route,
            $router: store.state.router,
          }); */
          router.push({ name: 'goodsUnderstock' });
        });
      } else {
        API_GoodsTransfer.addGoodsTransfer(params).then(() => {
            ElMessage.success(t('add_success')+'!');
          /* const { callback } = store.state.route.params;
          if (typeof callback === 'function') callback();
          store.dispatch('delCurrentViews', {
            view: store.state.route,
            $router: store.state.router,
          }); */
          router.push({ name: 'goodsUnderstock' });
        });
      }
    }
  });
};

const GET_DeptList = () => {
  API_Setting.getDeptList({page_no:1,page_size:1000}).then((response) => {
    deptList.value = response;
    deptListAll.value = response;
  });
};

const GET_WarehouseList = (value:any) => {
  API_BasicSetting.getWarehouseListAll().then((response) => {
    WarehouseList.value = response;
  });
};

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

const GET_GoodsTransferDetail = () => {
  API_GoodsTransfer.getGoodsTransferInfo(id.value).then((response) => {
    GoodsTransferForm.value = response;
  });
};

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

onMounted(() => {
 /*  if (store.state.route.name === 'goodsTransferAdd') {
    GoodsTransferForm.value.out_handled_by_id = user.value.uid;
    GoodsTransferForm.value.dept_id = user.value.dept_id;
  } else if (store.state.route.name === 'goodsUnderstockDetail') {
    id.value = store.state.route.params.id;
    type.value = 'detail';
  }
  if (store.state.route.params.id) {
    id.value = store.state.route.params.id;
    GET_GoodsTransferDetail();
  } */
 if(route.query.type==='view'){
    type.value=route.query.type
    id.value = route.query.id as string;
    GET_GoodsTransferDetail();
 }
  GET_DeptList();
  GET_DictDataInfo();
  GET_AdministratorList();
  GET_WarehouseList({ dept_id: user.value.dept_id });
  GET_ExpressList();
});
</script>
  
<style scoped>
.footer {
  width: 100%;
  padding: 10px;
  bottom: 0px;
  text-align: center;
  z-index: 999;
}

.mx {
  display: flex;
  align-items: center;
}

.mx .button {
  margin-left: 10px;
}

.bg-in-stock {
  background-color: #fff;
  margin: 10px;
  padding: 25px;
}

.goods-info {
  display: flex;
}

.goods-info .goods-name-box {
  text-align: left;
}

.goods-info .goods-name-box .goods-name {
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 16px;
}

.goods-info .goods-name-box .specs {
  color: #999999;
}

::v-deep .el-input--suffix .el-input__inner {
  padding-right: 10px;
}

::v-deep .error-input .el-input__inner {
  border: 1px solid red;
}

::v-deep .el-form-item {
  width: 350px;
}
</style>