<template>
  <div class="bg-in-stock">
    <el-form ref="goodsExchangeAddFormRef" :model="goodsExchangeAddForm" :rules="goodsExchangeAddFormRule" label-width="160px" inline class="change-form">
      <el-form-item prop="warehouse_id" label="出库仓库" class="change-form-item">
        <el-select v-model="goodsExchangeAddForm.warehouse_id" :disabled="type === 'view' || type === 'audit'">
          <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="类型" prop="type" class="change-form-item">
        <el-select v-model="goodsExchangeAddForm.type" filterable allow-create clearable default-first-option :disabled="type === 'view' || type === 'audit'">
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="item.value == 'SALE_OUT' || item.value == 'HAIL_OUT' || item.value == 'DAMAGE_OUT' || item.value == 'TRANSFER_OUT'"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="notes" class="change-form-item" style="width: 61%">
        <el-input
          style="flex: 1"
          v-model="goodsExchangeAddForm.notes"
          type="textarea"
          :disabled="type === 'view' || type === 'audit'"
          maxlength="250"
          :autosize="{ minRows: 3, maxRows: 4 }"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <div class="mx">
        <h3>商品明细</h3>
        <el-button class="button" size="mini" type="primary" v-if="type !== 'view' && type !== 'audit'" @click="scanCode">扫码出库</el-button>
        <el-button class="button" size="mini" type="primary" v-if="type !== 'view' && type !== 'audit'" @click="handleSelectWarehouseEntryBatch"
          >选择</el-button
        >
      </div>
      <div style="width: 100%; display: block">
        <el-form-item style="width: 100%">
          <el-table
            :data="goodsExchangeAddForm.product_list"
            border
            :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }"
            style="width: 100%; margin-top: 20px"
          >
            <el-table-column label="库位号">
              <template #default="scope">
                <el-popover placement="right" trigger="click" v-if="scope.row.area_stock_list">
                  <div>
                    <p v-for="item in scope.row.area_stock_list" :key="item.id">{{ item.warehouse_area_name }}</p>
                  </div>
                  <span slot="reference" v-if="scope.row.area_stock_list.length !== 0">{{ scope.row.area_stock_list[0].warehouse_area_name }}</span>
                </el-popover>
              </template>
            </el-table-column>
            <!-- <el-table-column label="商品编号">
              <template #default="scope">
                <span v-if="id">{{ scope.row.goods_vo.sn }}</span>
                <span v-else>{{ scope.row.goods_vo.sn }}</span>
              </template>
            </el-table-column> -->
            <el-table-column label="商品名称">
              <template #default="scope">
                <span v-if="id">{{ scope.row.product_vo.name }}</span>
                <span v-else>{{ scope.row.product_vo.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="sku">
              <template #default="scope">
                <span v-if="id">{{ scope.row.product_vo.sku }}</span>
                <span v-else>{{ scope.row.product_vo.sku }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column label="序列号" v-if="sn_code_list">
              <template #default="scope">
                <div class="sn-code-container">
                  <span v-for="item in scope.row.sn_code_list" :key="item.id">
                    <p>{{ item.sn_code }}</p>
                  </span>
                </div>
              </template>
            </el-table-column> 
            <el-table-column prop="product_vo.spec_name" label="规格型号" v-if="id"> </el-table-column>
            <el-table-column prop="product_vo.spec_name" label="规格型号" v-else> </el-table-column>-->
            <el-table-column label="单位">
              <template #default="scope">
                {{ scope.row.product_vo.unit }}
                <!--  <span v-if="id">{{ scope.row.product_vo.unit }}</span>
                <span v-else>{{ scope.row.product_vo.unit }}</span> -->
              </template>
            </el-table-column>
            <el-table-column label="出库数量">
              <template #default="scope">
                <el-input v-model="scope.row.out_num" type="number" :min="0" :maxlength="20" :disabled="type === 'view' || type === 'audit'"></el-input>
              </template>
            </el-table-column>
            <!-- <el-table-column label="订单数量">
              <template #default="scope">
                {{ scope.row.order_num }}
              </template>
            </el-table-column> -->
            <el-table-column label="可用库存">
              <template #default="scope">
                {{ scope.row.usable_stock }}
              </template>
            </el-table-column>
            <el-table-column label="实际库存">
              <template #default="scope">
                {{ scope.row.actual_stock }}
              </template>
            </el-table-column>
            <el-table-column width="200" label="操作" v-if="type !== 'view' && type !== 'audit'">
              <template #default="scope">
                <el-button size="mini" type="danger" @click="goodsExchangeAddForm.product_list.splice(scope.$index, 1)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>
    </el-form>
    <div class="footer">
      <el-button v-if="type !== 'audit' && type !== 'view' && checkPermission(['warehouseOut2:add'])" type="primary" @click="saveGoodsExchangeAddForm"
        >保存
      </el-button>
      <el-button v-if="type !== 'audit' && type !== 'view' && checkPermission(['warehouseOut:update'])" type="primary" @click="submitGoodsExchangeAddForm"
        >出库
      </el-button>
      <el-button @click="printIng" v-if="type == 'audit'">打印</el-button>
      <el-button @click="toBack()">返回</el-button>
    </div>

    <el-dialog title="提示" v-model:visible="dialogVisible" width="30%">
      <el-form ref="goodsExchangeAddForm" :model="goodsExchangeAddForm" label-width="120px" inline style="width: 900px">
        <el-form-item label="驳回原因" prop="reject_reason">
          <el-input v-model="goodsExchangeAddForm.reject_reason" type="textarea" :minlength="0" :maxlength="100"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRejectGoodsExchange()">确 定</el-button>
      </template>
    </el-dialog>
    <el-dialog title="扫码出库" v-model:visible="scanDialogVisible" width="30%" :close-on-click-modal="false">
      <el-form ref="scanGoodsForm" :model="scanGoodsForm" label-width="120px" inline>
        <el-form-item label="sku" prop="bar_code">
          <el-input v-model="scanGoodsForm.bar_code" ref="input" @keyup.enter="toSearch()" :minlength="0" :maxlength="100"></el-input>
        </el-form-item>
        <el-form-item label="序列号" prop="sn_code">
          <el-input v-model="sn_code" ref="sn_input" @keyup.enter="toSnCode()" :minlength="0" :maxlength="100"></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="出库商品" v-model="goodsVisible" width="1000px" @close="closeGoosData">
      <div style="display: flex; align-items: center; justify-content: flex-end; padding: 10px 0">
        <span>搜索商品:</span><el-input v-model="params.keyWord" style="width: 200px; margin-right: 5px"></el-input>
        <el-button @click="searchGoodEvent"> 搜索 </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="商品名称"></el-table-column>
        <el-table-column prop="product_vo.sku" label="sku"> </el-table-column>
        <el-table-column prop="" label="品牌">
          <template #default="scope">
            {{ scope.row.product_vo.brand }}
          </template>
        </el-table-column>
        <el-table-column prop="product_vo.weight" label="重量"> </el-table-column>
        <el-table-column prop="product_vo.unit" label="单位"> </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">取 消</el-button>
        <el-button type="primary" @click="submitGoosData()">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script setup>
import { ref, onMounted, computed, watch, reactive,nextTick } from 'vue';
import { useStore, mapGetters } from 'vuex';
import * as API_GoodsExchange from '@/api/goodsExchange';
import * as API_Setting from '@/api/setting';
import * as API_BasicSetting from '@/api/basicSetting';
import { useRoute, useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';

const route = useRoute();
const router = useRouter();
/* import * as API_Erp from '@/api/erp';
import * as API_Auth from '@/api/auth'; */

const store = useStore();
const goodsExchangeAddForm = ref({
  /*   order_list: [
    {
      order_id: '1752156400898293761',
      order_item_list: [
        {
          batch_list: [
            {
              batch_id: 0,
              batch_sn: '',
              out_num: 0,
              remain_num: 0,
              warehouse_entry_sn: '',
            },
          ],
          num: 0,
          order_item_id: 0,
          product_id: 0,
          product_name: 'string',
          product_sn: 'string',
          product_specification: 'string',
          product_unit: 'string',
        },
      ],
      order_sn: '',
    },
  ], */
  product_list: [],
  type: '',
});
const goodsExchangeAddFormRule = ref({
  warehouse_id: [{ required: true, message: '请选择出库仓库', trigger: 'change' }],
  type: [{ required: true, message: '请选择出库类型', trigger: 'change' }],
});
const typeList = ref([]);
const adminList = ref([]);
const dialogVisible = ref(false);
const warehouseList = ref([]);
const deptList = ref([]);
const deptListAll = ref([]);
const orderList = ref([]);
const id = ref('');
const type = ref('');
const warehouseProduct = ref(null);
const scanDialogVisible = ref(false);
const scanGoodsForm = ref({});
const routeName = ref('');
const sttorageType = ref('');
const goodsVisible = ref(false);
const goodsData = ref([]);
const snCodeVisible = ref(false);
const sn_code = ref('');
const sku = ref('');
const sn_code_list = ref([]);
const index = ref('');

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

const checkPrice = (rule, value, callback) => {
  if (!value && value !== 0) {
    return callback(new Error('换货金额不能为空'));
  } else if (!RegExp.money.test(value)) {
    callback(new Error('请输入正整数或者两位小数'));
  } else if (parseFloat(value) > 99999999) {
    callback(new Error('换货金额设置超过上限值'));
  } else {
    callback();
  }
};

const toBack = () => {
  router.push({
    name: 'goodsOutBound',
  });
};
/* 扫描sku */
const toSnCode = async () => {
  if (sku.value == '') return ElMessage.error('请录入正确的sku');
  await API_GoodsExchange.getSnCode('out', sku.value, sn_code.value.replace(/\s+/g, '')).then(async (res) => {
    sn_code.value = '';
    let exists = goodsExchangeAddForm.value.product_list[index.value].sn_code_list.find((item) => item.sn_code === res.sn_code && item.sku === res.sku);
    if (!exists) {
      if (id.value) {
        await API_GoodsExchange.skuRedis({
          send_order_id: id.value,
          item_id: goodsExchangeAddForm.value.product_list[index.value].id,
          sku: res,
        }).then((response) => {
          goodsExchangeAddForm.value.product_list[index.value].sn_code_list.push(res);
        });
      } else {
        goodsExchangeAddForm.value.product_list[index.value].sn_code_list.push(res);
      }
    }
    goodsExchangeAddForm.value.product_list[index.value].out_num = goodsExchangeAddForm.value.product_list[index.value].sn_code_list.length;
    scanGoodsForm.value.bar_code = '';
    nextTick(() => {
      refs.input.focus();
    });
  });
};

const addSnCode = (row, index) => {
  sku.value = row.product_vo.sku;
  index.value = index;
  snCodeVisible.value = true;
};

const outType = () => {
  API_Setting.getPage({ dictType: 'out_warehouse_type' }).then((res) => {
    typeList.value = res.data;
  });
};

const printIng = () => {};
/* 扫描序列号 */
const toSearch = () => {
  API_GoodsExchange.getProduct(goodsExchangeAddForm.value.warehouse_id, scanGoodsForm.value.bar_code.replace(/\s+/g, '')).then((res) => {
    res.sn_code_list = [];
    sku.value = res.product_vo.sku;
    const indexs = goodsExchangeAddForm.value.product_list.findIndex((el) => {
      return el.goods_id === res.goods_id && el.product_id === res.product_id && el.product_vo.sku === res.product_vo.sku;
    });
    if (indexs === -1) {
      index.value = goodsExchangeAddForm.value.product_list.length;
      goodsExchangeAddForm.value.product_list.push(res);
    } else {
      index.value = indexs;
    }
    if (res.product_vo.have_sn) {
      nextTick(() => {
        refs.sn_input.focus();
      });
    } else {
      goodsExchangeAddForm.value.product_list[index.value].num += 1;
    }
  });
};

const scanCode = () => {
  if (!goodsExchangeAddForm.value.warehouse_id) {
    ElMessage.error('请先选择仓库！');
    return;
  }
  scanDialogVisible.value = true;
  nextTick(() => {
    refs.input.focus();
  });
};

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

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

const goodsExchangeAddFormRef = ref();
const saveGoodsExchangeAddForm = () => {
  console.log(112);
  goodsExchangeAddFormRef.value.validate((valid) => {
    if (valid) {
      const { id } = goodsExchangeAddForm.value;
      const params = { ...goodsExchangeAddForm.value };
      params.save_or_submit = 'save';
      params.warehouse_consignee_id = deptListAll.value.id;
      params.out_time = Date.parse(new Date());
      params.staff_name = goodsExchangeAddForm.value.distribution_name;
      if (params.warehouse_id) {
        params.warehouse_name = warehouseList.value.find((ware) => ware.id === params.warehouse_id).name;
      }
      if (params.handled_by_id) {
        params.handled_by = adminList.value.find((admin) => admin.id === params.handled_by_id).real_name;
      }
      params.change_time = Math.floor(params.change_time / 1000);

      if (!goodsExchangeAddForm.value.product_list.length) {
        return;
      }
      if (params.type == 'OTHER_OUT' || params.type == 'BORROW_OUT') {
        const isStockSufficient = params.product_list.map((el) => {
          if (el.out_num > el.usable_stock) {
            ElMessage.error('该商品库存不足！');
            return false;
          }
          return true;
        });
        if (!isStockSufficient) {
          return;
        }
      }
      if (type.value == 'edit') {
        API_GoodsExchange.editWarehouseOut(id, params).then((response) => {
          ElMessage.success('修改成功！');
          /* const { callback } = this.$route.params;
          if (typeof callback === 'function') callback();
          store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router,
          }); */
          router.push({ name: 'goodsOutBound' });
        });
      } else {
        console.log(params);
        params.product_list.map((el) => {
          el.product_stock_id = el.id;
          el.id = '';
        });
        API_GoodsExchange.warehouseOut(params).then(() => {
          ElMessage.success('添加成功！');
          /* const { callback } = this.$route.params;
          if (typeof callback === 'function') callback();
          store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router,
          }); */
          router.push({ name: 'goodsOutBound' });
        });
      }
    }
  });
};

const submitGoodsExchangeAddForm = () => {
  goodsExchangeAddFormRef.value.validate((valid) => {
    if (valid) {
      const { id } = goodsExchangeAddForm.value;
      const params = { ...goodsExchangeAddForm.value };
      params.save_or_submit = 'submit';
      params.warehouse_consignee_id = deptListAll.value.id;
      params.out_time = Date.parse(new Date());
      params.staff_name = goodsExchangeAddForm.value.distribution_name;
      if (params.warehouse_id) {
        params.warehouse_name = warehouseList.value.find((ware) => ware.id === params.warehouse_id).name;
      }
      if (params.handled_by_id) {
        params.handled_by = adminList.value.find((admin) => admin.id === params.handled_by_id).real_name;
      }
      params.change_time = Math.floor(params.change_time / 1000);
      if (!goodsExchangeAddForm.value.product_list.length) {
        ElMessage.error('请选择商品！');
        return;
      }
      if (params.type == 'OTHER_OUT' || params.type == 'BORROW_OUT') {
        const isStockSufficient = params.product_list.map((el) => {
          if (el.out_num > el.usable_stock) {
            ElMessage.error('该商品库存不足！');
            return false;
          }
          return true;
        });
        if (!isStockSufficient) {
          return;
        }
      }
      if (type.value == 'edit') {
        API_GoodsExchange.editWarehouseOut(id, params).then((response) => {
          ElMessage.success('修改成功！');
          /* const { callback } = this.$route.params;
          if (typeof callback === 'function') callback();
          store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router,
          }); */
         router.push({ name: 'goodsOutBound' });
        });
      } else {
        params.product_list.map((el) => {
          el.product_stock_id = el.id;
          el.id = '';
        });
        API_GoodsExchange.warehouseOut(params).then(() => {
          ElMessage.success('添加成功！');
          /* const { callback } = this.$route.params;
          if (typeof callback === 'function') callback();
          store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router,
          }); */
          router.push({ name: 'goodsOutBound' });
        });
      }
    }
  });
};

/* 关闭入库窗口 */
const closeGoosData = () => {
  goodsVisible.value = false;
};

/* 打开商品弹窗 */
const params = reactive({
  page_no: 1,
  page_size: 10,
  keyWord: '',
});
const handleSelectWarehouseEntryBatch = async () => {
  if (!goodsExchangeAddForm.value.warehouse_id) {
    ElMessage.error('请先选择仓库！');
    return;
  }
  API_GoodsExchange.getGoodsInfo(params, goodsExchangeAddForm.value.warehouse_id, 'gt').then((res) => {
    goodsData.value = res;
    goodsVisible.value = true;
  });
};
/* 选中的商品列表 */
const goodsList = ref([]);
const handleSelectionChange = (val) => {
  goodsList.value = val.map((el) => {
    return el;
  });
};
const submitGoosData = () => {
  if (goodsList.value.length >= 1) {
    goodsExchangeAddForm.value.product_list = goodsList.value.map((el) => {
      return el;
    });
    goodsVisible.value = false;
  } else {
    ElMessage.error('请选择商品信息');
  }
};
const goodsPageSizeChange = (size) => {
  params.page_size = size;
  searchGoodEvent();
};

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

const handleSelectOrderSn = async () => {
  const orders = await this.$EnPickerOrder({
    orderApi: 'admin/erp/order',
    selectedIds: [goodsExchangeAddForm.value.order_sn],
    limit: 1,
  });
  this.$set(goodsExchangeAddForm.value, 'distribution_name', orders[0].distribution_name);
  const orderIds = orders.map((v) => v.sn);
  this.$set(goodsExchangeAddForm.value, 'order_sn', orderIds.join(','));
  GET_WarehouseOutProduct();
};

const GET_WarehouseOutProduct = async () => {
  const res = await API_Erp.getWarehouseOutProduct({
    order_sn: goodsExchangeAddForm.value.order_sn,
  });
  goodsExchangeAddForm.value.return_list = res.data.map((item) => {
    item.amount = item.product_price;
    item.product_sn = item.product_sn;
    item.product_name = item.product_name;
    item.specification = item.product_specification;
    item.product_id = item.product_id;
    item.unit = item.product_unit;
    item.out_num = item.return_num;
    item.stock_sn = item.warehouse_entry_sn;
    item.cost_price = item.product_cost_price;
    return item;
  });
};

const GET_DeptList = () => {
  API_GoodsExchange.getInfo().then((response) => {
    deptListAll.value = response;
    deptListAll.value.password = '';
  });
};

const handleChangeWareHouse = (val) => {
  // this.goodsExchangeAddForm.product_list = []change_list
};

const GET_goodsExchangeAddDetail = () => {
  nextTick(() => {
    API_GoodsExchange.getGoodsWarehouseOut(route.query.id).then((response) => {
      goodsExchangeAddForm.value = response;
      GET_WarehouseList({ dept_id: response.warehouse_id });
      goodsExchangeAddForm.value.change_time = Math.floor(goodsExchangeAddForm.value.change_time * 1000);
      /* response.product_list.map((el) => {
        el.order_num = el.out_num;
        el.out_num = 0;
        if (!el.sn_code_list) {
          el.sn_code_list = [];
        } else {
          el.out_num = el.sn_code_list;
        }
      }); */
      goodsExchangeAddForm.value.distribution_name = response.staff_name;
      goodsExchangeAddForm.value.product_list = response.product_list;
    });
  });
};

onMounted(() => {
  if (route.query.type == 'view') {
    type.value = 'view';
    GET_goodsExchangeAddDetail();
  } else if (route.query.type == 'edit') {
    type.value = 'edit';
    GET_goodsExchangeAddDetail();
  }
  routeName.value = route.name;
  sttorageType.value = route.params.type;
  GET_WarehouseList();
  GET_DeptList();
  outType();
});

/* watch(() => route, {
  immediate: true,
  handler(newVal) {
    if (route.name === 'goodsExchangeEdit') {
      type.value = 'edit';
    } else if (route.name === 'goodsExchangeAudit') {
      type.value = 'audit';
    } else if (route.name === 'goodsExchangeReturn') {
      type.value = 'return';
    } else if (route.name === 'goodsExchangeAdd') {
      type.value = 'add';
      GET_WarehouseList({ dept_id: user.value.dept_id });
      set(goodsExchangeAddForm.value, 'change_time', new Date().getTime());
    } else if (route.name === 'goodsExchangeDetail') {
      type.value = 'detail';
    }
    if (route.params.id) {
      id.value = route.params.id;
      GET_goodsExchangeAddDetail();
    }
    GET_AdministratorList();
  },
}); */
</script>

<style scoped>
.footer {
  width: 100%;
  padding: 10px;
  bottom: 0px;
  text-align: center;
  z-index: 999;
}

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

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

.change-form {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
  min-width: 900px;
}

.change-form .change-form-item {
  width: 30%;
  margin: 0 10px 20px 0;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
}

.change-form .el-form-item__content,
.change-form .el-date-editor,
.change-form .el-cascader,
.change-form .el-select {
  flex: 1;
  width: 100%;
}

.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;
}

.sn-code-container {
  max-height: 100px;
  overflow-y: auto;
}

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

.error-input .el-input__inner {
  border: 1px solid red;
}
</style>