<template>
    <div class="testdiv">
        <div class="divborder newSearchDiv" style="margin:0px;">
            <div class="filter">
                <label>{{$t('920010')}}：</label>
                <Cascader
                    :data="materialtype"
                    :value="material"
                    trigger="click"
                    change-on-select
                    class="searchSelect"
                    @on-change="getmaterial"
                ></Cascader>
            </div>
            <div class="filter">
                <label>{{$t('920160')}}：</label>
                <Input class="searchInput" type="text" v-model="name" />
            </div>
            <div class="filter">
                <label>{{$t('900933')}}：</label>
                <Input class="searchInput" type="text" v-model="pnnumber" />
            </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"
                @on-selection-change="handleSelectRow"
                highlight-row
                :data="tableData1"
                :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>
        </div>
        <Modal class="newModalClass" v-model="addmodal" :styles="{width:'850px'}">
            <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>
                        {{this.$t('920160')}}：
                    </label>
                    <Input class="searchInput" type="text" v-model="addobj.name" />
                </div>
                <div class="filter">
                    <label>
                        <i>*</i>
                        {{this.$t('950450')}}：
                    </label>
                    <Select v-model="addobj.typeid" label-in-value clearable class="searchSelect">
                        <Option
                            v-for="item in materialtypelist"
                            :value="item.id"
                            :key="item.id"
                        >{{ item.name }}</Option>
                    </Select>
                </div>
                <!-- <div class="filter">
            <label><i>*</i>{{this.$t('950451')}}：</label>
            <Select v-model="addobj.category" label-in-value clearable class="searchSelect">
              <Option :value='1' v-text="$t('900944')">{{$t('900944')}}</Option>
              <Option :value='2' v-text="$t('900943')">{{$t('900943')}}</Option>
              <Option :value='3' v-text="$t('950452')">{{$t('950452')}}</Option>
          </Select>
                </div>-->

                <div class="filter">
                    <label>
                        <i>*</i>
                        {{this.$t('600065')}}：
                    </label>
                    <Input class="searchInput" type="text" v-model="addobj.spec" />
                </div>
                <div class="filter">
                    <label>
                        <i>*</i>
                        {{this.$t('900933')}}：
                    </label>
                    <Input class="searchInput" type="text" v-if="type===1" v-model="addobj.pn" />
                    <Input
                        class="searchInput"
                        type="text"
                        v-if="type===2"
                        disabled
                        v-model="addobj.pn"
                    />
                </div>
                <div class="filter">
                    <label>
                        <i>*</i>
                        {{this.$t('600011')}}：
                    </label>
                    <Select
                        v-model="addobj.suppliers"
                        label-in-value
                        :max-tag-count="5"
                        clearable
                        multiple
                        class="searchSelect MaxWidth nowropStyle"
                    >
                        <Option
                            v-for="item in supplierlist"
                            :value="item.id"
                            :key="item.id"
                        >{{ item.text }}</Option>
                    </Select>
                </div>
                <div class="filter">
                    <label>
                        <i>*</i>
                        {{this.$t('920158')}}：
                    </label>
                    <Select
                        v-model="addobj.manage_mode"
                        label-in-value
                        clearable
                        class="searchSelect"
                    >
                        <Option
                            v-for="item in managermodelist"
                            :value="item.dkey"
                            :key="item.dkey"
                        >{{ item.dval }}</Option>
                    </Select>
                </div>
                <div class="filter">
                    <label>
                        <i>*</i>
                        {{this.$t('300034')}}：
                    </label>
                    <Select v-model="addobj.unit" label-in-value clearable class="searchSelect">
                        <Option
                            v-for="item in unitlist"
                            :value="item.dkey"
                            :key="item.dkey"
                        >{{ item.dval }}</Option>
                    </Select>
                </div>
                <div class="filter">
                    <label>{{this.$t('920157')}}：</label>
                    <Select
                        v-model="addobj.conv_unit"
                        label-in-value
                        clearable
                        class="searchSelect"
                    >
                        <Option
                            v-for="item in convunitslist"
                            :value="item.dkey"
                            :key="item.dkey"
                        >{{ item.dval }}</Option>
                    </Select>
                </div>
                <div class="filter">
                    <label>{{this.$t('920156')}}：</label>
                    <Input class="searchInput" type="number" v-model="addobj.conv_proportion" />
                </div>
                <div class="filter">
                    <label>{{this.$t('920155')}}：</label>
                    <Input class="searchInput" type="number" v-model="addobj.price" />
                </div>
                <div class="filter">
                    <label>{{this.$t('920154')}}：</label>
                    <Input class="searchInput" type="number" v-model="addobj.min_stock" />
                </div>
                <div class="filter">
                    <label>{{this.$t('920153')}}：</label>
                    <Input class="searchInput" type="number" v-model="addobj.max_stock" />
                </div>
                <div class="filter">
                    <label>{{this.$t('920152')}}：</label>
                    <Checkbox v-model="addobj.is_disable_bool" style="width:30px"></Checkbox>
                </div>
                <div class="filter">
                    <label>{{this.$t('920151')}}：</label>
                    <Checkbox v-model="addobj.is_first_bool" style="width:30px"></Checkbox>
                </div>
                <div class="filter">
                    <label>{{this.$t('920150')}}：</label>
                    <Select v-model="addobj.priority" label-in-value clearable class="searchSelect">
                        <Option
                            v-for="item in firstlevellist"
                            :value="item.dkey"
                            :key="item.dkey"
                        >{{ item.dval }}</Option>
                    </Select>
                </div>
                <div class="filter">
                    <label>{{this.$t('920149')}}：</label>
                    <Input class="searchInput" type="number" v-model="addobj.exp_str" />
                </div>
                <div class="filter">
                    <label>{{this.$t('1030')}}：</label>
                    <Input type="text" v-model="addobj.desc" class="searchInput MaxWidth" />
                </div>
                <div style="display: flex;">
                    <label>{{$t(600528)}}：</label>
                    <div class="uploadMax">
                        <img :src="loadimg" alt />
                        <input
                            type="file"
                            name
                            ref="fileIntimg"
                            id
                            @change="unloadimg"
                            accept="image/png, image/gif, image/jpeg"
                        />
                    </div>
                </div>
            </div>
            <div slot="footer">
                <Button type="text" size="large" @click="closeadd()">{{$t('1033')}}</Button>
                <Button type="primary" size="large" @click="adddata()">{{$t('1011')}}</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
import axios from "@/libs/api.request";
export default {
    name: "route",
    data() {
        return {
            headers: {
                token: localStorage.getItem("token"),
                timestamp: localStorage.getItem("timestamp"),
                nonce: localStorage.getItem("nonce"),
                sign: localStorage.getItem("sign"),
            },
            action:
                axios.publicPath +
                "acc/upload/UploadExcel?templateName=MaterialsInfo",
            name: "",
            pnnumber: "",
            materialtype: [],
            material: [],
            tableData1: [],
            total: 0,
            page: 1,
            pagesize: 10,
            addmodal: false,
            addobj: {},
            detailobj: {},
            type: 0,
            checknodeid: "0",
            materialtypelist: [],
            supplierlist: [],
            managermodelist: [],
            convunitslist: [],
            unitlist: [],
            firstlevellist: [],
            productlist: [],
            loadimg: require("../../../static/images/xiangjitwo.png"),
            uploadimg: "",
            selectids: [],
            tableColumns1: [
                {
                    type: "selection",
                    width: 50,
                    align: "center",
                },
                {
                    type: "index2",
                    title: this.$t("1008"),
                    key: "xuhao",
                    render: (h, params) => {
                        return h(
                            "span",
                            params.index + (this.page - 1) * this.pagesize + 1
                        );
                    },
                    width: "80px",
                },
                {
                    title: this.$t("920160"),
                    key: "name",
                    width: "120px",
                },
                {
                    title: this.$t("950450"),
                    key: "typeid_value",
                    width: "120px",
                },
                {
                    title: this.$t("950451"),
                    key: "typeid_category",
                    width: "120px",
                },
                {
                    title: this.$t("600065"),
                    key: "spec",
                    width: "140px",
                },
                {
                    title: this.$t("900933"),
                    key: "pn",
                    width: "140px",
                },
                {
                    title: this.$t("600011"),
                    key: "supplier_value",
                },
                {
                    title: this.$t("920158"),
                    key: "manage_mode",
                    render: (h, params) => {
                        let str = "";
                        switch (params.row.manage_mode) {
                            case '1':
                                str = "批次";
                                break;
                            case '2':
                                str = "序号";
                                break;
                            case '3':
                                str = "批量";
                                break;
                        }
                        return h(
                            "span",
                           str
                        );
                    },
                },
                {
                    title: this.$t("300034"),
                    key: "unit_value",
                },
                // {
                //   title: this.$t('920157'),
                //   key: 'conv_unit_value'
                // },
                // {
                //   title: this.$t('920156'),
                //   key: 'conv_proportion'
                // },
                {
                    title: this.$t("920155"),
                    key: "price",
                },
                // {
                //   title: this.$t('920154'),
                //   key: 'min_stock'
                // },
                // {
                //   title: this.$t('920153'),
                //   key: 'max_stock'
                // },
                // {
                //   title: this.$t('920151'),
                //   key: 'is_first_value'
                // },
                // {
                //   title: this.$t('920150'),
                //   key: 'priority_value'
                // },
                // {
                //   title: this.$t('920149'),
                //   key: 'exp'
                // },
                {
                    title: this.$t("1030"),
                    key: "desc",
                },
            ],
        };
    },
    created() {
        this.initree();
        this.search(1, 10);
        // 格式化表格样式
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1);
    },
    methods: {
        initree() {
            axios
                .request({
                    url: "/config/Materials/gettree",
                    method: "get",
                })
                .then((res) => {
                    const arr = [];
                    var data = res.data.data.children;
                    data.forEach((item) => {
                        let data = {};
                        data.value = item.id;
                        data.label = item.name;
                        data.expand = true;
                        data.children = this.getchildren(item);
                        this.materialtype.push(data);
                    });
                    arr.push(this.materialtype[0].value);
                    this.material = arr;
                });
        },
        getchildren(item) {
            let arry = [];
            if (
                item.children !== undefined &&
                item.children !== null &&
                item.children !== [] &&
                item.children.length > 0
            ) {
                item.children.forEach((child) => {
                    let data = {};
                    data.value = child.id;
                    data.label = child.name;
                    data.expand = true;
                    data.children = this.getchildren(child);
                    arry.push(data);
                });
            }
            return arry;
        },
        handleSelectRow: function (data) {
            this.selectids = [];
            for (var i in data) {
                this.selectids.push(data[i].id);
            }
        },
        getmaterial: function (data) {
            this.checknodeid = data[data.length - 1];
        },
        search(page, pagesize) {
            var params = {
                name: this.name,
                typeid: this.checknodeid,
                pn: this.pnnumber,
                page: page,
                pagesize: pagesize,
            };
            axios
                .request({
                    url: "/config/Materials/getList",
                    params,
                    method: "get",
                })
                .then((res) => {
                    this.total = res.data.total;
                    this.mockTableData1(res.data.data);
                });
        },
        mockTableData1(tablelist) {
            let data = [];
            tablelist.forEach((item) => {
                if (item) {
                    data.push({
                        name: item.name,
                        id: item.id,
                        typeid: item.typeid,
                        typeid_value: item.typeid_value,
                        typeid_category:
                            item.category === 1
                                ? this.$t("900944")
                                : item.category === 2
                                ? this.$t("900943")
                                : this.$t("950452"),
                        spec: item.spec,
                        pn: item.pn,
                        supplier: item.supplier,
                        suppliers:
                            item.supplier !== ""
                                ? item.supplier.split(",")
                                : "",
                        supplier_value: item.supplier_value,
                        manage_mode: item.manage_mode,
                        manage_mode_value: item.manage_mode_value,
                        unit: item.unit,
                        unit_value: item.unit_value,
                        conv_unit: item.conv_unit,
                        conv_unit_value: item.conv_unit_value,
                        conv_proportion: item.conv_proportion,
                        price: item.price,
                        min_stock: item.min_stock,
                        max_stock: item.max_stock,
                        is_first_bool: item.is_first === 1,
                        is_first: item.is_first,
                        is_first_value: item.is_first_value,
                        priority: item.priority,
                        priority_value: item.priority_value,
                        exp: item.exp,
                        exp_str: item.exp,
                        desc: item.desc,
                        is_disable: item.is_disable,
                        is_disable_bool: item.is_disable === 1,
                        image: item.image,
                        category: item.category,
                    });
                }
            });
            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.type = 1;
            // this.iniproduct()
            this.inimaterialtype();
            this.inisupplier();
            this.inimanagermode();
            this.iniunit();
            this.iniconvunitslist();
            this.inifirstlevellist();
            this.addobj = {
                name: "",
                typeid: 0,
                spec: "",
                pn: "",
                suppliers: "",
                manage_mode: 0,
                unit: 0,
                conv_unit: "",
                conv_proportion: "",
                price: 0,
                min_stock: 0,
                max_stock: 0,
                is_first: "0",
                priority: 0,
                exp_str: "",
                desc: "",
                is_disable: "",
                image: "",
                category: 0,
                product_id: 0,
            };
            this.addmodal = true;
        },
        iniproduct() {
            var params = {
                name: this.productname,
                count: 100,
            };
            axios
                .request({
                    url: "/config/ProjectProduct/GetProductsByCode",
                    params,
                    method: "get",
                })
                .then((res) => {
                    this.productlist = res.data.data;
                });
        },
        inimaterialtype() {
            axios
                .request({
                    url: "/config/MaterialType/GetLastLevelType",
                    method: "get",
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.materialtypelist = res.data.data;
                    }
                });
        },
        inisupplier() {
            axios
                .request({
                    url: "/config/Materials/GetSuppliers",
                    method: "get",
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.supplierlist = res.data.data;
                    }
                });
        },
        inimanagermode() {
            axios
                .request({
                    url: "/config/Dict/GetDictByCat?cat=managemodel",
                    method: "get",
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.managermodelist = res.data.data;
                    }
                });
        },
        iniunit() {
            axios
                .request({
                    url: "/config/Dict/GetDictByCat?cat=meterunits",
                    method: "get",
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.unitlist = res.data.data;
                    }
                });
        },
        iniconvunitslist() {
            axios
                .request({
                    url: "/config/Dict/GetDictByCat?cat=convunits",
                    method: "get",
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.convunitslist = res.data.data;
                    }
                });
        },
        inifirstlevellist() {
            axios
                .request({
                    url: "/config/Dict/GetDictByCat?cat=prioritytype",
                    method: "get",
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.firstlevellist = res.data.data;
                    }
                });
        },
        unloadimg() {
            // 上传照片
            const file = this.$refs.fileIntimg.files[0];
            const data = new FormData();
            data.append("file", file);
            axios
                .request({
                    url: "/config/upload/UploadImage",
                    data,
                    method: "post",
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t(100378));
                        this.loadimg = axios.publicPath + res.data.data;
                        this.uploadimg = this.loadimg;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                })
                .catch((err) => {
                    this.$Message.error(this.$t(err.msg));
                });
        },
        closeadd() {
            this.addmodal = false;
        },
        adddata() {
            let data = this.addobj;
            data.image = this.uploadimg;
            data.is_disable = this.addobj.is_disable_bool === true ? "1" : "0";
            data.is_first = this.addobj.is_first_bool === true ? "1" : "0";
            var allsuppliers = "";
            if (data.suppliers !== undefined && data.suppliers.length > 0) {
                var arry = [];
                for (var item in data.suppliers) {
                    arry.push(data.suppliers[item]);
                }
                allsuppliers = arry.join(",");
            } else {
                allsuppliers = "";
            }
            data.supplier = allsuppliers;
            data.exp = data.exp_str === "" ? 0 : parseFloat(data.exp_str);
            if (data.name === undefined || data.name === "") {
                this.$Message.error(this.$t("1063"));
                return false;
            }
            if (data.category === 3 && allsuppliers === "") {
                this.$Message.error(this.$t("9000179"));
                return false;
            }

            if (data.pn === undefined || data.pn === "") {
                this.$Message.error(this.$t("1063"));
                return false;
            }
            if (data.spec === undefined || data.spec === "") {
                this.$Message.error(this.$t("1063"));
                return false;
            }
            if (data.typeid === undefined || data.typeid === 0) {
                this.$Message.error(this.$t("1063"));
                return false;
            }
            if (data.manage_mode === undefined || data.manage_mode === 0) {
                this.$Message.error(this.$t("1063"));
                return false;
            }
            if (data.unit === undefined || data.unit === 0) {
                this.$Message.error(this.$t("1063"));
                return false;
            }
            if (!data.suppliers || data.suppliers.length == 0) {
                this.$Message.error(this.$t("1063"));
                return false;
            }
            if (this.type === 1) {
                this.addobj.id = "";
                axios
                    .request({
                        url: "/config/Materials/Add",
                        data,
                        method: "post",
                    })
                    .then((res) => {
                        if (res.data.ret === 1) {
                            this.$Message.success(this.$t("1055"));
                            this.search(this.page, this.pagesize);
                            this.addmodal = false;
                        } else {
                            this.$Message.error(this.$t(res.data.msg));
                        }
                    });
            } else if (this.type === 2) {
                axios
                    .request({
                        url: "/config/Materials/Modify",
                        data,
                        method: "post",
                    })
                    .then((res) => {
                        if (res.data.ret === 1) {
                            this.$Message.success(this.$t("1060"));
                            this.page = 1;
                            this.search(this.page, this.pagesize);
                            this.detailobj = {};
                            this.addmodal = false;
                        } else {
                            this.$Message.error(this.$t(res.data.msg));
                        }
                    });
            }
        },
        dele() {
            if (
                this.selectids === undefined ||
                this.selectids === "" ||
                this.selectids.length === 0
            ) {
                this.$Message.error(this.$t("1017"));
                return false;
            } else {
                var ids = [];
                this.selectids.forEach((ele) => {
                    ids.push(ele);
                });
                var data = {
                    ids: ids,
                };
                this.$Modal.confirm({
                    title: this.$t("1018"),
                    content: "",
                    width: "290px",
                    closable: true,
                    okText: this.$t("1004"),
                    onOk: () => {
                        axios
                            .request({
                                url: "/config/Materials/Deletes",
                                data: data,
                                method: "post",
                            })
                            .then((res) => {
                                if (res.data.ret === 1) {
                                    this.$Message.success(this.$t("1058"));
                                    this.search(1, this.pagesize);
                                    this.detailobj = {};
                                } else {
                                    this.$Message.error(this.$t(res.data.msg));
                                }
                            });
                    },
                });
            }
        },
        edit() {
            if (
                this.detailobj === {} ||
                this.detailobj.id === "" ||
                this.detailobj.id === undefined
            ) {
                this.$Message.error(this.$t("1017"));
                return false;
            }
            this.type = 2;
            // this.iniproduct()
            this.inimaterialtype();
            this.inisupplier();
            this.inimanagermode();
            this.iniunit();
            this.iniconvunitslist();
            this.inifirstlevellist();
            this.addobj = this.detailobj;
            this.addobj.supplier = this.detailobj.suppliers;
            this.addmodal = true;
        },
        loadexcel() {
            axios
                .request({
                    url: "/config/download/GetTemplate?name=MaterialsInfo",
                    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 params = {
                exp: "",
                name: this.name,
                typeid: this.checknodeid,
            };
            axios
                .request({
                    url: "/config/Materials/exportAll",
                    params,
                    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));
                    }
                });
        },
        handleFormatError(file) {
            this.$Message.error(
                this.$t("950396") + file.name + this.$t("950397")
            );
        },
        handleSuccess(res, file) {
            if (res.ret == 1) {
                this.search(1, 10);
                this.$Message.success(this.$t("950398"));
            } else {
                if (typeof res.msg !== "number") {
                    inittip(res.msg);
                } else {
                    this.$Message.error(this.$t(res.msg));
                }
            }
        },
        handleError() {
            this.$Message.error(this.$t("2010006") + "!");
        },
    },
};
</script>
<style lang="less" scoped>
</style>
