<template>
  <div>
    <el-card style="margin: 5px;margin-top: -20px">
      <el-form :model="formData" ref="dataForm" label-width="100px" style="margin-bottom: -15px">
        <el-button-group style="display: flex;margin: 0px 0 10px 80%; height: 35px">
          <el-button
            v-if="countType != 2"
            type="primary"
            :disabled="this.codeArray.length > 0"
            @click.native="startCount(1)"
          >开始盘点
          </el-button>
          <el-button
            type="primary"
            :disabled="this.codeArray.length > 0"
            @click.native="startCount()"
          >录入产品
          </el-button>
          <el-button
            type="primary"
            @click.native="saveOrder()"
          >保存
          </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.invCode" placeholder="盘点仓库信息"
                         :disabled="codeArray.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.invSpaceCode" placeholder="盘点货位信息"
                         :disabled="codeArray.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="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="2">
            <el-button
              type="primary"
              size="mini"
              @click.native.stop="addCode()"
              style="margin-left: 15px"
            >添加
            </el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="codeArray" style="width: 100%;margin-top: 20px;"
                  highlight-current-row
                  border max-height="300" height="300">
          <el-table-column label="序号" type="index" width="50"></el-table-column>
          <el-table-column width="150" label="产品通用名" prop="productName" show-overflow-tooltip></el-table-column>
          <el-table-column width="150" label="规格型号" prop="ggxh" show-overflow-tooltip></el-table-column>
          <el-table-column width="150" label="批次号" prop="batchNo"></el-table-column>
          <el-table-column width="150" label="库存数量" prop="invNum"></el-table-column>
          <el-table-column width="150" label="盘点数量" prop="countNum"></el-table-column>
          <el-table-column label="生产日期(yyMMdd)" prop="produceDate"></el-table-column>
          <el-table-column label="失效日期(yyMMdd)" prop="expireDate" show-overflow-tooltip></el-table-column>
          <el-table-column label="注册/备案凭证号" prop="zczbhhzbapzbh" show-overflow-tooltip></el-table-column>
          <el-table-column label="生产企业" prop="ylqxzcrbarmc" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click.stop="true"
                @click.native="showCodes(scope.$index, 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-form>
    </el-card>


    <el-dialog
      title="库存产品录入"
      :visible.sync="selectInvProductVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="85%"
      v-if="selectInvProductVisible"
      :append-to-body='true'
    >
      <el-form :inline="true" :model="filterQuery" size="mini">
        <el-row>
          <el-form-item class="query-form-item" label="产品标识DI:">
            <el-input v-model="filterQuery.nameCode" placeholder="产品标识DI" clearable></el-input>
          </el-form-item>
          <el-form-item class="query-form-item" label="产品名称:">
            <el-input v-model="filterQuery.cpmctymc" placeholder="产品名称" clearable></el-input>
          </el-form-item>
          <el-form-item class="query-form-item" label="批次号:">
            <el-input v-model="filterQuery.batchNo" placeholder="批次号" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button type="primary" icon="el-icon-refresh" @click="onReset">重置</el-button>
              <el-button type="primary" icon="search" @click="queryInvProductsList"
              >查询
              </el-button
              >
              <el-button type="primary" icon="search" @click="combine">确定</el-button>
            </el-button-group>
          </el-form-item>
        </el-row>
      </el-form>

      <el-table v-loading="loading" :data="productList" style="width: 100%"
                highlight-current-row="false"
                :row-key="getRowKeys"
                @selection-change="handleSelectionChange"
                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="产品标识" prop="nameCode" width="180"></el-table-column>
        <el-table-column label="产品名称" prop="cpmctymc"  show-overflow-tooltip></el-table-column>
        <el-table-column label="规格型号" prop="ggxh"  show-overflow-tooltip></el-table-column>
        <el-table-column label="批次号" prop="batchNo" width="200"></el-table-column>
        <el-table-column label="生产日期" prop="productionDate" width="120"></el-table-column>
        <el-table-column label="失效日期" prop="expireDate" width="120"></el-table-column>
        <el-table-column label="入库数量" prop="inCount" width="100"></el-table-column>
        <el-table-column label="出库数量" prop="outCount" width="100"></el-table-column>
        <el-table-column label="结余数量" prop="reCount" width="100"></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
} from "@/api/inventory/invCountOrder";
import {addCode} from "@/api/inventory/invCountCodes";
import {getCountInvProductProduct} from "@/api/inventory/invPorduct";
import {isBlank} from "@/utils/strUtil";
import {getInvListByUser} from "@/api/system/invWarehouse";
import invCountCodes from "@/views/inventory/InvCountCodes.vue";

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,
        invCode: null,
        invSpaceCode: null,
        countType: this.countType
      },
      codeArray: [],
      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
      },
      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: []
    }
  },
  methods: {
    getInvList() {
      getInvListByUser().then((res) => {
        if (res.code === 20000) {
          this.invList = res.data || [];
          if (!isBlank(this.countOrder.invSpaceCode)) {
            this.getSpaceList();
            this.formData.invCode = this.countOrder.invCode;
            this.invList.forEach((item) => {
              if (item.code === this.formData.invCode) {
                this.formData.deptCode = item.parentId;
              }
            })
          }
        }
      });
    },
    invChange() {
      // 切换仓库时同步切换部门ID
      this.invList.forEach((item) => {
        if (item.code === this.formData.invCode) {
          this.formData.deptCode = item.parentId;
        }
      });
      this.formData.invSpaceCode = null;
      this.getSpaceList();
    },
    getSpaceList() {
      this.spaceList = [];
      let params = {invWarehouseCode: this.formData.invCode, status: 1};
      getInvSpaceList(params).then((res) => {
        if (!isBlank(this.countOrder.invSpaceCode)) {
          this.formData.invSpaceCode = this.countOrder.invSpaceCode;
        }
        this.spaceList = res.data.list || [];
      });
    },
    invSpaceChange() {
      this.$forceUpdate();
    },
    saveOrder(type) {
      let orderData = {
        orderId: this.formData.orderId,
        createTime: this.formData.billDate,
        deptCode: this.formData.deptCode,
        invCode: this.formData.invCode,
        invSpaceCode: this.formData.invSpaceCode,
        countType: this.countOrder.countType
      };
      saveCountOrder(orderData).then((res) => {
        if (res.code === 20000) {
          this.formData.orderId = res.data.orderId;
          this.formData.createTime = res.data.createTime;
          this.$message.success("保存成功");
          if (type != null) {
            //保存当前单据详情
            let orderDetails = [];
            this.countProductList.forEach(product => {
              let detailData = {
                orderIdFk: this.formData.orderId,
                relId: product.relIdFk,
                nameCode: product.nameCode,
                batchNo: product.batchNo,
                produceDate: product.productionDate,
                expireDate: product.expireDate,
                invCode: this.formData.invCode,
                invSpaceCode: this.formData.invSpaceCode
              };
              orderDetails.push(detailData);
            });
            let params = {
              orderId: this.formData.orderId,
              countOrderDetailList: orderDetails
            }
            batchAddDetail(params).then((res) => {
              if (res.code === 20000) {
                this.getList();
                this.getCountOrderList();
              }
            })
          } else {
            this.closeDialog();
          }
        } else {
          this.$message.error(res.message);
        }
      });
    },
    getInputFocus(event) {
      event.currentTarget.select();
    },
    enterKey(event) {
      if (this.codeArray.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.invCode)) {
          this.$message.error("请先选择盘点仓库信息")
          return;
        }
      } else if (this.countType === 1) {
        if (isBlank(this.formData.invCode) || isBlank(this.formData.invSpaceCode)) {
          this.$message.error("请先选择盘点仓库和货位信息");
          return;
        }
      }

      if (this.codeArray.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()
        } else {
          this.$message.error(res.message);
        }
      })
    },
    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) {
          this.codeArray = res.data.list || [];
        }
      });
    },
    onReset() {
      this.filterQuery = {
        invCode: null,
        invSpaceCode: null,
        nameCode: null,
        cpmctymc: null,
        batchNo: null,
        page: 1,
        limit: 10
      };
      this.countProductList = [];
      this.queryInvProducts();
    },
    queryInvProductsList() {
      this.filterQuery.page = 1;
      this.queryInvProducts();
    },
    queryInvProducts() {
      this.filterQuery.invCode = this.formData.invCode;
      this.filterQuery.invSpaceCode = this.formData.invSpaceCode;
      getCountInvProductProduct(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;
      }
      this.multiProduct.forEach(product => {
        this.countProductList.push(product);
      })
      if (this.codeArray.length === 0) {
        //添加第一个产品，先保存单据，再添加单据详情
        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.invCode)) {
          this.$message.warning("请先选择盘点仓库");
          return;
        }
        // if (this.codeArray.length === 0) {
        //   this.$message.warning("请先录入产品");
        //   return;
        // }
        //拉取整个仓库的数据
        let params = {
          invCode: this.formData.invCode,
          invSpaceCode: this.formData.invSpaceCode
        };
        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.invCode)) {
          this.$message.warning("请先选择盘点仓库");
          return;
        }
        this.productList = [];
        this.selectInvProductVisible = true;
        this.queryInvProducts();
      } else if (this.countType === 1) {
        if (isBlank(this.formData.invCode) || isBlank(this.formData.invSpaceCode)) {
          this.$message.warning("请先选择盘点仓库和货位");
          return;
        }
        if (val === 1) {
          let params = {
            invCode: this.formData.invCode,
            invSpaceCode: this.formData.invSpaceCode
          };
          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.productList = [];
          this.selectInvProductVisible = true;
          this.queryInvProducts();
        }
      } else if (this.countType === 2) {
        if (isBlank(this.formData.invCode)) {
          this.$message.warning("请先选盘点仓库");
          return;
        }
        this.multiProduct = [];
        this.selectInvProductVisible = true;
        this.queryInvProducts();
      }
    },
    showCodes(index, row) {
      this.codesVisible = true;
      this.codeQuery = {
        orderIdFk: row.orderIdFk,
        relId: row.relId,
        batchNo: row.batchNo,
        edit: true
      }
    },
  },
  components: {
    invCountCodes
  },
  created() {
    this.getInvList();
    this.formData = this.countOrder;
    if (!isBlank(this.formData.orderId)) {
      //拉取单据详情信息
      let params = {orderIdFk: this.countOrder.orderId};
      getCountOrderDetailList(params).then((res) => {
        if (res.code === 20000) {
          this.codeArray = res.data.list || [];
          this.total = res.data.total || 0;
        }
      })
    }
  },
};
</script>

