<template>
  <basic-container>
    <div class="avue-crud">
      <el-row>
        <!-- 查询模块 -->
        <el-form
          :inline="true"
          ref="form"
          :model="form"
          label-width="120px"
          :rules="rules"
          :disabled="view"
        >
          <!-- 表单字段 -->
          <el-col :span="24">
            <el-form-item label="入库批次">
              <el-input v-model="form.receiptBatch" clearable placeholder="请输入入库批次" />
            </el-form-item>
            <el-form-item label="入库时间" prop="receiptDate">
              <!--              <el-input v-model="form.receiptDate" placeholder="请输入入库时间"/>-->
              <el-date-picker
                v-model="form.receiptDate"
                placeholder="请选择入库时间"
                type="datetime"
                clearable
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="客户名称" prop="clientId">
              <!--              <el-input v-model="form.customerName" placeholder="请输入客户名称"/>-->
              <el-select
                v-model="form.clientId"
                filterable
                remote
                reserve-keyword
                remote-show-suffix
                :remote-method="remoteMethod"
                :loading="loading"
                clearable
                @change="getMenDian($event, 1)"
                placeholder="请输入客户名称"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="客户编码" prop="customerCode">
              <!--              <el-input v-model="form.customerName" placeholder="请输入客户名称"/>-->
              <el-select
                v-model="form.customerCode"
                filterable
                remote
                reserve-keyword
                remote-show-suffix
                :remote-method="remoteCodeMethod"
                :loading="loading"
                @change="getMenDian($event, 2)"
                placeholder="请输入客户编码"
                clearable
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.code"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="门店名称">
              <!--              <el-input v-model="form.storeName" placeholder="请输入门店名称"/>-->
              <el-select
                v-model="form.storeId"
                filterable
                allow-create
                clearable
                default-first-option
                :reserve-keyword="false"
                @change="getMen($event, 1)"
                placeholder="请输入门店名称"
              >
                <el-option
                  v-for="item in shop"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="物流公司">
              <el-input v-model="form.logisticsCompany" clearable placeholder="请输入物流公司" />
            </el-form-item>
            <!--            <el-form-item label="物流单号" prop="trainNumber">-->
            <el-form-item label="物流运单号">
              <el-input v-model="form.trainNumber" clearable placeholder="请输入物流运单号" />
            </el-form-item>

            <!--            <el-form-item label="入库车牌" prop="licensePlate">-->
            <el-form-item label="入库车牌">
              <el-input v-model="form.licensePlate" clearable placeholder="请输入入库车牌" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="订单自编号" prop="orderNumber">
              <el-input v-model="form.orderNumber" clearable placeholder="请输入订单自编号" />
            </el-form-item>
            <!--            <el-form-item label="运单号" prop="waybillNumber ">-->
            <!--              <el-input v-model="form.waybillNumber " placeholder="请输入运单号"/>-->
            <!--            </el-form-item>-->

            <el-form-item label="所在仓库" prop="warehouseId">
              <!--              <el-input  placeholder="请输入所在仓库"/>-->
              <el-select
                v-model="form.warehouseId"
                filterable
                remote
                clearable
                reserve-keyword
                remote-show-suffix
                :remote-method="remoteWareHouse"
                @change="getMen($event, 2)"
                placeholder="请输入所在仓库"
              >
                <el-option
                  v-for="item in store"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :checked="store.length === 1"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="备注" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="服务类型" prop="serviceType">
              <el-radio-group
                v-model="form.serviceType"
                class="ml-4"
                v-for="(item, index) in distributionType"
              >
                <el-radio :label="item.dictKey" size="large" style="padding-right: 20px">{{
                  item.dictValue
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-row>
        <div class="avue-crud__header">
          <!-- 头部左侧按钮模块 -->
          <div class="avue-crud__left">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd" :disabled="view"
              >新 增</el-button
            >
            <!--            <el-button type="danger" icon="el-icon-delete" @click="handleDelete" plain>删 除</el-button>-->
          </div>
          <!-- 头部右侧按钮模块 -->
          <div class="avue-crud__right">
            <el-button
              icon="el-icon-refresh"
              @click="searchChange"
              circle
              :disabled="view"
            ></el-button>
            <!-- <el-button icon="el-icon-search" @click="searchHide" circle :disabled="view"></el-button> -->
          </div>
        </div>
      </el-row>
      <el-row>
        <!-- 列表模块 -->
        <el-table
          ref="table"
          v-loading="loading"
          @selection-change="selectionChange"
          :data="data"
          :height="height"
          style="width: 100%"
          :border="option.border"
        >
          <el-table-column
            type="selection"
            v-if="option.selection"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column type="expand" v-if="option.expand" align="center"></el-table-column>
          <el-table-column v-if="option.index" label="序号" type="index" width="80" align="center">
          </el-table-column>
          <template v-for="(item, index) in option.column">
            <!-- table字段 -->
            <el-table-column
              v-if="item.hide !== true"
              :prop="item.prop"
              :label="item.label"
              :width="item.width"
              :key="index"
            >
            </el-table-column>
          </template>
          <el-table-column
            prop="menu"
            label="实际入库数量"
            :width="150"
            align="center"
            v-if="this.$route.query.type == '3'"
          >
            <template #="{ row }">
              <el-input v-model="row.actualReceipt"></el-input>
            </template>
          </el-table-column>
          <!-- 操作栏模块 -->
          <el-table-column
            prop="menu"
            label="操作"
            :width="300"
            align="center"
            v-if="!view || this.$route.query.type != '3'"
          >
            <template #="{ row }">
              <!--              <el-button type="primary" text icon="el-icon-view" @click="handleView(row)">查看</el-button>-->
              <el-button
                type="primary"
                text
                icon="el-icon-edit"
                @click="handleEditOwn(row)"
                :disabled="typeView"
                >编辑</el-button
              >
              <el-button
                type="primary"
                text
                icon="el-icon-delete"
                @click="rowDelOwn(row)"
                :disabled="typeView"
                >删除</el-button
              >
              <!--              <el-button type="primary" text icon="el-icon-setting" @click="handleDrawer(row)">子表配置</el-button>-->
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <div
        style="line-height: 20px; text-align: center; padding-top: 10px"
        v-if="!typeView || this.$route.query.type == '3'"
      >
        <span class="dialog-footer">
          <el-button
            type="primary"
            icon="el-icon-circle-check"
            @click="handleSubmit"
            :disabled="view && !this.$route.query.type == '3'"
            v-if="this.$route.query.type"
            :loading="buttonLoadingList.handleSubmitBtn"
            >提 交</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-circle-check"
            @click="showCommitButton"
            :disabled="view && !this.$route.query.type == '3'"
            v-else-if="!hideButton"
            >提 交</el-button
          >
          <span v-else-if="hideButton">
            <el-button
              icon="el-icon-circle-check"
              :disabled="buttonLoadingList.handleHirectStorageBtn"
              :loading="buttonLoadingList.handleSubmitBtn"
              @click="handleSubmit"
            >
              预约入库
            </el-button>
            <el-button
              icon="el-icon-circle-check"
              :disabled="buttonLoadingList.handleSubmitBtn"
              :loading="buttonLoadingList.handleHirectStorageBtn"
              @click="handleHirectStorage"
            >
              直接入库
            </el-button>
          </span>
          <!-- <el-button icon="el-icon-circle-close" @click="box = false">取 消</el-button> -->
        </span>
      </div>

      <!--      <el-row>-->
      <!--        <div class="avue-crud__pagination" style="width:100%">-->
      <!--          &lt;!&ndash; 分页模块 &ndash;&gt;-->
      <!--          <el-pagination align="right"-->
      <!--                         background-->
      <!--                         @size-change="sizeChange"-->
      <!--                         @current-change="currentChange"-->
      <!--                         :current-page="page.currentPage"-->
      <!--                         :page-sizes="[30, 50,80, 120]"-->
      <!--                         :page-size="page.pageSize"-->
      <!--                         layout="total, sizes, prev, pager, next, jumper"-->
      <!--                         :total="page.total">-->
      <!--          </el-pagination>-->
      <!--        </div>-->
      <!--      </el-row>-->
      <!-- 表单模块 -->
      <el-dialog
        :title="title"
        v-model="box"
        width="50%"
        :before-close="beforeClose"
        :show-close="false"
        append-to-body
      >
        <el-form
          :disabled="view"
          ref="formDetail"
          :model="formDetail"
          label-width="80px"
          :rules="rules"
        >
          <!-- 表单字段 -->
          <el-form-item label="SKU" prop="sku">
            <el-input v-model="formDetail.sku" placeholder="请输入SKU" />
          </el-form-item>
          <el-form-item label="物品名称" prop="productName">
            <!--            <el-input v-model="formDetail.productName" placeholder="请输入物品名称"/>-->
            <el-select
              v-model="formDetail.productName"
              filterable
              remote
              reserve-keyword
              remote-show-suffix
              :remote-method="remoteMethodStuffName"
              @change="getMenDianName($event, 1)"
              placeholder="请输入物品名称"
            >
              <el-option
                v-for="item in stuffName"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="物品编码" prop="productCode">
            <!--            <el-input v-model="formDetail.productCode" placeholder="请输入物品编码"/>-->
            <el-select
              v-model="formDetail.productCode"
              filterable
              remote
              reserve-keyword
              remote-show-suffix
              :remote-method="remoteMethodStuffCode"
              @change="getMenDianName($event, 2)"
              placeholder="请输入物品编码"
            >
              <el-option
                v-for="item in stuffCode"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="物品单位" prop="productUnit">
            <!--            <el-input v-model="formDetail.productUnit" placeholder="请输入物品单位"/>-->
            <el-select
              v-model="formDetail.productUnit"
              filterable
              remote
              reserve-keyword
              remote-show-suffix
              placeholder="请输入物品单位"
            >
              <el-option
                v-for="item in distributionUnit"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="包装数量" prop="packagingNumber">
            <el-input v-model="formDetail.packagingNumber" placeholder="请输入包装数量" />
          </el-form-item>
          <el-form-item label="包装规格">
            <el-input v-model="formDetail.packagingSpecifications" placeholder="请输入包装规格" />
          </el-form-item>
          <el-form-item label="产品品牌" prop="brandId">
            <!--            <el-input v-model="formDetail.actualReceipt" placeholder="请选择物资品牌"/>-->
            <el-select
              v-model="formDetail.brandId"
              filterable
              remote
              reserve-keyword
              remote-show-suffix
              :remote-method="getBrandName"
              @change="getBanerqd($event)"
              placeholder="请输入产品品牌"
            >
              <el-option
                v-for="item in brandList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="入库数量" prop="createInventory">
            <el-input v-model="formDetail.createInventory" placeholder="请输入创建入库数量" />
          </el-form-item>

          <!--          <el-form-item label="入库单ID" prop="warehousingEntryId">-->
          <!--            <el-input v-model="formDetail.warehousingEntryId" placeholder="请输入入库单ID"/>-->
          <!--          </el-form-item>-->
        </el-form>
        <!-- 表单按钮 -->
        <template #footer>
          <span v-if="!view" class="dialog-footer">
            <el-button type="primary" icon="el-icon-circle-check" @click="handleDetail"
              >确定</el-button
            >
            <el-button icon="el-icon-circle-close" @click="box = false">取 消</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </basic-container>
</template>

<script>
import {
  getDetail,
  add,
  update,
  remove,
  getWarehouseDetail,
  getList,
} from '@/api/warehouse/warehouseWarehousingEntry';
import option from '@/option/warehouse/warehouseWarehousingDetail';
import { mapGetters, mapMutations } from 'vuex';
import { getDictionaryBiz } from '@/api/system/dict';
import { getListClient } from '@/api/basicdata/basicClient';
import { getListMaterial } from '@/api/basic/basicMaterial';
import { getDetailWarehouse, getListCopy } from '@/api/basicdata/basicdataWarehouse';
import { getListIdsName } from '@/api/basicdata/basicdataStoreBrand';
import { getListName } from '@/api/basicdata/basicdataStoreBusiness';
import { ElMessage, ElMessageBox } from 'element-plus';
export default {
  name: 'warehouseWarehouseingAddReceipt',
  data() {
    return {
      height: 0,
      distributionType: [],
      distributionUnit: [],
      distributionBrand: [],
      // 主键
      warehouseWarehousingEntryId: '',
      // 弹框标题
      title: '',
      // 是否展示弹框
      box: false,
      // 是否展示抽屉
      drawer: false,
      // 抽屉方向
      direction: 'rtl',
      // 是否显示查询
      search: true,
      // 加载中
      loading: false,
      // 是否为查看模式
      view: false,
      typeView: false,
      // 按钮隐藏
      hideButton: false,
      // 查询信息
      query: {},
      // 分页信息
      page: {
        currentPage: 1,
        pageSize: 30,
        total: 40,
      },
      // 表单数据
      form: {
      },
      formDetail: {},
      // 选择行
      selectionList: [],
      // 表单配置
      option: option,
      // 表单列表
      data: [],
      store: [], //仓库
      stuffName: [], //物品名称
      stuffCode: [], //物品编码
      stuff: [], //物品集合
      brandList: [], //品牌集合
      shop: [], //门店
      options: [], //客户
      optionCodes: [], //客户编号
      rules: {
        sku: [
          { requirwarehouseIded: true, message: '请输入SKU', trigger: 'blur' },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '请输入物品名称', trigger: 'blur' },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        productCode: [{ required: true, message: '请输入物品编码', trigger: 'change' }],
        packagingNumber: [
          { required: true, message: '请输入包装数量', trigger: 'change' },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        packagingSpecifications: [{ required: true, message: '请输入包装规格', trigger: 'change' }],
        createInventory: [{ required: true, message: '请输入入库数量', trigger: 'change' }],
        productUnit: [{ required: true, message: '请选择物品单位', trigger: 'change' }],
        brandId: [{ required: true, message: '请选择品牌', trigger: 'change' }],

        receiptBatch: [{ required: true, message: '请填写入库批次', trigger: 'blur' }],
        receiptDate: [
          { type: 'date', required: true, message: '请选择入库时间', trigger: 'change' },
        ],
        clientId: [{ required: true, message: '请填写客户名称', trigger: 'blur' }],
        storeId: [{ required: true, message: '请填写门店名称', trigger: 'blur' }],
        trainNumber: [{ required: true, message: '请填写物流单号', trigger: 'blur' }],
        licensePlate: [{ required: true, message: '请填写入库车牌', trigger: 'change' }],
        warehouseId: [{ required: true, message: '请选择所在仓库', trigger: 'blur' }],
        orderNumber: [{ required: true, message: '请输入订单自编号', trigger: 'blur' }],
        // serviceType: [{ required: true, message: '请选择服务类型', trigger: 'blur' }],
        customerCode: [{ required: true, message: '请选择客户编码', trigger: 'blur' }],
      },
      buttonLoadingList: {
        handleSubmitBtn: false,
        handleHirectStorageBtn: false,
      },
    };
  },
  mounted() {
    this.init();
    this.onLoad(this.page);
  },
  watch: {
    '$route.query.id': {
      handler(newVal, oldVal) {
        console.log(newVal, oldVal);
        console.log('$route.query.id', this.$route.query.type);
        this.selectionClear();
        this.getOwnDeliver();
      },
      deep: true,
      immediate: true,
    },
    //     'form.clientId': {
    //       handler(newVal) {
    //         console.log("newVal>>>>>>>>>>>>>>>",newVal)
    //         console.log("this.options>>>>>>>>>>>>>>>",this.options)
    //       },
    // }
  },

  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    ...mapMutations('tags', ['DEL_TAG']),
    //物品名称回显
    async getBanerqd(row) {
      let a = this.brandList.find(i => i.value == row);
      console.log('aA', a);
      this.formDetail.brandName = a.label;
    },

    //查询详情信息
    async getOwnDeliver() {
      let a = this.$route.query.id;
      let ty = this.$route.query.type;
      if (!!a) {
        this.loading = true;
        this.stuffCode = [];
        this.stuffName = [];
        this.store = [];

        let b = await getWarehouseDetail(a);
        // 新增回显功能，如果当前参数没用值就用预计入库数量显示
        b.data.data.list.forEach(item => {
          if (!item.actualReceipt) {
            item.actualReceipt = item.createInventory;
          }
        });
        console.log('bbbb>>>>', b.data.data);
        const da = b.data.data;
        console.log(b, '接收到的值');

        this.options.push({
          label: da.customerName,
          code: da.customerCode,
          value: da.clientId,
        });
        this.optionCodes.push({
          label: da.customerCode,
          value: da.clientId,
        });

        if (!!da.storeId && da.storeId != '-1') {
          console.log('门店》》》》');
          this.shop.push({
            label: da.storeName,
            value: da.storeId,
          });
        }

        if (this.store.length < 1) {
          this.store.push({
            label: !!da.warehouse ? da.warehouse : null,
            value: !!da.warehouseId ? da.warehouseId : null,
          });
        }
        this.form = da;
        console.log('da :>> ', da);
        // console.log(">>>>>>",this.form.storeId);
        if (!!this.form.storeId && parseInt(this.form.storeId) == -1) {
          console.log('>>>>>>', this.form.storeId);
          this.form.storeId = null;
        }
        this.data = da.list;
        this.loading = false;
        if (!!ty && ty == '2') {
          this.view = false;
        } else {
          this.typeView = true;
          this.view = true;
        }
      } else {
        this.view = false;
        this.loading = false;
        this.typeView = false;
      }
    },
    //物品名称
    async remoteMethodStuffName(query) {
      if (query) {
        this.stuff = [];
        this.stuffName = [];
        let cl = await getListMaterial(this.page.currentPage, this.page.pageSize, { name: query });
        console.log('物品名称', cl.data.data.records);
        cl.data.data.records.forEach(i => {
          let st = {
            label: i.name,
            value: i.id,
          };
          this.stuffName.push(st);
        });
        this.stuff = cl.data.data.records;
      } else {
        this.stuffName = [];
      }
    },
    //物品名称回显
    async getMenDianName(row, ty) {
      // console.log("值阿德飒飒的",row);
      this.formDetail.materialId = row;
      this.stuff.some(i => {
        if (ty == 1) {
          if (i.id == row) {
            console.log('111', i);
            //名称
            this.formDetail.sku = i.sku;
            this.formDetail.productUnit = i.logpmUnit;
            this.formDetail.packagingNumber = i.packageNum;
            if (!!i.extent) {
              this.formDetail.packagingSpecifications =
                i.extent + '长' + i.breadth + '宽' + i.altitude + '高';
            }
            let st = {
              label: i.productCode,
              value: i.id,
            };
            this.stuffCode.push(st);
            this.formDetail.productCode = i.id;
            return;
          }
        } else {
          if (i.id == row) {
            //编码
            this.formDetail.sku = i.sku;
            this.formDetail.productUnit = i.logpmUnit;
            this.formDetail.packagingNumber = i.packingSpecification;
            if (!!i.extent) {
              this.formDetail.packagingSpecifications =
                i.extent + '长' + i.breadth + '宽' + i.altitude + '高';
            }
            let st = {
              label: i.name,
              value: i.id,
            };
            this.stuffName.push(st);
            this.formDetail.productName = i.id;
            return;
          }
        }
      });
    },
    //物品编码
    async remoteMethodStuffCode(query) {
      if (query) {
        let cl = await getListMaterial(this.page.currentPage, this.page.pageSize, {
          productCode: query,
        });
        // console.log(">>>>",cl.data.data.records);
        cl.data.data.records.forEach(i => {
          let st = {
            label: i.productCode,
            value: i.id,
          };
          this.stuffCode.push(st);
        });
        this.stuff = cl.data.data.records;
      } else {
        this.stuffCode = [];
      }
    },
    //查询品牌信息
    async getBrandName(query) {
      if (query) {
        console.log('客户ID', this.form.clientId);
        if (!!this.form.clientId) {
          this.brandList = [];
          let si = !!this.form.storeId ? this.form.storeId : this.form.clientId;
          let cl = await getListIdsName(this.page.currentPage, this.page.pageSize, {
            brandName: query,
            ids: si,
            type: !!this.form.storeId ? 2 : 1,
          });
          console.log('>>>>', cl.data.data);
          cl.data.data.forEach(i => {
            let st = {
              label: i.brandName,
              value: i.id,
            };
            this.brandList.push(st);
          });
        } else {
          this.$message.warning('请先填写客户信息，在选择品牌！！');
        }
      } else {
        this.brandList = [];
      }
    },
    //门店查询
    async getMen(row, type) {
      if (type == 1) {
        this.shop.some(i => {
          if (i.value == row) {
            this.form.storeName = i.label;
            return;
          }
        });
      } else if (type == 2) {
        this.store.some(i => {
          if (i.value == row) {
            this.form.warehouse = i.label;
            return;
          }
        });
      }
    },
    //门店查询
    async getMenDian(row, num) {
      // console.log("值阿德飒飒的",row);
      if (num == 1) {
        const obj = this.options.find(item => item.value === row);
        console.log('obj>>>>>>>>>>>', obj);
        this.options = [
          {
            key: obj.value,
            value: obj.value,
            label: obj.label,
            code: obj.code,
          },
        ];
        this.form.customerCode = obj.code;
      } else {
        const obj = this.options.find(item => item.value === row);
        console.log('obj>>>>>>>>>>>', obj);
        this.options = [
          {
            key: obj.value,
            value: obj.value,
            label: obj.label,
            code: obj.code,
          },
        ];
        this.form.clientId = obj.value;
      }
      // this.form.serviceType = null;
      let aa = '';
      this.options.some(i => {
        // console.log(">><><><<>",i);
        if (i.value == row) {
          this.form.customerName = i.label;
          this.form.clientCode = i.code;
          //查询客户服务类型
          aa = i.value;
        }
      });
      let bu = await getListName(this.page.currentPage, this.page.pageSize, {
        clientId: aa,
        typeService: '3',
      });
      // console.log("bububu",bu.data.data.records);
      // if (bu.data.data?.records.length > 0) {
      //   this.form.serviceType = bu.data.data.records[0].mold;
      // }
      let cl = await getListClient(this.page.currentPage, this.page.pageSize, { pid: row });
      // console.log(">>>>",cl.data.data.records);
      this.shop = [];
      cl.data.data.records.forEach(i => {
        let st = {
          label: i.clientName,
          value: i.id,
        };
        this.shop.push(st);
      });
    },
    //仓库查询
    async remoteWareHouse(query) {
      if (query) {
        // this.loading = true;
        let cl = await getListCopy(this.page.currentPage, this.page.pageSize, { name: query });
        console.log('仓库查询>>>>', cl.data.data.records);
        this.store = [];
        cl.data.data.records.forEach(i => {
          let st = {
            label: i.name,
            value: i.id,
          };
          this.store.push(st);
        });
        // 当仓库数据只有一条时, 直接数据回显
        if (this.store.length === 1) {
          this.form.warehouseId = this.store[0].value;
        }
        // setTimeout(() => {
        //   this.loading = false
        //   this.loading = this.list.filter((item) => {
        //     return item.label.toLowerCase().includes(query.toLowerCase())
        //   })
        // }, 200)
      } else {
        if (this.store.length === 0) {
          this.store = [];
        }
      }
    },
    //客户查询
    async remoteMethod(query) {
      if (query) {
        // this.loading = true;
        this.options = [];
        this.form.customerCode = null;
        let cl = await getListClient(this.page.currentPage, this.page.pageSize, {
          clientName: query,
        });
        console.log('客户信息1234>>>>', cl.data.data.records);
        cl.data.data.records.forEach(i => {
          let st = {
            label: i.clientName,
            value: i.id,
            code: i.clientCode,
          };
          this.options.push(st);
        });
        // setTimeout(() => {
        //   this.loading = false
        //   this.loading = this.list.filter((item) => {
        //     return item.label.toLowerCase().includes(query.toLowerCase())
        //   })
        // }, 200)
      } else {
        this.options = [];
      }
    },
    //客户编号
    async remoteCodeMethod(query) {
      if (query) {
        // this.loading = true;
        this.options = [];
        this.form.clientId = null;
        let cl = await getListClient(this.page.currentPage, this.page.pageSize, {
          clientCode: query,
        });
        console.log('客户信息1234>>>>', cl.data.data.records);
        cl.data.data.records.forEach(i => {
          let st = {
            label: i.clientName,
            value: i.id,
            code: i.clientCode,
          };
          this.options.push(st);
        });
        // setTimeout(() => {
        //   this.loading = false
        //   this.loading = this.list.filter((item) => {
        //     return item.label.toLowerCase().includes(query.toLowerCase())
        //   })
        // }, 200)
      } else {
        this.options = [];
      }
    },
    handleEditOwn(row) {
      this.title = '编辑';
      this.box = true;
      this.formDetail = row;
    },
    //数据回显
    handleDetail() {
      this.$refs.formDetail.validate(valid => {
        if (valid) {
          ElMessageBox.confirm(`是否确认入库${this.formDetail.createInventory}件`, '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              console.log(this.formDetail);
              this.stuff.some(i => {
                console.log(i);
                if (i.id == this.formDetail.productName) {
                  this.formDetail.productName = i.name;
                }
                if (i.id == this.formDetail.productCode) {
                  this.formDetail.productCode = i.productCode;
                }
              });
              this.distributionUnit.some(p => {
                if (p.dictKey == this.formDetail.productUnit) {
                  this.formDetail.productUnit = p.dictValue;
                  return;
                }
              });
              if (this.data.length > 0) {
                console.log(
                  '当前在这里=-================================================================'
                );
                if (!!this.formDetail.createInventory) {
                  let s = false;
                  this.data.some(i => {
                    if (i.productCode === this.formDetail.productCode) {
                      s = true;
                      if (this.title != '编辑') {
                        i.createInventory =
                          parseInt(i.createInventory) + parseInt(this.formDetail.createInventory);
                        i.actualReceipt = 0;
                      }
                    }
                  });
                  if (!s) {
                    this.formDetail.actualReceipt = 0;
                    this.data.push(this.formDetail);
                  }
                } else {
                  this.$message.warning('请填写入库数量');
                }
              } else {
                this.formDetail.actualReceipt = 0;
                this.data.push(this.formDetail);
              }
              this.box = false;
              this.formDetail = {};
            })
            .catch(() => {
              this.formDetail.createInventory = 0;
            });
        }
      });
    },
    init() {
      this.height = this.setPx(document.body.clientHeight - 545);
      getDictionaryBiz('distribution_type').then(res => {
        // console.log("...",res.data.data);
        this.distributionType = [];
        this.distributionType=  res.data.data.map(item=>{
        if(item.dictKey=='2'){
          console.log(item,'item==???/');
          return item
        }
       })
       this.form.serviceType='2'
        // this.distributionType
      });
      getDictionaryBiz('logpm_unit').then(res => {
        // console.log("...",res.data.data);
        this.distributionUnit = [];
        this.distributionUnit = res.data.data;
      });
    },
    searchHide() {
      this.search = !this.search;
    },
    searchChange() {
      // 当是新增入库时
      if (!this.$route.query.type) {
        // 清空外部表单
        this.form = {};
      }
      // 清空弹出框表单
      this.formDetail = {};
      // 重新加载列表数据
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    showCommitButton() {
      this.hideButton = true;
    },
    handleSubmit() {
      this.$refs.form.validate(async valid => {
        try {
          // 开启防抖
          this.buttonLoadingList.handleSubmitBtn = true;
          if (valid) {
            if (!this.form.id) {
              console.log('this.form111', this.form);
              if (this.data.length > 0) {
                this.form.list = this.data;
                // 预约入库类型为1
                this.form.type = '1';
                await add(this.form);
                this.box = false;
                this.onLoad(this.page);
                this.$message({
                  type: 'success',
                  message: '操作成功!',
                });
                this.form = {};
                this.data = [];
              } else {
                this.$message.warning('请添加物资详情！！！');
              }
            } else {
              console.log('this.form222', this.form);
              if (!!this.form.totalInput && parseInt(this.form.totalInput) == '-1') {
                this.form.totalInput = null;
              }
              this.form.type = '1';
              this.form.list = this.data;
              await update(this.form);
              this.box = false;
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!',
              });
              // 操作完成后关闭本页标签
              this.$store.commit('DEL_TAG', this.$store.state.tags.tag);
              // 操作完成后返回入库列表页面
              this.$router.push('/warehouse/warehousingentry/warehouseWarehousingEntry');
            }
          }
        } catch (error) {
        } finally {
          // 关闭防抖
          this.buttonLoadingList.handleSubmitBtn = false;
        }
      });
    },
    // 直接入库
    handleHirectStorage() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.form.id) {
            console.log('this.form111', this.form);
            if (this.data.length > 0) {
              this.form.list = this.data;
              // 直接入库类型为2
              this.form.type = '2';
              add(this.form).then(() => {
                this.box = false;
                this.onLoad(this.page);
                this.$message({
                  type: 'success',
                  message: '操作成功!',
                });
              });
              this.form = {};
              this.data = [];
              // 操作完成后关闭本页标签
              this.$store.commit('DEL_TAG', this.$store.state.tags.tag);
              // 操作完成后返回入库列表页面
              this.$router.push('/warehouse/warehousingentry/warehouseWarehousingEntry');
            } else {
              this.$message.warning('请添加物资详情！！！');
            }
          }
        }
      });
    },
    handleAdd() {
      this.title = '新增';
      // this.form = {}
      this.box = true;
      //查询品牌
      this.getBingPai();
    },
    async getBingPai() {
      console.log('客户ID', this.form.clientId);
      this.brandList = [];
      if (!!this.form.clientId) {
        let si = !!this.form.storeId ? this.form.storeId : this.form.clientId;
        let cl = await getListIdsName(this.page.currentPage, this.page.pageSize, {
          ids: si,
          type: !!this.form.storeId ? 2 : 1,
        });
        console.log('>>>>', cl.data.data);
        cl.data.data.forEach(i => {
          let st = {
            label: i.brandName,
            value: i.id,
          };
          this.brandList.push(st);
        });
      } else {
        this.$message.warning('请先填写客户信息，产品品牌信息才能带出！！');
      }
    },
    handleEdit(row) {
      this.title = '编辑';
      this.box = true;
      getDetail(row.id).then(res => {
        this.form = res.data.data;
      });
    },
    handleView(row) {
      this.title = '查看';
      this.view = true;
      this.box = true;
      getDetail(row.id).then(res => {
        this.form = res.data.data;
      });
    },
    handleDrawer(row) {
      this.warehouseWarehousingEntryId = row.id;
      this.drawer = true;
    },
    handleDrawerClose() {
      this.warehouseWarehousingEntryId = '';
      this.drawer = false;
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.selectionClear();
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    rowDelOwn(row) {
      console.log('>>>>', row);
      let a = this.data.findIndex(i => {
        if (i.productCode === row.productCode) {
          return true;
        }
      });
      this.data.splice(a, 1);
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    beforeClose(done) {
      // done();
      // this.view = false;
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.form = {};
      this.data = [];
      this.options = [];
      // this.$refs.table.clearSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      // this.loading = true;
      //查询仓库
      this.getWareHoust(page, (params = {}));
      //查询客户
      // this.getChile(page,params = {});
    },
    /* async getChile(page, params = {}){
     let cl = await getListClient(page.currentPage, page.pageSize,{clientName:});
      console.log(">>>>",cl.data.data);


    },*/
    /**
     * 查询仓库信息
     * @param page
     * @param params
     * @returns {Promise<void>}
     */
    async getWareHoust(page, params = {}) {
      let sl = {};
      let li = await getDetailWarehouse(sl);
      console.log('li>>>>', li.data.data);
      this.store = [];
      li.data.data.forEach(i => {
        let st = {
          label: i.name,
          value: i.id,
        };
        this.store.push(st);
        // 如果仓库只有一条数据时, 直接回显
        if (this.store.length === 1) {
          console.log('this.store.length :>> ', [...this.store]);
          this.form.warehouseId = this.store[0].value;
        }
      });

      /*    if(b.data.data.deptCategory == "4"){
        //部门
        let li = await getListCopy(page.currentPage, page.pageSize,{department: b.data.data.id});
        console.log("li>>>>",li.data.data);
        li.data.data.some( i =>{
          let st= {
            label: b.data.data.deptName,
            value: b.data.data.id
          }
          this.store.push(st);
        })
        this.form.warehouseId = b.data.data.id;
      }else{
        //查询全部仓库

        let li = await getListCopy(page.currentPage, page.pageSize,{});
        console.log("li>>>>",li.data.data);
        this.store = [];
        li.data.data.records.forEach(i =>{
          let st= {
            label: i.name,
            value: i.id
          }
          this.store.push(st);
        });
      }*/
    },
    // 获取列表数据
    async getListData(data) {
      data.currentPage = data.currentPage || 1; // 当前页码, 默认为1
      data.pageSize = data.pageSize || 10; // 当前页数, 默认为10
      const res = await getList(data.currentPage, data.pageSize, { conditions: data.conditions });
      // 抛出数据
      return res;
    },
  },
};
</script>

<style scoped lang="scss">
.avue-crud {
  :deep(.el-input__wrapper) {
    // element-plus输入框高度为内容的高度
    height: fit-content;
    width: 300px;
  }

  :deep(.el-select .el-input__inner) {
    height: auto !important;
  }

  :deep(.el-textarea__inner) {
    width: 320px;
  }
}

.avue-crud {
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: auto !important;
    height: auto !important;
  }
}

:deep(.el-form--inline .el-form-item) {
  width: 25vw;
  min-width: 20vw;
}
</style>
