<template>
    <div class="testdiv">
        <div class="divborder newSearchDiv" style="margin:0px;">
            <div class="filter">
                <label>{{$t(900630)}}：</label>
                <Input v-model="tool_number" class="searchInput" />
            </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" 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"
                :columns="tableColumns1"
            ></Table>
            <Poptip trigger="hover" title="Title">
                <div slot="content"></div>
            </Poptip>
            <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 class="filter">
                        <label>
                            <i>*</i>刀具号：
                        </label>
                        <Input
                            v-model="code"
                            placeholder="请输入刀具编号"
                            maxlength="50"
                            show-word-limit
                            class="searchInput"
                            :disabled="type==2"
                        />
                    </div>
                    <div>
                        <div class="filter">
                            <label>
                                <i>*</i>类型：
                            </label>
                            <Select
                                v-model="tooltype"
                                clearable
                                filterable
                                class="searchSelect"
                                @on-change="getToolDataByType"
                            >
                                <!-- <Option
                                    v-for="item in typeArr"
                                    :value="item.value"
                                    :key="item.value"
                                >{{ item.label }}</Option>-->
                                <Option :value="1" label-in-value>刀具</Option>
                                <Option :value="2" label-in-value>刀柄</Option>
                                <Option :value="3" label-in-value>附件</Option>
                                <Option :value="4" label-in-value>刀头</Option>
                            </Select>
                        </div>
                        <div class="filter">
                            <label>
                                <i>*</i>编码：
                            </label>
                            <Select
                                v-model="toolid"
                                clearable
                                filterable
                                label-in-value
                                class="searchSelect"
                                @on-change="getName"
                            >
                                <Option
                                    v-for="item in codeList"
                                    :value="item.id"
                                    :key="item.id"
                                >{{ item.number }}</Option>
                            </Select>
                        </div>
                        <Button
                            type="primary"
                            class="twoWord"
                            icon="md-add-circle"
                            @click="addTable()"
                        >{{$t('1002')}}</Button>
                    </div>
                    <div>
                        <Table
                            class="tableClass"
                            max-height="500"
                            :data="modalData"
                            :columns="addColumns"
                        ></Table>
                    </div>
                </div>
                <div slot="footer">
                    <Button type="text" size="large" @click="closeadd()">{{$t('1033')}}</Button>
                    <Button type="primary" @click="addPost()">{{$t('1011')}}</Button>
                </div>
            </Modal>
        </div>
    </div>
</template>
<script>
import axios from "@/libs/api.request";
import "view-design/dist/styles/iview.css";
export default {
    name: "productmanagement", // 组件不刷新
    data() {
        return {
            action:
                axios.publicPath +
                "tlm/Upload/Submit?templateName=ToollifeToolConfig",
            headers: {
                token: localStorage.getItem("token"),
                timestamp: localStorage.getItem("timestamp"),
                nonce: localStorage.getItem("nonce"),
                sign: localStorage.getItem("sign"),
            },
            tool_number: "",
            tool_number1: "",
            tableData1: [],
            total: 0,
            page: 1,
            pagesize: 10,
            addmodal: false,
            editmodal: false,
            detailobj: {},
            editobj: {},
            type: 0,
            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: "刀具号",
                    key: "code",
                },
                {
                    title: "创建人",
                    key: "creatorName",
                },
                {
                    title: "创建时间",
                    key: "createTime",
                },
                {
                    title: "BOM清单",
                    key: "cutNumber1",
                    // fixed:'right',
                    render: (h, params) => {
                        let data = [],
                            columns = [];
                        data = params.row.material;
                        columns = [
                            {
                                title: "类别",
                                key: "categoryName",
                            },
                            {
                                title: "刀具名称",
                                key: "name",
                            },
                            {
                                title: "刀具编号",
                                key: "toolNumber",
                            },
                        ];
                        return h(
                            "div",
                            {
                                style: {
                                    // position:'relative'
                                },
                            },
                            [
                                h(
                                    "Poptip",
                                    {
                                        props: {
                                            trigger: "hover",
                                            width: 400,
                                            placement: "bottom",
                                            transfer: true,
                                        },
                                    },
                                    [
                                        h("a", "查看"),
                                        h(
                                            "div",
                                            {
                                                slot: "content",
                                            },
                                            [
                                                h("Table", {
                                                    props: {
                                                        data: data,
                                                        columns: columns,
                                                    },
                                                }),
                                            ]
                                        ),
                                    ]
                                ),
                            ]
                        );
                    },
                },
            ],
            typeArr: [
                {
                    value: 1,
                    label: "刀具",
                },
                {
                    value: 2,
                    label: "刀柄",
                },
                {
                    value: 3,
                    label: "附件",
                },
                {
                    value: 4,
                    label: "刀头",
                },
            ],
            code: "",
            adddata: {},
            tooltype: "",
            toolcode: "",
            toolid: "",
            modalData: [],
            addColumns: [
                {
                    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: "类型",
                    key: "type",
                    render: (h, params) => {
                        let str = "";
                        switch (params.row.type) {
                        case 1:
                            str = "刀具";
                            break;
                        case 2:
                            str = "刀柄";
                            break;
                        case 3:
                            str = "附件";
                            break;
                        case 4:
                            str = "刀头";
                            break;
                        }
                        return h("div", str);
                    },
                },
                {
                    title: "编号",
                    key: "code",
                },
                {
                    title: "操作",
                    key: "action",
                    render: (h, params) => {
                        return h(
                            "a",
                            {
                                on: {
                                    click: () => {
                                        console.log(params.index);
                                        this.modalData.splice(params.index, 1);
                                    },
                                },
                            },
                            this.$t(1004)
                        );
                    },
                },
            ],
            codeList: [],
            loading1: false,
            editState: false,
        };
    },
    created() {
        // this.getToolDataByType(1);
        // this.getToolDataByType(2);
        // this.getToolDataByType(3);
        // this.getToolDataByType(4);

        this.search(1, 10);
        // 格式化表格样式
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1);
    },
    methods: {
        remoteMethod1(query, type) {
            if (query !== "") {
                this.loading1 = true;

                // let type = 2
                // return
                setTimeout(() => {
                    let data = {
                        type: type,
                        number: query,
                        count: 50,
                    };
                    this.request(
                        "/tlm/ToolConfig/GetToolDataByType",
                        data,
                        "get"
                    ).then((res) => {
                        // console.log(res.data.data);
                        // this.list = res.data.data;
                        switch (type) {
                        case 1:
                            this.cutList = res.data.data;

                            break;
                        case 2:
                            this.handleList = res.data.data;
                            break;
                        case 3:
                            this.attachmentList = res.data.data;
                            break;
                        case 4:
                            this.headList = res.data.data;
                            break;
                        }
                    });
                    this.loading1 = false;
                }, 200);
            } else {
                // this.options1 = [];
            }
        },
        getToolDataByType(val) {
            // this.loading1 = true;
            // console.log(val);
            if (val) {
                this.codeList = [];
                this.toolid = "";
                let data = {
                    type: val,
                    number: "",
                    name: "",
                    count: 0,
                };
                this.request(
                    "/tlm/ToolConfig/GetToolDataByType",
                    data,
                    "get"
                ).then((res) => {
                    // if (res.data.ret == 1) {
                    console.log(this.toolid);

                    this.codeList = res.data.data;
                    // }
                    // this.loading1 = false;
                });
            }
        },
        search(page, pagesize) {
            var data = {
                code: this.tool_number,
                projectId: 0,
                page: page,
                pagesize: pagesize,
            };
            axios
                .request({
                    url: "/tlm/ToolConfig/GetToolConfig",
                    data,
                    method: "post",
                })
                .then((res) => {
                    this.total = res.data.total;
                    this.tableData1 = res.data.data;
                });
        },
        getData() {
            this.getToolDataByType(1);
            this.getToolDataByType(2);
            this.getToolDataByType(3);
            this.getToolDataByType(4);
        },
        getName(value) {
            if (value) {
                this.toolcode = value.label;
            } else {
                this.toolcode = "";
            }
        },
        addTable() {
            if (this.tooltype != "" && this.toolid != "" && this.toolid != undefined && this.toolid != null) {
                // if () {
                let obj = {},
                    arr = [];
                obj.type = this.tooltype;
                obj.code = this.toolcode;
                obj.id = this.toolid;
                if (this.modalData.length > 0) {
                    this.modalData.forEach((ele) => {
                        arr.push(ele.id);
                    });
                }
                if (arr.indexOf(this.toolid) < 0) {
                    this.modalData.push(obj);
                }
                // }

                // console.log(this.modalData);
            }
        },
        add() {
            this.code = "";
            this.tooltype = "";
            this.toolid = "";
            this.modalData = [];
            this.type = 1;
            this.addmodal = true;
        },
        closeadd() {
            this.addmodal = false;
        },
        addPost() {
            if (this.code == undefined || this.code == "" || this.code == 0) {
                this.$Message.error("请输入刀具编号");
                return false;
            }
            let arr = [];
            if (this.modalData.length > 0) {
                this.modalData.forEach((ele) => {
                    arr.push(ele.id);
                });
            } else {
                this.$Message.error("请添加物料");
                return false;
            }
            let data = {
                    code: this.code,
                    toolIds: arr.join(","),
                },
                msg = "";
            console.log(data);
            // return false;
            // if (this.type == 2) {
            //     this.adddata.id = this.detailobj.id;
            //     msg = this.$t(1060);
            // } else {
            //     msg = this.$t(1055);
            // }
            // data = this.adddata;
            // console.log(this.adddata);

            // return false;
            axios
                .request({
                    url: "/tlm/ToolConfig/SetToolConfig",
                    data,
                    method: "post",
                })
                .then((res) => {
                    console.log(res.data);
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t(res.data.msg));
                        this.addmodal = false;
                        this.search(this.page, this.pagesize);
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        dele() {
            if (!this.detailobj.code) {
                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: () => {
                        let data = {
                            code: this.detailobj.code,
                        };
                        this.request(
                            "/tlm/ToolConfig/DelToolConfig?code=" +
                                this.detailobj.code,
                            "",
                            "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) {
                this.$Message.error(this.$t(200231));
                return false;
            }

            this.type = 2;
            this.adddata = this.detailobj;

            // for (let key in this.adddata) {
            //     if (this.adddata[key] != "" || this.adddata[key] != 0) {
            //         // console.log(key);

            //         if (key.indexOf("handleNumber") > -1) {
            //             this.remoteMethod1(this.adddata[key], 2);
            //         }
            //         if (key.indexOf("cutNumber") > -1) {
            //             this.remoteMethod1(this.adddata[key], 1);
            //         }
            //         if (key.indexOf("toolNumber") > -1) {
            //             this.remoteMethod1(this.adddata[key], 4);
            //         }
            //         if (key.indexOf("attachmentNumber") > -1) {
            //             this.remoteMethod1(this.adddata[key], 3);
            //         }
            //     }
            // }
            // this.editState = true;
            this.addmodal = true;
        },
        handleRowChange(currentRow, oldCurrentRow) {
            // console.log(this.detailobj);
            this.getData();
            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);
        },
        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(",");
        },
        loadexcel() {
            axios
                .request({
                    url: "/config/download/GetTemplate?name=ToollifeToolConfig",
                    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 = {
                Page: this.page,
                Pagesize: this.pagesize,
                code: this.tool_number,
                ProjectId: 0,
            };
            axios
                .request({
                    url: "/tlm/ToolConfig/ExportProjectToollifeToolConfig",
                    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=toollifetoolconfig",
                    data,
                    method: "post",
                })
                .then((res) => {
                    if (res.ret === 1) {
                        this.$Message.success(this.$t("100378"));
                    } else {
                        this.$Message.error(this.$t(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;
}
.modalbody {
    padding: 25px;
    width: 630px;
    margin: 0 auto;
    /* display: flex; */

    /* width:800px; */
}
.flex {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}
.m10 {
    margin: 10px auto;
}
.formItem {
    width: 270px;
    align-items: center;
    display: flex;
    justify-content: space-between;
    margin: 10px 0;
}
</style>
