<template>
  <div>
    <el-form :model="formData" :rules="formRules" ref="dataForm" label-width="100px">
      <el-row type="flex" justify="end">
        <el-button-group style="display: flex;margin-bottom: 15px; margin-right: 50px;margin-top: -5px">
          <el-button
            type="primary"
            @click.native="saveOrder('1')"
            :loading="loading"
          >草稿保存
          </el-button
          >
          <el-button
            type="primary"
            @click.native="saveOrder('2')"
            :loading="loading"
          >提交单据
          </el-button
          >
        </el-button-group>
      </el-row>
      <el-card style="margin-top: -5px;">
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item prop="billNo" label="单据号:">
              <el-input v-model="formData.billNo" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="billDate" label="单据日期:">
              <el-date-picker
                v-model="formData.billDate"
                type="datetime"
                placeholder="选择日期"
                style="width: 100%"
                :clearable="false"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item prop="invCode" label="当前仓库:">
              <el-select v-model="formData.invCode" :disabled="editType" @change="subStorageChange" placeholder="当前仓库信息"
                         style="width: 100%;"
                         clearable>
                <el-option
                  v-for="item in invList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item class="query-form-item" prop="targetInvCode" label="往来信息:">
              <el-select v-model="formData.targetInvCode" :disabled="editType" placeholder="请选择仓库"
                         clearable="true"
                         style="width: 100%"
              >
                <el-option
                  v-for="item in fromOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item prop="billType" label="领用类型:">
              <el-select v-model="formData.billType" placeholder="请选择领用类型" style="width: 100%"
                         clearable>
                <el-option
                  v-for="item in busTypes"
                  :key="item.originAction"
                  :label="item.originName"
                  :value="item.originAction">
                  <span style="float: left">{{ item.originName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="remark" label="备注:">
              <el-input v-model="formData.remark" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card>
        <el-button-group style="display: flex">
          <el-button
            type="primary"
            @click.native.stop="selectProductFunction()"
            style="margin: 0px 60px 10px auto; height: 35px"
            :loading="loading"
          >产品录入
          </el-button
          >
        </el-button-group>
        <el-table v-loading="loading" :data="codeArray" style="width: 100%;"
                  :row-class-name="tableRowClassName"
                  border
                  max-height="300" height="300" ref="multipleTable">
          <el-table-column label="序号" type="index" width="50"></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="单据数量">
            <template slot-scope="scope">
              <el-input v-model="scope.row.count"
                        placeholder="请输入数量" style="width: 80%"
                        type='number'
                        @change="tableCountChange(scope.row)"
                        :disabled="scope.row.index !== selectedIndex"
                        oninput="value=value.replace(/[^\d]/g,'')"></el-input>
            </template>
          </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="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text" size="small" :disabled="scope.row.index === selectedIndex" @click.stop="true"
                         @click.native="rowChange(scope.row)">编辑
              </el-button>
              <el-button type="text" size="small" @click.stop="true"
                         @click.native="deleteCodeArray(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-form>


    <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'
    >
      <dialogInvProduct
        :closeDialog="closeDialogC2"
        :invQueryData="formData"
        :codeArray="codeArray"
        :type="1"
      ></dialogInvProduct>
    </el-dialog>
  </div>
</template>

<script>
import {getBusChange} from "@/api/basic/busTypeChange";
import {inserThrOrderWeb, updateReceive, updateReceiveDetail, delReceiveDetail} from "@/api/thrsys/thrOrderReceive";
import {filterSubByInv, findByFrom, findInvByUser} from "@/api/system/invSubWarehouse";
import dialogInvProduct from "../DialogSelectInvProduct";
import {getOrderDetail} from "@/api/inout/receiveOrder";

export default {
  name: "idQuery",
  props: {
    closeDialog: {
      type: Function,
      required: true,
    },
    idQuery: {
      type: Object,
      required: true,
    },
    closeConfirmFunction: {
      type: Function,
      required: true,
    },
    editType: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      showSearch: true,
      code: "",
      query: {
        orderIdFk: "",
        page: 1,
        limit: 10,
      },
      formData: {
        invCode: null,
        targetInvCode: null,

        billNo: null,
        billDate: "",
        billType: "HCLY",
      },
      formRules: {
        billDate: [
          {required: true, message: "请输入单据日期", trigger: "blur"}
        ],
        billType: [
          {required: true, message: "请选择业务类型", trigger: "blur"}
        ],
        invCode: [
          {required: true, message: "请选择当前仓库", trigger: "blur"}
        ],
        targetInvCode: [
          {required: true, message: "请选择往来仓库", trigger: "blur"}
        ],
      },
      codeArray: [],
      invList: [],
      fromStorageOptions: [],
      fromOptions: [],
      total: 0,
      loading: false,
      index: null,
      formLoading: false,
      formVisible: false,
      deleteLoading: false,
      orderNo: null,
      statusMap: {
        1: "草稿",
        2: "未审核",
        3: "已审核",
      },
      orderEditor: true,
      iCount: 0,
      sOptions: [],
      sValue: [],
      sList: [],
      sLoading: false,
      busTypes: [],
      currentRow: {},
      selectedIndex: "",
      selectInvProductVisible: false,
      thisData: {},
      storageList: [],
      invQueryData: {},
      type: 1,

    };
  },
  components: {
    dialogInvProduct
  },
  methods: {
    //当前分库
    finCurInv() {
      this.invList = [];
      let query = {
        filter: 3
      };
      findInvByUser(query)
        .then((response) => {
          this.invList = response.data || [];
        })
        .catch(() => {
        });
    },
    //往来分库
    findFromInv() {
      let cQuery = {
        locInvCode: this.formData.invCode,
      };
      findByFrom(cQuery)
        .then((response) => {
          this.fromOptions = response.data || [];
        })
        .catch(() => {
        });
    },
    //领用类型
    getBusType() {
      let query = {
        enable: true,
        type: 1,
      };
      getBusChange(query)
        .then((response) => {
          this.busTypes = response.data.list || [];
        })
        .catch(() => {
        });
    },
    hideSearch() {
      this.showSearch = !this.showSearch;
    },

    saveOrder(status) {
      this.code = "";
      this.$refs.multipleTable.setCurrentRow();
      this.currentRow = {};
      this.selectedIndex = "";
      this.iCount = 0;
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.codeArray.length < 1) {
            this.$message.warning('未添加产品');
            return;
          }

          for (let i = 0; i < this.codeArray.length; i++) {
            if (!this.$isBlank(this.codeArray[i].productDate) && this.codeArray[i].productDate.length != 6) {
              return this.$message.error('生产日期格式错误');
            }
            if (!this.$isBlank(this.codeArray[i].expireDate) && this.codeArray[i].expireDate.length != 6) {
              return this.$message.error('失效日期格式错误');
            }

          }

          if (status === '2') {
            for (let i = 0; i < this.codeArray.length; i++) {
              if (this.$isBlank(this.codeArray[i].count) || this.codeArray[i].count == "0") {
                return this.$message.error('单据数量不能为0');
              }


            }
          }
          if (status === '0') {
            for (let i = 0; i < this.codeArray.length; i++) {
              if (this.$isBlank(this.codeArray[i].count) || this.codeArray[i].count == "0") {
                return this.$message.error('单据数量不能为0');
              }
            }
          }

          if (status == "1") {
            this.submitFunction(status);
          } else {
            let tip = "是否确定提交订单?";
            this.$confirm(tip, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              this.submitFunction(status);
              this.loading = false
            }).catch(() => {
              this.loading = false;
            });
          }


        }
      });
    },


    submitFunction(status) {
      let tMessage = status === '501' ? '保存' : '提交';
      let tQuery = this.formData;
      tQuery.status = status;
      tQuery.subErpOrders = this.codeArray;
      tQuery.thirdPartyDate = 2;
      updateReceive(tQuery)
        .then(response => {
          if (response.code === 20000) {
            this.$message.success(tMessage + "成功");
            this.closeDialog(true);
          } else {
            this.$message.error(response.message);
          }
        })
        .catch(() => {
          this.loading = false;
        })
    },
    selectProductFunction(event) {

      if (this.formData.targetInvCode == null) {
        this.$message.error("往来信息为空！");
        return;
      }

      if (this.$isBlank(event)) {
        this.selectInvProductVisible = true;
      }
    },
    closeDialogC2(rData) {
      this.selectInvProductVisible = false;
      this.formData.billNo = rData;
      this.getOrderDetailList();

    },
    rowChange(val) {
      this.currentRow = val;
      this.selectedIndex = val.index;
      this.iCount = val.count;
      this.focusNext('iCount');

    },
    tableCountChange(row) {
      if (this.$isNotBlank(row)) {
        updateReceiveDetail(row).then(res => {
          if (res.code == 20000) {
            this.loading = false;
          } else {
            this.$message.error(res.message);
          }

        })
      }
    },
    tableRowClassName({row, rowIndex}) {
      row.index = rowIndex;
    },
    focusNext(nextRef) {
      this.$refs[nextRef].focus()
    },
    // 刷新表单
    resetForm() {
      if (this.$refs["dataForm"]) {
        // 清空验证信息表单
        this.$refs["dataForm"].clearValidate();
        // 刷新表单
        this.$refs["dataForm"].resetFields();
        this.getList();
      }
    },
    deleteCodeArray(index, row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (this.orderEditor) {
          this.detailLoading = true;
          if (this.$isNotBlank(row.id)) {
            delReceiveDetail({id: row.id})
              .then(response => {
                this.detailLoading = false;
                if (response.code === 20000) {
                  this.getOrderDetailList();
                } else {
                  this.$message.error(response.message);
                }
              })
              .catch(() => {
                this.detailLoading = false;
              })
          } else {
            this.$message.success('删除成功');
            this.codeArray.splice(index, 1);
          }
        } else {
          this.$message.success('删除成功');
          this.codeArray.splice(index, 1);
        }
      }).catch(() => {

      });
    },
    subStorageChange(item) {
      this.getBusType();
      this.findFromInv();
    },

    getOrderDetailList() {
      this.loading = true;
      this.query.orderIdFk = this.formData.billNo;
      getOrderDetail(this.query) //查找该单号下的所有条码
        .then((response) => {
          this.codeArray = response.data.list || [];
          this.total = response.data.total || 0;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },
  },
  filters: {},
  mounted() {
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
  },
  created() {
    if (this.$isNotBlank(this.idQuery.id)) {
      this.editType = true;
      this.query.limit = 100;
      this.query.orderIdFk = this.idQuery.id;
      this.formData = this.idQuery.formData;
      this.orderEditor = true;
      this.sValue = this.formData.corpName;
      this.getOrderDetailList();
    } else {

      this.editType = false;
      this.formData = {
        invCode: this.$store.getters.locInvCode,
        targetInvCode: null,
        billType: "HCLY",
        billNo: null,
        billDate: "",
      };
      this.orderEditor = false;
    }

    this.getBusType();
    this.findFromInv();
    this.finCurInv();
  },
};
</script>
<style>

.ao-text {
  width: 100%;
  font-size: 13px;
  font-family: "Microsoft YaHei";
  float: right;
  text-align: right;
  margin-top: 10px;
}

</style>



