<template>
  <!-- 采购明细出库 -->
  <div>
    <div class="common-card">
      <el-form :model="listQuery" ref="planForm" :inline="true">
        <el-form-item label="采购单号" prop="purcOrdId">
          <el-input
            v-model="listQuery.purcOrdId"
            placeholder="请输入采购单号"
          ></el-input>
        </el-form-item>
        <el-form-item label="医保编码" prop="hiCode">
          <el-input
            v-model="listQuery.hiCode"
            placeholder="请输入医保编码"
          ></el-input>
        </el-form-item>
        <el-form-item label="耗材信息" prop="prodName">
          <el-input
            v-model="listQuery.prodName"
            placeholder="请输入耗材信息"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getDetails('search')"
            >查询
          </el-button>
          <el-button type="primary" @click="reset()">重置 </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="common-card">
      <el-form :model="tableform" ref="tableform">
        <el-table
          :data="tableform.tableData"
          v-loading="loding"
          ref="tabelView"
          element-loading-text="加载中..."
          border
          row-key="id"
          height="500"
          @selection-change="handleSelectionChange"
        >
          <template slot="empty">
            <img src="@/assets/nopage.png" alt />
            <p>暂无数据</p>
          </template>
          <el-table-column
            type="selection"
            :reserve-selection="true"
            width="55"
          ></el-table-column>
          <el-table-column fixed type="index" label="序号" width="60" />
          <el-table-column label="采购单号" prop="purcOrdId" />
          <el-table-column label="耗材编码" prop="prodCode" />
          <el-table-column label="医保编码" prop="hiCode" />
          <el-table-column label="耗材信息" width="300">
            <template slot-scope="scope">
              <mcs-info :info="scope.row"></mcs-info>
            </template>
          </el-table-column>
          <el-table-column label="规格" prop="spec" />
          <el-table-column label="型号" prop="mol" />
          <el-table-column label="材质" prop="matl" />
          <el-table-column label="单价" prop="purcPric" />
          <el-table-column label="批号" prop="lotNum" width="120">
            <template slot-scope="scope">
              <el-form-item
                label-width="0"
                class="item"
                :prop="'tableData.' + scope.$index + '.lotNum'"
                :rules="lotNumCheck(scope.row, lotNumRule)"
              >
                <el-input
                  placeholder="请输入"
                  v-model="scope.row.lotNum"
                  @change="handleEDIT(scope.row, scope.$index)"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="生产日期" prop="manuDate" width="220">
            <template slot-scope="scope">
              <el-form-item
                label-width="0"
                class="item"
                :prop="'tableData.' + scope.$index + '.manuDate'"
                :rules="lotNumCheck(scope.row, manuDate)"
              >
                <el-date-picker
                  style="width: 100%"
                  v-model="scope.row.manuDate"
                  type="date"
                  :picker-options="TimeOption1"
                  placeholder="请选择生产日期"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="有效期至" width="220" props="prodExpy">
            <template slot-scope="scope">
              <el-form-item
                label-width="0"
                class="item"
                :prop="'tableData.' + scope.$index + '.prodExpy'"
                :rules="lotNumCheck(scope.row, prodExpyRule)"
              >
                <el-date-picker
                  style="width: 100%"
                  v-model="scope.row.prodExpy"
                  type="date"
                  placeholder="请选择有效期"
                  :picker-options="TimeOption"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="需求数量" prop="purcCnt" />
          <el-table-column label="剩余出库量" prop="toDelvCnt" width="90px" />
          <el-table-column label="出库数量" props="delvCnt" width="150">
            <template slot-scope="scope">
              <el-form-item
                label-width="0"
                class="item"
                :prop="'tableData.' + scope.$index + '.delvCnt'"
                :rules="lotNumCheck(scope.row, delvCntRule)"
              >
                <el-input-number
                  v-model="scope.row.delvCnt"
                  controls-position="right"
                  @change="updateNum(scope.row, scope.$index)"
                  :min="0"
                ></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="报关单" prop="invoFileId" width="200">
            <template slot-scope="scope">
              <yl-upload
                v-if="scope.row.prodSouc == '2'"
                :fileId="scope.row.invoFileId"
                @getUpload="getUpload1"
                urlName="acco"
                :index="scope.$index"
              >
                <template v-slot:dec
                  >只能上传pdf文件</template
                >
              </yl-upload>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="memo" width="120">
            <template slot-scope="scope">
              <el-form-item label-width="0" class="item">
                <el-input
                  placeholder="请输入"
                  v-model="scope.row.memo"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            fixed="right"
            label="操作"
            width="120"
          >
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.showDeleteButton"
                class="red"
                type="text"
                @click="handleDelete(scope.row, scope.$index)"
                >删除</el-button
              >
              <el-button
                v-else
                type="text"
                @click="handleBatch(scope.row, scope.$index)"
                >添加批次
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <ylPagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getdialog"
    />
    <div class="foot-button" style="margin-top: 30px">
      <!-- <el-button type="success" @click="handleSave">保存</el-button> -->
      <el-button type="primary" @click="handleDelivery">出库</el-button>
    </div>
  </div>
</template>

<script>
import mcsInfo from "@/views/components/mcs-info.vue";
import ylUpload from "@/components/yl-upload";
import { countNumPrice, getTotalAmount } from "@/utils/utils";
import rules from "@/utils/rules";
import ylPagination from "@/components/yl-pagination";
import { getMcsPurcOrdMx, submitMcsDelvOrd } from "@/api/orderManage-sup/index";
export default {
  components: {
    mcsInfo,
    ylUpload,
    ylPagination
  },
  data() {
    return {
      lotNumRule: [
        {
          required: true,
          message: "请输入",
          trigger: "change"
        }
      ],
      manuDate: [
        {
          required: true,
          message: "请选择生产日期",
          trigger: "change"
        }
      ],
      prodExpyRule: [
        {
          required: true,
          message: "请选择有效日期",
          trigger: "change"
        }
      ],
      delvCntRule: [
        {
          required: true,
          pattern: /^[0-9]\d*$/,
          message: "请输入正整数",
          trigger: "blur"
        }
      ],
      rules,
      listForm: {
        dyntNo: "",
        current: 1,
        size: 10
      },
      total: 0,
      planForm: {},
      // 表格数据
      loding: false,
      tableform: {
        tableData: []
      },
      // 弹框表格数据
      dialog: false,
      listQuery: {
        current: 1,
        size: 10,
        purcOrdId: "",
        hiCode: "",
        prodName: ""
      },
      consumableData: [],
      selectData: [],
      dialogLoading: false,
      Loading: false,
      cellList: [],
      isFasData: [{ value: "1", name: "是" }, { value: "0", name: "否" }],
      TimeOption: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        }
      },
      TimeOption1: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      udidialog: false
    };
  },
  mounted() {
    this.getDetails();
  },
  methods: {
    getDetails() {
      this.getdialog("search");
    },

    // 重置
    reset() {
      this.$refs.planForm.resetFields();
      this.getdialog();
    },
    // 采购明细数据
    getdialog(type) {
      if (type == "search") {
        this.listQuery.current = 1;
      }
      this.dialogLoading = true;
      getMcsPurcOrdMx(this.listQuery)
        .then(res => {
          this.tableform.tableData = res.data.records;
          this.total = res.data.total;
          this.dialogLoading = false;
        })
        .catch(err => {
          this.dialogLoading = false;
        });
    },
    //表格选中再进行校验
    lotNumCheck(row, ruleArray) {
      let rule = [];
      let isId = this.selectData.filter(item => {
        return item.id == row.id;
      });
      if (isId.length > 0) {
        rule = ruleArray;
      } else {
        rule = [];
      }
      return rule;
    },
    //删除
    handleDelete(row, i) {
      const index = this.tableform.tableData.findIndex(
        item => item.prodCode === row.prodCode
      );
      if (index !== -1) {
        let qwe = this.tableform.tableData.findIndex(function(item) {
          return item.prodCode == row.prodCode;
        });
        this.tableform.tableData.splice(i, 1);
        this.cellList.splice(i, 1);
        this.cellList[qwe]--;
      }
      row.showDeleteButton = false;
      this.shanchu3(row);
      if (this.number[index]) {
        this.shanchu2(row, index);
      } else {
        this.shanchu(row);
      }
      this.number.splice(i, 1);
    },
    //弹框选择
    handleSelectionChange(e) {
      this.selectData = e;
    },
    // 判断一个数组对象的属性是否有重复
    pf(arr) {
      for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          console.log(arr[i].prodCode, arr[j].prodCode);
          if (arr[i].prodCode == arr[j].prodCode) {
            var set = new Set(); //创建个集合Set对象（用object对象也可以）
            return arr.some(function(v, i) {
              //遍历 arr数组，当返回值为true时提前退出遍历。
              var f = set.has(v.lotNum); //判断每个对象里number属性的值是否在集合Set
              set.add(v.lotNum); //将number属性的值添加到集合Set中
              return f;
            });
          } else {
            console.log("else");
          }
        }
      }
    },
    // 出库
    handleDelivery() {
      if (this.selectData.length <= 0) {
        this.$message({
          message: "请选择出库明细",
          type: "warning"
        });
        return;
      }
      this.selectData.forEach(item => {
        if (item.delvCnt == "0") {
          this.$message({
            message: "本次出库数量必须大于0",
            type: "warning"
          });
          throw new Error("本次出库数量必须大于0");
        }
        if (item.prodSouc == "2" && !item.invoFileId) {
          this.$message({
            message: "请填写相应信息，并选择报关单",
            type: "warning"
          });
          throw new Error("请填写相应信息，并选择报关单");
        }
      });
      let lotnum = this.pf(this.selectData);
      if (lotnum == true) {
        this.$message({
          message: "同一产品的批号不能重复",
          type: "info"
        });
        throw new Error("同一产品的批号不能重复");
      }
      this.$refs.tableform.validate(valid => {
        if (valid) {
          let data = this.selectData.map(i => {
            return i.purcOrdId;
          });
          let data2 = data.slice(1);
          let qwe = data2.some(item => {
            if (item != data[0]) {
              return true;
            }
          });
          if (qwe == true) {
            this.$message.info("请勾选同一采购单明细");
          } else {
            this.$confirm("确认出库", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              let data = this.selectData.map(i => {
                return {
                  materialId: i.prodCode,
                  memo: i.memo,
                  delvCnt: i.delvCnt,
                  hiCode: i.hiCode,
                  purcPric: i.purcPric,
                  lotNum: i.lotNum,
                  manuDate: i.manuDate,
                  prodExpy: i.prodExpy,
                  invoFileId: i.invoFileId,
                  dyntFileId: i.dyntFileId,
                  noRow: i.index,
                  purcOrdId: this.selectData[0].purcOrdId
                };
              });
              let data2 = {
                delvOrdId: "",
                spdId: "",
                detlList: data,
                dyntNo: ""
              };
              submitMcsDelvOrd(data2)
                .then(res => {
                  this.getdialog();
                  this.selectData = [];
                  this.$message({
                    message: "出库成功",
                    type: "success"
                  });
                  this.selectData = [];
                  this.$refs.tabelView.clearSelection();
                })
                .catch(err => {
                  this.$message.error("出库失败");
                });
            });
          }
        } else {
          this.$message({
            type: "warning",
            message: "请填写必填项信息"
          });
        }
      });
    },
    // 查看UDI码
    // 填写UDI码
    handleudi(row) {
      this.udidialog = true;
      let udiObj = {
        spec: row.spec,
        mol: row.mol,
        matl: row.matl,
        isFas: row.isFas,
        lotNum: row.lotNum,
        manuDate: row.manuDate,
        prodExpy: row.prodExpy,
        convrat: row.convrat,
        prcUnt: row.prcUnt,
        purcUnt: row.purcUnt,
        prodName: row.prodName,
        regcertno: row.regcertno,
        prodEntp: row.prodEntp,
        fasBtch: row.fasBtch
      };
      // const obj = { a: 1, b: 2 };
      const n = 5;
      // const copiedObjects = Array.from({ length: n }, () => ({ ...obj }));
      // const n = row.udid;
      const copiedObjects = Array.from({ length: n }, () => ({ ...udiObj }));
      console.log(copiedObjects, "copiedObjects");
      this.udiData = copiedObjects;
    },
    // 添加批次
    handleBatch(row, index) {
      let list = {
        purcOrdId: row.purcOrdId,
        prodCode: row.prodCode,
        regcertno: row.regcertno,
        delvCnt: "",
        delvCntYck: row.delvCntYck,
        docmkDate: row.docmkDate,
        docmker: row.docmker,
        essdrugType: row.essdrugType,
        prodEntp: row.prodEntp,
        materialId: row.materialId,
        id: row.id,
        prodName: row.prodName,
        hiCode: row.hiCode,
        mol: row.mol,
        matl: row.matl,
        memo: row.memo,
        mcsType: row.mcsType,
        purcPric: row.purcPric,
        purcAmt: row.purcAmt,
        purcCnt: row.purcCnt,
        prodSouc: row.prodSouc,
        spec: row.spec,
        toDelvCnt: row.toDelvCnt,
        invoFileId: "",
        lotNum: "",
        manuDate: "",
        prodExpy: "",
        dyntFileId: ""
      };
      this.tableform.tableData.splice(index + 1, 0, list);
      list.showDeleteButton = true;
      this.computeCell(this.tableform.tableData);
    },
    getUpload1(id, index) {
      this.tableform.tableData[index].invoFileId = id;
      if (id) {
        this.$refs.tableform.clearValidate("invoFileId");
      } else {
        this.$refs.tableform.validateField("invoFileId");
      }
    },
    // 筛选合并项
    computeCell(tableData) {
      this.cellList = [];
      this.count = null;
      for (let i = 0; i < tableData.length; i++) {
        if (i == 0) {
          // 先设置第一项
          this.cellList.push(1); // 初为1，若下一项和此项相同，就往cellList数组中追加0
          this.count = 0;
          console.log("索引", 0, this.count);
        } else {
          // 判断当前项与上项的设备类别是否相同，因为是合并这一列的单元格
          if (tableData[i].id == tableData[i - 1].id) {
            this.cellList[this.count] += 1; // 增加计数
            this.cellList.push(0); // 相等就往cellList数组中追加0
            console.log("索引", i, this.count);
          } else {
            this.cellList.push(1); // 不等就往cellList数组中追加1
            this.count = i; // 将索引赋值为计数
            console.log("索引", i, this.count);
          }
        }
      }
    },
    //获取出库数量和
    numAll(row) {
      let num = 0;
      this.tableform.tableData.forEach(item => {
        if (item.prodCode == row.prodCode) {
          num += item.delvCnt;
        }
      });
      return num;
    },
    shanchu3(row) {
      this.tableform.tableData.forEach(async item => {
        await this.numAll(row);
        if (item.prodCode == row.prodCode) {
          if (this.numAll(row) > item.toDelvCnt) {
            this.$message.warning("出库数量不能大于待出库数量");
            row.delvCnt = 0;
            return;
          }
        }
        let choose = this.tableData;
        this.tableData = choose;
      });
    },
    numOrPriceChange(index, row) {
      this.$set(
        this.tableform.tableData[index],
        "purcPric",
        getTotalAmount(row.delvCnt, row.purcPric)
      );
      this.amount = countNumPrice(this.tableData);
    },
    // 出库数量变更
    updateNum(row, index) {
      // const aa = this.tableData.findIndex((item) => item.id === row.id);
      // if(this.number[aa]){
      //     this.shanchu2(row,aa);
      // }else{
      //     this.shanchu(row);
      // }
      this.shanchu3(row);
      // this.numOrPriceChange(index, row);
    },
    // 确认
    handleConfirm() {
      let data = this.selectData.map(i => {
        return i.purcOrdId;
      });
      let data2 = data.slice(1);
      let qwe = data2.some(item => {
        if (item != data[0]) {
          return true;
        }
      });
      if (qwe == true) {
        this.$message.info("请勾选同一采购单明细");
      } else {
        this.tableform.tableData = this.selectData;
        this.computeCell(this.tableform.tableData);
        this.dialog = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog-tq ::v-deep .el-input__inner {
  width: 170px;
}
</style>
