<template>
  <div>
    <el-card style="margin: 5px;margin-top: -20px">
      <el-form :model="formData" ref="dataForm" label-width="100px" style="margin-bottom: -15px;margin-bottom: -1px">
        <el-button-group style="display: flex;margin: 0px 0 1px 70%; height: 35px">
          <el-button
            type="primary"
            @click.native="saveOrder()"
            :loading="saveLoading"
          >草稿保存
          </el-button>
          <el-button
            type="primary"
            @click.native="submitAudit()"
            :loading="submitLoading"
          >提交审核
          </el-button>
        </el-button-group>

        <el-row>
          <el-col :span="10">
            <el-form-item class="query-form-item" label="盘点单号:">
              <el-input v-model="formData.orderId"
                        auto-complete="off"
                        :disabled="true"
                        style="width: 90%"
                        clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item class="query-form-item" label="盘点日期:">
              <el-input v-model="formData.createTime"
                        auto-complete="off"
                        :disabled="true"
                        style="width: 90%"
                        clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item class="query-form-item" label="盘点仓库:">
              <el-select v-model="formData.invStorageCode" placeholder="盘点仓库信息"
                         :disabled="countProductList.length >0 "
                         @change="invChange"
                         style="width: 90%"
                         clearable>
                <el-option
                  v-for="item in invList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.code">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item class="query-form-item" label="盘点货位:">
              <el-select v-model="formData.invWarehouseCode" placeholder="盘点货位信息"
                         :disabled="countProductList.length >0 || this.countType == 0"
                         @change="invSpaceChange"
                         style="width: 90%;"
                         clearable>
                <el-option
                  v-for="item in spaceList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.code">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.parentName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item class="query-form-item" label="盘点方式:">
              <el-select v-model="formData.codeCount" style="width: 90%" placeholder="请选择盘点方式"
                         :disabled="countProductList.length >0 ">
                <el-option label="手动盘点" :value="1"></el-option>
                <el-option label="扫码盘点" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="formData.codeCount == 2">
          <el-col :span="18">
            <el-form-item class="query-form-item" label="扫码录入:">
              <el-input
                id="inputer"
                @focus="getInputFocus($event)"
                @keypress.enter.native="enterKey($event)"
                ref='inputRef'
                style="ime-mode:disabled"
                type="tel"
                v-model="formData.code"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button
              type="primary"
              style="margin-top: 8px"
              size="mini"
              @click.native.stop="addCode()"
            >添加
            </el-button>
          </el-col>
        </el-row>


      </el-form>
    </el-card>

    <!--    :disabled="this.countProductList.length > 0"-->
    <el-tabs type="border-card" style="margin: 5px">

      <el-tab-pane label="盘点详情">
        <el-button-group style="display: flex;margin: 0px 0 10px 85%; ">
          <el-button
            v-if="countType != 2"
            type="primary"
            size="mini"

            @click.native="startCount(1)"
          >录入产品
          </el-button>
          <el-button
            v-if="countType == 2"
            type="primary" size="mini"
            @click.native="startCount()"
          >录入产品
          </el-button>
        </el-button-group>
        <el-table v-loading="loading" :data="countProductList" style="width: 100%;"
                  highlight-current-row
                  border max-height="300" height="300">
          <el-table-column label="序号" type="index" width="50"></el-table-column>
          <el-table-column width="160" label="物资名称" prop="productName" show-overflow-tooltip></el-table-column>
          <el-table-column width="160" label="DI/物资编码" prop="nameCode" show-overflow-tooltip></el-table-column>
          <el-table-column width="160" label="规格型号" prop="ggxh" show-overflow-tooltip></el-table-column>
          <el-table-column width="120" label="批次号" prop="batchNo"></el-table-column>
          <el-table-column width="100" label="库存数量" prop="invNum"></el-table-column>
          <el-table-column width="100" label="盘点数量" prop="countNum">

            <template slot-scope="scope" v-if="formData.codeCount == 1">
              <el-input v-model="scope.row.countNum"
                        :disabled="scope.row.id !== selectedIndex"
                        ref='inputBatchNoRef'
                        placeholder="请输入盘点数量"></el-input>
            </template>

          </el-table-column>
          <el-table-column label="生产日期" width="120" prop="produceDate"></el-table-column>
          <el-table-column label="失效日期" width="120" prop="expireDate" show-overflow-tooltip></el-table-column>
          <el-table-column label="生产企业" width="180" prop="ylqxzcrbarmc" show-overflow-tooltip></el-table-column>
          <el-table-column label="注册/备案凭证号" width="180" prop="zczbhhzbapzbh" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" fixed="right" width="120">
            <template slot-scope="scope">
              <el-button type="text" size="small" v-if="scope.row.id == selectedIndex" @click.stop="true"
                         @click.native="saveChange(scope.row)">保存
              </el-button>

              <el-button
                type="text"
                size="small"
                v-if="scope.row.id != selectedIndex   && formData.codeCount == 1"
                @click.stop="true"
                @click.native="rowChange(scope.row)"
              >编辑
              </el-button>
              <el-button
                type="text"
                size="small"
                @click.stop="true"
                @click.native="deleteOrderDetail(scope.$index, scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="滴码明细" v-if="formData.codeCount == 2">
        <invCountCodes
          :codeQuery="codeQuery"
          :getCountOrderDetail="getList"
          :orderIdFk="formData.orderId"
          v-if="isCodeAlive"
        ></invCountCodes>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      title="库存产品录入"
      :visible.sync="selectInvProductVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="80%"
      v-if="selectInvProductVisible"
      :append-to-body='true'
    >
      <el-form label-width="100px" :model="filterQuery" size="mini" v-if="showSearch" style="margin-top: -10px">
        <el-row>
          <el-col :span="8">
            <el-form-item class="query-form-item" label="仓库:">
              <el-select v-model="filterQuery.invCode" placeholder="" disabled style="width: 90%" clearable>
                <el-option
                  v-for="item in invList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.code">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="query-form-item" label="货位:">
              <el-select v-model="filterQuery.invSpaceCode" placeholder="" disabled style="width: 90%" clearable>
                <el-option
                  v-for="item in spaceList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.code">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="query-form-item" label="DI/物资编码:">
              <el-input v-model="filterQuery.nameCode" style="width: 90%" placeholder="请输入DI/物资编码"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="query-form-item" label="设备名称:">
              <el-input v-model="filterQuery.cpmctymc" style="width: 90%" placeholder="请输入设备名称"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="query-form-item" label="规格型号:">
              <el-input v-model="filterQuery.ggxh" style="width: 90%" placeholder="请输入规格型号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="query-form-item" label="生产企业:">
              <el-input v-model="filterQuery.manufactory" style="width: 90%" placeholder="请输入生产企业"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="query-form-item" label="注册/备案号:">
              <el-input v-model="filterQuery.zczbhhzbapzbh" style="width: 90%" placeholder="请输入注册/备案号"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="query-form-item" label="供应商:">
              <el-input v-model="filterQuery.supName" style="width: 90%" placeholder="请输入供应商"
                        clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="top-right-btn">
        <el-button-group>
          <el-button icon="el-icon-view" type="primary" @click="hideSearch">显示/隐藏搜索栏</el-button>
          <el-button type="primary" icon="el-icon-refresh" @click="onReset">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="queryInvProductsList">查询</el-button>
          <el-button type="primary" icon="el-icon-check" @click="combine">确定</el-button>
        </el-button-group>
      </div>
      <el-divider style="margin: 15px"></el-divider>


      <el-table v-loading="loading" :data="productList" style="width: 100%" highlight-current-row="false"
                :row-key="getRowKeys"
                @selection-change="handleSelectionChange" border
                ref="multipleTable">
        <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="DI/物资编码" prop="nameCode" width="140" show-overflow-tooltip></el-table-column>
        <el-table-column label="物资名称" prop="cpmctymc" width="160" show-overflow-tooltip></el-table-column>
        <el-table-column label="规格型号" prop="ggxh" width="160" show-overflow-tooltip></el-table-column>
        <el-table-column label="批次号" prop="batchNo" show-overflow-tooltip></el-table-column>
        <el-table-column label="生产日期" prop="productionDate" show-overflow-tooltip></el-table-column>
        <el-table-column label="失效日期" prop="expireDate" show-overflow-tooltip></el-table-column>
        <el-table-column label="入库数量" prop="inCount" show-overflow-tooltip></el-table-column>
        <el-table-column label="出库数量" prop="outCount" show-overflow-tooltip></el-table-column>
        <el-table-column label="结余数量" prop="reCount" show-overflow-tooltip></el-table-column>
        <el-table-column label="生产企业" prop="manufactory" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column label="注册/备案号" prop="zczbhhzbapzbh" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column label="供应商" prop="supName" width="180" show-overflow-tooltip></el-table-column>
      </el-table>

      <pagination
        v-show="productTotal>0"
        :total="productTotal"
        :limit.sync="filterQuery.limit"
        :page.sync="filterQuery.page"
        @pagination="queryInvProducts"
      ></pagination>
    </el-dialog>

    <el-dialog
      title="码详情"
      :visible.sync="codesVisible"
      width="60%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      v-if="codesVisible"
      append-to-body
    >
      <invCountCodes
        :codeQuery="codeQuery"
        :getCountOrderDetail="getList"
      ></invCountCodes>
    </el-dialog>
  </div>
</template>

<script>
import {getInvSpaceList} from "@/api/inventory/invSpace";
import {
  saveCountOrder,
  getCountOrderDetailList,
  deleteCountOrderDetail,
  addCountOrderDetail,
  batchAddDetail, submitAudit, updateCountOrderStatus, updateCountOrderDetail
} from "@/api/inventory/invCountOrder";
import {addCode} from "@/api/inventory/invCountCodes";
import {getCountInvProductProduct, getProduct} from "@/api/inventory/invPorduct";
import {isBlank} from "@/utils/strUtil";
import {getInvListByUser} from "@/api/system/invWarehouse";
import invCountCodes from "@/views/inventory/count/InvCountCodes.vue";
import {updateBizProduct} from "@/api/inout/orderDetailCode";

export default {
  props: {
    countOrder: {
      type: Object,
      required: true,
    },
    closeDialog: {
      type: Function,
      required: true,
    },
    countType: {
      type: Number,
      required: true
    },
    getCountOrderList: {
      type: Function,
      required: true
    }
  },

  data() {
    return {
      formData: {
        code: null,
        orderId: null,
        createTime: null,
        deptCode: null,
        invWarehouseCode: null,
        invStorageCode: null,
        countType: this.countType,
        codeCount: 1,
      },
      total: 0,
      loading: false,
      index: null,
      selectInvProductVisible: false,
      invList: [],
      spaceList: [],
      filterQuery: {
        invCode: null,
        invSpaceCode: null,
        nameCode: null,
        cpmctymc: null,
        batchNo: null,
        page: 1,
        limit: 10
      },
      showSearch: true,
      productList: [],
      scanText: "扫码录入：",
      codesList: [],
      detailQuery: {
        orderIdFk: null
      },
      detailTotal: 0,
      countProductList: [],
      productTotal: 0,
      codesNum: 0,
      codeQuery: {
        relId: null,
        orderIdFk: null,
        batchNo: null,
        edit: true
      },
      codesVisible: false,
      disableSpace: false,
      multiProduct: [],
      selectedIndex: null,
      isCodeAlive: true,
      saveLoading: false,
      submitLoading: false,
    }
  },
  methods: {
    getInvList() {
      getInvListByUser().then((res) => {
        if (res.code === 20000) {
          this.invList = res.data || [];
          if (!isBlank(this.countOrder.invSpaceCode)) {
            this.getSpaceList();
            this.formData.invStorageCode = this.countOrder.invStorageCode;
            this.invList.forEach((item) => {
              if (item.code === this.formData.invStorageCode) {
                this.formData.deptCode = item.parentId;
              }
            })
          }
        }
      });
    },
    invChange() {
      // 切换仓库时同步切换部门ID
      this.invList.forEach((item) => {
        if (item.code === this.formData.invStorageCode) {
          this.formData.deptCode = item.parentId;
        }
      });
      this.formData.invSpaceCode = null;
      this.getSpaceList();
    },
    getSpaceList() {
      this.spaceList = [];
      let params = {invWarehouseCode: this.formData.invStorageCode, status: 1};
      getInvSpaceList(params).then((res) => {
        if (!isBlank(this.countOrder.invWarehouseCode)) {
          this.formData.invWarehouseCode = this.countOrder.invWarehouseCode;
        }
        this.spaceList = res.data.list || [];
      });
    },
    invSpaceChange() {
      this.$forceUpdate();
    },
    saveOrder(type) {
      let orderData = {
        orderId: this.formData.orderId,
        createTime: this.formData.billDate,
        deptCode: this.formData.deptCode,
        invStorageCode: this.formData.invStorageCode,
        invWarehouseCode: this.formData.invWarehouseCode,
        countType: this.countOrder.countType,
        codeCount: this.formData.codeCount,
      };
      this.saveLoading = true
      saveCountOrder(orderData).then((res) => {
        this.saveLoading = false
        if (res.code === 20000) {
          this.formData.orderId = res.data.orderId;
          this.formData.createTime = res.data.createTime;
          this.$message.success("保存成功");
          if (type != null) {
            //保存当前单据详情
            this.saveOrderDetail();
          } else {
            this.closeDialog();
          }
        } else {
          this.saveLoading = false
          this.$message.error(res.message);
        }
      });
    },


    saveOrderDetail() {
      let params = {
        orderId: this.formData.orderId,
        countOrderDetailList: this.countProductList
      }
      batchAddDetail(params).then((res) => {
        if (res.code === 20000) {
          this.getList();
          this.getCountOrderList();
        }
      })
    },

    submitAudit() {
      this.submitLoading = true
      submitAudit(this.formData).then((res) => {
        this.submitLoading = false
        if (res.code === 20000) {
          this.$message.success("提交成功！");
          this.getList();
          this.closeDialog();
        } else {
          this.$message.error(res.message);
        }
      }).catch((error) => {
        this.submitLoading = false
        this.$message.error(error.message);
      });
    },

    getInputFocus(event) {
      event.currentTarget.select();
    },
    enterKey(event) {
      if (this.countProductList.length === 0) {
        this.$message.error("请先录入盘点产品！");
        return;
      }
      this.addCode();
      this.$refs.inputRef.focus();
      this.$refs.inputRef.select();
    },
    addCode() {
      if (this.countType != 1) {
        if (isBlank(this.formData.invStorageCode)) {
          this.$message.error("请先选择盘点仓库信息")
          return;
        }
      } else if (this.countType === 1) {
        if (isBlank(this.formData.invStorageCode) || isBlank(this.formData.invWarehouseCode)) {
          this.$message.error("请先选择盘点仓库和货位信息");
          return;
        }
      }

      if (this.countProductList.length < 1) {
        this.$message.error("未选择盘点产品！")
        return;
      }
      this.formData.code.trim();
      let params = {
        orderIdFk: this.formData.orderId,
        code: this.formData.code
      };
      addCode(params).then((res) => {
        if (res.code === 20000) {
          this.getList()
          this.refreshCodesPanel();
        } else {
          this.$message.error(res.message);
        }
      })
    },

    rowChange(val) {
      this.selectedIndex = val.id;
    },

    saveChange(row) {
      updateCountOrderDetail(row)
        .then((response) => {
          this.loading = false;
          if (response.code === 20000) {
            this.$message.success("保存成功！");
            this.selectedIndex = null;
            this.getCountOrderList();
          } else {
            this.$message.error(response.message);
          }
        })
        .catch(() => {
          this.loading = false;
          this.dataList = [];
          this.pageTotal = 0;
        });
    },


    deleteOrderDetail(index, row) {
      this.$confirm('此操作将删除单据详情，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = {id: row.id};
        deleteCountOrderDetail(params).then((res) => {
          if (res.code === 20000) {
            this.$message.success("删除成功");
            this.getList();
          }
        })
      }).catch(() => {
      });
    },
    getList() {
      let params = {orderIdFk: this.formData.orderId};
      getCountOrderDetailList(params).then((res) => {
        if (res.code === 20000) {
          console.log(res.data)
          this.countProductList = res.data.list || [];
          console.log(this.countProductList)
        }
      });
    },
    onReset() {
      this.filterQuery = {
        invCode: null,
        invSpaceCode: null,
        nameCode: null,
        cpmctymc: null,
        batchNo: null,
        page: 1,
        limit: 10
      };
      this.countProductList = [];
      this.queryInvProducts();
    },

    hideSearch() {
      this.showSearch = !this.showSearch;
    },

    queryInvProductsList() {
      this.filterQuery.page = 1;
      this.queryInvProducts();
    },
    queryInvProducts() {
      this.filterQuery.invCode = this.formData.invStorageCode;
      this.filterQuery.invSpaceCode = this.formData.invWarehouseCode;
      getProduct(this.filterQuery).then((res) => {
        if (res.code === 20000) {
          this.productList = res.data.list || [];
          this.productTotal = res.data.total || 0;
        } else {
          this.$message.error(res.message);
          this.productList = [];
          this.productTotal = 0;
        }
      }).catch((error) => {
        this.$message.error(error.message);
        this.productList = [];
        this.productTotal = 0;
      });
    },
    combine() {
      if (this.multiProduct.length === 0) {
        this.$message.warning("请选择产品");
        return;
      }

      // if (this.countProductList.length === 0) {
      //添加第一个产品，先保存单据，再添加单据详情
      this.multiProduct.forEach(product => {
        let detailData = {
          orderIdFk: this.formData.orderId,
          productId: product.relIdFk,
          nameCode: product.nameCode,
          batchNo: product.batchNo,
          produceDate: product.productionDate,
          expireDate: product.expireDate,
          invCode: this.formData.invStorageCode,
          invSpaceCode: this.formData.invSpaceCode,
          invNum: product.reCount,
          supId: product.supId
        };
        this.countProductList.push(detailData);
      });
      // this.saveOrderDetail();
      this.saveOrder(1);
      // }
      this.selectInvProductVisible = false;
    },
    getRowKeys(row) {
      return row.id;
    },
    handleSelectionChange(selectedRows) {
      this.multiProduct = [];
      selectedRows.forEach(item => {
        this.multiProduct.push(item);
      });
    },
    startCount(val) {
      // this.countProductList = [];
      if (this.countType === 0 && val === 1) {
        if (isBlank(this.formData.invStorageCode)) {
          this.$message.warning("请先选择盘点仓库");
          return;
        }
        //拉取整个仓库的数据
        let params = {
          invCode: this.formData.invStorageCode,
          invSpaceCode: this.formData.invWarehouseCode
        };
        getCountInvProductProduct(params).then((res) => {
          if (res.data.total !== 0) {
            let invProductList = res.data.list;
            for (let product of invProductList) {
              this.countProductList.push(product);
            }
            this.saveOrder(1);
          }
        });
      } else if (this.countType === 0) {
        if (isBlank(this.formData.invStorageCode)) {
          this.$message.warning("请先选择盘点仓库");
          return;
        }

        this.filterQuery.invCode = this.formData.invStorageCode
        this.filterQuery.invSpaceCode = this.formData.invWarehouseCode
        this.productList = [];
        this.selectInvProductVisible = true;
        this.queryInvProducts();
      } else if (this.countType === 1) {
        if (isBlank(this.formData.invStorageCode) || isBlank(this.formData.invWarehouseCode)) {
          this.$message.warning("请先选择盘点仓库和货位");
          return;
        }
        if (val === 1) {
          let params = {
            invCode: this.formData.invStorageCode,
            invSpaceCode: this.formData.invWarehouseCode
          };
          getCountInvProductProduct(params).then((res) => {
            if (res.data.total !== 0) {
              let invProductList = res.data.list;
              for (let product of invProductList) {
                this.countProductList.push(product);
              }
              this.saveOrder(1);
            }
          });
        } else {
          this.filterQuery.invCode = this.formData.invStorageCode
          this.filterQuery.invSpaceCode = this.formData.invWarehouseCode
          this.productList = [];
          this.selectInvProductVisible = true;
          this.queryInvProducts();
        }
      } else if (this.countType === 2) {
        if (isBlank(this.formData.invStorageCode)) {
          this.$message.warning("请先选盘点仓库");
          return;
        }
        this.multiProduct = [];
        this.filterQuery.invCode = this.formData.invStorageCode
        this.filterQuery.invSpaceCode = this.formData.invWarehouseCode
        this.selectInvProductVisible = true;
        this.queryInvProducts();
      }
    },
    showCodes(index, row) {
      this.codesVisible = true;
      this.codeQuery = {
        orderIdFk: row.orderIdFk,
        relId: row.relId,
        batchNo: row.batchNo,
        edit: true
      }
    },


    refreshCodesPanel() {
      this.isCodeAlive = false;

      this.$nextTick(() => {
        //重新加载组件
        this.isCodeAlive = true;
      });

    },
  },
  components: {
    invCountCodes
  },
  created() {
    this.getInvList();

    if (!isBlank(this.countOrder.orderId)) {
      //拉取单据详情信息
      this.formData = this.countOrder;
      let params = {orderIdFk: this.countOrder.orderId};
      getCountOrderDetailList(params).then((res) => {
        if (res.code === 20000) {
          this.countProductList = res.data.list || [];
          this.total = res.data.total || 0;
        }
      })
    }
  },
};


</script>


<style scoped>

</style>
