<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
            type="primary"
            @click.native="saveDeviceReceiveOrder()"
          >保存
          </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.fromDeptCode" placeholder="领用部门信息"
                         :disabled="detailList.length >0 "
                         @change="deptChange"
                         style="width: 90%;"
                         clearable>
                <el-option
                  v-for="item in deptList"
                  :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-col :span="10">
            <el-form-item class="query-form-item" label="领用仓库:">
              <el-select v-model="formData.fromInvCode" placeholder="领用仓库信息"
                         :disabled="detailList.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-row>

        <el-row>
          <el-col :span="10">
            <el-form-item class="query-form-item" label="领用货位:">
              <el-select v-model="formData.fromInvSpaceCode" placeholder="领用货位信息"
                         :disabled="detailList.length >0 "
                         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-col :span="10">
            <el-form-item class="query-form-item" label="领用人:">
              <el-select v-model="formData.receiveUser" placeholder="领用人信息"
                         :disabled="detailList.length >0 "
                         style="width: 90%"
                         clearable>
                <el-option
                  v-for="item in userList"
                  :key="item.employeeName"
                  :label="item.employeeName"
                  :value="item.userId">
                  <span style="float: left">{{ item.employeeName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.userId }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="17">
            <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="4">
            <el-button
              type="primary"
              size="mini"
              @click.native.stop="addCode()"
              style="margin-left: 15px"
            >扫码添加
            </el-button>
            <el-button
              type="primary"
              :disabled="this.detailList.length > 0"
              @click.native="selectInvProduct()"
            >手动添加
            </el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="detailList" 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 label="条码" width="180" prop="code" show-overflow-tooltip></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="count"></el-table-column>
          <el-table-column width="150" label="养护状态" prop="maintenanceStatus">
            <template slot-scope="scope">
              <el-radio :disabled="scope.$index !== currentIndex" v-model="scope.row.maStatus"
                        :label="0">未养护
              </el-radio>
              <el-radio :disabled="scope.$index !== currentIndex" v-model="scope.row.maStatus"
                        :label="1">已养护
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column width="150" label="设备状态" prop="deviceStatus">
            <template slot-scope="scope">
              <el-radio :disabled="scope.$index !== currentIndex" v-model="scope.row.deviceStatus" :label="1">
                正常
              </el-radio>
              <el-radio :disabled="scope.$index !== currentIndex" v-model="scope.row.deviceStatus" :label="0">
                异常
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column width="200" label="养护备注" prop="remark">
            <template slot-scope="scope">
              <el-input :disabled="scope.$index !== currentIndex" v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="生产日期(yyMMdd)" prop="productionDate"></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="editOrderDetail(scope.$index, scope.row)"
              >编辑
              </el-button
              >
              <el-button
                type="text"
                size="small"
                @click.stop="true"
                @click.native="updateOrderDetail(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="领用仓库:">
            <el-select v-model="filterQuery.invCode" placeholder="领用仓库信息"
                       :disabled="true"
                       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.parentName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="query-form-item" prop="invSpaceCode">
            <el-select v-model="filterQuery.invSpaceCode" placeholder="领用货位信息"
                       :disabled="true"
                       clearable>
              <el-option
                v-for="item in spaceList"
                :key="item.name"
                :label="item.name"
                :value="item.code">
                <span style="float: left">{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <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"></el-table-column>
        <el-table-column label="产品名称" prop="cpmctymc"></el-table-column>
        <el-table-column label="规格型号" prop="ggxh"></el-table-column>
        <el-table-column label="批次号" prop="batchNo"></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>

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

<script>
import {getDeptListByUser} from "@/api/auth/authDept";
import {findInvByUser} from "@/api/system/invSubWarehouse";
import {getInvSpaceList} from "@/api/inventory/invSpace";
import {
  addDeviceReceiveOrder,
  addDeviceReceiveOrderDetail,
  updateDeviceReceiveOrder,
  updateDeviceReceiveOrderDetail,
  getDeviceReceiveOrderDetailList,
  deleteDeviceReceiveOrderDetail,
  checkCode
} from "@/api/inventory/deviceReceiveOrder";
import {getInvMAProducts} from "@/api/inventory/invPorduct";
import {isBlank} from "@/utils/strUtil";
import {listDeptUser} from "@/api/system/deptUser";

export default {
  props: {
    deviceReceiveOrder: {
      type: Object,
      required: true,
    },
    closeDialog: {
      type: Function,
      required: true,
    },
  },

  data() {
    return {
      filterQuery: {
        nameCode: null,
        cpmctymc: null,
        batchNo: null,
        invCode: null,
        cplb: "设备",
        invSpaceCode: null,
        page: 1,
        limit: 10
      },
      productList: [],
      productTotal: 0,
      deptList: [],
      invList: [],
      spaceList: [],
      formData: {
        id: null,
        orderId: null,
        createTime: null,
        fromDeptCode: null,
        fromInvCode: null,
        fromInvSpaceCode: null,
        receiveUser: null,
        status: 0,
        code: null,
      },
      detailList: [],
      loading: false,
      scanText: "扫码录入：",
      currentIndex: -1,
      selectInvProductVisible: false,
      multiProduct: [],
      userList: [],
      productInvList: [],
      productSpaceList: []
    }
  },
  methods: {
    getInvList() {
      let params = {deptCode: this.formData.fromDeptCode};
      findInvByUser(params).then((res) => {
        if (res.code === 20000) {
          this.invList = res.data || [];
          if (!isBlank(this.deviceReceiveOrder.fromInvSpaceCode)) {
            this.formData.fromInvSpaceCode = this.deviceReceiveOrder.fromInvSpaceCode;
            this.invChange();
          }
        }
      });
    },
    deptChange() {
      //查询此部门下的仓库和用户
      this.formData.fromInvCode = null;
      this.formData.fromInvSpaceCode = null;
      this.invList = [];
      this.spaceList = [];
      this.getInvList();

      //拉取部门用户列表
      this.getDeptUserList();
    },
    getDeptUserList() {
      this.userList = [];
      let params = {deptId: this.formData.fromDeptCode};
      listDeptUser(params).then((res) => {
        this.userList = res.data.list || [];
      })
    },
    getDeptList() {
      getDeptListByUser().then((res) => {
        this.deptList = res.data || [];
        if (!isBlank(this.deviceReceiveOrder.fromInvCode)) {
          this.formData.fromInvCode = this.deviceReceiveOrder.fromInvCode;
          this.getInvList();
        }
      });

      if (!isBlank(this.formData.fromDeptCode)) {
        this.getDeptUserList();
      }
    },
    invChange() {
      this.formData.invSpaceCode = null;
      this.spaceList = [];
      let params = {invWarehouseCode: this.formData.fromInvCode, status: 1};
      getInvSpaceList(params).then((res) => {
        if (!isBlank(this.deviceReceiveOrder.fromInvSpaceCode)) {
          this.formData.fromInvSpaceCode = this.deviceReceiveOrder.fromInvSpaceCode;
        }
        this.spaceList = res.data.list || [];
      })
      this.formData.fromInvSpaceCode="";
    },
    selectInvProduct() {
      let message = this.verifyOrder();
      if (!isBlank(message)) {
        this.$message.warning(message);
        return;
      }

      //保存或更新设备领用仓库信息

      this.saveOrder();
      this.onReset();
      this.selectInvProductVisible = true;
      this.filterQuery.invCode=this.formData.fromInvCode;
      this.filterQuery.invSpaceCode=this.formData.fromInvSpaceCode;
    },
    saveMAOrder() {
      this.saveOrder();
      this.closeDialog();
    },
    saveOrder(code) {
      if (!isBlank(this.formData.orderId)) {
        //更新单据
        updateDeviceReceiveOrder(this.formData).then((res) => {
        }).catch((error) => {
          this.$message.error("更新单据信息失败！");
        })
      } else {
        addDeviceReceiveOrder(this.formData).then((res) => {
          if (res.code === 20000) {
            this.formData.id = res.data.id;
            this.formData.orderId = res.data.orderId;
            this.formData.createTime = res.data.createTime;
            if (!isBlank(code)) {
              //扫码添加设备领用记录详情
              if (!isBlank(this.formData.code)) {
                this.addScanCode();
              }
            }
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },

    saveDeviceReceiveOrder() {
      let message = this.verifyOrder();
      if (isBlank(message)) {
        this.saveOrder();
        this.closeDialog();
      } else {
        this.$message.warning(message);
      }
    },

    getInputFocus(event) {
      event.currentTarget.select();
    },
    enterKey(event) {
      this.addCode();
      this.$refs.inputRef.focus();
      this.$refs.inputRef.select();
    },
    addCode() {
      let message = this.verifyOrder();
      if (!isBlank(message)) {
        this.$message.warning(message);
        return;
      }

      if (isBlank(this.formData.code)) {
        this.$message.warning("请扫描或输入UDI码");
        return;
      }

      if (isBlank(this.formData.orderId)) {
        this.saveOrder(this.formData.code);
      } else {
        this.addScanCode();
      }

    },
    verifyOrder() {
      if (isBlank(this.formData.fromDeptCode)) {
        return "请选择领用部门！";
      } else if (isBlank(this.formData.fromInvCode)) {
        return "请选择领用仓库！";
      } else if (isBlank(this.formData.fromInvSpaceCode)) {
        return "请选择领用货位！";
      } else if (isBlank(this.formData.receiveUser)) {
        return "请选择领用人！";
      }
    },
    addScanCode() {
      //校验条码是否符合规则
      let checkParams = {
        code: this.formData.code
      };
      checkCode(checkParams).then((res) => {
        if (res.code === 20000) {
          this.addDeviceReceiveOrderDetail();
        } else {
          if (res.code === 3) {
            this.$message.error(res.message);
          } else if (res.code === 7) {
            this.$confirm(res.message + "，是否继续添加？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              this.addDeviceReceiveOrderDetail();
            }).catch(() => {
            });
          }
        }
      }).catch((error) => {
      });
    },
    addDeviceReceiveOrderDetail() {
      //扫码添加库存养护记录详情
      let params = {
        orderIdFk: this.formData.orderId,
        code: this.formData.code
      }
      addDeviceReceiveOrderDetail(params).then((res) => {
        if (res.code === 20000) {
          this.$message.success("添加成功！");
          this.getList();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    deleteOrderDetail(index, row) {
      if (row.count === 1) {
        this.$confirm('此产品领用数量为1，减一后将删除此产品领用记录，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {id: row.id};
          deleteDeviceReceiveOrderDetail(params).then((res) => {
            if (res.code === 20000) {
              this.$message.success("删除成功");
              this.getList();
            }
          })
        }).catch(() => {
        });
      } else {
        let params = {id: row.id};
        deleteDeviceReceiveOrderDetail(params).then((res) => {
          if (res.code === 20000) {
            this.$message.success("删除成功");
            this.getList();
          }
        })
      }
    },
    getList() {
      let params = {orderIdFk: this.formData.orderId};
      getDeviceReceiveOrderDetailList(params).then((res) => {
        if (res.code === 20000) {
          this.detailList = res.data.list || [];
        }
      })
    },
    updateOrderDetail(row) {
      updateDeviceReceiveOrderDetail(row).then((res) => {
        if (res.code === 20000) {
          this.$message.success("保存成功！")
          this.getList();
        }
      })
    },
    editOrderDetail(index, row) {
      this.currentIndex = index;
    },
    onReset() {
      this.filterQuery = {
        nameCode: null,
        cpmctymc: null,
        batchNo: null,
        invCode: this.formData.fromInvCode,
        cplb: "设备",
        invSpaceCode: null,
        page: 1,
        limit: 10
      };
      this.multiProduct = [];
      this.queryInvProducts();
    },
    handleCurrentChange(val) {
      this.filterQuery.page = val;
      this.queryInvProducts();
    },
    queryInvProductsList() {
      this.filterQuery.page = 1;
      this.queryInvProducts();
    },
    queryInvProducts() {
      this.filterQuery.invCode=this.formData.fromInvCode;
      this.filterQuery.invSpaceCode=this.formData.fromInvSpaceCode;
      getInvMAProducts(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.error("请选择养护产品！");
        return;
      }
      let invProductIds = [];
      this.multiProduct.forEach(item => {
        invProductIds.push(item.id);
      });
      let params = {
        orderIdFk: this.formData.orderId,
        invProductIds: invProductIds,
      };
      addDeviceReceiveOrderDetail(params).then((res) => {
        if (res.code === 20000) {
          this.$message.success("录入成功！");
          this.selectInvProductVisible = false;
          this.getList();
        } else {
          this.$message.error(res.message);
        }
      }).catch((error) => {
        this.$message.error(error.message);
      })
    },
    getRowKeys(row) {
      return row.id;
    },
    handleSelectionChange(selectedRows) {
      this.multiProduct = [];
      selectedRows.forEach(item => {
        this.multiProduct.push(item);
      });
    },
  },
  created() {
    this.getDeptList();
    if (!(isBlank(this.deviceReceiveOrder.orderId)) ) {
      this.formData.orderId = this.deviceReceiveOrder.orderId;
      this.formData.createTime = this.deviceReceiveOrder.createTime;
      this.formData.fromDeptCode = this.deviceReceiveOrder.fromDeptCode;
      this.formData.fromInvCode = this.deviceReceiveOrder.fromInvCode;
      this.formData.fromInvSpaceCode = this.deviceReceiveOrder.fromInvSpaceCode;
      this.formData.receiveUser = this.deviceReceiveOrder.receiveUser;
      this.getList();
    }
  },
};
</script>

