<template>
  <!-- 添加或修改盘点单对话框 -->
  <el-dialog
    id="dialog-container"
    :title="title"
    width="1200px"
    append-to-body
    :visible.sync="dialogVisible"
    @close="handleClose"
  >
    <div class="edit-container">
      <el-form ref="form" :model="form" :rules="rules" label-width="85px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="盘点单号" prop="panId">
              <el-input
                v-model="form.panId"
                placeholder="请输入盘点单号"
                :disabled="true"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="仓库编号" prop="storageId">
              <el-input
                v-model="form.storageId"
                placeholder="请输入仓库编号"
                :disabled="isDisable"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="库区编号" prop="storageAreaId">
              <el-input
                v-model="form.storageAreaId"
                placeholder="请输入库区编号"
                :disabled="isDisable"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button @click="importCurrentStock">导入当前库存</el-button>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="盘点人" prop="recordPerson">
              <el-input
                v-model="form.recordPerson"
                placeholder="请输入盘点人"
                :disabled="isDisable"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="盘点时间" prop="recordDate">
              <el-date-picker
                clearable
                v-model="form.recordDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择盘点时间"
                :disabled="isDisable"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="table-container1" height="500px">
        <div ref="mainTablePanel" height="500px">
          <el-table border size="mini" height="500px" :data="panDetailList">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="仓库编号" align="center" prop="storageId" />
            <el-table-column
              label="库区编号"
              align="center"
              prop="storageAreaId"
            />
            <el-table-column
              label="库位编号"
              align="center"
              prop="locationId"
            />
            <el-table-column label="物料编号" align="center" prop="goodsId" />
            <el-table-column label="条形码" align="center" prop="barcode" />
            <el-table-column label="物料名称" align="center" prop="goodsName" />
            <el-table-column label="生产批号" align="center" prop="batchNo" />
            <el-table-column label="库存数量" align="center" prop="stockNum" />
            <el-table-column
              width="100px"
              align="center"
              prop="checkNum"
              v-if="action != 'new'"
            >
              <template slot="header" slot-scope="scope">
                <span>盈亏数量</span>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="盈正 亏负 平0"
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.checkNum"
                  :disabled="isDisable"
                  @focus="onFocus(scope.row)"
                  @blur="onBlur(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="清点状态" align="center" prop="status">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.check_status"
                  :value="scope.row.status"
                />
              </template>
            </el-table-column>
            <el-table-column label="物料状态" align="center" prop="goodsStatus">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.goods_status"
                  :value="scope.row.goods_status"
                />
              </template>
            </el-table-column>

            <el-table-column label="物料SKU" align="center" prop="goodsSku" />
            <el-table-column
              label="物料分类"
              align="center"
              prop="goodsTypeId"
            />
            <el-table-column label="单位" align="center" prop="unit" />
            <el-table-column label="规格" align="center" prop="specification" />
            <el-table-column
              label="入库时间"
              align="center"
              prop="wareDate"
              width="100px"
            />
            <el-table-column label="测量单位" align="center" prop="scaleUnit" />
          </el-table>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button
        v-if="auditBtnShow"
        type="primary"
        @click="auditHandler"
        style="margin-right: 10px"
        >盘点审核</el-button
      >
      <el-button type="primary" @click="saveAllProc">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  listPanOrder,
  getPanOrder,
  delPanOrder,
  addPanOrder,
  updatePanOrder,
  disabledOrder,
  enabledOrder,
  changeStatusOrder,
  importCurrStock,
  saveAll,
} from "@/api/system/panOrder";
import { listPanDetail, updatePanDetail } from "@/api/system/panDetail";
import { listCOLUMN } from "@/api/system/column";
import { generateSeq, generateTempSeq } from "@/api/tool/gen";
import Cookies from "js-cookie";
import { getCurrentDateStr } from "@/utils/common";
import { debounce } from "lodash";
import DictData from "@/components/DictData";
DictData.install();
export default {
  name: "detail",
  dicts: ["check_status", "goods_status"],
  props: {
    action: {
      type: String,
      default: "new",
    },
    record: {
      type: Object,
      default: {},
    },
    title: {
      type: String,
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      firstRow: null,
      secondRow: null,
      auditBtnShow: false,
      isDisable: false,
      cnt: 0,
      // 是否显示弹出层
      dialogVisible: this.visible,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 盘点单表格数据
      panDetailList: [],
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      mainTableHeight1: "0px",
      mainTableDivHeight1: "0px",
      businessCodeTrk: "pan",
      rightToolbarShow: false,
      tableNo: 0,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        panId: null,
        orderId: null,
        storageId: "F0001",
        storageAreaId: "A001",
        total: null,
        muchNum: null,
        lessNum: null,
        justNum: null,
        status: null,
        auditMan: null,
        auditDate: null,
        confirmStatus: null,
        recordPerson: null,
        recordDate: null,
        taskId: null,
      },

      // 表单参数
      form: {
        panId: null,
        storageId: "F0001",
        storageAreaId: "A001",
        status: "0",
        confirmStatus: "0",
      },
      // 表单校验
      rules: {
        panId: [
          { required: true, message: "盘点单号不能为空", trigger: "blur" },
        ],
      },
      columns: [
        {
          key: 4,
          label: `库区编号`,
          columnName: "storage_area_id",
        },
        {
          key: 13,
          label: `确认状态`,
          columnName: "confirm_status",
        },
        {
          key: 14,
          label: `操作人`,
          columnName: "record_person",
        },
        {
          key: 15,
          label: `操作时间`,
          columnName: "record_date",
        },
        {
          key: 17,
          label: `创建时间`,
          columnName: "create_time",
        },
        {
          key: 18,
          label: `更新时间`,
          columnName: "update_time",
        },
      ],
    };
  },
  created() {},
  computed: {
    checkNum() {
      return this.panDetailList.map((item) => item.checkNum);
    },
  },
  watch: {
    checkNum: {
      handler(newVal, oldVal) {
        // for (let i = 0; i < newVal.length; i++) {
        //   if (newVal[i] != oldVal[i]) {
        //     this.panDetailList[i].status = "1";
        //     // updatePanDetail(this.panDetailList[i]).then((res) => {
        //     //   console.log("更新成功。。。");
        //     // });
        //   }
        // }
      },
      deep: true,
    },
    visible: {
      handler(newVal) {
        this.dialogVisible = newVal;
        const self = this;
        if (newVal) {
          if (this.action == "new") {
            this.reset();
            generateTempSeq({ key: `PAN-` + getCurrentDateStr(), len: 2 }).then(
              (res) => {
                self.form.panId = res.seq;
                self.auditBtnShow = false;
              }
            );
            this.panDetailList = [];
            this.form.recordDate = new Date();
            this.form.recordPerson = this.$store.state.user.name;
            this.isDisable = false;
          }
          if (this.action == "edit") {
            if (this.record.id) {
              this.form = this.record;
              listPanDetail({ mainId: this.record.id }).then((res) => {
                this.panDetailList = res.rows;
              });
            }
            this.isDisable = false;
          }
          if (this.action == "audit") {
            this.form = this.record;
            this.isDisable = true;
          }
          if (this.action == "view") {
            this.form = this.record;
            this.isDisable = true;
          }
        }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    onFocus(firstRow) {
      this.firstRow = { ...firstRow };
      console.log("firstRow", firstRow);
    },
    onBlur(secondRow) {
      this.secondRow = secondRow;
      if (this.firstRow.checkNum !== secondRow.checkNum) {
        console.log("secondRow", secondRow);
      }
    },
    // onRowChange(newRow, oldRow) {
    //   console.log(newRow, oldRow);
    // },
    auditHandler() {
      panAudit().then((res) => {
        console.log("00000000- ", res);
      });
    },
    saveAllProc: debounce(function () {
      const self = this;
      if (this.form.id) {
        const panData = { ...this.form, detailList: this.panDetailList };
        saveAll(panData).then((res) => {
          self.dialogVisible = false;
          this.$emit("close");
        });
      } else {
        generateSeq({ key: `PAN-` + getCurrentDateStr(), len: 2 }).then(
          (res) => {
            self.form.panId = res.seq;
            // 为从表数据设置mainId的任务交由后端负责。
            this.panDetailList = this.panDetailList.map((item) => {
              delete item.id;
              return item;
            });
            const panData = { ...this.form, detailList: this.panDetailList };
            saveAll(panData).then((res) => {
              self.dialogVisible = false;
              this.$emit("close");
            });
          }
        );
      }
    }, 1000),
    // 表单重置
    reset() {
      this.form = {
        id: null,
        panId: null,
        orderId: null,
        storageId: null,
        storageAreaId: null,
        total: null,
        muchNum: null,
        lessNum: null,
        justNum: null,
        status: "0",
        createBy: null,
        auditMan: null,
        auditDate: null,
        confirmStatus: "0",
        recordPerson: null,
        recordDate: null,
        taskId: null,
        createTime: null,
        updateTime: null,
        updateBy: null,
      };
      this.resetForm("form");
    },

    handleClose() {
      this.dialogVisible = false;
      this.$emit("close");
    },

    cancel() {
      this.dialogVisible = false;
      this.$emit("close");
    },
    importCurrentStock() {
      importCurrStock({
        storageId: this.form.storageId,
        storageAreaId: this.form.storageAreaId,
      }).then((res) => {
        debugger;
        this.panDetailList = res.rows.map((item) => {
          item.stockNum = item.shelvesNum;
          item.checkNum = 0;
          return item;
        });
      });
    },
  },
};
</script>
<style scoped></style>
