<template>
    <div class="testdiv">
        <div class="divborder newSearchDiv" style="margin:0px;">
            <div class="filter">
                <label>{{$t('100088')}}：</label>
                <Select
                    v-model="productname"
                    clearable
                    filterable
                    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>{{$t(100308)}}：</label>
                <Select v-model="machineId1" clearable class="searchSelect">
                    <Option
                        v-for="item in machineList1"
                        :value="item.id"
                        :key="item.id"
                    >{{ item.title }}</Option>
                </Select>
            </div> -->
            <div class="searchBtn">
                <Button
                    type="primary"
                    class="twoWord"
                    icon="ios-search"
                    @click="search(1,10)"
                >{{$t('1001')}}</Button>
                <Button
                    type="success"
                    class="twoWord"
                    icon="md-add-circle"
                    @click="add()"
                >{{$t('1002')}}</Button>
                <Button
                    type="warning"
                    class="twoWord"
                    icon="ios-create-outline"
                    @click="edit()"
                >{{$t('1003')}}</Button>
                <Button
                    type="error"
                    class="twoWord intervalRight"
                    icon="md-close-circle"
                    @click="dele()"
                >{{$t('1004')}}</Button>
                <Button
                    type="primary"
                    class="fourWord"
                    icon="md-download"
                    @click="loadexcel()"
                >{{$t('1005')}}</Button>
                <Upload
                    style="display:inline-block"
                    ref="upload"
                    :action="action"
                    name="excel-file"
                    :headers="headers"
                    :show-upload-list="false"
                    :on-format-error="handleFormatError"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    :format="['xlsx']"
                >
                    <Button type="primary" class="fourWord" icon="md-cloud-upload">{{$t('1006')}}</Button>
                </Upload>
                <Button
                    type="primary"
                    class="fourWord"
                    icon="ios-cloud-download"
                    @click="Export()"
                >{{$t('1007')}}</Button>
            </div>
        </div>
        <div class="divborder newTableDiv">
            <Table
                class="tableClass"
                @on-current-change="handleRowChange"
                highlight-row
                :data="tableData1"
                @on-selection-change="handleSelectRow"
                :columns="tableColumns1"
            ></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>
            <!-- 弹框 -->
            <Modal class="newModalClass" v-model="addmodal" :styles="{width:'700px'}">
                <p slot="header">
                    <span v-if="type===1">{{$t('1002')}}</span>
                    <span v-if="type===2">{{$t('1003')}}</span>
                </p>
                <div class="modal_body">
                    <div style="width:400px; height:300px;overflow:auto">
                        <Tree :data="treeList" ref="tree" @on-select-change="getList()"></Tree>
                    </div>
                    <div class="middle"></div>
                    <div style="width:400px">
                        <!-- 产品名称 -->
                        <div class="filter">
                            <label>
                                <i>*</i>
                                {{$t('100088')}}：
                            </label>
                            <Select
                                v-model="addproductid"
                                clearable
                                class="searchSelect"
                                @on-change="getLine2"
                            >
                                <Option
                                    v-for="item in products"
                                    :value="item.id"
                                    :key="item.code"
                                >{{ item.name }}({{item.code}})</Option>
                            </Select>
                        </div>
                        <!-- 工序 -->
                        <div class="filter">
                            <label>
                                <i>*</i>
                                {{$t(500006)}}：
                            </label>
                            <Select
                                v-model="routename"
                                label-in-value
                                clearable
                                class="searchSelect"
                            >
                                <Option
                                    v-for="item in lines"
                                    :value="item.route"
                                    :key="item.id"
                                >{{ item.text }}</Option>
                            </Select>
                        </div>
                        <!-- 设备 -->
                        <div class="filter">
                            <label>
                                <i>*</i>
                                {{$t(100308)}}：
                            </label>
                            <Input
                                type="text"
                                v-model="machine"
                                disabled
                                class="searchInput"
                                id="machine"
                            />
                        </div>
                        <!-- 零件图号 -->
                        <div class="filter">
                            <label>{{$t(8046)}}：</label>
                            <Input type="text" v-model="code" class="searchInput" id="machine" />
                        </div>
                        <!-- 程序号 -->
                        <div class="filter">
                            <label>{{$t(600009)}}：</label>
                            <Input type="text" v-model="program" class="searchInput" id="machine" />
                        </div>
                        <!-- 备注 -->
                        <div class="filter" style="display:flex;margin-bottom: 30px;">
                            <label>{{$t(1030)}}：</label>
                            <Input
                                type="textarea"
                                v-model="remark"
                                class="searchInput MaxWidth"
                                id="machine"
                                :autosize="{minRows: 2,maxRows: 2}"
                            />
                        </div>
                    </div>
                </div>
                <div slot="footer">
                    <Button type="text" size="large" @click="closeadd()">{{$t('1033')}}</Button>
                    <Button
                        type="primary"
                        v-if="type===1"
                        size="large"
                        @click="adddata()"
                    >{{$t('1002')}}</Button>
                    <Button
                        type="primary"
                        v-if="type===2"
                        size="large"
                        @click="editdata()"
                    >{{$t('1003')}}</Button>
                </div>
            </Modal>
        </div>
    </div>
</template>
<script>
import axios from "@/libs/api.request";
export default {
    name: "productmanagement", // 组件不刷新
    data() {
        return {
            action:
                axios.publicPath +
                "tlm/Upload/Submit?templateName=TechnologyList",
            headers: {
                token: localStorage.getItem("token"),
                timestamp: localStorage.getItem("timestamp"),
                nonce: localStorage.getItem("nonce"),
                sign: localStorage.getItem("sign"),
            },
            products: [],
            productname: 0,
            addproductid: "",
            lines: [],
            lineid: "",
            machineId1: '',
            machineList1: [],
            treeList: [], // 树形
            sections: [],
            sectionid: "0",
            routenames: [],
            routename: "",
            machine: "", // 新增设备
            machineId: 0,
            code: "", // 零件图号
            program: "", // 程序号
            remark: "", // 备注
            addprelineid: 0,
            currentsections: [],
            addcurrentsectionid: "",
            presectionid: 0,
            prelines: [],
            presections: [],
            previoussections: [],
            addprevioussectionid: [],
            results: [],
            addresultid: "",
            tableData1: [],
            total: 0,
            page: 1,
            pagesize: 10,
            addmodal: false,
            editmodal: false,
            detailobj: {},
            editobj: {},
            type: 0,
            editLines: [],
            editPreLines: [],
            editStations: [],
            editPreStations: [],
            editResults: [],
            tableColumns1: [
                {
                    type: "index2",
                    title: this.$t("1008"),
                    key: "xuhao",
                    render: (h, params) => {
                        return h(
                            "span",
                            params.index + (this.page - 1) * this.pagesize + 1
                        );
                    },
                    width: "70px",
                },
                {
                    title: this.$t("100088"),
                    key: "product_name",
                },
                {
                    title: this.$t(8046),
                    key: "drawcode",
                },
                {
                    title: this.$t(1041),
                    key: "machineType_name",
                },
                {
                    title: this.$t(500006),
                    key: "route",
                },
                {
                    title: this.$t(600009),
                    key: "program",
                },
                {
                    title: this.$t(100040),
                    key: "create_name",
                },
                {
                    title: this.$t(1030),
                    key: "remark",
                },
                {
                    title: this.$t(1038),
                    key: "result",
                    render: (h, params) => {
                        return h("div", [
                            h(
                                "p",
                                {
                                    style: {
                                        color: "#2D8CF0",
                                        cursor: "pointer",
                                    },
                                    on: {
                                        click: () => {
                                            this.$router.push({
                                                path: "./tool_list",
                                                query: {
                                                    productId:
                                                        params.row.product_id,
                                                    route: params.row.route_id,
                                                    machine_type:
                                                        params.row.machine_type,
                                                },
                                            });
                                            sessionStorage.setItem(
                                                "productId",
                                                params.row.product_id
                                            );
                                            sessionStorage.setItem(
                                                "route",
                                                params.row.route_id
                                            );
                                        },
                                    },
                                },
                                this.$t(8057)
                            ),
                        ]);
                    },
                },
            ],
        };
    },
    created() {
        this.iniproducts();
        // this.inilines();
        this.search(1, 10);
        this.menu_1();
        // 格式化表格样式
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1);
    },
    methods: {
        iniproducts() {
            var params = {
                name: "",
                count: 50,
            };
            axios
                .request({
                    url: "/config/ProjectProduct/GetProductsByCode",
                    params,
                    method: "get",
                })
                .then((res) => {
                    this.products = res.data.data;
                });
        },
        // 获取工序
        inilines(id) {
            axios
                .request({
                    url: "/tlm/Technology/GetRoutes?productid=" + id,
                    method: "get",
                })
                .then((res) => {
                    if (res.data.ret == 1) {
                        this.lines = res.data.data;
                    }
                });
        },
        // 树
        menu_1() {
            let url =
                "/config/MachineAttribution/GetSectionMachineTreeData?attribution=1";
            axios
                .request({
                    url: url,
                    method: "get",
                })
                .then((res) => {
                    if (res.data.ret == 1) {
                        this.treeList = res.data.data;

                        this.contentTree(this.treeList);
                        // console.log(this.treeList);
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        contentTree(arr) {
            arr.forEach((ele) => {
                ele.title = ele.label;
                if (ele.selected == true) {
                    ele.selected = false;
                }

                if (
                    ele.children.length != 0 &&
                    ele.children != undefined &&
                    ele.children != null
                ) {
                    this.contentTree(ele.children);
                }
            });
        },
        // 获取树id
        getList() {
            let node = this.$refs.tree.getSelectedNodes();
            // console.log(node);
            if (node.length > 0) {
                if (node[0].children && node[0].children.length > 0) {
                    this.$Message.error(this.$t(9000416));
                } else {
                    this.machine = node[0].title;
                    this.machineId = node[0].value;
                }
            }
        },
        // 动态获取工序
        getLine(value) {
            if (value) {
                this.productname = value;
                this.inilines(this.productname);
                this.getMachine(this.productname);
            }
        },
        getLine2(value) {
            this.addprelineid = value;
            this.inilines(this.addprelineid);
        },
        getMachine(id) {
            this.request(
                "/tlm/Technology/GetTechMachine?product_id=" + id,
                "",
                "get"
            ).then((res) => {
                if (res.data.ret == 1) {
                    // this.machineList = res.data.data;
                    this.machineList1 = res.data.data;
                }
            });
        },
        handleFormatError(file) {
            this.$Message.error(
                this.$t("950396") + file.name + this.$t("950397")
            );
        },
        handleSuccess(res, file) {
            if (res.ret == 1) {
                this.$Message.success(this.$t("950398"));
                this.search(1, 10);
            } else {
                if ((res.msg + "").indexOf(",") != -1) {
                    inittip(res.msg);
                } else {
                    this.$Message.error(this.$t(res.msg));
                }
            }
        },
        handleError() {
            this.$Message.error(this.$t("2010006") + "!");
        },
        handleSelectRow: function (data) {
            var ids = [];
            for (var i in data) {
                ids.push(data[i].id);
            }
            this.selectids = ids.join(",");
        },
        search(page, pagesize) {
            var data = {
                product_id: this.productname,
                route: this.lineid,
                page: page,
                pagesize: pagesize,
            };
            axios
                .request({
                    url: "/tlm/Technology/GetPagedList",
                    data,
                    method: "post",
                })
                .then((res) => {
                    this.total = res.data.total;
                    this.mockTableData1(res.data.data);
                });
        },
        mockTableData1(tablelist) {
            let data = [];
            tablelist.forEach((item) => {
                if (item) {
                    data.push({
                        product_name: item.product_name,
                        product_id: item.product_id,
                        drawcode: item.drawcode,
                        machineType_name: item.machineType_name,
                        machine_type: item.machine_type,
                        create_id: item.create_id,
                        create_name: item.create_name,
                        program: item.program,
                        remark: item.remark,
                        route: item.route,
                        route_id: item.route_id,
                        id: item.id,
                    });
                }
            });
            this.tableData1 = data;
        },
        handleRowChange(currentRow, oldCurrentRow) {
            this.detailobj = currentRow;
        },
        handlePageSize(value) {
            this.pagesize = value;
            this.tableData1 = this.search(this.page, this.pagesize);
        },
        changePage(value) {
            this.page = value;
            this.tableData1 = this.search(this.page, this.pagesize);
        },
        add() {
            this.routename = "";
            this.addproductid = "";
            this.machine = "";
            this.code = "";
            this.program = "";
            this.remark = "";
            this.contentTree(this.treeList);
            this.type = 1;
            this.addmodal = true;
        },
        closeadd() {
            this.addmodal = false;
            this.detailobj = {};
        },
        adddata() {
            if (this.addproductid == undefined || this.addproductid == "") {
                this.$Message.error(this.$t(8062));
                return false;
            }
            if (this.routename == undefined || this.routename == "") {
                this.$Message.error(this.$t(8063));
                return false;
            }
            if (this.machine == undefined || this.machine == "") {
                this.$Message.error(this.$t(9000416));
                return false;
            }

            let data = {
                product_id: this.addproductid,
                drawcode: this.code,
                machine_type: this.machineId,
                route: this.routename,
                program: this.program,
                remark: this.remark,
            };
            //   console.log(data);
            //   return false;
            axios
                .request({
                    url: "/tlm/Technology/Add",
                    data,
                    method: "post",
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t("1055"));
                        this.addmodal = false;
                        this.search(this.page, this.pagesize);
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        dele() {
            if (
                this.detailobj === undefined ||
                this.detailobj.id === undefined ||
                this.detailobj.id === 0
            ) {
                this.$Message.error(this.$t("1017"));
                return false;
            } else {
                // var data = {
                //   Id: this.detailobj.id,
                // };
                this.$Modal.confirm({
                    title: this.$t("1018"),
                    content: "",
                    width: "290px",
                    closable: true,
                    okText: this.$t("1004"),
                    onOk: () => {
                        axios
                            .request({
                                url:
                                    "/tlm/Technology/Delete?id=" +
                                    this.detailobj.id,

                                method: "post",
                            })
                            .then((res) => {
                                if (res.data.ret === 1) {
                                    this.$Message.success(this.$t("1058"));
                                    //   this.tableData1 = this.search(this.page, this.pagesize);
                                    this.detailobj = {};
                                    this.search(1, 10);
                                } else {
                                    this.$Message.error(this.$t(res.data.msg));
                                }
                            });
                    },
                });
            }
        },
        edit() {
            if (this.detailobj.id == undefined) {
                this.$Message.error(this.$t(200231));
                return false;
            }
            this.routename = this.detailobj.route_id;
            this.addproductid = this.detailobj.product_id;
            this.machine = this.detailobj.machineType_name;
            this.machineId = this.detailobj.machine_type;
            this.code = this.detailobj.drawcode;
            this.program = this.detailobj.program;
            this.remark = this.detailobj.remark;
            this.contentTree(this.treeList);

            this.addmodal = true;
            this.inilines(this.addproductid);

            this.type = 2;
        },
        editdata() {
            if (
                this.addproductid == undefined ||
                this.routename === undefined
            ) {
                this.$Message.error(this.$t(200232));
                return false;
            }

            let data = {
                product_id: this.addproductid,
                drawcode: this.code,
                machine_type: this.machineId,
                route: this.routename,
                program: this.program,
                remark: this.remark,
                id: this.detailobj.id,
            };

            axios
                .request({
                    url: "/tlm/Technology/Edit",
                    data,
                    method: "post",
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t("1060"));
                        this.detailobj = {};
                        this.addmodal = false;
                        this.search(this.page, this.pagesize);
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        loadexcel() {
            axios
                .request({
                    url: "/config/download/GetTemplate?name=TechnologyList",
                    method: "get",
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        window.location.href =
                            axios.publicPath + "" + res.data.data;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        Export() {
            let data = {
                product_id: this.routename,
                route: this.lineid,
                toexcel: 1,
            };
            axios
                .request({
                    url: "/tlm/Technology/GetPagedList",
                    data,
                    method: "post",
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        window.location.href =
                            axios.publicPath + "" + res.data.data;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        unloadexcel() {
            let file = this.readyFiles[0];
            const data = new FormData();
            data.append("file", file);
            data.append("type", 2);
            axios
                .request({
                    url:
                        "/acc/Upload/UploadExcel?templateName=RoutingstationInfo",
                    data,
                    method: "post",
                })
                .then((res) => {
                    if (res.ret === 1) {
                        this.$Message.success(this.$t("100378"));
                    } else {
                        alert(res.data.msg);
                    }
                })
                .catch((err) => {
                    alert(err.msg);
                });
        },
        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 scoped>
#machine .ivu-input[disabled] {
    color: #515a6e !important;
}
.middle {
    width: 400px;
    height: 3px;
    background-color: #ccc;
    margin-top: 10px;
    margin-bottom: 20px;
}
</style>
