<template>
    <div>
        <div class="divborder newSearchDiv">
            <div class="filter">
                <label>产品名称：</label>
                <Select v-model="productname" clearable class="searchSelect" @on-change="getLine">
                    <!--  -->
                    <Option
                        v-for="item in products"
                        :value="item.id"
                        :key="item.code"
                    >{{ item.name }}({{item.code}})</Option>
                </Select>
            </div>
            <div class="filter">
                <label>{{$t(500006)}}：</label>
                <Select v-model="lineid" clearable class="searchSelect">
                    <Option v-for="item in lines" :value="item.route" :key="item.id">{{ item.text }}</Option>
                </Select>
            </div>
            <!-- <div class="filter">
                <label>工单号：</label>
                <Select v-model="workOrder" label-in-value clearable class="searchSelect">
                    <Option
                        v-for="item in orderList"
                        :value="item.workorder_code"
                        :key="item.id"
                    >{{ item.workorder_code }}</Option>

                </Select>
            </div>-->
            <div class="searchBtn">
                <Button
                    type="primary"
                    class="twoWord intervalRight"
                    icon="ios-search"
                    @click="search(1,10)"
                >{{$t('1001')}}</Button>
                <Button
                    type="warning"
                    class="fourWord"
                    icon="ios-create-outline"
                    @click="del()"
                >申请出库</Button>
            </div>
        </div>
        <div class="divborder newTableDiv">
            <Table
                class="tableClass"
                :columns="columns"
                :data="data1"
                @on-current-change="handleRowChange"
                highlight-row
            ></Table>
            <div class="pageDiv">
                <div class="pageDirection">
                    <Page
                        :total="total"
                        :current="page"
                        @on-change="changePage"
                        show-elevator
                        show-sizer
                        show-total
                        @on-page-size-change="handlePageSize"
                        :page-size-opts="[10,20,30,40,100]"
                    ></Page>
                </div>
            </div>
        </div>
        <div class="divborder newTableDiv">
            <div style="width:100px;margin:10px;">物料汇总</div>
            <div>
                <Table
                    class="tableClass"
                    style="height:360px;"
                    height="360"
                    :data="processList"
                    :columns="addColums"
                ></Table>
            </div>
        </div>
    </div>
</template>
<script>
import moment from "moment";

export default {
    data() {
        return {
            productname: "",
            products: [],
            lines: [],
            lineid: "",
            user: 0,
            workOrder: "",
            orderList: [],
            index_time: [],
            addModal: false,
            total: 0,
            page: 1,
            pagesize: 10,
            detailobj: {},
            data1: [],
            columns: [
                {
                    title: this.$t("1008"),
                    key: "order",
                    render: (h, params) => {
                        return h("span", params.index + 1);
                    },
                    width: 70,
                    align: "center",
                },
                {
                    title: this.$t(600042),
                    key: "cutter_number",
                    align: "center",
                },
                {
                    title: "类别",
                    key: "category_name",
                    align: "center",
                },
                {
                    title: this.$t(100391),
                    key: "material_name",
                    align: "center",
                },
                {
                    title: this.$t(600011),
                    key: "supplier",
                    align: "center",
                },
                {
                    title: this.$t(600647),
                    key: "quantity",
                    align: "center",
                },
                {
                    title: this.$t(500068),
                    key: "machine_quantity",
                    align: "center",
                },
                {
                    title: "备注",
                    key: "remark",
                    align: "center",
                },
                {
                    title: this.$t(200054),
                    key: "status",
                    align: "center",
                },
            ],
            editModal: false,
            addworkOrder: "",
            addproductid: "",
            addpdtName: "",
            processList: [],
            addColums: [
                {
                    title: this.$t("1008"),
                    key: "order",
                    render: (h, params) => {
                        return h("span", params.index + 1);
                    },
                    width: 70,
                    align: "center",
                },
                {
                    title: this.$t(100391),
                    key: "material_name",
                    align: "center",
                },
                {
                    title: this.$t(900933),
                    key: "part_no",
                    align: "center",
                },
                {
                    title: this.$t(600011),
                    key: "supplier",
                    align: "center",
                },
                {
                    title: "位置",
                    key: "position",
                    align: "center",
                },
                {
                    title: "序号/批次",
                    key: "number",
                    align: "center",
                },
                {
                    title: "总数",
                    key: "quantity",
                    align: "center",
                    render: (h, params) => {
                        return h("Input", {
                            props: {
                                size: "small",
                                type: "number",
                                value: 0,
                            },
                            on: {
                                "on-change": (e) => {
                                    let id = params.row.id;
                                    let val = e.target.value;
                                    this.processList[params.index][
                                        params.column.key
                                    ] = e.target.value;
                                    if (val > params.row.stock) {
                                        this.$Message.error(this.$t(8104));
                                    }
                                    // this.updateData(id, val);
                                },
                            },
                        });
                    },
                },
                {
                    title: this.$t(300016),
                    key: "stock",
                    align: "center",
                },
            ],
            order_number: "",
            productName: "",
            route: "",
            machineName: "",
            count: "",
            date: "",
            machineId: "",
            tool_code: "",
            queryId: "",
        };
    },
    created() {
        this.getMtList();
        this.productname = this.$route.query.productId;
        this.inilines(this.productname);
        this.lineid = this.$route.query.route;
        this.getOrderList();
        this.machineId = this.$route.query.machine_type;
        this.tool_code = this.$route.query.tool_code;

        this.queryId = this.$route.query.id;

        // this.workOrder = this.$route.query.order_number;
        if (this.machineId && this.productname && this.lineid) {
        this.search(1, 10);
        }
        this.getmaterialList();
        // 格式化表格样式
        this.columns = this.$time.initTableTitle(this.columns);
        this.addColums = this.$time.initTableTitle(this.addColums);
    },
    methods: {
        getMtList() {
            var data = {
                name: "", // 供应商id
                count: 50, // 显示数量
            };
            this.request(
                "/config/ProjectProduct/GetProductsByCode",
                data,
                "get"
            ).then((res) => {
                this.products = res.data.data;
            });
        },
        getOrderList() {
            this.request("/tlm/ToolWorkorder/GetWorkOrderList", "", "get").then(
                (res) => {
                    if (res.data.ret == 1) {
                        this.orderList = res.data.data;
                    }
                }
            );
        },
        inilines() {
            // this.productname = ''+ this.productname;
            this.request(
                "/tlm/Technology/GetRoutes?productid=" + this.productname,
                "",
                "get"
            ).then((res) => {
                if (res.data.ret == 1) {
                    this.lines = res.data.data;
                }
                //   this.prelines = res.data.data;
            });
        },
        getLine(value) {
            this.productname = value;
            // console.log(this.productname);
            this.inilines();
            this.lineid = "";
        },
        getTable(value) {
            this.addproductid = value;
            let data = {
                productid: this.addproductid,
            };
            this.request("/tlm/ToolWorkorder/GetTechList", data, "get").then(
                (res) => {
                    //   console.log(res.data);
                    if (res.data.ret == 1) {
                        let arr = res.data.data;
                        // this.renderModalTable(arr);
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                }
            );
        },
        renderModalTable(arr) {
            let data = [];
            if (arr.length > 0) {
                arr.forEach((item) => {
                    if (item) {
                        data.push({
                            id: item.id,
                            cutter_number: item.cutter_number,
                            part_no: item.part_no,
                            material_name: item.material_name,
                            supplier: item.supplier,
                            position: item.position,
                            quantity: 0,
                            stock: item.stock, // 库存
                            tech_tool_id: item.tech_tool_id,
                            number: item.number,
                        });
                    }
                });
            }
            this.processList = data;
        },
        getmaterialList() {
            var data = {
                workorder_code: this.workOrder,
                product_id: this.productname,
                machine_type: this.machineId,
                route: this.lineid,
                page: 1,
                pagesize: 10,
            };
            this.request(
                "/tlm/ToolChoice/GetSummaryPagedList",
                data,
                "post"
            ).then((res) => {
                // this.orderList = res.data.data;
                if (res.data.ret == 1) {
                    this.renderModalTable(res.data.data);
                }
            });
        },
        search(page, pagesize) {
            // if (this.workOrder == "" || this.workOrder == undefined) {
            //     // this.$Message.error("工单号、产品名称、工序不能为空");
            //     this.$Message.error("工单号、产品名称、工序不能为空");
            //     return false;
            // }
            // if (this.productname == "" || this.productname == undefined) {
            //     // this.$Message.error("工单号、产品名称、工序不能为空");
            //     this.$Message.error("工单号、产品名称、工序不能为空");
            //     return false;
            // }
            // if (this.lineid == "" || this.lineid == undefined) {
            //     // this.$Message.error("工单号、产品名称、工序不能为空");
            //     this.$Message.error("工单号、产品名称、工序不能为空");
            //     return false;
            // }
            var data = {
                workorder_code: "" + this.workOrder,
                product_id: this.productname,
                route: this.lineid,
                page: page,
                pagesize: pagesize,
                machine_type: this.machineId,
                tool_code: this.tool_code,
                id: this.queryId,
            };
            this.request("/tlm/ToolChoice/GetPagedList", data, "post").then(
                (res) => {
                    if (res.data.ret == 1) {
                        this.total = res.data.total;
                        this.renderTable(res.data.data);
                        this.getmaterialList();
                    } else {
                        this.data1 = [];
                        this.processList = [];
                        this.$Message.error(this.$t(res.data.msg));
                    }
                }
            );
        },
        renderTable(arr) {
            let data = [];
            if (arr.length > 0) {
                arr.forEach((item) => {
                    if (item) {
                        let status = "";
                        if (item.choice_status == 1) {
                            status = this.$t(8101);
                        }
                        if (item.choice_status == 2) {
                            status = this.$t(900521);
                        }
                        data.push({
                            cutter_number: item.cutter_number,
                            category_name: item.category_name,
                            material_name: item.material_name,
                            supplier: item.supplier,
                            machine_quantity: item.machine_quantity,
                            id: item.id,
                            material_id: item.material_id,
                            quantity: item.quantity,
                            remark: item.remark,
                            choice_status: item.choice_status,
                            status: status,
                            part_no: item.part_no,
                            number: item.number,
                        });
                    }
                });
            }
            this.data1 = data;
        },

        del() {
                if (this.data1[0].choice_status == 2) {
                  this.$Message.error('该条记录已出库');
                  return false;
                }
                const test = (ele) => {
                return ele.quantity <= ele.stock;
            };
            // console.log(this.processList.every(test));
            if (!this.processList.every(test)) {
                this.$Message.error(this.$t(8102));
                return false;
            }

            this.$Modal.confirm({
                title: this.$t("1124"),
                content: this.$t(8103),
                onOk: () => {
                    if (this.data1.length == 0) {
                        this.$Message.error(this.$t(8104));
                        return false;
                    }

                    var arr = [],
                        checkArr = [],
                        total = false;
                    this.processList.forEach((ele) => {
                        if (ele.quantity != 0) {
                            // total += ele.quantity;
                            checkArr.push(ele);
                        }
                    });
                    console.log(checkArr);

                    for (let i = 0; i < this.data1.length; i++) {
                        const ele = this.data1[i];
                        let qty = 0;
                        checkArr.forEach((item) => {
                            if (item.part_no == ele.part_no) {
                                qty += +item.quantity;
                            }
                        });
                        console.log(qty);
                        if (qty != ele.quantity * ele.machine_quantity) {
                            total = true;
                        }
                        // for (let j = 0; j < checkArr.length; j++) {
                        //   const element = checkArr[j];
                        //   if(element.part_no == ele.part_no){
                        //     let qty = 0;
                        //     qty += element.quantity
                        //   }
                        //   console.log(qty);
                        //   if(qty != ele.quantity*ele.machine_quantity){
                        //       total = true;
                        //   }
                        // }
                    }
                    if (total) {
                        this.$Message.error("请检查相应的出库数量");
                        return false
                    }
                    // return;

                    checkArr.forEach((item) => {
                        var arr1 = {};
                        arr1.cutter_number = item.cutter_number; // 刀位号
                        arr1.part_no = item.part_no; // 料号
                        arr1.count = +item.quantity;
                        arr1.No = item.number
                        arr.push(arr1);
                    });

                    var data = {
                        workorder_code: this.workOrder,
                        product_id: this.productname,
                        route: this.lineid,
                        machine_type: this.machineId,
                        paras: arr,
                        id:this.queryId
                    };
                    // console.log(data);
                    // return false;
                    // let id = this.detailobj.id;
                    this.request(
                        "/tlm/ToolChoice/ToolOutStock",
                        data,
                        "post"
                    ).then((res) => {
                        if (res.data.ret === 1) {
                            this.$Message.success(this.$t(400063));
                            this.detailobj = {};
                            this.search(1, 10);
                        } else {
                            this.$Message.error(this.$t(res.data.msg));
                        }
                    });
                },
            });
        },
        toTool() {
            if (
                this.detailobj.id &&
                this.detailobj.order_status == this.$t(1000020)
            ) {
                this.$router.push({
                    path: "./tool_select",
                    query: {
                        productId: params.row.product_id,
                        route: params.row.route_id,
                    },
                });
            }
        },
        handleRowChange(currentRow, oldCurrentRow) {
            this.detailobj = currentRow;

            // this.getStaffList();
        },
        handlePageSize(value) {
            this.pagesize = value;
            this.search(this.page, this.pagesize);
        },
        changePage(value) {
            this.page = value;
            this.search(this.page, this.pagesize);
        },
        request(url, data, type) {
            if (type == "get") {
                return this.axios
                    .request({
                        url: url,
                        params: data,
                        method: type,
                    })
                    .then((res) => {
                        return res;
                    })
                    .catch((error) => error);
            } else {
                return this.axios
                    .request({
                        url: url,
                        data,
                        method: type,
                    })
                    .then((res) => {
                        return res;
                    })
                    .catch((error) => error);
            }
        },
    },
};
</script>
<style lang="less" scoped>
</style>
