<template>
    <div>
        <el-form :model="formData" :rules="formRules" label-width="120px" ref="dataForm">
            <el-row type="flex" justify="end">
                <el-button-group style="display: flex;margin-bottom: 15px; margin-right: 50px">
                    <el-button
                        type="primary"
                        @click.native="saveOrder('1')"
                        :loading="loading"
                    >提交单据
                    </el-button
                    >
                </el-button-group>
            </el-row>

            <el-card style="margin-top: -5px;" >
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="单据号" prop="billNo">
                            <el-input v-model="formData.billNo" style="width: 90%" auto-complete="off" :disabled="true"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item  label="单据日期" prop="billNo">
                            <el-input v-model="formData.billDate" style="width: 90%"  auto-complete="off" :disabled="true"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="打印说明" prop="billNo">
                            <el-input v-model="formData.remark" style="width: 90%"  auto-complete="off" type="textarea" autosize></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-card>

            <el-card>
                <el-button-group style="display: flex">
                    <el-button type="primary" size="small" @click.native.stop="selectProductFunction()" style="margin: 0px 0px 10px auto; height: 35px" :loading="loading">物资录入</el-button>
                  <el-button type="primary" size="small" @click.native.stop="stockOrderList()" style=" height: 35px">选入单据</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="productName" show-overflow-tooltip></el-table-column>
                    <el-table-column label="规格型号" prop="spec"  show-overflow-tooltip></el-table-column>
                    <el-table-column label="计量单位" prop="measname"  show-overflow-tooltip></el-table-column>
                    <el-table-column label="生产企业"  prop="manufactory" show-overflow-tooltip></el-table-column>
                    <el-table-column label="单据数量">
                        <template slot-scope="scope">
                            <el-input size="small" v-model="scope.row.count"
                                      placeholder="请输入数量" style="width: 80%"
                                      type='number'
                                      :disabled="scope.row.index !== selectedIndex"
                                      oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column  label="批次号">
                        <template slot-scope="scope">
                            <el-input size="small" v-model="scope.row.batchNo"
                                      :disabled="scope.row.index !== selectedIndex"
                                      @input="scope.row.batchNo =scope.row.batchNo.replace(/[\W]/g, '')"
                                      ref='inputBatchNoRef'
                                      placeholder="请输入批次号" style="width: 80%"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column  label="生产日期">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.productDate" auto-complete="off"
                                      oninput="if(value.length>6)value=value.slice(0,6)"
                                      :disabled="scope.row.index !== selectedIndex"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column  label="失效日期">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.expireDate" auto-complete="off"
                                      oninput="if(value.length>6)value=value.slice(0,6)"
                                      :disabled="scope.row.index !== selectedIndex"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" :disabled="scope.row.index !== selectedIndex" @click.stop="true" @click.native="addRowChang(scope.row)">提交</el-button>
                            <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="selectProductVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="80%"
            v-if="selectProductVisible"
            :append-to-body='true'
        >
            <stockOrderNewSelectProduct
                :closeDialog="closeDialogC2"
                :data="thisData"
                :pId="pId"
                :billNo="billNo"
                :filterType="2"
            ></stockOrderNewSelectProduct>
        </el-dialog>


      <el-dialog
        title="内部码打印"
        :visible.sync="haveDistributionVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="80%"
        v-if="haveDistributionVisible"
        :append-to-body='true'
      >
        <stockOrder
          :closeDialog="closeDialogC2"
          :data="thisData"
          :pId="pId"
          :billNo="billNo"
          :filterType="2"
        ></stockOrder>
      </el-dialog>
    </div>
</template>

<script>
import draggable from "vuedraggable";
import stockOrderNewSelectProduct from "@/views/inventory/inner/innerOrderSelectProduct";
import stockOrder from "@/views/basic/business/stockOrderPrint";
import {
  inserThrOrderWeb,
  delInnerOrderDetail,
  listInnerOrderDetail,
  updateOrderDetail
} from "@/api/inventory/innerOrder";
import {isBlank} from "@/utils/strUtil";

export default {
    name: "idQuery",
    props: {
        closeDialog: {
            type: Function,
            required: true,
        },
        idQuery: {
            type: Object,
            required: true,
        },
    },
    data() {
        return {
            code: "",
            query: {
                orderIdFk: "",
                page: 1,
                limit: 10,
            },
            formData: {
                id: null,
                billNo: null,
                billDate: "",
                remark: "",
                deptCode: null,
                locStorageCode: null,
                invWarehouseCode: null,
            },
            formRules: {},
            codeArray: [],
            total: 0,
            pId:null,
            billNo:null,
            loading: false,
            index: null,
            formLoading: false,
            formVisible: false,
            deleteLoading: false,
            orderNo: null,
          haveDistributionVisible:false,
            statusMap: {
                1: "草稿",
                2: "未审核",
                3: "已审核",
            },
            typeMap: {
                1: "预入库",
                2: "普通采购",
            },
            orderEditor: true,
            sOptions: [],
            sValue: [],
            sList: [],
            sLoading: false,
            busTypes: [],
            currentRow: {},
            selectedIndex: "",
            selectProductVisible: false,
            thisData: {},
            storageList: [],
            subInvList: [],
            invQueryData: {},

        };
    },
    components: {
        draggable,
        stockOrderNewSelectProduct,
      stockOrder,
    },
    methods: {
        saveOrder(status) {
            this.$refs["dataForm"].validate(valid => {
                if (valid) {
                    if (this.codeArray.length < 1) {
                        this.$message.warning('未添加产品');
                        return;
                    }
                    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 {
                        if (this.codeArray.length < 1) {
                            this.$message.warning('未添加产品');
                            return;
                        }
                        for (let i = 0; i < this.codeArray.length; i++) {
                            if (isBlank(this.codeArray[i].count) || this.codeArray[i].count === 0) {
                                this.$message.error('单据数量不能为0');
                                return;
                            }
                        }
                        let tip = "是否确定提交订单?";
                        this.$confirm(tip, "提示", {
                            confirmButtonText: "确定",
                            cancelButtonText: "取消",
                            type: "warning",
                        }).then(() => {
                            this.submitFunction(status);
                        }).catch(() => {
                            this.loading = false;
                        });
                    }
                }
            });
        },
        submitFunction(status) {
            let tMessage = status === '1' ? '保存' : '提交';
            this.loading = true;
            let tQuery = {
                editStatus: status,
                innerOrderEntity: this.formData,
            }
            inserThrOrderWeb(tQuery)
                .then(response => {
                    this.loading = false;
                    if (response.code === 20000) {
                        this.$message.success(tMessage + "成功");
                        this.closeDialog(true);
                    } else {
                        this.$message.error(response.message);
                    }
                })
                .catch(() => {
                    this.loading = false;
                })
        },
        addRowChang(row){
          updateOrderDetail(row);
          this.selectedIndex = "";
        },
      stockOrderList(){
        if(this.query.id==null) {
          inserThrOrderWeb({innerOrderEntity: this.formData,editStatus:1})
            .then(response => {
              this.loading = false;
              if (response.code === 20000) {
                this.pId=response.data.id;
                this.billNo=response.data.recordKey;
                this.formData.billNo=response.data.recordKey;
                this.formData.id=this.pId
              } else {

              }
            })
            .catch(() => {
              this.loading = false;
            })
        }

        this.haveDistributionVisible = true;
      },
        selectProductFunction() {
          if(this.query.id==null) {
            inserThrOrderWeb({innerOrderEntity: this.formData,editStatus:1})
              .then(response => {
                this.loading = false;
                if (response.code === 20000) {
                  this.pId=response.data.id;
                  this.billNo=response.data.recordKey;
                  this.formData.billNo=response.data.recordKey;
                  this.formData.id=this.pId
                } else {

                }
              })
              .catch(() => {
                this.loading = false;
              })
          }

            this.selectProductVisible = true;
        },
        closeDialogC2(rData) {
            this.selectProductVisible = false;
            this.haveDistributionVisible = false;
            this.getStockOrderDetailList();
        },
        rowChange(val) {
            this.currentRow = val;
            this.selectedIndex = val.index;
        },
        tableCountChange(row) {
            if (this.$isNotBlank(row)) {
                // row.count = row.reCount;
            }
        },
        tableRowClassName({row, rowIndex}) {
            row.index = rowIndex;
        },
        // 刷新表单
        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(() => {
                this.$refs.multipleTable.setCurrentRow();
                this.currentRow = {};
                this.selectedIndex = "";

                if (this.orderEditor) {
                    this.detailLoading = true;
                    if (this.$isNotBlank(row.id)) {
                        delInnerOrderDetail(row.id)
                            .then(response => {
                                this.detailLoading = false;
                                if (response.code === 20000) {
                                    this.$message.success(response.data);
                                    // this.getStockOrderDetailList();
                                    this.codeArray.splice(index, 1);
                                } 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(() => {

            });
        },
        getStockOrderDetailList() {
            this.loading = true;
            listInnerOrderDetail({orderIdFk:this.formData.billNo}) //查找该单号下的所有条码
                .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.query.limit = 100;
            this.query.orderIdFk = this.idQuery.id;
            this.formData = this.idQuery.formData;
            this.formData.billNo = this.idQuery.formData.recordKey;
            this.formData.billDate = this.idQuery.formData.createTime;
            this.orderEditor = true;
            this.sValue = this.formData.corpName;
            this.getStockOrderDetailList();
        } else {
            this.formData = {
                id: null,
                billNo: null,
                billDate: "",
                remark: "",
                deptCode: null,
                locStorageCode: null,
                invWarehouseCode: null,
            };
            this.orderEditor = false;
        }
        this.codeArray = [];
    },
};
</script>
<style>

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

</style>



