<template>
  <view
    :class="[
      first_supplierId != '' ? 'scanContainer0' : 'scanContainer1',
      qrCodeProps.allot ? 'scan_allot' : '',
    ]"
  >
    <view class="header">
      <span>{{ qrCodeProps.title }}</span>
      <uni-icons
        type="scan"
        color="#333"
        size="26"
        style="display: block"
      ></uni-icons>
      <!-- @click="toScanAdd" -->
    </view>
    <view class="table_container">
      <t-table border="0">
        <t-tr font-size="14" class="tr-head">
          <t-th v-if="qrCodeProps.inventory">仓位</t-th>
          <t-th>物料代码</t-th>
          <t-th>物料名称</t-th>
          <t-th>规格型号</t-th>
          <t-th>辅助单位</t-th>
          <t-th>数量</t-th>
          <t-th>批号</t-th>
          <!-- <t-th>{{ qrCodeProps.countType }}</t-th> -->
        </t-tr>
        <view class="tr-body">
          <t-tr
            font-size="14"
            v-for="(item, index) in tableList"
            :key="index"
            :class="[
              item.detail ? 'show_detail' : '',
              qrCodeProps.inventory && item.detail ? 'show_detail2' : '',
            ]"
          >
            <view class="tr_view" @click="chooseTr(index)">
              <t-td v-if="qrCodeProps.inventory">{{
                item.facilityLocationName
              }}</t-td>
              <t-td>{{ item.serialNo }}</t-td>
              <t-td>{{ item.name }}</t-td>
              <t-td>{{ item.specification }}</t-td>
              <t-td>{{ item.supportUomName }}</t-td>
              <t-td>{{ item.countSupport }}</t-td>
              <t-td>{{ item.batch }}</t-td>
              <!-- <t-td>{{ item.count }}</t-td> -->
            </view>
            <view v-if="item.detail" class="detailContainer">
              <view class="item_detail" v-if="qrCodeProps.inventory">
                <span class="detail_name">仓位</span>
                <span class="detail_value">{{
                  item.facilityLocationName
                }}</span>
              </view>
              <view class="item_detail">
                <span class="detail_name">物料代码</span>
                <span class="detail_value">{{ item.serialNo }}</span>
              </view>
              <view class="item_detail">
                <span class="detail_name">物料名称</span>
                <span class="detail_value">{{ item.name }}</span>
              </view>
              <view class="item_detail">
                <span class="detail_name">规格型号</span>
                <span class="detail_value">{{ item.specification }}</span>
              </view>
              <view class="item_detail">
                <span class="detail_name">主计量单位</span>
                <span class="detail_value">{{ item.unitUomName }}</span>
              </view>
              <view class="item_detail">
                <span class="detail_name detail_name_required"
                  >{{ qrCodeProps.countType }}(主单位)</span
                >
                <span class="detail_value">{{ item.count }}</span>
                <!-- <span class="detail_value"><input :class="[qrCodeProps.countEdit?'detail_value_input detail_value_input_disabled':'detail_value_input']" type="number" v-model="item.count" :disabled="qrCodeProps.countEdit"/></span> -->
              </view>
              <view class="item_detail">
                <span class="detail_name">辅助单位</span>
                <span class="detail_value">{{ item.supportUomName }}</span>
              </view>
              <view class="item_detail">
                <span class="detail_name">换算系数</span>
                <span class="detail_value">{{ item.convCoefficient }}</span>
              </view>
              <view class="item_detail">
                <span class="detail_name">批号</span>
                <span class="detail_value">{{ item.batch }}</span>
              </view>
              <view class="item_detail">
                <span class="detail_name detail_name_required"
                  >{{ qrCodeProps.countType }}(辅助单位)</span
                >
                <!-- <span class="detail_value"><input :class="[qrCodeProps.countEdit?'detail_value_input detail_value_input_disabled':'detail_value_input']" type="number" v-model="item.count_input" :disabled="qrCodeProps.countEdit"/></span> -->
                <span class="detail_value"
                  ><input
                    class="detail_value_input"
                    @input="changeCount(index)"
                    type="number"
                    v-model="item.count_input"
                /></span>
              </view>
              <view class="item_detail_btn_container">
                <view class="item_detail_btn" @click="sureDetail(index)"
                  >确定</view
                >
                <view class="item_detail_btn" @click="deleteDetail(index)"
                  >删除</view
                >
              </view>
            </view>
          </t-tr>
        </view>
      </t-table>
    </view>
    <view class="bottom_btn"
      ><view class="btn" @click="toSubmit">提交</view></view
    >
  </view>
</template>

<script>
// import jweixin from "../../jweixin-module/index.js";
import uniIcons from "@/components/uni-icons/uni-icons.vue";
import tTable from "@/components/wms/t-table/t-table.vue";
import tTh from "@/components/wms/t-table/t-th.vue";
import tTr from "@/components/wms/t-table/t-tr.vue";
import tTd from "@/components/wms/t-table/t-td.vue";
export default {
  name: "xinsoft-scan",
  components: {
    uniIcons,
    tTable,
    tTh,
    tTr,
    tTd,
  },
  props: {
    isSameWarehouse: {
      type: Boolean,
      default: true,
    },
    // title 扫码入库明细/扫码出库明细 。countType 入库数量/出库数量。 qrCodeDetailUrl：获取二维码信息的接口。入库和出库的不一样。countEdit 入库/出库数量是否可以修改true false
    qrCodeProps: {
      type: Object,

      // title:'扫码出库明细',
      // 	countType:'出库数量',
      // 	qrCodeDetailUrl:'/apis/scm/qrcode/outDetail',
      // 	countEdit:false,//入库/出库数量是否有disabled. true数量不可修改,false数量可修改
      // id:'',//源单id
      // facilityId:'',//仓库
      // facilityLocationId:'',
      // facilityIdRequired:true,//扫码之前是否要验证仓库必填
      // facilityLocationIdRequired:false,//扫码之前是否要验证仓位必填
      // clear:true,//清空扫码列表
    },
  },
  data() {
    return {
      first_supplierId: "",
      first_supplierName: "",
      tableList: [
        // {
        // 	serialNo: 'aa12345',
        // 	name: 'aa物料1物料1物料1物料1aa物料1物料1物料1物料1aa物料1物料1物料1物料1',
        // 	specification: 'aabcd',
        // 	unitUomName: 'a个',
        // 	batch: 'a12',
        // 	count: '500',
        // 	availableCount: 500,
        // 	detail: true
        // },
        // { serialNo: 'b12345', name: 'b物料1物料1物料1物料1', specification: 'babcd', unitUomName: 'b个', batch: 'b12', availableCount: 500, count: '500' },
        // { serialNo: 'b12345', name: 'b物料1物料1物料1物料1', specification: 'babcd', unitUomName: 'b个', batch: 'b12', availableCount: 500, count: '500' }
      ],
    };
  },
  mounted() {
    // this.initiateWX();
    if (this.qrCodeProps.inType == 0 || this.qrCodeProps.inType == 2) {
      //采购入库，委外入库,有供应商
      this.first_supplierId = this.qrCodeProps.supplierId;
      this.first_supplierName = this.qrCodeProps.supplierName;
    }

    this.first_supplierId = this.qrCodeProps.supplierId
      ? this.qrCodeProps.supplierId
      : "";
  },
  methods: {
    changeCount(index) {
      this.$set(
        this.tableList[index],
        "count",
        this.tableList[index].count_input *
          this.tableList[index].convCoefficient
      );
    },

    //获取微信相关
    initiateWX() {
      this.$http
        .request({
          url: "/apis/weChat/getSignature",
          params: {
            // url:"http://gyhl.wxxinsoft.org:18093/gyhl-app/"
            url: window.location.href.split("#")[0],
          },
        })
        .then((res) => {
          if (res.data.code == 0) {
            var s = res.data;
            jweixin.config({
              beta: true,
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: s.corpId, // 必填，公众号的唯一标识
              timestamp: s.timestamp, // 必填，生成签名的时间戳
              nonceStr: s.nonceStr, // 必填，生成签名的随机串
              signature: s.signature.toLowerCase(), // 必填，签名，见附录1
              jsApiList: [
                "onMenuShareTimeline",
                "onMenuShareAppMessage",
                "onMenuShareQQ",
                "onMenuShareWeibo",
                "onMenuShareQZone",
                "scanQRCode",
              ],
            });
          } else {
            uni.showToast({
              title: res.msg ? res.msg : "获取微信配置失败",
              icon: "none",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          uni.showToast({
            title: err,
            icon: "none",
            duration: 2000,
          });
        });
    },
    //扫码添加
    toScanAdd() {
      let _this = this;
      //扫码前仓库先选择
      if (
        this.qrCodeProps.facilityId == "" &&
        this.qrCodeProps.facilityIdRequired
      ) {
        let text = this.qrCodeProps.allot ? "请先选择调出仓库" : "请先选择仓库";
        uni.showToast({
          title: text,
          icon: "none",
          duration: 2000,
        });
        return;
      }
      //扫码前仓位先选择
      if (
        this.qrCodeProps.facilityLocationId == "" &&
        this.qrCodeProps.facilityLocationIdRequired
      ) {
        uni.showToast({
          title: "请先选择仓位",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      // this.getQrCodeInfo(358)////////采购退货 要先采购入库
      // this.getQrCodeInfo(362)////////销售退货
      // this.getQrCodeInfo(344)////////生产退料
      // this.getQrCodeInfo(373)////////委外退料
      // _this.getQrCodeInfo(197)
      jweixin.scanQRCode({
        desc: "scanQRCode desc",
        needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
        scanType: ["qrCode"], // 可以指定扫二维码还是条形码（一维码），默认二者都有"qrCode", "barCode"
        success: function (res) {
          if (res.errMsg != "scanQRCode:ok") {
            uni.showToast({
              title: "扫描结果:" + res.resultStr,
              icon: "none",
              duration: 2000,
            });
          } else {
            //扫码正确
            let resultStr = res.resultStr;
            try {
              resultStr = JSON.parse(resultStr);
              if (resultStr.id) {
                _this.getQrCodeInfo(resultStr.id);
              } else {
                uni.showToast({
                  title: "二维码错误，请扫描正确的二维码",
                  icon: "none",
                  duration: 2000,
                });
              }
            } catch (e) {
              uni.showToast({
                title: "二维码错误，请扫描正确的二维码",
                icon: "none",
                duration: 2000,
              });
            }
          }
          // 回调
        },
        fail: function (res) {
          uni.showToast({
            title: "error:" + res.errMsg,
            icon: "none",
            duration: 2000,
          });
          if (res.errMsg.indexOf("function_not_exist") > 0) {
            alert("版本过低请升级");
          }
        },
      });
    },
    //调用接口获取二维码信息
    getQrCodeInfo(id) {
      // id = 197
      let _this = this;
      let flag = true;
      _this.tableList.forEach((p) => {
        if (p.qrcodeId == id) {
          flag = false;
        }
      });
      if (!flag) {
        uni.showToast({
          title: "不可重复扫码添加",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      this.$http
        .request({
          url: _this.qrCodeProps.qrCodeDetailUrl,
          params: {
            qrCodeId: id,
            supplierId: this.qrCodeProps.supplierId
              ? this.qrCodeProps.supplierId
              : "",
            inType:
              this.qrCodeProps.inType != undefined
                ? this.qrCodeProps.inType
                : "",
            isMultiple:
              this.qrCodeProps.isMultiple != undefined
                ? this.qrCodeProps.isMultiple
                : "",
            contractNo:
              this.qrCodeProps.contractNo != undefined
                ? this.qrCodeProps.contractNo
                : "",
            sourceCode:
              this.qrCodeProps.sourceCode != undefined
                ? this.qrCodeProps.sourceCode
                : "",
            inOut:
              this.qrCodeProps.inOut != undefined ? this.qrCodeProps.inOut : "",
          },
          method: "GET",
        })
        .then((res) => {
          if (res.data.code == 0) {
            if (this.qrCodeProps.inType == 0 || this.qrCodeProps.inType == 2) {
              //采购入库，委外入库
              if (this.first_supplierId == "" || !this.first_supplierId) {
                //第一次扫码
                this.first_supplierId = res.data.qrCodeInfo.supplierId;
                this.first_supplierName = res.data.qrCodeInfo.supplierName;
                this.qrCodeProps.supplierId = res.data.qrCodeInfo.supplierId;
                this.qrCodeProps.supplierName =
                  res.data.qrCodeInfo.supplierName;
                if (!this.qrCodeProps.contractNo) {
                  this.qrCodeProps.contractNo = res.data.qrCodeInfo.contractNo;
                  this.qrCodeProps.id = res.data.qrCodeInfo.sourceId;
                }
              } else {
                if (this.first_supplierId != res.data.qrCodeInfo.supplierId) {
                  uni.showToast({
                    title: "同一张入库单据中只能选择同一个供应商的物料！",
                    icon: "none",
                    duration: 2000,
                  });
                  return;
                }
              }
            }
            //验证头部仓库必须先选的时候，扫码的仓库和选择的仓库一样
            if (
              this.isSameWarehouse &&
              this.qrCodeProps.facilityIdRequired &&
              res.data.qrCodeInfo.facilityId != this.qrCodeProps.facilityId
            ) {
              //验证仓库一样
              uni.showToast({
                title: "仓库不一样，无法添加",
                icon: "none",
                duration: 2000,
              });
              return;
            }
            //验证头部仓位必须先选的时候，扫码的仓位和选择的仓库一样
            if (
              this.isSameWarehouse &&
              this.qrCodeProps.facilityLocationIdRequired &&
              res.data.qrCodeInfo.facilityLocationId !=
                this.qrCodeProps.facilityLocationId
            ) {
              //验证仓库一样
              uni.showToast({
                title: "仓位不一样，无法添加",
                icon: "none",
                duration: 2000,
              });
              return;
            }
            let flag_add = true;
            //盘点需要多一步验证
            if (this.qrCodeProps.inventory) {
              let obj1 = {
                materielId: res.data.qrCodeInfo.materielId,
                warehouse: res.data.qrCodeInfo.facilityId,
                warehLocation: res.data.qrCodeInfo.facilityLocationId,
              };
              if (res.data.qrCodeInfo.batch) {
                obj1.batch = res.data.qrCodeInfo.batch;
              }
              let qrMsg = [];
              qrMsg.push(obj1);
              this.$http
                .request({
                  url: "/apis/scm/inventoryPlan/wetherCheckByQrId",
                  params: {
                    planId: this.qrCodeProps.inventoryId,
                    qrId: id,
                    qrMsg: encodeURIComponent(JSON.stringify(qrMsg)),
                  },
                })
                .then((res2) => {
                  if (res2.data.code == 0) {
                    uni.showToast({
                      title: res2.data.msg ? res2.data.msg : "此物料可以盘点",
                      icon: "none",
                      duration: 2000,
                    });
                    let obj = {
                      qrcodeId: id,
                      materielId: res.data.qrCodeInfo.materielId,
                      serialNo: res.data.qrCodeInfo.materielNo,
                      name: res.data.qrCodeInfo.materielName,
                      specification: res.data.qrCodeInfo.specification,
                      unitUomName: res.data.qrCodeInfo.uomName,
                      count: res.data.qrCodeInfo.remainCount, //列表显示的数量
                      count_input: res.data.qrCodeInfo.remainCount, //输入框里的数量
                      availableCount: res.data.qrCodeInfo.remainCount, //库存数量
                      detail: true,
                      unitPrice: res.data.qrCodeInfo.unitPrice
                        ? res.data.qrCodeInfo.unitPrice
                        : 0,
                      amount: res.data.qrCodeInfo.amount
                        ? res.data.qrCodeInfo.amount
                        : 0,
                    };
                    if (res.data.qrCodeInfo.batch) {
                      obj.batch = res.data.qrCodeInfo.batch;
                    }
                    if (res.data.qrCodeInfo.stockId) {
                      obj.stockId = res.data.qrCodeInfo.stockId;
                    }
                    if (res.data.qrCodeInfo.facilityId) {
                      obj.facilityId = res.data.qrCodeInfo.facilityId;
                    }
                    if (res.data.qrCodeInfo.facilityLocationId) {
                      obj.facilityLocationId =
                        res.data.qrCodeInfo.facilityLocationId;
                    }
                    //盘点需要显示仓位
                    if (res.data.qrCodeInfo.facilityLocationName) {
                      obj.facilityLocationName =
                        res.data.qrCodeInfo.facilityLocationName;
                    }
                    _this.tableList.forEach((p) => {
                      if (p.detail) {
                        delete p.detail;
                      }
                    });
                    _this.tableList.unshift(obj);
                  } else {
                    uni.showToast({
                      title: res2.data.msg ? res2.data.msg : "盘点失败",
                      icon: "none",
                      duration: 2000,
                    });
                  }
                })
                .catch((err) => {
                  this.loading_status = "noMore";
                });
            } else {
              let obj = {
                qrcodeId: id,
                materielId: res.data.qrCodeInfo.materielId,
                serialNo: res.data.qrCodeInfo.materielNo,
                name: res.data.qrCodeInfo.materielName,
                specification: res.data.qrCodeInfo.specification,
                unitUomName: res.data.qrCodeInfo.uomName,
                // count: this.count_input * res.data.qrCodeInfo.convCoefficient, //列表显示的数量
                count_input: res.data.qrCodeInfo.countSupport, //输入框里的数量
                availableCount: res.data.qrCodeInfo.remainCount, //库存数量
                detail: true,
                unitPrice: res.data.qrCodeInfo.unitPrice
                  ? res.data.qrCodeInfo.unitPrice
                  : 0,
                amount: res.data.qrCodeInfo.amount
                  ? res.data.qrCodeInfo.amount
                  : 0,
                supportUomName: res.data.qrCodeInfo.supportUomName,
                supportUom: res.data.qrCodeInfo.supportUom,
                countSupport: res.data.qrCodeInfo.countSupport,
                convCoefficient: res.data.qrCodeInfo.convCoefficient,
              };
              obj.count = obj.convCoefficient * obj.count_input;
              console.log(obj);
              if (res.data.qrCodeInfo.batch) {
                obj.batch = res.data.qrCodeInfo.batch;
              }
              // if(this.qrCodeProps.count=='inOutCount'){
              // 	obj.count=parseFloat(res.data.inOutCount)
              // 	obj.count_input=parseFloat(res.data.inOutCount)
              // 	obj.availableCount=parseFloat(res.data.inOutCount)
              // }
              if (res.data.qrCodeInfo.stockId) {
                obj.stockId = res.data.qrCodeInfo.stockId;
              }
              if (res.data.qrCodeInfo.facilityId) {
                obj.facilityId = res.data.qrCodeInfo.facilityId;
              }
              if (res.data.qrCodeInfo.facilityLocationId) {
                obj.facilityLocationId = res.data.qrCodeInfo.facilityLocationId;
              }
              _this.tableList.forEach((p) => {
                if (p.detail) {
                  delete p.detail;
                }
              });
              _this.tableList.unshift(obj);
            }
          } else {
            uni.showToast({
              title: res.data.msg ? res.data.msg : "获取二维码信息失败",
              icon: "none",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          uni.showToast({
            title: err,
            icon: "none",
            duration: 2000,
          });
        });
    },
    //点击某一行
    chooseTr(index) {
      let flag = this.tableList[index].detail ? true : false;
      this.tableList.forEach((p) => {
        if (p.detail) {
          delete p.detail;
        }
      });
      this.$set(this.tableList[index], "detail", !flag);
      this.$set(
        this.tableList[index],
        "count_input",
        this.tableList[index].count_input
      );
    },
    //确定
    sureDetail(index) {
      if (
        this.tableList[index].count_input > this.tableList[index].availableCount
      ) {
        //输入的数量大于总数量
        uni.showToast({
          title: "数量不能大于库存数量",
          icon: "none",
          duration: 2000,
        });
      } else {
        this.$set(this.tableList[index], "detail", false);
        this.$set(
          this.tableList[index],
          "count",
          this.tableList[index].count_input
        );
      }
    },
    //删除
    deleteDetail(index) {
      let _this = this;
      uni.showModal({
        title: "",
        content: "确定删除吗?",
        success: function (res) {
          if (res.confirm) {
            _this.tableList.splice(index, 1);
          } else if (res.cancel) {
          }
        },
      });
    },
    //点击提交按钮
    toSubmit() {
      this.$emit("submitData", this.tableList);
    },
  },
  watch: {
    "qrCodeProps.clear": {
      handler(newName, oldName) {
        if (newName) {
          this.tableList = [];
          this.$forceUpdate();
          let qrCodeProps_ = this.qrCodeProps;
          qrCodeProps_.clear = false;
          this.$emit("update:qrCodeProps", qrCodeProps_);
        }
      },
    },
  },
};
</script>

<style scoped>
.scanContainer0 {
  position: absolute;
  top: 132px;
  bottom: 0;
  width: 100%;
}
.scanContainer1 {
  position: absolute;
  top: 92px;
  bottom: 0;
  width: 100%;
}
.scan_allot {
  top: 184px;
}
.header {
  position: relative;
  width: 100%;
  height: 40px;
  color: #333;
  border-bottom: 1px solid #e6e6e6;
}
.header span {
  line-height: 40px;
  font-size: 15px;
  margin-left: 10px;
}
.header .uni-icon {
  position: absolute;
  right: 10px;
  top: 0px;
  padding: 7px;
}
.table_container {
  position: relative;
  width: calc(100% - 10px);
  margin: auto;
  height: calc(100% - 91px);
  font-size: 13px;
  color: #333;
}
.t-table {
  position: relative;
  height: 100%;
  padding-bottom: 10px;
}
.tr-body {
  position: absolute;
  width: 100%;
  left: 0;
  bottom: 0;
  top: 38px;
  overflow: auto;
}
.t-table .t-tr {
  position: relative;
  border-bottom: 1px solid #efefef;
}
.tr_view {
  /* position: relative;
		display: block;
		width: 100%; */

  position: relative;
  overflow: auto;
  width: 100%;
}
.tr-head {
  position: relative;
  top: 0;
  width: 100%;
}
.tr-head .t-th {
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.t-td {
  position: relative;
  box-sizing: border-box;
  float: left;
  width: calc((100% / 6));
}
.show_detail2 .t-td {
  width: calc((100% / 7));
}
.td_input {
  background-color: #fff;
  width: 80%;
  height: 100%;
  font-size: 15px;
}
.bottom_btn {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.btn {
  position: relative;
  width: 95%;
  height: 40px;
  line-height: 40px;
  background-color: #007aff;
  text-align: center;
  color: #fff;
  font-size: 18px;
  letter-spacing: 5px;
}
.show_detail {
  height: 290px;
}
.show_detail2 {
  height: 240px;
}
.detailContainer {
  position: absolute;
  width: 100%;
  left: 0;
  top: 33px;
}
.item_detail {
  position: relative;
  padding-left: 5px;
  height: 24px;
  line-height: 24px;
  color: #555c60;
  font-size: 14px;
}
.item_detail_btn_container {
  position: relative;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.item_detail_btn {
  position: relative;
  text-align: center;
  line-height: 28px;
  width: 80px;
  height: 28px;
  background-color: #007aff;
  color: #fff;
  margin-right: 5px;
  margin-left: 5px;
  border-radius: 2px;
}
.detail_name {
  position: relative;
  display: inline-block;
  width: 140px;
}
.detail_name_required:after {
  position: absolute;
  right: 10px;
  line-height: 24px;
  content: "*";
  color: red;
}
.detail_value {
  position: absolute;
  padding-left: 5px;
  left: 145px;
  right: 5px;
  height: 100%;
  top: 0;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.detail_value_input {
  width: 100px;
  padding-left: 5px;
  height: 16px;
  font-size: 14px;
  border: 1px solid #b2b2b2;
}
.detail_value_input_disabled {
  border: none;
}
</style>
